//! `shell.deck` and `shell.plus` over synthetic databases of each app: the //! deck's page answered whole, paged by cursor, narrowed by ink. use super::*; use crate::handle::CottonHandle; const TODAY: &str = "2026-11-05"; /// A fresh phone opened as the app `manifest` names (Cotton's when None). fn phone(manifest: Option<&str>) -> (tempfile::TempDir, CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); // Any app's manifest, read from its folder: a new app needs no line here. let app = cotton_store::manifest_dir().join("../../apps/cotton/App"); let path = match manifest { None => app.join("CottonManifest/flavour.json"), // Rigby and Cotton Project retired (22 Nov 2026): their manifests are kept as fixtures. Some(slug @ ("rigby" | "development")) => app.join(format!("../Tests/Fixtures/Flavours/{slug}.json")), Some(slug) => app.join(format!("Flavours/{slug}/flavour.json")), }; let manifest: Value = serde_json::from_slice(&std::fs::read(&path).unwrap_or_else(|error| panic!("no manifest {}: {error}", path.display()))).expect("a manifest"); let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(manifest), }) .expect("an open core"); // Local first: a phone keeps its own database before anyone signs in. crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started"); (dir, handle) } fn make(handle: &CottonHandle, table: &str, data: Value) -> String { let made = crate::methods::dispatch(handle, "records.create", &json!({"table": table, "data": data, "timezone": "Asia/Kolkata"})) .unwrap_or_else(|error| panic!("a {table} is made: {error:?}")); made["id"].as_str().or_else(|| made["record"]["id"].as_str()).unwrap_or_else(|| panic!("a made id: {made}")).to_string() } fn deck(handle: &CottonHandle, request: Value) -> Value { let mut request = request; request["timezone"] = json!("Asia/Kolkata"); request["today"] = json!(TODAY); crate::methods::dispatch(handle, "shell.deck", &request).unwrap_or_else(|error| panic!("the deck reads: {error:?}")) } fn titles(answer: &Value) -> Vec { answer["cards"].as_array().unwrap().iter().map(|card| card["slots"]["title"].as_str().unwrap_or_default().to_string()).collect() } fn ids(answer: &Value) -> Vec { answer["cards"].as_array().unwrap().iter().map(|card| card["id"].as_str().unwrap().to_string()).collect() } // RULE (boundary review move 2, 5 Nov 2026): the deck's page is the core's: order, face, every slot's words, position, the tap map and the acts by id. #[test] fn todos_today_is_answered_whole() { assert!(crate::methods::read_only("shell.deck") && crate::methods::read_only("shell.plus")); let (_dir, handle) = phone(None); for title in ["Pay the invented rent", "Water the plants", "Call the plumber"] { make(&handle, "todo", json!({"title": title, "due_at": "2026-11-05T12:00:00+05:30"})); } make(&handle, "todo", json!({"title": "Someday later", "due_at": "2026-12-20T12:00:00+05:30"})); let answer = deck(&handle, json!({"table": "todo", "view": "todos/today"})); assert_eq!(answer["count"], 3, "{answer}"); assert_eq!(answer["cards"].as_array().unwrap().len(), 3); let card = &answer["cards"][0]; assert_eq!(card["face"], "todo.card"); assert_eq!(card["position"], "1 / 3"); assert_eq!(answer["cards"][2]["position"], "3 / 3"); assert_eq!(card["slots"]["check"], false, "a todo's check is a slot: {card}"); assert_eq!(card["tap"]["check"], "check"); assert_eq!(answer["acts"]["check"]["kind"], "toggle"); let open = card["tap"]["card"].as_str().unwrap(); assert!(open.starts_with("open."), "{open}"); assert_eq!(answer["acts"][open]["kind"], "open"); assert!(answer["acts"][open]["label"].is_string(), "every act is said"); // Its acts are named once per page, the cards naming them by id. let offered: Vec<&str> = card["acts"].as_array().unwrap().iter().map(|id| id.as_str().unwrap()).collect(); assert!(!offered.is_empty()); for id in &offered { assert!(answer["acts"][*id]["label"].is_string(), "act {id} is in the table"); } // They are the held card's acts, in its order, each as it says it: one rule, never a copy. let opened = crate::methods::dispatch(&handle, "shell.opened", &json!({"table": "todo", "id": card["id"], "view": "todos/today", "face": card["face"]})).unwrap(); let held: Vec<&str> = opened["acts"].as_array().unwrap().iter().map(|act| act["id"].as_str().unwrap()).collect(); assert_eq!(offered, held, "the deck's acts are shell.opened's"); for act in opened["acts"].as_array().unwrap() { let said = &answer["acts"][act["id"].as_str().unwrap()]; assert_eq!((&said["label"], &said["red"], &said["primary"]), (&act["label"], &act["red"], &act["primary"]), "{said} is {act}"); } // The labels go once per page, never per card. assert!(answer["labels"]["by_column"]["title"].is_string()); assert!(card.get("labels").is_none()); // The record the shell's routes still take, its card lifted out of it. assert!(card["record"]["data"].get("@card").is_none()); assert_eq!(answer["next"], Value::Null); assert_eq!(answer["plus"]["does"], "blank"); } // RULE (owner, 2 Nov 2026): Calendar's Upcoming deals the events ahead in their order, each on its rolodex. #[test] fn calendar_upcoming_deals_what_is_ahead() { let (_dir, handle) = phone(None); make(&handle, "event", json!({"title": "Invented dentist", "starts_at": "2026-11-09T10:00:00+05:30"})); make(&handle, "event", json!({"title": "Invented launch", "starts_at": "2026-11-07T18:00:00+05:30"})); make(&handle, "event", json!({"title": "Invented past", "starts_at": "2026-10-01T09:00:00+05:30"})); let answer = deck(&handle, json!({"table": "event", "view": "calendar/upcoming"})); assert_eq!(titles(&answer), ["Invented launch", "Invented dentist"], "{answer}"); assert_eq!(answer["cards"][0]["face"], "event.rolodex"); } // RULE (362 walk, Calendar 04c): Calendar's Today deals today's events alone, a timed one and a whole day, never tomorrow's; its count is the Today tile's. #[test] fn calendar_today_deals_today_alone() { let (_dir, handle) = phone(None); zoned(&handle); make(&handle, "event", json!({"title": "Invented standup", "starts_at": "2026-11-05T09:30:00+05:30"})); make(&handle, "event", json!({"title": "Invented holiday", "starts_at": "2026-11-05"})); make(&handle, "event", json!({"title": "Invented dentist", "starts_at": "2026-11-06T09:00:00+05:30"})); make(&handle, "event", json!({"title": "Invented past", "starts_at": "2026-11-04T09:00:00+05:30"})); let today = deck(&handle, json!({"table": "event", "view": "calendar/today"})); let mut said = titles(&today); said.sort(); assert_eq!(said, ["Invented holiday", "Invented standup"], "{today}"); assert_eq!(today["count"], 2, "{today}"); let upcoming = deck(&handle, json!({"table": "event", "view": "calendar/upcoming"})); assert_eq!(titles(&upcoming), ["Invented dentist"], "{upcoming}"); } // RULE (362 walk, Calendar 04c): the phone asks the deck with no day of its own (`today` absent): Today is the person's day in their zone by the clock, never the coming days. #[test] fn calendar_today_by_the_clock_is_the_persons_day() { let (_dir, handle) = phone(None); zoned(&handle); let here = chrono::Utc::now() + chrono::Duration::minutes(330); let day = here.format("%Y-%m-%d").to_string(); let tomorrow = (here + chrono::Duration::days(1)).format("%Y-%m-%d").to_string(); make(&handle, "event", json!({"title": "Invented early", "starts_at": format!("{day}T00:05:00+05:30")})); make(&handle, "event", json!({"title": "Invented late", "starts_at": format!("{day}T23:55:00+05:30")})); make(&handle, "event", json!({"title": "Invented tomorrow", "starts_at": format!("{tomorrow}T09:00:00+05:30")})); let asked = |view: &str| crate::methods::dispatch(&handle, "shell.deck", &json!({"table": "event", "view": view, "timezone": "Asia/Kolkata"})).expect("the deck reads"); let today = asked("calendar/today"); assert_eq!(titles(&today), ["Invented early", "Invented late"], "{today}"); assert_eq!(titles(&asked("calendar/upcoming")), ["Invented tomorrow"]); } // RULE (Calendar after Plus, #294): a deck asked to land (`lands`) stands on the view the core names, never on no view: the view chosen when it reads this table, else the tool's default, else the first that reads it; a table no tool lists has none. #[test] fn a_fresh_record_lands_on_the_view_the_core_names() { let (_dir, handle) = phone(None); zoned(&handle); let day = (chrono::Utc::now() + chrono::Duration::minutes(330)).format("%Y-%m-%d").to_string(); make(&handle, "event", json!({"title": "Invented today", "starts_at": format!("{day}T23:55:00+05:30")})); let landed = |request: Value| crate::methods::dispatch(&handle, "shell.deck", &request).expect("the deck reads"); let ask = |chosen: Value| json!({"table": "event", "lands": true, "chosen": chosen, "timezone": "Asia/Kolkata"}); let fresh = landed(json!({"table": "event", "lands": true, "timezone": "Asia/Kolkata"})); assert_eq!(fresh["view"], "calendar/today", "the tool's default: {}", fresh["view"]); assert_eq!(fresh["landed"]["id"], "today"); assert_eq!(fresh["landed"]["default"], true, "said as the fan says a view"); assert_eq!(fresh["landed"]["read"]["table"], "event"); assert_eq!(titles(&fresh), ["Invented today"], "the cards are that view's"); assert_eq!(landed(ask(json!({"calendar": "upcoming"})))["view"], "calendar/upcoming", "the view chosen"); assert_eq!(landed(ask(json!({"calendar": "group:invented-list"})))["view"], "calendar/today", "a list is no view to land on"); assert_eq!(landed(ask(json!({"calendar": "gone"})))["view"], "calendar/today", "a view no longer held"); let asked = landed(json!({"table": "event", "view": "calendar/all", "timezone": "Asia/Kolkata"})); assert!(asked["landed"].is_null(), "a deck that names its view lands nowhere: {}", asked["landed"]); let plain = landed(json!({"table": "event", "timezone": "Asia/Kolkata"})); assert!(plain["view"].is_null() && plain["landed"].is_null(), "only a landing is answered a view"); let tabled = landed(json!({"table": "face_settings", "lands": true, "timezone": "Asia/Kolkata"})); assert!(tabled["landed"].is_null() && tabled["view"].is_null(), "no tool lists it: {}", tabled["view"]); } // RULE (#294): a tool that lists several tables lands a record on a view of its own table, not on the tool's default over another; a landing is never kept under the deck's own read. #[test] fn a_landing_reads_the_records_own_table() { // Books lists book and highlight, its default view over book (Music, the old example, is retired: TABLE DROP 1). let (_dir, handle) = phone(Some("books")); let answer = crate::methods::dispatch(&handle, "shell.deck", &json!({"table": "highlight", "lands": true, "timezone": "Asia/Kolkata"})).expect("the deck reads"); assert_eq!(answer["landed"]["read"]["table"], "highlight", "{}", answer["view"]); assert!(answer["view"].as_str().is_some_and(|view| view.starts_with("books/")), "{}", answer["view"]); let again = crate::methods::dispatch(&handle, "shell.deck", &json!({"table": "highlight", "lands": true, "timezone": "Asia/Kolkata"})).expect("the deck reads"); assert_eq!(again["landed"], answer["landed"], "asked again, it still says where it landed"); } // RULE: a person's card says how they are reached (here by nothing yet), and wears the face the person chose for People. #[test] fn people_are_reached_and_wear_the_chosen_face() { let (_dir, handle) = phone(None); make(&handle, "person", json!({"full_name": "Invented Asha", "language": "en"})); make(&handle, "person", json!({"full_name": "Invented Bela", "language": "en"})); let answer = deck(&handle, json!({"table": "person", "view": "people/all"})); assert_eq!(answer["count"], 2); let asha = answer["cards"].as_array().unwrap().iter().find(|card| card["slots"]["title"] == "Invented Asha").expect("Asha's card"); // No number or address yet: no disc to reach her by. assert_eq!((asha["reach"]["call"].clone(), asha["reach"]["email"].clone()), (json!(false), json!(false))); assert_eq!(asha["face"], "person.rolodex"); assert_eq!(answer["hand"], json!(["person.rolodex", "person.file", "person.passport"])); assert_eq!(answer["worn"], "person.rolodex"); assert_eq!(answer["hand_next"]["face"], "person.file", "the tap wears the next face"); assert!(answer["hand_next"]["label"].as_str().is_some_and(|said| !said.is_empty() && !said.contains('{')), "{}", answer["hand_next"]); make(&handle, "face_settings", json!({"table": "person", "face": "person.passport"})); let worn = deck(&handle, json!({"table": "person", "view": "people/all"})); assert_eq!(worn["worn"], "person.passport"); assert_eq!(worn["hand_next"]["writes"], json!({"kind": "face", "table": "person", "face": "person.rolodex"}), "past the last face, the first"); let got = crate::methods::dispatch(&handle, "records.get", &json!({"table": "person", "id": asha["id"]})).expect("the card reads"); assert_eq!(got["data"]["@card"]["face"], "person.passport", "a card dealt outside the deck wears the choice: {got}"); assert!(worn["cards"].as_array().unwrap().iter().all(|card| card["face"] == "person.passport"), "{worn}"); } // RULE (owner, 4 Nov 2026): Books' decks are hardbacks; Plus is the doors (Find a book, Add a file, Bring Goodreads in); a list's deck is its members. #[test] fn books_all_reading_a_list_and_plus() { let (_dir, handle) = phone(Some("books")); let dune = make(&handle, "book", json!({"title": "Invented Dune", "author": "A. Writer", "status": "reading"})); make(&handle, "book", json!({"title": "Invented Emma", "author": "B. Writer", "status": "finished", "rating": 4})); let all = deck(&handle, json!({"table": "book", "view": "books/all"})); assert_eq!(all["count"], 2, "{all}"); assert!(all["cards"].as_array().unwrap().iter().all(|card| card["face"] == "book.hardback")); let reading = deck(&handle, json!({"table": "book", "view": "books/reading"})); assert_eq!(ids(&reading), std::slice::from_ref(&dune)); assert_eq!(all["plus"]["does"], "doors"); let doors: Vec<&str> = all["plus"]["doors"].as_array().unwrap().iter().map(|door| door["id"].as_str().unwrap()).collect(); assert!(doors.len() >= 2, "{doors:?}"); assert!(all["plus"]["doors"].as_array().unwrap().iter().all(|door| door["label"].is_string() && door["accepts"].is_object())); let plus = crate::methods::dispatch(&handle, "shell.plus", &json!({"table": "book"})).unwrap(); assert_eq!(plus, all["plus"], "the deck and its Plus agree"); // A list's deck: its members alone (`a_lists_deck_opens_in_every_app_with_lists`). let shelf = list(&handle, "book", "Invented shelf", &[&dune]); let listed = deck(&handle, json!({"table": "book", "view": fan_list(&handle, "books", &shelf)})); assert_eq!(ids(&listed), std::slice::from_ref(&dune), "{listed}"); } // RULE (Cotton Photos, 12 Nov 2026): Photos' Plus is its three doors — Choose photos (the system's picker, photos and videos, many), Take a photo (the camera, one at a time) and From Files (any picture or film, with their media types) — on Recent's deck and from shell.plus alike, signed out as signed in. #[test] fn photos_plus_is_the_picker_the_camera_and_files() { let (_dir, handle) = phone(Some("photos")); let recent = deck(&handle, json!({"table": "media", "view": "photos/all"})); assert_eq!(recent["plus"]["does"], "doors", "{recent}"); let accepts: Vec<(&str, &Value)> = recent["plus"]["doors"].as_array().unwrap().iter().map(|door| (door["id"].as_str().unwrap(), &door["accepts"])).collect(); assert_eq!(accepts, [ ("library", &json!({"pick": {"source": "library", "kinds": ["photo", "video"], "many": true}})), ("camera", &json!({"pick": {"source": "camera", "kinds": ["photo", "video"], "many": false}})), ("files", &json!({"files": {"types": ["public.image", "public.movie"], "mimes": ["image/*", "video/*"], "many": true}})), ]); let plus = crate::methods::dispatch(&handle, "shell.plus", &json!({"table": "media"})).unwrap(); assert_eq!(plus, recent["plus"], "the deck and its Plus agree"); } // RULE (owner, 6 Nov 2026): Cinemas' All is every film and series, the latest added first; A to Z every one by title. #[test] fn cinemas_all_and_a_to_z() { let (_dir, handle) = phone(Some("cinemas")); make(&handle, "film", json!({"title": "Invented B film", "kind": "film", "added_on": "2026-11-05"})); make(&handle, "film", json!({"title": "Invented A series", "kind": "series", "added_on": "2026-11-01"})); make(&handle, "film", json!({"title": "Invented C film", "kind": "film", "added_on": "2026-11-03"})); let all = deck(&handle, json!({"table": "film", "view": "cinemas/all"})); assert_eq!(titles(&all), ["Invented B film", "Invented C film", "Invented A series"], "{all}"); let a_to_z = deck(&handle, json!({"table": "film", "view": "cinemas/a_to_z"})); assert_eq!(titles(&a_to_z), ["Invented A series", "Invented B film", "Invented C film"], "{a_to_z}"); } // RULE (Cotton Keys, 8 Nov 2026: the core refused an unknown face, so a passkey had no card): a passkey deals as the passkey card, holding the site's name and address, the account, the note and its made, last used and uses facts under their labels; nothing of the key (credential id, public key) is in the face's places, and the sealed private half is nowhere on the card. #[test] fn a_passkey_wears_the_passkey_card() { let (_dir, handle) = phone(Some("keys")); make(&handle, "passkey", json!({ "rp_id": "invented.example", "rp_name": "Invented Site", "user_name": "ada@invented.example", "credential_id": "SYNTHETIC-CREDENTIAL", "algorithm": "ES256", "public_key": "SYNTHETIC-PUBLIC", "created_at": "2026-10-02T09:14:00Z", "last_used_at": "2026-11-05T18:40:00Z", "uses": 12, "note": "Invented note.", })); let all = deck(&handle, json!({"table": "passkey"})); let card = &all["cards"][0]; assert_eq!(card["face"], "passkey.card", "{all}"); let slots = &card["slots"]; assert_eq!(slots["title"], "Invented Site", "{slots}"); assert_eq!(slots["subtitle"], "invented.example", "{slots}"); assert_eq!(slots["holder"], "ada@invented.example", "{slots}"); assert_eq!(slots["body"], "Invented note.", "{slots}"); let facts = slots["facts"].as_array().unwrap_or_else(|| panic!("facts: {slots}")); let labels: Vec<&str> = facts.iter().filter_map(|fact| fact["label"].as_str()).collect(); assert_eq!(labels, ["Made", "Last used", "Uses"], "{slots}"); assert_eq!(facts[2]["said"], "12 uses", "{slots}"); let face = slots.to_string(); for key in ["SYNTHETIC-CREDENTIAL", "SYNTHETIC-PUBLIC", "private_key_enc"] { assert!(!face.contains(key), "{key} in the face's places: {slots}"); } assert!(!card.to_string().contains("private_key_enc"), "the sealed key rides on the card: {card}"); } // RULE (Cinemas leftovers, 7 Nov 2026: a season's own page stood on plain cream paper): a series' seasons deal as their season card, each holding its number, year, its episodes in their count words and as a number, the episodes watched, the series' title and the series' poster. #[test] fn a_series_seasons_wear_the_season_card() { let (_dir, handle) = phone(Some("cinemas")); let series = make(&handle, "film", json!({"title": "Invented Serial", "kind": "series", "poster": "media-invented-poster"})); let season = make(&handle, "film_season", json!({"film": series, "number": 2, "title": "The Invented Crossings", "year": "2021"})); for (number, status) in [(1, Some("watched")), (2, Some("watching")), (3, None)] { let mut data = json!({"title": format!("Invented episode {number}"), "season": season, "series": series, "number": number}); if let Some(status) = status { data["status"] = json!(status); } make(&handle, "film_episode", data); } let seasons = deck(&handle, json!({"table": "film_season", "where": {"film": series}})); let card = &seasons["cards"][0]; assert_eq!(card["face"], "season.card", "{seasons}"); let slots = &card["slots"]; assert_eq!(slots["title"], "The Invented Crossings", "{slots}"); assert_eq!(slots["number"], "2", "{slots}"); assert_eq!(slots["year"], "2021", "{slots}"); assert_eq!(slots["subtitle"], "3 episodes", "{slots}"); assert_eq!(slots["limit"], 3, "{slots}"); assert_eq!(slots["used"], 1, "{slots}"); assert_eq!(slots["source"], "Invented Serial", "{slots}"); assert_eq!(slots["photo"], "media-invented-poster", "{slots}"); // One episode is said as one, by the line's own plural forms: the count // words are the card's, so an object whose episodes column predates them // says them too. let single = make(&handle, "film_season", json!({"film": series, "number": 3, "title": "Season 3"})); make(&handle, "film_episode", json!({"title": "Invented lone episode", "season": single, "series": series, "number": 1})); let seasons = deck(&handle, json!({"table": "film_season", "where": {"film": series}})); let lone = seasons["cards"].as_array().unwrap().iter().find(|card| card["id"] == single.as_str()).expect("the third season"); assert_eq!(lone["slots"]["subtitle"], "1 episode", "{lone}"); } // RULE (Android Cinemas, 12 Nov 2026: a shell reads no card.opens and counts nothing): a series' card in the deck says the deck its seasons are and its seasons and episodes counted, in the kit's words; a season's says its episodes' deck; a film's says neither. #[test] fn a_series_card_says_its_parts_and_counts_them() { let (_dir, handle) = phone(Some("cinemas")); let series = make(&handle, "film", json!({"title": "Invented Serial", "kind": "series"})); make(&handle, "film", json!({"title": "Invented Feature", "kind": "film"})); let first = make(&handle, "film_season", json!({"film": series, "number": 1, "title": "Season 1"})); make(&handle, "film_season", json!({"film": series, "number": 2, "title": "Season 2"})); for number in 1..=3 { make(&handle, "film_episode", json!({"title": format!("Invented episode {number}"), "season": first, "series": series, "number": number})); } let all = deck(&handle, json!({"table": "film", "view": "cinemas/all"})); let card = |title: &str| all["cards"].as_array().unwrap().iter().find(|card| card["slots"]["title"] == title).cloned().expect(title); let serial = card("Invented Serial"); assert_eq!(serial["tap"]["card"], "open.whole", "{serial}"); assert_eq!(serial["parts"], json!({"table": "film_season", "where": {"film": series}}), "{serial}"); assert_eq!(serial["related"], json!([ {"id": "film_season", "said": "2 seasons", "count": 2}, {"id": "film_episode", "said": "3 episodes", "count": 3}, ]), "{serial}"); let feature = card("Invented Feature"); assert!(feature.get("parts").is_none() && feature.get("related").is_none(), "a film plays: {feature}"); let seasons = deck(&handle, json!({"table": "film_season", "where": {"film": series}})); assert_eq!(seasons["cards"][0]["parts"], json!({"table": "film_episode", "where": {"season": first}}), "{seasons}"); } // RULE: Rigby's deck is Todos, answered as Cotton's is. #[test] fn rigby_todos() { let (_dir, handle) = phone(Some("rigby")); make(&handle, "todo", json!({"title": "Invented Rigby todo", "due_at": "2026-11-05T12:00:00+05:30"})); let answer = deck(&handle, json!({"table": "todo", "view": "todos/today"})); assert_eq!(titles(&answer), ["Invented Rigby todo"], "{answer}"); } // RULE (boundary review, 5 Nov 2026): the deck pages by cursor, ~50 cards, with no gap and no repeat. #[test] fn pages_follow_on_with_no_gap_or_repeat() { let (_dir, handle) = phone(None); for at in 0..120 { make(&handle, "todo", json!({"title": format!("Invented todo {at:03}")})); } let mut seen: Vec = Vec::new(); let mut cursor = Value::Null; let mut pages = 0; loop { let answer = deck(&handle, json!({"table": "todo", "view": "todos/all", "cursor": cursor})); assert_eq!(answer["count"], 120); let page = ids(&answer); assert!(page.len() <= PAGE); let first = answer["cards"][0]["position"].as_str().unwrap().to_string(); assert_eq!(first, format!("{} / 120", seen.len() + 1), "the position runs on across pages"); seen.extend(page); pages += 1; if answer["next"].is_null() { break } cursor = answer["next"].clone(); } assert_eq!(pages, 3); let mut unique = seen.clone(); unique.sort(); unique.dedup(); assert_eq!((seen.len(), unique.len()), (120, 120), "every card once"); } // RULE (boundary review move 2, 5 Nov 2026): a deck of 2,000 cards is read a page at a time, each page as quick as the first, never the whole deck per page. #[test] fn two_thousand_cards_page_without_a_stall() { let (_dir, handle) = phone(None); for at in 0..2000 { make(&handle, "todo", json!({"title": format!("Invented todo {at:04}")})); } let mut seen = 0; let mut cursor = Value::Null; let mut slowest = std::time::Duration::ZERO; loop { let started = std::time::Instant::now(); let answer = deck(&handle, json!({"table": "todo", "view": "todos/all", "cursor": cursor})); slowest = slowest.max(started.elapsed()); assert_eq!(answer["count"], 2000); seen += ids(&answer).len(); if answer["next"].is_null() { break } cursor = answer["next"].clone(); } assert_eq!(seen, 2000); eprintln!("2,000 cards: the slowest page {} ms", slowest.as_millis()); assert!(slowest < std::time::Duration::from_millis(1500), "a page took {} ms", slowest.as_millis()); } // RULE (owner, 2 Nov 2026): letters narrow the deck to the words that start with them, counted and paged over what they keep; nothing kept says so. #[test] fn ink_narrows_and_says_nothing_starts() { let (_dir, handle) = phone(None); for title in ["Take the bins out", "Go to the shop", "Tidy the desk", "Buy tea"] { make(&handle, "todo", json!({"title": title})); } let narrowed = deck(&handle, json!({"table": "todo", "view": "todos/all", "ink": "t"})); let mut kept = titles(&narrowed); kept.sort(); assert_eq!(kept, ["Buy tea", "Take the bins out", "Tidy the desk"], "never by a stop word"); assert_eq!(narrowed["count"], 3); assert_eq!(narrowed["head"], Value::Null); let nothing = deck(&handle, json!({"table": "todo", "view": "todos/all", "ink": "zq"})); assert_eq!(nothing["count"], 0); assert_eq!(nothing["empty"]["title"], "Nothing starts with \u{201c}zq\u{201d}"); } // RULE: an empty deck says its view's or its table's words, and a record outside the view stands as a visitor. #[test] fn an_empty_deck_and_a_visitor() { let (_dir, handle) = phone(None); let answer = deck(&handle, json!({"table": "todo", "view": "todos/today"})); assert_eq!(answer["count"], 0); assert!(answer["empty"]["title"].as_str().is_some_and(|title| !title.is_empty()), "{answer}"); let later = make(&handle, "todo", json!({"title": "Invented later", "due_at": "2026-12-20T12:00:00+05:30"})); let visited = deck(&handle, json!({"table": "todo", "view": "todos/today", "visitor": later})); assert_eq!(visited["visitor"]["id"], json!(later)); assert_eq!(visited["visitor"]["held"], false); assert!(visited["empty"].is_null(), "a visitor stands on the deck"); } fn table(handle: &CottonHandle, id: &str) -> TableDefinition { definitions(&handle.client()).unwrap().into_iter().find(|table| table.id == id).unwrap_or_else(|| panic!("no table {id}")) } // RULE (coordinator, 4 Nov 2026): a table's "+" does what its create names wherever it stands — doors, an act, a route, a phone method called at once — and only a create naming none makes a blank record. #[test] fn plus_does_what_the_create_names() { let (_dir, handle) = phone(None); let book = plus_of(&table(&handle, "book")); assert_eq!(book["does"], "doors"); let doors: Vec<(&str, &str)> = book["doors"].as_array().unwrap().iter() .map(|door| (door["id"].as_str().unwrap(), door["picture"].as_str().unwrap())).collect(); assert_eq!(doors, [("find", "act-catalogue"), ("file", "act-parcel"), ("folder", "act-parcel"), ("goodreads", "act-stack")], "Find a book, Add a file, Add a folder, Bring Goodreads in"); assert_eq!(book["doors"][0]["accepts"]["words"]["act"], "find_book"); assert_eq!(book["doors"][0]["accepts"]["words"]["lands"], "book"); assert!(book["doors"][1]["accepts"]["files"]["types"].as_array().is_some_and(|types| !types.is_empty())); // The picker's media types ride beside the uniform types: an Android shell maps nothing. assert_eq!(book["doors"][1]["accepts"]["files"]["mimes"], json!(["application/epub+zip", "application/pdf"])); assert_eq!(book["doors"][2]["accepts"]["files"]["mimes"], json!(["inode/directory"]), "Add a folder picks a tree"); assert_eq!(book["doors"][3]["accepts"]["files"]["mimes"], json!(["text/csv", "text/comma-separated-values"])); // Music's song (Add singles, Add a crate) was the second example until TABLE DROP 1 retired it. assert_eq!(plus_of(&table(&handle, "person")), json!({"does": "route", "label": table(&handle, "person").create.unwrap().label, "doors": [], "route": "/people/import", "or": "blank"})); assert_eq!(plus_of(&table(&handle, "todo"))["does"], "blank"); // Cotton Story's New scene calls story.scene.new at once (nothing asked); its answer opens the writer. let mut scene = serde_json::to_value(table(&handle, "todo")).unwrap(); scene["create"] = json!({"label": "New scene", "method": "story.scene.new"}); let scene: TableDefinition = serde_json::from_value(scene).unwrap(); assert_eq!(plus_of(&scene), json!({"does": "call", "label": "New scene", "doors": [], "method": "story.scene.new"})); } // RULE: a card's tap opens, in this order, a scene whose table writes it (`story.write` on `$id`) in the writer, a book holding its file in the reader (one without opens at rest), a whole into its parts, a group card into its list, a thread into its chat, a thing the viewer shows into the viewer, a card of its own words into its reading page; any other opens at rest. #[test] fn a_cards_tap_opens_as_its_definition_says() { let (_dir, handle) = phone(None); let none = Map::new(); let words = |pairs: Value| pairs.as_object().cloned().unwrap(); let book = table(&handle, "book"); assert_eq!(opening(&book, "book.hardback", &words(json!({"file": "sha256-invented"}))), "reader", "a book with its file reads before anything else it opens"); assert_eq!(opening(&book, "book.hardback", &none), "opened", "a book held by its details alone opens at rest, where Add file is"); assert_eq!(opening(&book, "book.hardback", &words(json!({"file": null}))), "opened"); let film = table(&handle, "film"); assert_eq!(opening(&film, "film.poster", &words(json!({"kind": "series"}))), "whole", "a series opens into its seasons"); assert_eq!(opening(&film, "film.poster", &words(json!({"kind": "film"}))), "viewer", "a film plays"); assert_eq!(opening(&table(&handle, "note"), "note.page", &words(json!({"body": "Some invented words"}))), "reading"); assert_eq!(opening(&table(&handle, "note"), "note.page", &none), "opened", "nothing to read opens at rest"); assert_eq!(opening(&table(&handle, "todo"), "todo.card", &none), "opened"); assert_eq!(opening(&table(&handle, "person"), "group", &none), "group"); // Cotton Story's scene: its Write command opens the writer before anything else. let mut scene = serde_json::to_value(table(&handle, "note")).unwrap(); scene["commands"] = json!([{"id": "write", "label": "Write", "kind": "update", "method": "story.write", "bindings": {"id": "$id"}}]); let scene: TableDefinition = serde_json::from_value(scene).unwrap(); assert_eq!(opening(&scene, "scene.card", &words(json!({"body": "Some invented words"}))), "writer", "a scene opens in the writer"); } // RULE: a card whose tap opens a whole says the deck of its parts (a series its seasons, a season its episodes), so a shell asks it without reading the card's `opens`; a card opening anything else says none. #[test] fn a_whole_says_the_deck_of_its_parts() { let (_dir, handle) = phone(None); let whole = json!({"card": "open.whole"}); assert_eq!(parts_deck(&table(&handle, "film"), &whole, "film-1"), json!({"table": "film_season", "where": {"film": "film-1"}})); assert_eq!(parts_deck(&table(&handle, "film_season"), &whole, "season-1"), json!({"table": "film_episode", "where": {"season": "season-1"}})); assert_eq!(parts_deck(&table(&handle, "film"), &json!({"card": "open.viewer"}), "film-1"), Value::Null, "a film plays: no parts"); assert_eq!(parts_deck(&table(&handle, "film_episode"), &whole, "episode-1"), Value::Null, "an episode is no whole"); } // RULE: a check writes what the slip's toggle says: a choice that is off goes to its first toggle_on value, one that is on back to its first choice. #[test] fn a_check_writes_the_toggle() { let (_dir, handle) = phone(None); let todo = table(&handle, "todo"); let column = todo.slip.toggle.clone().expect("a todo's slip toggles"); let open = toggled(&todo, &json!({column.clone(): "open"}).as_object().cloned().unwrap()); let next = open[&column].as_str().expect("a write").to_string(); assert_ne!(next, "open"); let back = toggled(&todo, &json!({column.clone(): next}).as_object().cloned().unwrap()); assert_eq!(back[&column], "open"); assert_eq!(toggled(&table(&handle, "person"), &Map::new()), Value::Null, "a person has no check"); } /// The phone's zone set down as the workspace's, as the app's first pass does /// (`RecurrenceMaterializer`): a whole-day event is a day in it. fn zoned(handle: &CottonHandle) { crate::methods::dispatch(handle, "write", &json!({"tool": "materialize_todo_recurrences", "args": {"timezone": "Asia/Kolkata"}})) .unwrap_or_else(|error| panic!("the zone is set down: {error:?}")); } fn event(handle: &CottonHandle, id: &str) -> Value { crate::methods::dispatch(handle, "records.get", &json!({"table": "event", "id": id})).unwrap_or_else(|error| panic!("the event reads: {error:?}")) } // RULE (walk 362, step 04): Plus → title makes a whole day; a time set on its card (When → a time) makes it timed at that hour, never swallowed by the day's window. #[test] fn a_time_set_on_a_whole_day_event_makes_it_timed() { let (_dir, handle) = phone(None); zoned(&handle); let made = crate::methods::dispatch(&handle, "records.create", &json!({"table": "event", "data": {"title": "Invented dentist", "starts_at": "2026-11-06"}})) .unwrap_or_else(|error| panic!("the event is made: {error:?}")); let id = made["record"]["id"].as_str().unwrap_or_else(|| panic!("a made id: {made}")).to_string(); assert_eq!(event(&handle, &id)["data"]["all_day"], true, "Plus → title is a whole day"); let when = |request: Value| { let mut request = request; request["table"] = json!("event"); request["id"] = json!(id); request["timezone"] = json!("Asia/Kolkata"); crate::methods::dispatch(&handle, "cards.when", &request).unwrap_or_else(|error| panic!("the when is written: {error:?}")); event(&handle, &id)["data"].clone() }; let moved = when(json!({"date": "2026-11-07"})); assert_eq!((moved["starts_at"].as_str(), moved["all_day"].as_bool()), (Some("2026-11-07"), Some(true)), "a new day keeps it whole: {moved}"); let timed = when(json!({"time": "09:00"})); assert_eq!(timed["all_day"], false, "a time makes it timed: {timed}"); assert_eq!(timed["starts_at"], "2026-11-07T03:30:00.000Z", "the start carries 9 am in Kolkata: {timed}"); assert!(timed["ends_at"].is_null(), "no end of its day is kept: {timed}"); let said = timed["@card"]["fields"]["date"].as_str().unwrap_or_default().to_string(); assert!(said.contains("9:00") || said.contains("9 am") || said.contains("9:00 am"), "the card says the time: {}", timed["@card"]); let again = when(json!({"time": "18:00"})); assert_eq!((again["starts_at"].as_str(), again["all_day"].as_bool()), (Some("2026-11-07T12:30:00.000Z"), Some(false)), "{again}"); } /// A list of `table` made as the phone makes one (`groups.create`), its id. fn list(handle: &CottonHandle, table: &str, name: &str, members: &[&str]) -> String { let made = crate::methods::dispatch(handle, "groups.create", &json!({"table": table, "name": name, "records": members})) .unwrap_or_else(|error| panic!("{name} is made: {error:?}")); made["group"]["id"].as_str().unwrap_or_else(|| panic!("a made list: {made}")).to_string() } /// The name the fan gives the list `group` on `tool`'s views tier: the /// view a list's tile opens, `/group:`. fn fan_list(handle: &CottonHandle, tool: &str, group: &str) -> String { let fan = crate::methods::dispatch(handle, "shell.fan", &json!({"tool": tool, "timezone": "Asia/Kolkata", "today": TODAY})).expect("the fan"); let tile = fan["tiles"].as_array().unwrap().iter().find(|tile| tile["key"] == tool).unwrap_or_else(|| panic!("no {tool} tile: {fan}")); let id = format!("group:{group}"); assert!(tile["views"].as_array().unwrap().iter().any(|view| view["id"] == id.as_str()), "{tool}'s tier holds the list: {tile}"); format!("{}/{id}", tile["key"].as_str().unwrap()) } // RULE (Cotton Cinemas 1.0 (2), 6 Nov 2026: a list's tile counted its films but its deck said "Films could not be read" — the shell named it `film/group:`, and the core refused "No tool film"): in every app with lists — Books' shelves, Music's playlists, Cinemas' lists — the list the fan's views tier answers opens as a deck of its members by the name the tier gives it, `/group:`; a name made of the table's id is no tool's and is refused, never read as a list. #[test] fn a_lists_deck_opens_in_every_app_with_lists() { for (app, table, tool, member, other) in [ ("books", "book", "books", json!({"title": "Invented Dune", "author": "A. Writer"}), json!({"title": "Invented Emma", "author": "B. Writer"})), ("music", "song", "music", json!({"title": "Invented single", "artist_name": "Invented band"}), json!({"title": "Invented b-side", "artist_name": "Invented band"})), ("cinemas", "film", "cinemas", json!({"title": "Invented film", "kind": "film"}), json!({"title": "Invented series", "kind": "series"})), ] { let (_dir, handle) = phone(Some(app)); let held = make(&handle, table, member); make(&handle, table, other); let group = list(&handle, table, "Invented list", &[&held]); let name = fan_list(&handle, tool, &group); assert_eq!(name, format!("{tool}/group:{group}"), "{app}: the list is its tool's"); let listed = deck(&handle, json!({"table": table, "view": name})); // Music's list leads with its own cassette (`a_music_lists_deck_opens_on_its_cassette`). let members: Vec = ids(&listed).into_iter().filter(|id| *id != group).collect(); assert_eq!(members, std::slice::from_ref(&held), "{app}: the list's deck is its member: {listed}"); assert_eq!(listed["count"], if app == "music" { 2 } else { 1 }, "{app}: {listed}"); let by_table = crate::methods::dispatch(&handle, "shell.deck", &json!({"table": table, "view": format!("{table}/group:{group}"), "timezone": "Asia/Kolkata", "today": TODAY})); assert!(by_table.is_err(), "{app}: `{table}` is no tool, and a list named by it is refused: {by_table:?}"); } } /// Three songs on an invented album with a cover, made as their files make them. fn three_songs(handle: &CottonHandle) -> [String; 3] { let album = make(handle, "music_album", json!({"title": "Invented Coastline", "artist_name": "Invented Ferries", "cover": "photo:invented-cover"})); let song = |title: &str, seconds: f64, file: &str| make(handle, "song", json!({"title": title, "artist_name": "Invented Ferries", "album": album, "duration": seconds, "file": file})); [song("Harbour Lights", 221.0, "media:harbour"), song("Slow Train", 302.0, "media:slow"), song("Blue Hour", 178.0, "media:blue")] } // RULE (owner, 7 Nov 2026: the list is a cassette): Music's list deck opens on the list's own card — `list.cassette`, the tool's `lists` face — first and counted, its songs in the list's order with their lengths, its count and length said, its picture its first song's cover while it has none of its own, a tap playing the list; its songs follow as the deck's next cards in the song table's own face. Ink narrows the songs alone. #[test] fn a_music_lists_deck_opens_on_its_cassette_then_its_songs() { let (_dir, handle) = phone(Some("music")); let [harbour, slow, blue] = three_songs(&handle); let group = list(&handle, "song", "Night Drives", &[&slow, &harbour]); let name = fan_list(&handle, "music", &group); let answer = deck(&handle, json!({"table": "song", "view": name})); assert_eq!(ids(&answer), [group.clone(), slow.clone(), harbour.clone()], "{answer}"); assert_eq!(answer["count"], 3); let cassette = &answer["cards"][0]; assert_eq!((cassette["face"].as_str(), cassette["list"].as_str()), (Some("list.cassette"), Some(group.as_str())), "{cassette}"); assert_eq!(cassette["record"]["table"], "record_group"); assert_eq!(cassette["slots"]["title"], "Night Drives"); assert_eq!(cassette["slots"]["count"], "2 songs"); assert_eq!(cassette["slots"]["length"], "8:43"); assert_eq!(cassette["slots"]["photo"], "photo:invented-cover", "no picture of its own: its first song's cover"); let songs = cassette["slots"]["songs"].as_array().unwrap(); assert_eq!(songs.iter().map(|song| song["record"].as_str().unwrap()).collect::>(), [slow.as_str(), harbour.as_str()]); assert_eq!((songs[0]["title"].as_str(), songs[0]["duration"].as_f64(), songs[0]["play"].as_str()), (Some("Slow Train"), Some(302.0), Some("media:slow"))); assert_eq!(cassette["tap"]["card"], "open.play"); assert_eq!(cassette["acts"], json!([])); assert!(answer["acts"]["open.play"]["label"].is_string(), "{}", answer["acts"]); assert_eq!(cassette["position"], "1 / 3"); assert_eq!(answer["cards"][1]["face"], "song.single"); assert_eq!(answer["cards"][1]["position"], "2 / 3"); assert!(!ids(&answer).contains(&blue)); // The hand cycles the songs' faces, never the cassette's. assert_eq!(answer["hand"], json!(["song.single", "song.tray", "song.cassette"]), "{}", answer["hand"]); // The list's own picture stands in place of its first song's cover. let file = handle.client().with_file(|file| Ok(file.identity.id().to_string())).unwrap(); let own = format!("{file}/photos/{}.jpg", "e".repeat(64)); crate::methods::dispatch(&handle, "groups.update", &json!({"id": group, "picture": own})).expect("a picture"); let pictured = deck(&handle, json!({"table": "song", "view": name})); assert_eq!(pictured["cards"][0]["slots"]["photo"], json!(own)); // Ink narrows the members alone. let inked = deck(&handle, json!({"table": "song", "view": name, "ink": "sl"})); assert_eq!(ids(&inked), std::slice::from_ref(&slow), "{inked}"); // Paged, the cursor counts the members: the cassette leads the first page alone. let first = deck(&handle, json!({"table": "song", "view": name, "limit": 1})); assert_eq!(ids(&first), [group.clone(), slow.clone()]); let second = deck(&handle, json!({"table": "song", "view": name, "cursor": first["next"], "limit": 1})); assert_eq!(ids(&second), std::slice::from_ref(&harbour)); assert_eq!(second["cards"][0]["position"], "3 / 3"); // An empty list is a blank tape. let empty = crate::methods::dispatch(&handle, "groups.create", &json!({"table": "song", "name": "For the new flat"})).expect("an empty list")["group"]["id"] .as_str().unwrap().to_string(); let blank = deck(&handle, json!({"table": "song", "view": format!("music/group:{empty}")})); assert_eq!(ids(&blank), std::slice::from_ref(&empty)); assert_eq!((blank["cards"][0]["slots"]["count"].as_str(), blank["cards"][0]["slots"]["songs"].as_array().map(Vec::len)), (Some("0 songs"), Some(0))); assert!(blank["empty"].is_null()); } // RULE (owner, 7 Nov 2026): a list is one table every app shares, so its look is its tool's: Books' and Cinemas' lists keep their plain deck of members, no list card before them. #[test] fn books_and_cinemas_lists_lead_with_no_card_of_their_own() { for (app, table, tool, member) in [ ("books", "book", "books", json!({"title": "Invented Dune", "author": "A. Writer"})), ("cinemas", "film", "cinemas", json!({"title": "Invented film", "kind": "film"})), ] { let (_dir, handle) = phone(Some(app)); let held = make(&handle, table, member); let group = list(&handle, table, "Invented list", &[&held]); let answer = deck(&handle, json!({"table": table, "view": format!("{tool}/group:{group}")})); assert_eq!(ids(&answer), [held], "{app}: {answer}"); assert!(answer["cards"][0].get("list").is_none(), "{app}"); } } /// Rows cloned from one made row in SQL, `count` of them, `set` giving an /// expression over `i` (0..count) and `day` (two years back from TODAY). fn cloned(handle: &CottonHandle, table: &str, template: &str, count: usize, set: &[(&str, &str)]) { handle.client().write_rows("bench.clone", &mut |ctx| { let db = ctx.db(); let columns: Vec = db.all(&format!("PRAGMA table_info({table})"), &[]).map_err(|e| e.to_string())? .iter().filter_map(|row| row.text("name").map(str::to_string)).collect(); let select: Vec = columns.iter().map(|column| match set.iter().find(|(key, _)| key == column) { Some((_, expression)) => expression.to_string(), None => format!("t.{column}"), }).collect(); db.exec(&format!( "WITH RECURSIVE n(i, day) AS (SELECT 0, '{TODAY}' UNION ALL SELECT i + 1, date('{TODAY}', '-' || ((i + 1) % 700) || ' days') FROM n WHERE i + 1 < {count}) \ INSERT INTO {table} ({}) SELECT {} FROM n, {table} t WHERE t.id = '{template}'", columns.join(", "), select.join(", "))).map_err(|e| e.to_string())?; Ok(Value::Null) }).unwrap_or_else(|error| panic!("{table} cloned: {error}")); } /// A letter at a time over a 50k Money book, each timed. Run release: /// `cargo test --release -p cotton-ffi --lib shell_deck::tests::ink_over_fifty_thousand -- --ignored --nocapture`. #[test] #[ignore = "a release measure over 50k synthetic rows"] fn ink_over_fifty_thousand() { let (_dir, handle) = phone(Some("money")); let money = make(&handle, "transaction", json!({"description": "Template spend", "occurred_on": TODAY, "amount_minor": 100, "currency": "INR", "direction": "out", "status": "actual", "moves_money": false})); let letters = |size: &str| { for letters in ["r", "re", "ren", "x", "q"] { let began = std::time::Instant::now(); let answer = deck(&handle, json!({"table": "transaction", "view": "money/past", "ink": letters})); eprintln!("{size}: ink {letters:?}: {} results, {} on the page, {:?}", answer["count"], answer["cards"].as_array().map_or(0, Vec::len), began.elapsed()); } }; // The dev seed's size first: some sixty transactions. cloned(&handle, "cotton_money_transactions", &money, 60, &[ ("id", "printf('seed-money-%03d', i)"), ("occurred_on", "n.day"), ("description", "CASE i % 4 WHEN 0 THEN printf('Invented grocer %03d', i) WHEN 1 THEN printf('Invented rent %03d', i) WHEN 2 THEN printf('Invented fuel %03d', i) ELSE printf('Invented taxi %03d', i) END"), ("amount_minor", "100 + i"), ("status", "CASE i % 10 WHEN 0 THEN 'expected' ELSE 'actual' END"), ]); letters("dev-seed size"); cloned(&handle, "cotton_money_transactions", &money, 50_000, &[ ("id", "printf('bench-money-%06d', i)"), ("occurred_on", "n.day"), ("description", "CASE i % 4 WHEN 0 THEN printf('Invented grocer %06d', i) WHEN 1 THEN printf('Invented rent %06d', i) WHEN 2 THEN printf('Invented fuel %06d', i) ELSE printf('Invented taxi %06d', i) END"), ("amount_minor", "100 + i"), ("status", "CASE i % 10 WHEN 0 THEN 'expected' ELSE 'actual' END"), ]); for account in ["Invented Savings", "Invented Card", "Invented Rent Wallet"] { crate::methods::dispatch(&handle, "write", &json!({"tool": "create_money_account", "args": {"name": account, "kind": "bank", "currency": "INR"}})).expect("an account"); } letters("50k"); } /// Each result as `(table, words)`: a record's table and title (a /// highlight's passage), a fan view's `view` and its label. fn results(answer: &Value) -> Vec<(String, String)> { answer["cards"].as_array().unwrap().iter().map(|card| { let table = if card["kind"] == "view" { "view".to_string() } else { card["table"].as_str().unwrap_or_default().to_string() }; let slots = &card["slots"]; (table, slots["title"].as_str().or(slots["quote"].as_str()).unwrap_or_default().to_string()) }).collect() } fn said(pairs: &[(&str, &str)]) -> Vec<(String, String)> { pairs.iter().map(|(table, title)| (table.to_string(), title.to_string())).collect() } // RULE (owner, 11 Nov 2026: "when someone draws the alphabets, we do a universal search … first list books, then highlights"): letters written in an app of one tool keep the view in view's records first, then the rest of its table, then the kit's other tables in the tool's order, then the fan's views by name; each counted, said in place and drawn as its own table's card. #[test] fn ink_searches_the_whole_kit_in_order() { let (_dir, handle) = phone(Some("books")); let rebecca = make(&handle, "book", json!({"title": "Rebecca", "status": "reading"})); make(&handle, "book", json!({"title": "Ulysses", "status": "reading"})); make(&handle, "book", json!({"title": "Red Harvest", "status": "finished"})); make(&handle, "highlight", json!({"book": rebecca, "text": "Last night I dreamt I went to Manderley again, the road ahead"})); make(&handle, "highlight", json!({"book": rebecca, "text": "Rest is silence"})); let answer = deck(&handle, json!({"table": "book", "view": "books/reading", "ink": "re"})); // a. the view in view; b. the rest of its table; c. its highlights; d. the fan's Reading and Want to read. assert_eq!(results(&answer), said(&[("book", "Rebecca"), ("book", "Red Harvest"), ("highlight", "Rest is silence"), ("view", "Reading"), ("view", "Want to read")]), "{answer}"); assert_eq!(answer["count"], 5); assert_eq!(answer["cards"][0]["position"], "1 / 5"); assert_eq!(answer["cards"][4]["position"], "5 / 5"); assert_eq!(answer["head"], Value::Null); // Each record is its own table's card: its face, its tap, its acts, its labels. let highlight = &answer["cards"][2]; assert_eq!(highlight["face"], "highlight.passage", "{highlight}"); assert!(highlight["tap"]["card"].as_str().is_some_and(|tap| tap.starts_with("open.")), "{highlight}"); for act in highlight["acts"].as_array().unwrap() { assert!(answer["acts"][act.as_str().unwrap()]["label"].is_string(), "{act}"); } let opened = crate::methods::dispatch(&handle, "shell.opened", &json!({"table": "highlight", "id": highlight["id"], "face": highlight["face"]})).unwrap(); let held: Vec<&str> = opened["acts"].as_array().unwrap().iter().map(|act| act["id"].as_str().unwrap()).collect(); assert_eq!(highlight["acts"].as_array().unwrap().iter().map(|id| id.as_str().unwrap()).collect::>(), held, "a highlight's acts are its own deck's"); assert!(answer["labels_of"]["highlight"]["by_column"]["text"].is_string(), "{}", answer["labels_of"]); assert_eq!(answer["cards"][0]["face"], "book.hardback"); // The view's tile opens its view, drawn by the fan's own tile. let tile = &answer["cards"][3]; assert_eq!((tile["kind"].as_str(), tile["tool"].as_str(), tile["view"]["id"].as_str()), (Some("view"), Some("books"), Some("reading")), "{tile}"); assert_eq!(tile["tap"]["card"], "open.view"); assert!(answer["acts"]["open.view"]["label"].is_string()); assert_eq!(tile["acts"], json!([])); // Paged over everything kept. let first = deck(&handle, json!({"table": "book", "view": "books/reading", "ink": "re", "limit": 2})); assert_eq!(results(&first), said(&[("book", "Rebecca"), ("book", "Red Harvest")])); let second = deck(&handle, json!({"table": "book", "view": "books/reading", "ink": "re", "limit": 2, "cursor": first["next"]})); assert_eq!(results(&second), said(&[("highlight", "Rest is silence"), ("view", "Reading")])); let third = deck(&handle, json!({"table": "book", "view": "books/reading", "ink": "re", "limit": 2, "cursor": second["next"]})); assert_eq!(results(&third), said(&[("view", "Want to read")])); assert_eq!(third["next"], Value::Null); } // RULE (owner, 11 Nov 2026): what the view in view holds stands first, exactly as the letters narrowed it alone; a record on screen is never pushed down by another table's. #[test] fn ink_keeps_the_view_in_view_first() { let (_dir, handle) = phone(Some("books")); make(&handle, "book", json!({"title": "Finished Business", "status": "finished"})); let fable = make(&handle, "book", json!({"title": "Fables", "status": "reading"})); make(&handle, "highlight", json!({"book": fable, "text": "Far from the madding crowd"})); let finished = deck(&handle, json!({"table": "book", "view": "books/finished", "ink": "f"})); assert_eq!(results(&finished), said(&[("book", "Finished Business"), ("book", "Fables"), ("highlight", "Far from the madding crowd"), ("view", "Finished")]), "{finished}"); // From Highlights, the highlight leads and the books follow it, in their table's order. let highlights = deck(&handle, json!({"table": "highlight", "view": "books/highlights", "ink": "f"})); assert_eq!(results(&highlights), said(&[("highlight", "Far from the madding crowd"), ("book", "Fables"), ("book", "Finished Business"), ("view", "Finished")]), "{highlights}"); } // RULE (owner, 11 Nov 2026): letters nothing anywhere starts with leave the deck empty, the core saying so; with the letters cleared the deck is its view again. #[test] fn ink_nothing_anywhere_and_cleared() { let (_dir, handle) = phone(Some("books")); make(&handle, "book", json!({"title": "Rebecca", "status": "reading"})); make(&handle, "book", json!({"title": "Ulysses", "status": "finished"})); let nothing = deck(&handle, json!({"table": "book", "view": "books/reading", "ink": "zq"})); assert_eq!(nothing["count"], 0); assert_eq!(nothing["cards"], json!([])); assert_eq!(nothing["empty"]["title"], "Nothing starts with \u{201c}zq\u{201d}"); let cleared = deck(&handle, json!({"table": "book", "view": "books/reading"})); assert_eq!(results(&cleared), said(&[("", "Rebecca")]), "the view's own deck: {cleared}"); assert!(cleared.get("labels_of").is_none()); } // RULE (owner, 11 Nov 2026: "we'll figure out a priority order"): the order is the kit's: a tool's tables as it lists them, else its `search` order (Music's albums before its songs was the example until TABLE DROP 1 retired Music.) #[test] fn ink_searches_in_the_kits_order() { let (_dir, todos) = phone(Some("days")); make(&todos, "todo", json!({"title": "Tidy the desk", "due_at": "2026-11-05T12:00:00+05:30"})); make(&todos, "todo", json!({"title": "Taxes", "due_at": "2026-12-20T12:00:00+05:30"})); let today = deck(&todos, json!({"table": "todo", "view": "todos/today", "ink": "t"})); // Days, which keeps the to-dos now: its views of them go by the tool's name, after the records. assert_eq!(results(&today), said(&[("todo", "Tidy the desk"), ("todo", "Taxes"), ("view", "Todos"), ("view", "Todos Upcoming"), ("view", "Todos All")]), "{today}"); } // RULE (12 Nov 2026: a platform shell draws a fetch row's state, it never reads one): a download deals as the plain card holding its title, its state said in the kit's words (Waiting for the Mac, Fetching, Failed, Done), the reason a failed one gave, and its fetched share, records landed and size under their labels, each said by the core; the views split the queue by state. #[test] fn a_download_deals_its_state_in_the_kits_words() { let (_dir, handle) = phone(Some("downloads")); make(&handle, "fetch", json!({"source": "magnet:?xt=urn:btih:synthetic", "title": "Invented waiting", "state": "queued", "added_on": "2026-11-12T08:00:00Z"})); make(&handle, "fetch", json!({"source": "https://invented.example/a.epub", "title": "Invented fetching", "state": "fetching", "progress": 42, "of_bytes": 2_000_000, "added_on": "2026-11-12T09:00:00Z"})); make(&handle, "fetch", json!({"source": "https://invented.example/b", "title": "Invented failed", "state": "failed", "error": "The invented site refused.", "added_on": "2026-11-12T10:00:00Z"})); make(&handle, "fetch", json!({"source": "https://invented.example/c.mp3", "title": "Invented done", "state": "done", "progress": 100, "landed_count": 3, "added_on": "2026-11-12T11:00:00Z"})); let all = deck(&handle, json!({"table": "fetch", "view": "downloads/all"})); assert_eq!(titles(&all), ["Invented done", "Invented failed", "Invented fetching", "Invented waiting"], "{all}"); let card = |title: &str| all["cards"].as_array().unwrap().iter().find(|card| card["slots"]["title"] == title).unwrap_or_else(|| panic!("{title}: {all}")).clone(); for (title, state) in [("Invented waiting", "Waiting for the Mac"), ("Invented fetching", "Fetching"), ("Invented failed", "Failed"), ("Invented done", "Done")] { let card = card(title); assert_eq!(card["face"], "plain", "{card}"); assert_eq!(card["slots"]["subtitle"], state, "{card}"); } assert_eq!(card("Invented failed")["slots"]["body"], "The invented site refused."); let said = |title: &str| -> Vec<(String, String)> { card(title)["slots"]["facts"].as_array().cloned().unwrap_or_default().iter() .map(|fact| (fact["label"].as_str().unwrap_or_default().to_string(), fact["said"].as_str().unwrap_or_default().to_string())).collect() }; let fetching = said("Invented fetching"); assert_eq!(fetching.first().map(|(label, said)| (label.as_str(), said.as_str())), Some(("Fetched", "42%")), "{fetching:?}"); assert!(fetching.iter().any(|(label, said)| label == "Size" && !said.is_empty() && said != "2000000"), "the size said as bytes: {fetching:?}"); assert!(said("Invented done").contains(&("Landed".to_string(), "3 records".to_string())), "{:?}", said("Invented done")); let active = deck(&handle, json!({"table": "fetch", "view": "downloads/active"})); assert_eq!(titles(&active), ["Invented fetching", "Invented waiting"], "{active}"); let failed = deck(&handle, json!({"table": "fetch", "view": "downloads/failed"})); assert_eq!(titles(&failed), ["Invented failed"], "{failed}"); }