use serde_json::{json, Value};usesuper::{impersonal, size_said, space_words, FREEABLE};usecrate::handle::CottonHandle;fn days_phone() -> (tempfile::TempDir, CottonHandle) { phone(include_str!("../../../../apps/cotton/App/Flavours/days/flavour.json"))}fn phone(manifest: &str) -> (tempfile::TempDir, CottonHandle) {let dir = tempfile::tempdir().expect("a temp container");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(serde_json::from_str(manifest).expect("an app's manifest")), }) .expect("an open core");crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started"); (dir, handle)}fn settings(handle: &CottonHandle) -> Value {crate::methods::dispatch(handle, "shell.settings", &json!({"commit": "abc1234"})).expect("shell.settings")}/// RULE (owner, 21 Nov 2026): bytes are said in megabytes a person reads, gigabytes past a thousand, never bytes.#[test]fn sizes_are_said_in_megabytes() { assert_eq!(size_said(0), "0 MB"); assert_eq!(size_said(40_000), "less than 0.1 MB"); assert_eq!(size_said(400_000), "0.4 MB"); assert_eq!(size_said(12_400_000), "12 MB"); assert_eq!(size_said(157_000_000), "157 MB"); assert_eq!(size_said(1_340_000_000), "1.3 GB"); assert_eq!(size_said(23_000_000_000), "23 GB");}/// RULE (owner, 21 Nov 2026): a report a person shares holds no personal content: whatever is quoted, every long number, an email address and a record id are taken out of an error before it is written.#[test]fn an_error_in_a_report_says_nothing_personal() { assert_eq!(impersonal("could not send “Lunch with Asha” to +44 7700 900123"), "could not send “…” to +…"); assert_eq!(impersonal("refused 'Invented title' at 12:30"), "refused '…' at 12:30"); assert_eq!(impersonal("mail from someone@example.com bounced"), "mail from … bounced"); assert_eq!(impersonal("row 0f9a1c2b3d4e5f60718293a4 failed"), "row … failed"); assert_eq!(impersonal("Bearer abc.def.ghi expired"), cotton_core::device::reported_state::redact_line("Bearer abc.def.ghi expired"));}/// RULE (owner, 21 Nov 2026): Settings has one shape in every app — Account, Storage, Help and feedback, About — and Storage says what this app keeps here in a person's four parts, in megabytes, with Free up space saying how much it frees before it asks.#[test]fn settings_answer_one_shape_with_storage_in_a_persons_words() {let (_dir, handle) = days_phone();crate::methods::dispatch(&handle, "records.create", &json!({"table": "todo", "data": {"title": "An invented errand"}})).expect("a todo");let answer = settings(&handle); assert_eq!(answer["sections"], json!(["account", "storage", "help", "about"]), "{answer}"); assert_eq!(answer["account"]["key"], "account");let storage = &answer["storage"]; assert_eq!(storage["title"], "Storage");let parts: Vec<&str> = storage["parts"].as_array().expect("parts").iter().filter_map(|part| part["label"].as_str()).collect(); assert_eq!(parts, ["Your data", "Photos and files", "Other"], "Days keeps no downloads, so it shows no Downloads part");let data = &storage["parts"][0]; assert!(data["bytes"].as_u64().is_some_and(|bytes| bytes > 0), "the database file is counted: {data}"); assert!(data["said"].as_str().is_some_and(|said| said.ends_with(" MB")), "{data}");let total: u64 = storage["parts"].as_array().expect("parts").iter().map(|part| part["bytes"].as_u64().unwrap_or(0)).sum(); assert_eq!(storage["total_bytes"], json!(total)); assert!(storage["line"].as_str().is_some_and(|line| line.contains("keeps") && line.ends_with("on this phone.")), "{storage}");// Nothing is in the account yet, so nothing can be freed, and it says so rather than asking. assert_eq!(storage["free_up"]["bytes"], 0); assert!(storage["free_up"].get("ask").is_none(), "{storage}"); assert_eq!(answer["help"]["share"]["label"], "Share a report"); assert_eq!(answer["about"]["title"], "About"); assert!(answer["about"]["facts"].as_array().is_some_and(|facts| facts.iter().any(|fact| fact["id"] == "database")), "internal facts live under About: {answer}");}/// RULE (owner's Words walk, 22 Nov 2026): Downloads ("Films, books and songs kept for offline") is a part only in an app that keeps them; Words, Days and Story never show it, in Settings or in a shared report.#[test]fn downloads_show_only_in_an_app_that_keeps_them() {let labels = |manifest: &str| {let (_dir, handle) = phone(manifest);let answer = settings(&handle);let parts: Vec<String> = answer["storage"]["parts"].as_array().expect("parts").iter().filter_map(|part| part["label"].as_str().map(str::to_string)).collect();let report = crate::methods::dispatch(&handle, "shell.report", &json!({"commit": "abc1234"})).expect("shell.report"); (parts, report.to_string()) };for manifest in [ include_str!("../../../../apps/cotton/App/Flavours/notes/flavour.json"), include_str!("../../../../apps/cotton/App/Flavours/story/flavour.json"), ] {let (parts, report) = labels(manifest); assert_eq!(parts, ["Your data", "Photos and files", "Other"]); assert!(!report.contains("Downloads"), "{report}"); }let (parts, _) = labels(include_str!("../../../../apps/cotton/App/Flavours/books/flavour.json")); assert_eq!(parts, ["Your data", "Photos and files", "Downloads", "Other"]);}/// RULE (owner, 23 Nov 2026: "Comms' settings are well organised now; the other three are not"): Settings' top level/// is Comms' You's rows in Comms' order and groups, each saying how it stands. Signed out, Words, Days and Story show/// Sync, Storage, Help and feedback and About (Days, which alerts, Notifications too); signed in, Your Claude and/// Privacy (Your people) join them. Nothing is said raw, and the card says what signing in does.#[test]fn settings_rows_are_comms_rows_in_comms_order() {usesuper::row_ids;let ids = |kit: Option<&str>, signed_in: bool| row_ids(kit, signed_in).into_iter().map(|(id, _)| id).collect::<Vec<_>>(); assert_eq!(ids(Some("notes"), true), ["sync", "claude", "privacy", "storage", "help", "about"]); assert_eq!(ids(Some("days"), true), ["sync", "claude", "privacy", "notifications", "storage", "help", "about"]); assert_eq!(ids(Some("story"), false), ["sync", "storage", "help", "about"]);// Comms' own order, groups and all (chat.you): Sync and Your Claude, then Privacy, Notifications and Storage, then help.let comms = row_ids(Some("messages"), true); assert_eq!(comms.iter().map(|(id, _)| *id).collect::<Vec<_>>(), ["sync", "claude", "privacy", "notifications", "storage", "help", "about"]); assert_eq!(comms.iter().map(|(_, group)| *group).collect::<Vec<_>>(), ["keep", "keep", "behave", "behave", "behave", "help", "help"]);for (manifest, rows, name) in [ (include_str!("../../../../apps/cotton/App/Flavours/notes/flavour.json"), vec!["Sync", "Storage", "Help and feedback", "About"], "Words"), (include_str!("../../../../apps/cotton/App/Flavours/days/flavour.json"), vec!["Sync", "Notifications", "Storage", "Help and feedback", "About"], "Days"), (include_str!("../../../../apps/cotton/App/Flavours/story/flavour.json"), vec!["Sync", "Storage", "Help and feedback", "About"], "Story"), ] {let (_dir, handle) = phone(manifest);let answer = crate::methods::dispatch(&handle, "shell.settings", &json!({"commit": "abc1234", "notifications": false})).expect("shell.settings");let labels: Vec<&str> = answer["rows"].as_array().expect("rows").iter().map(|row| row["label"].as_str().unwrap()).collect(); assert_eq!(labels, rows, "{answer}");let line = |id: &str| answer["rows"].as_array().unwrap().iter().find(|row| row["id"] == id).and_then(|row| row["line"].as_str()).unwrap_or_default().to_string(); assert_eq!(line("sync"), "Signed out"); assert!(line("storage").ends_with(" on this phone"), "{answer}"); assert_eq!(line("help"), "Share a report"); assert!(line("about").starts_with("Version "), "{answer}");if name == "Days" { assert_eq!(line("notifications"), "Off"); }for row in answer["rows"].as_array().unwrap() {for words in [&row["label"], &row["line"]].into_iter().filter_map(Value::as_str) { assert!(!words.is_empty() && !words.contains('{') && !words.contains("app.you"), "said in words, no key or fill left: {row}"); } } assert_eq!(answer["sync"]["title"], "Signed out"); assert_eq!(answer["sync"]["trouble"], false); assert_eq!(answer["profile"]["signed_in"], false); assert_eq!(answer["profile"]["line"], "Everything stays on this phone until you sign in. Then it syncs."); assert!(answer["pages"]["storage_kept"].as_str().is_some_and(|said| said.contains(" keeps this much on this phone") && !said.contains('{')), "{answer}"); assert!(answer["pages"]["notifications_phone_line"].as_str().is_some_and(|said| said.starts_with("Sounds, banners") && !said.contains('{')), "{answer}"); }}/// The card while the first sync saves the person's data: signed in, never "what signing in does" (Words on the/// emulator, 23 Nov 2026, said "Signed in" over "Everything stays on this phone until you sign in").#[test]fn the_card_is_signed_in_while_the_first_sync_saves() {let saving = json!({"stand": "backing_up", "card": {"subtitle": "Signed in"}}); assert_eq!(super::profile_of(&saving, None), json!({"signed_in": true})); assert_eq!(super::profile_of(&saving, Some("Kavi Walktest".into())), json!({"signed_in": true, "name": "Kavi Walktest"}));let out = super::profile_of(&json!({"stand": "local", "card": {"subtitle": "Signed out"}}), None); assert_eq!(out["signed_in"], false); assert_eq!(out["line"], "Everything stays on this phone until you sign in. Then it syncs.");let stopped = super::profile_of(&json!({"stand": "local", "card": {"subtitle": "Your data is safe on this phone. Sign in again to finish syncing it."}}), None); assert_eq!(stopped["line"], "Your data is safe on this phone. Sign in again to finish syncing it.");}/// Privacy's glance counts Your people: who asks first, then who is connected or waits for them, else that no one is added yet.#[test]fn privacy_says_how_many_of_your_people() {let part = |asking: usize, people: usize| {let rows = |n: usize| (0..n).map(|i| json!({"number": format!("+1555019{i:04}")})).collect::<Vec<_>>(); json!({"sections": [{"id": "asking", "rows": rows(asking)}, {"id": "people", "rows": rows(people)}]}) };let said = |people: &Value| super::people_counts(people).map(super::people_said); assert_eq!(said(&part(0, 0)).as_deref(), Some("No one added yet")); assert_eq!(said(&part(0, 1)).as_deref(), Some("1 person")); assert_eq!(said(&part(0, 3)).as_deref(), Some("3 people")); assert_eq!(said(&part(2, 3)).as_deref(), Some("2 people want to connect"));let waiting = json!({"sections": [{"id": "waiting", "rows": [{"number": "+15550190001"}]}]}); assert_eq!(said(&waiting).as_deref(), Some("1 person"), "one he added and waits for is one of his people, never No one"); assert_eq!(said(&json!({"unreachable": "Can't reach"})), None, "out of reach it says nothing rather than a guess"); assert_eq!(said(&Value::Null), None, "not asked, it says nothing rather than No one");}/// RULE (owner, 21 Nov 2026): Share a report is a small text the person reads before it is shared: the app and its version, how sync stands, the storage figures and recent errors, and none of what they keep — no titles, no names, no numbers.#[test]fn a_report_holds_the_facts_and_none_of_the_persons_things() {let (_dir, handle) = days_phone();crate::methods::dispatch(&handle, "records.create", &json!({"table": "todo", "data": {"title": "Ring Asha Example about the invented lease"}})).expect("a todo"); handle.client().note_trouble(Some("could not send “Ring Asha Example” to +44 7700 900123".into()));let report = crate::methods::dispatch(&handle, "shell.report", &json!({"commit": "abc1234"})).expect("shell.report");let text = report["text"].as_str().expect("the text"); assert!(report["file_name"].as_str().is_some_and(|name| name.ends_with(".txt")), "{report}");for part in ["## Sync", "## Storage on this phone", "## Recent errors", "Your data:", "Signed in: no", "Changes waiting to sync:"] { assert!(text.contains(part), "the report says {part}: {text}"); }for personal in ["Asha", "lease", "7700", "900123", "Ring"] { assert!(!text.contains(personal), "the report holds {personal}: {text}"); }}/// RULE: Free up space takes only a file the account already holds, not kept for offline, not made here, never a thumbnail; it refuses when more would go than the person agreed to.#[test]fn free_up_takes_only_what_the_account_holds() {let (_dir, handle) = days_phone();let client = handle.client();let media = client.layout().root().join("invented-media"); std::fs::create_dir_all(&media).expect("a folder");let rows: [(&str, &str, i64, i64, &str, i64); 5] = [ ("synced-free", "synced", 0, 0, "original", 1_000_000), ("synced-kept", "synced", 1, 0, "original", 2_000_000), ("synced-made-here", "synced", 0, 1, "original", 3_000_000), ("pending", "pending", 0, 0, "original", 4_000_000), ("thumb", "synced", 0, 0, "thumb", 5_000_000), ]; client .with_writer(|file| {for (key, state, pinned, captured, tier, bytes) in rows {let path = media.join(key); std::fs::write(&path, b"invented").map_err(|error| error.to_string())?; file.driver .run("INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, state, created_at, updated_at, tier, pinned, captured_here) \ VALUES (?, ?, 'invented', 'image/jpeg', ?, ?, ?, '2026-11-21T00:00:00Z', '2026-11-21T00:00:00Z', ?, ?, ?)", &[key.to_string().into(), file.workspace_id.to_string().into(), bytes.into(), path.to_string_lossy().to_string().into(), state.to_string().into(), tier.to_string().into(), pinned.into(), captured.into()], ) .map_err(|error| error.to_string())?; }Ok(()) }) .expect("invented files");let free: i64 = client .with_file(|file| Ok(file.driver.get(&format!("SELECT SUM(size_bytes) AS n FROM _media WHERE {FREEABLE}"), &[]).map_err(|e| e.to_string())?.and_then(|row| row.int("n")).unwrap_or(0))) .expect("a sum"); assert_eq!(free, 1_000_000, "only the synced, unkept file made elsewhere");let storage = &settings(&handle)["storage"]; assert_eq!(storage["free_up"]["bytes"], 1_000_000, "{storage}"); assert_eq!(storage["free_up"]["ask"], "Free up 1 MB?", "{storage}");let refused = crate::methods::dispatch(&handle, "shell.freeUp", &json!({"expected": 10})).expect_err("more than agreed"); assert_eq!(refused.code, "storage_changed");}const WORDS: &str = include_str!("../../../../apps/cotton/App/Flavours/notes/flavour.json");/// The same phone opened again, as a cold launch opens it: a new core over the container a first one left.fn reopen(dir: &tempfile::TempDir, manifest: &str) -> CottonHandle {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(serde_json::from_str(manifest).expect("an app's manifest")), }) .expect("the core opened again")}fn ask(handle: &CottonHandle, method: &str) -> Value {crate::methods::dispatch(handle, method, &json!({"commit": "abc1234", "notifications": true})).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn row<'a>(answer: &'a Value, id: &str) -> &'a Value { answer["rows"].as_array().expect("rows").iter().find(|row| row["id"] == id).unwrap_or_else(|| panic!("no {id} row: {answer}"))}/// A door to a scripted server, so a test sees every request a method makes.fn door(handle: &CottonHandle, replies: Vec<cotton_client::transport::scripted::Reply>) -> std::sync::Arc<cotton_client::transport::scripted::ScriptedExchange> {let exchange = cotton_client::transport::scripted::ScriptedExchange::new(replies);let address = cotton_client::transport::object::ObjectAddress::open("https://cottondb.example.test").expect("an address");let door = crate::phone::personal_object::ObjectDoor { address, exchange: exchange.clone(), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".to_string() }; handle.client().set_object_door(Some(std::sync::Arc::new(door))); exchange}/// RULE (owner, build 24, 23 Nov 2026: in Comms, Words, Days and Story the card drew first and the rows one to two/// seconds later; everything there is on this phone, so the whole list draws on the first frame): `shell.settings.now`/// answers every row the whole answer does, in its order, without asking the server or walking the app's folder. A/// phone that never had a whole answer gets Storage standing with `later` and no line, and no `storage` page yet; a/// file put in the app's folder after the whole answer is not in the quick answer's figures until the whole answer/// measures again (so it walked nothing).#[test]fn the_quick_answer_walks_no_folder_and_asks_no_server() {let (_dir, handle) = phone(WORDS);let server = door(&handle, Vec::new());let first = ask(&handle, "shell.settings.now"); assert!(server.seen().is_empty(), "the quick answer asked the server: {:?}", server.seen().iter().map(|seen| seen.path.clone()).collect::<Vec<_>>());let whole = ask(&handle, "shell.settings");let ids = |answer: &Value| answer["rows"].as_array().unwrap().iter().map(|row| row["id"].as_str().unwrap().to_string()).collect::<Vec<_>>(); assert_eq!(ids(&first), ids(&whole), "every row stands on the first frame: {first}"); assert_eq!(row(&first, "storage")["later"], true, "{first}"); assert!(row(&first, "storage").get("line").is_none(), "never a guessed size: {first}"); assert!(first.get("storage").is_none(), "{first}"); assert_eq!(row(&first, "sync")["line"], row(&whole, "sync")["line"], "the rest is said at once"); assert_eq!(first["profile"], whole["profile"]); assert!(row(&whole, "storage").get("later").is_none(), "{whole}");let measured = whole["storage"]["total_bytes"].as_u64().expect("measured"); std::fs::write(handle.client().layout().root().join("invented-film.bin"), vec![7u8; 3_000_000]).expect("a big file");let quick = ask(&handle, "shell.settings.now"); assert_eq!(quick["storage"]["total_bytes"], json!(measured), "the quick answer walked the folder: {quick}"); assert_eq!(row(&quick, "storage")["line"], row(&whole, "storage")["line"]); assert!(row(&quick, "storage").get("later").is_none(), "{quick}");let again = ask(&handle, "shell.settings"); assert!(again["storage"]["total_bytes"].as_u64().unwrap() >= measured + 3_000_000, "the whole answer measures: {again}"); assert!(server.seen().is_empty());}/// RULE (coordinator, 23 Nov 2026: the owner's case is a cold launch): what the last whole answer found is kept on/// this phone, so a fresh launch's quick answer says it at once: Storage's figures, and in Comms the blocked count.#[test]fn a_fresh_launch_says_what_the_last_whole_answer_found() {use cotton_client::transport::scripted::Reply;let (dir, handle) = phone(WORDS);let blocked = json!({"people": [], "asking": [], "blocked": [{"number": "+15550190001", "name": "Invented One", "at": "2026-11-20T10:00:00.000Z"}, {"number": "+15550190002", "at": "2026-11-21T10:00:00.000Z"}]});let server = door(&handle, vec![Reply::ok(&blocked.to_string())]);let whole = ask(&handle, "shell.settings");let you = ask(&handle, "chat.you"); assert_eq!(server.calls(), 1, "chat.you asks the server for the blocked people"); assert_eq!(row(&you, "privacy")["line"], "2 blocked · read receipts off", "{you}"); drop(handle);let handle = reopen(&dir, WORDS);let server = door(&handle, Vec::new());let now = ask(&handle, "shell.settings.now"); assert_eq!(row(&now, "storage")["line"], row(&whole, "storage")["line"], "{now}"); assert!(row(&now, "storage").get("later").is_none(), "{now}");// As the last whole answer measured it (chat.you's, a moment after shell.settings'), said the same. assert_eq!(now["storage"]["said"], whole["storage"]["said"], "{now}");let you_now = ask(&handle, "chat.you.now"); assert_eq!(row(&you_now, "privacy")["line"], "2 blocked · read receipts off", "{you_now}"); assert!(row(&you_now, "privacy").get("later").is_none() && row(&you_now, "storage").get("later").is_none(), "{you_now}"); assert_eq!(you_now["rows"].as_array().unwrap().len(), 8, "Export joined You (a1087a9daa)"); assert!(server.seen().is_empty(), "chat.you.now asked the server");}/// RULE: on a phone that never had a whole answer, Comms' quick You says what this phone holds (Read receipts) and/// marks the rows still to come; the whole answer fills them in place.#[test]fn comms_quick_you_marks_what_comes_later() {let (_dir, handle) = phone(WORDS);let server = door(&handle, Vec::new());let now = ask(&handle, "chat.you.now"); assert!(server.seen().is_empty()); assert_eq!(row(&now, "privacy")["line"], "Read receipts off"); assert_eq!(row(&now, "privacy")["later"], true); assert_eq!(row(&now, "storage")["later"], true); assert!(row(&now, "storage").get("line").is_none(), "{now}"); assert_eq!(row(&now, "sync")["line"], "Signed out"); assert!(now["profile"].is_object(), "the card as this phone knows it: {now}");}/// RULE: the quick answer stays quick on a big phone: twenty thousand files in the app's folder cost it nothing (it/// takes as long as on an empty phone), while the whole answer walks them.#[test]fn the_quick_answer_stays_quick_over_a_big_folder() {let (_dir, handle) = phone(WORDS);let quickest = |handle: &CottonHandle| { (0..5) .map(|_| {let started = std::time::Instant::now(); ask(handle, "shell.settings.now"); ask(handle, "chat.you.now"); started.elapsed() }) .min() .unwrap() }; ask(&handle, "shell.settings");let empty = quickest(&handle);let root = handle.client().layout().root().join("invented-files");for folder in0..100 {let dir = root.join(format!("f{folder:03}")); std::fs::create_dir_all(&dir).expect("a folder");for file in0..200 { std::fs::write(dir.join(format!("{file:03}.bin")), [1u8; 64]).expect("a file"); } }let started = std::time::Instant::now(); ask(&handle, "shell.settings");let whole = started.elapsed();let big = quickest(&handle); eprintln!("settings and you, quick: {empty:?} on an empty phone, {big:?} over 20,000 files; whole settings over them {whole:?}"); assert!(big < empty * 2 + std::time::Duration::from_millis(10), "the quick answers grew with the folder: {empty:?} then {big:?}"); assert!(big < whole, "quick {big:?}, whole {whole:?}");}/// RULE (SPACE.md): the Storage line says how full the space for photos and files is from 80%, and when it is full,/// that new ones wait on the phone and what is saved is safe; below 80% it says nothing.#[test]fn the_storage_line_says_how_full_the_space_for_files_is() { assert_eq!(space_words(0.5), None); assert_eq!(space_words(0.84).as_deref(), Some("Your space for photos and files is 84% full.")); assert_eq!( space_words(1.0).as_deref(),Some("Your space for photos and files is full. New photos and files wait on this phone until there is room. Everything already saved is safe.") );let pass = cotton_client::transport::object::Space::of(&json!({ "bytes": 2_000_000_000u64, "allowance": 2_147_483_648u64, "used": 0.9313 })).unwrap(); assert_eq!((pass.allowance, pass.used), (2_147_483_648, 0.9313)); assert!(cotton_client::transport::object::Space::of(&json!({ "bytes": 1 })).is_none(), "a part of one is none");}