Cotton code
1365 lines · 75.0 KB · RustRaw
//! SITES ROWS (assets/design/sites/SYNC-DESIGN.md, design 2): the synced `site` rows are the list. Each test is one//! case of the design; written before the build, against 5744d0e6b0. Every address and name is invented.use serde_json::{json, Value};use crate::handle::CottonHandle;const KEY: &str = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";const NINE: [&str; 9] = ["key", "label", "home", "stay", "hidden", "pinned", "position", "trackers", "login"];fn ask(h: &CottonHandle, method: &str, mut request: Value) -> Value {    request["key"] = json!(KEY);    crate::methods::dispatch(h, method, &request).unwrap_or_else(|e| panic!("{method}: {} {}", e.code, e.message))}fn refused(h: &CottonHandle, method: &str, mut request: Value) -> (String, String) {    request["key"] = json!(KEY);    let e = crate::methods::dispatch(h, method, &request).expect_err(method);    (e.code, e.message)}fn id(answer: &Value) -> String {    answer["row"]["id"].as_str().unwrap().to_string()}fn labels(rows: &Value) -> Vec<String> {    rows.as_array().unwrap().iter().map(|r| r["label"].as_str().unwrap().to_string()).collect()}fn shown(h: &CottonHandle) -> Vec<String> {    labels(&ask(h, "sites.home", json!({}))["rows"])}fn sites_phone(dir: &tempfile::TempDir) -> CottonHandle {    crate::phone::sites::reset_for_tests();    let manifest = json!({        "genesis": "personal", "flavour": "sites", "name": "Cotton Sites", "databases": "single", "database": "personal", "kit": "sites",    });    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::Dev,        manifest: Some(manifest),    })    .expect("an open core");    crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started");    handle}fn table(h: &CottonHandle, write: bool, tool: &str, args: Value) -> Value {    crate::phone::sites::table_for_tests(&h.client(), write, tool, args).unwrap_or_else(|e| panic!("{tool}: {} {}", e.code, e.message))}/// The live rows of `site`, as another phone would read them.fn rows(h: &CottonHandle) -> Vec<Value> {    let listed = table(h, false, "list_records", json!({ "table": "site", "limit": 500 }));    listed["records"].as_array().unwrap().iter().filter(|r| r.get("deleted_at").is_none_or(Value::is_null)).map(|r| r["data"].clone()).collect()}fn row_of<'a>(rows: &'a [Value], key: &str) -> &'a Value {    rows.iter().find(|r| r["key"] == key).unwrap_or_else(|| panic!("a row at {key}: {rows:?}"))}/// Another phone's write arriving in this copy, as a pull lands it.fn from_elsewhere(h: &CottonHandle, data: Value) {    table(h, true, "create_record", json!({ "table": "site", "data": data }));}fn removed_elsewhere(h: &CottonHandle, key: &str) {    table(h, true, "delete_record", json!({ "table": "site", "id": key }));}/// One text of this copy's own SQL.fn one(h: &CottonHandle, sql: &str) -> Option<String> {    h.client().with_file(|file| Ok(file.driver.get(sql, &[]).map_err(|e| e.to_string())?.and_then(|row| row.text("v").map(str::to_string)))).unwrap()}/// Whether the copy holds the row at all, live, binned or otherwise.fn held_at_all(h: &CottonHandle, key: &str) -> bool {    one(h, &format!("SELECT id AS v FROM cotton_site WHERE id = '{key}'")).is_some()}fn updated(h: &CottonHandle, key: &str) -> String {    one(h, &format!("SELECT updated_at AS v FROM cotton_site WHERE id = '{key}'")).unwrap_or_default()}/// Whether this copy's pull has truly caught up (no page still to come).fn caught_up(h: &CottonHandle, on: bool) {    crate::phone::sites::caught_up_for_tests(&h.client(), on);}/// Sites' clock moved on by `ms` (the five seconds of Undo).fn later(ms: i64) {    crate::phone::sites::later_for_tests(ms);}/// An old book (build 1's `client/sites.c1`), sealed under the phone's Sites key.fn old_book(h: &CottonHandle, book: &cotton_core::sites::Book) {    let key = cotton_core::chat::seal::key_from_text(KEY).unwrap();    let bytes = book.seal(&key, &[7; 12]).unwrap();    std::fs::write(h.client().layout().client_dir().join("sites.c1"), bytes).unwrap();}fn old_book_left(h: &CottonHandle) -> bool {    h.client().layout().client_dir().join("sites.c1").exists()}fn set_aside_left(h: &CottonHandle) -> bool {    h.client().layout().client_dir().join("sites.c1.migrated").exists()}const A: &str = "0a0a0a0a-1111-4222-8333-444444444441";const B: &str = "0a0a0a0a-1111-4222-8333-444444444442";const C: &str = "0a0a0a0a-1111-4222-8333-444444444443";// ---- One row, one write#[test]fn a_change_is_one_row_write() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let work = id(&ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" })));    let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })));    let work_at = updated(&h, &work);    std::thread::sleep(std::time::Duration::from_millis(5));    ask(&h, "sites.edit", json!({ "id": club, "label": "Chess club" }));    ask(&h, "sites.home", json!({}));    assert_eq!(updated(&h, &work), work_at, "an edit of one site writes only its row");    assert_eq!(row_of(&rows(&h), &club)["label"], "Chess club");}#[test]fn only_the_nine_live_columns_are_written() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })));    ask(&h, "sites.left", json!({ "id": club, "url": "https://club.example/board", "title": "Board" }));    ask(&h, "sites.edit", json!({ "id": club, "pinned": true }));    for row in rows(&h) {        for column in row.as_object().unwrap().keys() {            assert!(NINE.contains(&column.as_str()), "{column} is not one of the live Worker's nine: {row}");        }        assert!(!row.to_string().contains("board") && !row.to_string().contains("Board"), "never the last page");    }}#[test]fn the_list_is_read_from_the_rows() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" }));    from_elsewhere(&h, json!({ "key": A, "label": "Club", "home": "https://club.example/", "stay": true, "position": 1_000_000, "trackers": true }));    let home = ask(&h, "sites.home", json!({}));    assert_eq!(labels(&home["rows"]), ["Work mail", "Club"]);    assert_eq!(home["rows"][1]["line"], "Sign in once");    // Renamed on the other phone, with no stamp of any kind: the row says it, so the list says it.    from_elsewhere(&h, json!({ "key": A, "label": "Chess club", "home": "https://club.example/", "stay": true, "position": 1_000_000, "trackers": true }));    assert_eq!(shown(&h), ["Work mail", "Chess club"]);    removed_elsewhere(&h, A);    assert_eq!(shown(&h), ["Work mail"]);}// ---- Removal: Undo, then erased, never the Bin#[test]fn a_removal_offers_undo_then_erases() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    crate::phone::sites::freeze_for_tests();    let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })));    let removed = ask(&h, "sites.delete", json!({ "id": club }));    assert_eq!(removed["undo"]["label"], "Undo");    assert_eq!(removed["undo"]["seconds"], 5);    assert!(shown(&h).is_empty(), "gone from the list at once");    assert_eq!(rows(&h).len(), 1, "the row waits out the Undo");    ask(&h, "sites.undo", json!({ "id": club }));    assert_eq!(shown(&h), ["Club"]);    ask(&h, "sites.delete", json!({ "id": club }));    later(6_000);    ask(&h, "sites.home", json!({}));    assert!(rows(&h).is_empty());    assert_eq!(refused(&h, "sites.undo", json!({ "id": club })).0, "no_row", "nothing after the five seconds");}#[test]fn a_removed_site_is_not_in_the_bin() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })));    ask(&h, "sites.delete", json!({ "id": club }));    later(6_000);    ask(&h, "sites.home", json!({}));    assert!(!held_at_all(&h, &club), "erased, not binned");    let binned = crate::methods::dispatch(&h, "records.list", &json!({ "table": "bin" })).map(|v| v.to_string()).unwrap_or_default();    assert!(!binned.contains(&club), "{binned}");}#[test]fn a_create_at_a_removed_key_is_never_sent() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    // Build 1's book: Work (still a row) and Club (removed on another phone since).    let mut book = cotton_core::sites::Book::default();    book.add(A.into(), "Work mail", "mail.example", true, false).unwrap();    book.add(B.into(), "Club", "club.example", true, false).unwrap();    book.settings.synced = true;    from_elsewhere(&h, json!({ "key": A, "label": "Work mail", "home": "https://mail.example/", "stay": true, "position": 0, "trackers": true }));    from_elsewhere(&h, json!({ "key": B, "label": "Club", "home": "https://club.example/", "stay": true, "position": 1, "trackers": true }));    removed_elsewhere(&h, B);    old_book(&h, &book);    caught_up(&h, true);    // Club is kept on this phone (never dropped on inference), and never written at its removed key.    assert_eq!(shown(&h), ["Work mail", "Club"]);    ask(&h, "sites.add", json!({ "label": "News", "home": "news.example" }));    assert!(rows(&h).iter().all(|r| r["key"] != B), "the removed key stays removed");    assert!(rows(&h).iter().all(|r| r["key"] != A || r["label"] == "Work mail"));    let news = rows(&h).into_iter().find(|r| r["label"] == "News").unwrap();    assert!(news["key"] != A && news["key"] != B, "a new site has a fresh key");}// ---- Two names, twins, hidden#[test]fn the_same_address_under_two_names_is_two_sites() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let work = ask(&h, "sites.add", json!({ "label": "Work mail", "home": "mail.example" }));    let mine = ask(&h, "sites.add", json!({ "label": "My mail", "home": "mail.example" }));    assert_ne!(work["row"]["store"], mine["row"]["store"], "each its own sign-in");    assert_eq!(rows(&h).len(), 2);    assert!(ask(&h, "sites.home", json!({})).get("twins").is_none_or(|t| t.as_array().is_some_and(Vec::is_empty)));}#[test]fn twin_sites_say_appears_twice_and_keep_one_erases_the_other() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let here = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })));    from_elsewhere(&h, json!({ "key": A, "label": "club", "home": "https://club.example/", "stay": true, "position": 5_000_000, "trackers": true }));    let home = ask(&h, "sites.home", json!({}));    assert_eq!(labels(&home["rows"]).len(), 2, "two until he keeps one");    assert_eq!(home["twins"][0]["line"], "Club appears twice");    assert_eq!(home["twins"][0]["keep"], "Keep one");    ask(&h, "sites.keep_one", json!({ "keep": here, "drop": A }));    later(6_000);    assert_eq!(shown(&h), ["Club"]);    assert!(!held_at_all(&h, A));}#[test]fn twins_line_never_names_a_hidden_site() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    ask(&h, "sites.add", json!({ "label": "Bank", "home": "ledgerbank.example", "hidden": true }));    from_elsewhere(&h, json!({ "key": A, "label": "Bank", "home": "https://ledgerbank.example/", "stay": true, "hidden": true, "position": 5_000_000, "trackers": true }));    let locked = ask(&h, "sites.home", json!({}));    assert!(!locked.to_string().contains("Bank"), "nothing names a hidden site behind the lock: {locked}");    let open = ask(&h, "sites.home", json!({ "unlocked": true }));    assert_eq!(open["hidden"]["twins"][0]["line"], "Bank appears twice");}// ---- Order#[test]fn positions_survive_50_moves_between_two_neighbours() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let ids: Vec<String> = ["Alpha", "Beta", "Gamma", "Delta"].iter().map(|l| id(&ask(&h, "sites.add", json!({ "label": l, "home": format!("{}.example", l.to_lowercase()) })))).collect();    let mut order = ids.clone();    for n in 0..50 {        // Delta goes between the first two, then Gamma does: always the gap that halves.        let moving = if n % 2 == 0 { order.pop().unwrap() } else { order.remove(2) };        order.insert(1, moving);        let before_others: Vec<String> = order.iter().filter(|i| **i != order[1]).map(|i| updated(&h, i)).collect();        ask(&h, "sites.arrange", json!({ "order": order, "pinned": [] }));        let after_others: Vec<String> = order.iter().filter(|i| **i != order[1]).map(|i| updated(&h, i)).collect();        let home = ask(&h, "sites.home", json!({}));        let drawn: Vec<String> = home["rows"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap().to_string()).collect();        assert_eq!(drawn, order, "move {n}");        if n == 0 {            assert_eq!(before_others, after_others, "a move writes the one site that moved");        }    }    // Read whole by another phone: the same order from the positions alone.    let mut by_place = rows(&h);    by_place.sort_by(|a, b| a["position"].as_f64().unwrap().total_cmp(&b["position"].as_f64().unwrap()));    let keys: Vec<String> = by_place.iter().map(|r| r["key"].as_str().unwrap().to_string()).collect();    assert_eq!(keys, order);}// ---- Login#[test]fn a_cleared_login_stays_cleared_on_the_other_phone() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })));    ask(&h, "sites.login", json!({ "id": club, "secret": "login-one" }));    assert_eq!(row_of(&rows(&h), &club)["login"], "login-one");    ask(&h, "sites.login", json!({ "id": club, "secret": "" }));    let cleared = row_of(&rows(&h), &club)["login"].clone();    assert!(cleared.is_null() || cleared == "", "the clear is in the row: {cleared}");    // The other phone renames it, its row saying no login: still none here.    from_elsewhere(&h, json!({ "key": club, "label": "Chess club", "home": "https://club.example/", "stay": true, "position": 0, "trackers": true, "login": "" }));    assert_eq!(shown(&h), ["Chess club"]);    let after = row_of(&rows(&h), &club)["login"].clone();    assert!(after.is_null() || after == "", "nothing put the old login back: {after}");}// ---- Only on this phone// ---- The migration#[test]fn migration_waits_for_the_pull_and_never_revives_a_removed_site() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut book = cotton_core::sites::Book::default();    book.add(A.into(), "Work mail", "mail.example", true, false).unwrap();    book.add(B.into(), "Club", "club.example", true, false).unwrap();    book.leave_titled(A, Some("https://mail.example/inbox"), Some("Inbox (4)")).unwrap();    book.settings.synced = true;    old_book(&h, &book);    caught_up(&h, false);    // Mid-pull: only Work has arrived so far. Club's row (removed elsewhere) has not.    from_elsewhere(&h, json!({ "key": A, "label": "Work mail", "home": "https://mail.example/", "stay": true, "position": 0, "trackers": true }));    ask(&h, "sites.home", json!({}));    assert_eq!(rows(&h).len(), 1, "nothing is created while the pull is behind");    assert!(old_book_left(&h), "the book waits for the pull");    // The pull ends: Club arrives removed.    from_elsewhere(&h, json!({ "key": B, "label": "Club", "home": "https://club.example/", "stay": true, "position": 1, "trackers": true }));    removed_elsewhere(&h, B);    caught_up(&h, true);    let home = ask(&h, "sites.home", json!({}));    assert_eq!(home["rows"][0]["line"], "mail.example · Inbox (4)", "its page came from the book");    assert!(rows(&h).iter().all(|r| r["key"] != B), "Club is never written again at its removed key");    // Never dropped on inference (review of SITES ROWS 2, decision 2), and never kept only here (the switch is gone,    // 27 Nov 2026): written into the list at a fresh key, keeping its sign-in; he can remove it again.    let club = home["rows"].as_array().unwrap().iter().find(|r| r["label"] == "Club").expect("Club kept").clone();    assert_eq!(club["store_uuid"], B, "its own sign-in: {club}");    assert!(rows(&h).iter().any(|r| r["label"] == "Club" && r["key"] == club["id"]), "a row of the list");    assert!(club.get("not_elsewhere").is_none());    assert!(!old_book_left(&h), "migrated once");    assert!(set_aside_left(&h), "the book is kept aside, not deleted");}#[test]fn the_build_1_book_moves_its_local_fields_by_key() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut book = cotton_core::sites::Book::default();    book.add(A.into(), "Work mail", "mail.example", true, false).unwrap();    book.leave_titled(A, Some("https://mail.example/inbox"), Some("Inbox (4)")).unwrap();    book.keep_state(A, Some("c3RhdGU")).unwrap();    book.settings.engine = "brave".into();    book.settings.synced = true;    // Build 1 mirrored it in its nine columns, with the book's id as the key.    from_elsewhere(&h, json!({ "key": A, "label": "Work mail", "home": "https://mail.example/", "stay": true, "hidden": false, "pinned": false, "position": 0, "trackers": true }));    old_book(&h, &book);    caught_up(&h, true);    let home = ask(&h, "sites.home", json!({}));    assert_eq!(home["rows"][0]["line"], "mail.example · Inbox (4)");    assert_eq!(home["rows"][0]["id"], A, "the same site, so the same sign-in");    assert_eq!(ask(&h, "sites.state", json!({ "id": A }))["blob"], "c3RhdGU");    let settings = ask(&h, "sites.settings", json!({}));    let engine = settings["rows"].as_array().unwrap().iter().find(|r| r["id"] == "engine").unwrap().clone();    assert!(engine["choices"].as_array().unwrap().iter().any(|c| c["id"] == "brave" && c["chosen"] == true), "{engine}");    assert_eq!(rows(&h).len(), 1, "nothing written twice");}/// Build 1's one book belongs to the copy that stood at the rows build's first launch: another account's copy never/// takes it, never is offered it, and owes none of its stores (review of SITES ROWS, item 8).#[test]fn a_book_of_another_account_is_never_offered_or_taken() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut book = cotton_core::sites::Book::default();    book.add(A.into(), "Work mail", "mail.example", true, false).unwrap();    book.add(B.into(), "Club", "club.example", true, false).unwrap();    book.settings.synced = true;    old_book(&h, &book);    std::fs::write(h.client().layout().client_dir().join("sites.c1.owner"), "an-invented-other-database").unwrap();    caught_up(&h, true);    let home = ask(&h, "sites.home", json!({}));    assert!(labels(&home["rows"]).is_empty());    assert!(home.get("before").is_none(), "never offered: {home}");    assert!(rows(&h).is_empty(), "nothing goes up");    assert!(old_book_left(&h), "left for the copy it belongs to");    assert!(ask(&h, "sites.stores.gone", json!({}))["stores"].as_array().unwrap().is_empty(), "none of its stores owed");}/// The old book goes only after what it held is written here: Sites' own file holds it first.#[test]fn the_old_book_goes_only_after_its_sites_are_kept_here() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut book = cotton_core::sites::Book::default();    book.add(A.into(), "Work mail", "mail.example", true, false).unwrap();    book.leave_titled(A, Some("https://mail.example/inbox"), Some("Inbox (4)")).unwrap();    book.settings.synced = true;    from_elsewhere(&h, json!({ "key": A, "label": "Work mail", "home": "https://mail.example/", "stay": true, "position": 0, "trackers": true }));    old_book(&h, &book);    let folder = crate::phone::sites::local_folder_for_tests(&h.client()).unwrap();    caught_up(&h, true);    ask(&h, "sites.home", json!({}));    assert!(!old_book_left(&h));    assert!(folder.join("sites.local.c1").exists(), "kept here before the book went");    assert_eq!(ask(&h, "sites.home", json!({}))["rows"][0]["line"], "mail.example · Inbox (4)");}// ---- Website stores#[test]fn a_row_removed_elsewhere_offers_its_sign_in_and_removes_it_only_when_asked() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    ask(&h, "sites.add", json!({ "label": "News", "home": "news.example" }));    let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })));    let store = ask(&h, "sites.open", json!({ "id": club }))["store"].clone();    ask(&h, "sites.left", json!({ "id": club, "url": "https://club.example/board" }));    caught_up(&h, false);    removed_elsewhere(&h, &club);    assert!(ask(&h, "sites.stores.gone", json!({}))["stores"].as_array().unwrap().is_empty(), "never on a partial view");    caught_up(&h, true);    assert_eq!(shown(&h), ["News"]);    // A row absent is never a reason (review of SITES ROWS 2, blocking 1): the sign-in is offered, not taken.    let home = ask(&h, "sites.home", json!({}));    assert!(ask(&h, "sites.stores.gone", json!({}))["stores"].as_array().unwrap().is_empty(), "nothing queued by absence");    assert_eq!(home["orphans"]["sites"], json!([{ "id": club, "label": "Club" }]), "{home}");    assert_eq!(home["orphans"]["line"], "Sign-ins for sites no longer in your list");    // One at a time, by id: one not offered removes nothing.    assert_eq!(ask(&h, "sites.orphans.remove", json!({ "id": "an-invented-other-id" }))["removed"], 0);    assert_eq!(ask(&h, "sites.orphans.remove", json!({ "id": club }))["removed"], 1);    let gone = ask(&h, "sites.stores.gone", json!({}));    assert_eq!(gone["stores"][0]["store"], store);    assert!(gone["stores"][0]["store_uuid"].is_string());    ask(&h, "sites.stores.removed", json!({ "stores": [store] }));    assert!(ask(&h, "sites.stores.gone", json!({}))["stores"].as_array().unwrap().is_empty());}// ---- Comms, dev rows#[test]fn comms_moves_in_as_fresh_rows() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut comms = cotton_core::sites::Book::default();    comms.add(A.into(), "Club", "club.example", true, false).unwrap();    comms.add(B.into(), "Bank", "ledgerbank.example", true, true).unwrap();    let hand_over = [3_u8; 32];    let bytes = comms.seal(&hand_over, &[1; 12]).unwrap();    use base64::Engine as _;    let moved = ask(&h, "sites.move.in", json!({ "from_key": base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hand_over), "bytes": base64::engine::general_purpose::STANDARD.encode(bytes) }));    assert!(moved["count"].as_str().unwrap().contains('2'), "{moved}");    let synced = rows(&h);    assert_eq!(synced.len(), 2);    assert!(synced.iter().all(|r| r["key"] != A && r["key"] != B), "fresh keys: {synced:?}");    assert_eq!(synced.iter().find(|r| r["label"] == "Bank").unwrap()["hidden"], true);    assert!(ask(&h, "sites.home", json!({}))["rows"].as_array().unwrap().iter().all(|r| r["line"] == "Sign in once"));}#[test]fn a_dev_row_marked_gone_is_erased_and_never_shown() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    // As a dev copy holds one: the dev Worker's definition still names `gone`, so the copy's table has it.    h.client()        .with_writer(|file| {            file.driver                .run("UPDATE cotton_table_definitions SET definition = json_insert(definition, '$.columns[#]', json('{\"key\":\"gone\",\"name\":\"Removed\",\"type\":\"bool\"}')) WHERE id = 'site'", &[])                .map_err(|e| e.to_string())?;            file.driver.run("ALTER TABLE cotton_site ADD COLUMN gone INTEGER", &[]).map(|_| ()).map_err(|e| e.to_string())        })        .unwrap();    from_elsewhere(&h, json!({ "key": C, "label": "Old", "home": "https://old.example/", "gone": true }));    caught_up(&h, false);    assert!(shown(&h).is_empty());    assert!(held_at_all(&h, C), "left alone while the pull is behind");    caught_up(&h, true);    assert!(shown(&h).is_empty());    assert!(!held_at_all(&h, C), "erased once caught up");}// ---- An account switch mid-write#[test]fn a_write_after_the_copy_moved_lands_nowhere() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })));    let folder = crate::phone::sites::local_folder_for_tests(&h.client()).unwrap();    // The copy's folder moved aside between the read and the write (a sign-out on another thread).    let aside = folder.with_extension("aside");    std::fs::rename(&folder, &aside).unwrap();    let wrote = crate::phone::sites::write_local_for_tests(&h.client(), &folder);    std::fs::rename(&aside, &folder).unwrap();    assert!(wrote.is_err(), "no folder is made for it");    assert!(!folder.with_extension("aside").exists());    assert_eq!(shown(&h), ["Club"]);    let _ = club;}// ---- A copy made again (an adopt, a restore): what this phone kept comes with it, or the site says Sign in once.#[test]fn a_remade_copy_keeps_sign_ins_or_says_sign_in_once() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })));    ask(&h, "sites.left", json!({ "id": club, "url": "https://club.example/board", "title": "Board" }));    from_elsewhere(&h, json!({ "key": A, "label": "News", "home": "https://news.example/", "stay": true, "position": 9_000_000, "trackers": true }));    let folder = crate::phone::sites::local_folder_for_tests(&h.client()).unwrap();    // As `carry` leaves it in the new copy's folder, where nothing of its own was kept yet.    std::fs::rename(folder.join("sites.local.c1"), folder.join("sites.carried.0b0b0b0b-old-copy.c1")).unwrap();    let home = ask(&h, "sites.home", json!({}));    assert_eq!(home["rows"][0]["line"], "club.example · Board", "carried across: {home}");    assert_eq!(home["rows"][1]["line"], "Sign in once", "nothing kept of it: it says so");    ask(&h, "sites.edit", json!({ "id": club, "label": "Chess club" }));    assert!(!folder.join("sites.carried.0b0b0b0b-old-copy.c1").exists(), "taken in once");    assert_eq!(ask(&h, "sites.home", json!({}))["rows"][0]["line"], "club.example · Board");}// ---- Build 1's "Keep my list on this phone only", and the old book (review of SITES ROWS 2, decision 2 and 3 to 8)/// Synced, a book site the copy never held is written into the list at its own key: on every phone, its sign-in kept.#[test]fn a_book_site_the_copy_never_held_is_written_into_the_list_at_its_key() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut book = cotton_core::sites::Book::default();    book.add(B.into(), "Club", "club.example", true, false).unwrap();    book.settings.synced = true;    old_book(&h, &book);    caught_up(&h, true);    let home = ask(&h, "sites.home", json!({}));    assert_eq!(home["rows"][0]["id"], B, "{home}");    assert_eq!(rows(&h).len(), 1);    assert_eq!(rows(&h)[0]["key"], B);    assert!(home["rows"][0].get("not_elsewhere").is_none());}/// What he saved while the migration waited wins over the book's older values, field by field.#[test]fn what_he_saved_while_it_waited_wins_over_the_book() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut book = cotton_core::sites::Book::default();    book.add(A.into(), "Work mail", "mail.example", true, false).unwrap();    book.leave_titled(A, Some("https://mail.example/old"), Some("Old page")).unwrap();    book.keep_state(A, Some("Ym9vaw")).unwrap();    book.settings.synced = true;    from_elsewhere(&h, json!({ "key": A, "label": "Work mail", "home": "https://mail.example/", "stay": true, "position": 0, "trackers": true }));    old_book(&h, &book);    caught_up(&h, false);    ask(&h, "sites.left", json!({ "id": A, "url": "https://mail.example/new", "title": "New page" }));    caught_up(&h, true);    let home = ask(&h, "sites.home", json!({}));    assert_eq!(home["rows"][0]["line"], "mail.example · New page");    assert_eq!(ask(&h, "sites.state", json!({ "id": A }))["blob"], "Ym9vaw", "the book fills what the wait left empty");}/// A book this phone's key cannot open is said once in the list with what to do, and he can leave it.#[test]fn a_book_that_does_not_open_is_said_and_can_be_left() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    std::fs::write(h.client().layout().client_dir().join("sites.c1"), b"not a book this key opens").unwrap();    caught_up(&h, true);    let home = ask(&h, "sites.home", json!({}));    assert_eq!(home["book_stuck"]["leave"], "Leave them", "{home}");    assert!(old_book_left(&h));    ask(&h, "sites.book.leave", json!({}));    assert!(ask(&h, "sites.home", json!({})).get("book_stuck").is_none());    assert!(!old_book_left(&h) && set_aside_left(&h));}/// The app ended after Sites' file held the book but before the book was set aside: set aside at the next open, and/// nothing taken in twice.#[test]fn a_book_left_by_an_ended_app_is_set_aside_next_time() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut book = cotton_core::sites::Book::default();    book.add(A.into(), "Work mail", "mail.example", true, false).unwrap();    old_book(&h, &book);    caught_up(&h, true);    ask(&h, "sites.home", json!({}));    assert_eq!(rows(&h).len(), 1);    // As if the set-aside never happened: the book back where it was, still this copy's.    let dir_ = h.client().layout().client_dir();    std::fs::rename(dir_.join("sites.c1.migrated"), dir_.join("sites.c1")).unwrap();    std::fs::write(dir_.join("sites.c1.owner"), h.client().current_database().unwrap()).unwrap();    ask(&h, "sites.home", json!({}));    assert!(!old_book_left(&h) && set_aside_left(&h));    assert_eq!(rows(&h).len(), 1, "nothing taken in twice");}/// A connection file that cannot be read is an error, never "signed out": nothing is taken in on it.#[test]fn an_unreadable_connection_file_takes_nothing_in() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut book = cotton_core::sites::Book::default();    book.add(A.into(), "Work mail", "mail.example", true, false).unwrap();    old_book(&h, &book);    std::fs::write(h.client().layout().connection_json(), b"{ not json").unwrap();    let _ = refused_or_home(&h);    assert!(old_book_left(&h), "the book waits");    assert!(rows(&h).is_empty());}fn refused_or_home(h: &CottonHandle) -> Value {    let mut request = json!({});    request["key"] = json!(KEY);    crate::phone::sites::call(h, "sites.home", &request).unwrap_or(Value::Null)}/// While a signed-in copy is still loading, the sites it held before are drawn greyed with "Loading your list…", so/// the list is never only an Add.#[test]fn a_copy_still_loading_shows_what_it_held_greyed() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    from_elsewhere(&h, json!({ "key": A, "label": "Work mail", "home": "https://mail.example/", "stay": true, "position": 0, "trackers": true }));    caught_up(&h, true);    ask(&h, "sites.home", json!({}));    // Made again: the copy holds nothing yet and is not caught up.    h.client().with_writer(|file| file.driver.run("DELETE FROM cotton_site", &[]).map(|_| ()).map_err(|e| e.to_string())).unwrap();    caught_up(&h, false);    let home = ask(&h, "sites.home", json!({}));    assert_eq!(home["loading"]["line"], "Loading your list…");    assert_eq!(home["waiting_rows"][0]["label"], "Work mail");    assert_eq!(home["waiting_rows"][0]["waiting"], true);    assert!(ask(&h, "sites.stores.gone", json!({}))["stores"].as_array().unwrap().is_empty());}/// While a signed-in copy is still loading, a hidden site it held is never drawn greyed before Face ID: only once the/// hidden sites show, exactly as the loaded list draws it.#[test]fn a_copy_still_loading_never_shows_a_hidden_site_before_the_unlock() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    from_elsewhere(&h, json!({ "key": A, "label": "Work mail", "home": "https://mail.example/", "stay": true, "position": 0, "trackers": true }));    from_elsewhere(&h, json!({ "key": B, "label": "Ledger", "home": "https://ledgerbank.example/", "stay": true, "hidden": true, "position": 1, "trackers": true }));    caught_up(&h, true);    ask(&h, "sites.home", json!({}));    h.client().with_writer(|file| file.driver.run("DELETE FROM cotton_site", &[]).map(|_| ()).map_err(|e| e.to_string())).unwrap();    caught_up(&h, false);    let home = ask(&h, "sites.home", json!({}));    let text = home.to_string();    assert_eq!(home["waiting_rows"].as_array().unwrap().len(), 1, "{home}");    assert_eq!(home["waiting_rows"][0]["label"], "Work mail");    assert!(!text.contains("Ledger") && !text.contains("ledgerbank"), "neither its name nor its address: {home}");    let open = ask(&h, "sites.home", json!({ "unlocked": true }));    let hidden: Vec<&Value> = open["waiting_rows"].as_array().unwrap().iter().filter(|r| r["hidden"] == true).collect();    assert_eq!(hidden.len(), 1, "{open}");    assert_eq!(hidden[0]["label"], "Ledger");}/// "Delete the sign-ins of N removed sites?" answered Keep for now is never asked again: not on the next launch, and/// when another site is removed only the newly owed store is named; Keep then adds it, the kept ones stay kept.#[test]fn keep_for_now_is_asked_once_per_set_of_removed_sites() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let client = h.client();    let ids: Vec<String> = (0..6).map(|i| format!("0c0c0c0c-1111-4222-8333-44444444444{i}")).collect();    let names = |a: &Value| -> Vec<String> { a["stores"].as_array().unwrap().iter().map(|s| s["store"].as_str().unwrap().to_string()).collect() };    super::owe_stores(&client, &ids[..4]);    let gone = ask(&h, "sites.stores.gone", json!({}));    assert_eq!(names(&gone).len(), 4);    assert_eq!(gone["kept"], false, "asked the first time");    ask(&h, "sites.stores.keep", json!({ "stores": names(&gone) }));    // The next launch: nothing named, nothing asked.    let again = ask(&h, "sites.stores.gone", json!({}));    assert_eq!(again["kept"], true, "{again}");    assert!(names(&again).is_empty(), "{again}");    // One more removed: only that one is named.    super::owe_stores(&client, &ids[4..5]);    let grown = ask(&h, "sites.stores.gone", json!({}));    assert_eq!(grown["kept"], false);    assert_eq!(names(&grown), [format!("site-{}", ids[4])], "only the new one: {grown}");    // Keep for it too: added, the four still kept.    ask(&h, "sites.stores.keep", json!({ "stores": names(&grown) }));    assert!(names(&ask(&h, "sites.stores.gone", json!({}))).is_empty());    super::owe_stores(&client, &ids[5..]);    assert_eq!(names(&ask(&h, "sites.stores.gone", json!({}))), [format!("site-{}", ids[5])]);    // A kept one removed by the shell all the same leaves the rest kept.    ask(&h, "sites.stores.removed", json!({ "stores": [format!("site-{}", ids[5])] }));    let left = ask(&h, "sites.stores.gone", json!({}));    assert_eq!(left["kept"], true, "{left}");}/// After an upgrade, a copy whose phone file an older build wrote has no hidden flags for what it knew: while it/// loads nothing it knew is drawn waiting (no hidden name before the unlock), and once caught up the flags are filled.#[test]fn an_older_builds_file_draws_nothing_waiting_until_its_hidden_flags_are_filled() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    from_elsewhere(&h, json!({ "key": A, "label": "Work mail", "home": "https://mail.example/", "stay": true, "position": 0, "trackers": true }));    from_elsewhere(&h, json!({ "key": B, "label": "Ledger", "home": "https://ledgerbank.example/", "stay": true, "hidden": true, "position": 1, "trackers": true }));    caught_up(&h, true);    ask(&h, "sites.home", json!({}));    // As an older build left it: names known, no flags.    let mut old = crate::phone::sites::local_for_tests(&h.client());    assert!(old.known_hidden_filled && old.known_hidden.contains(B), "this build fills them");    old.known_hidden.clear();    old.known_hidden_filled = false;    crate::phone::sites::write_local_as_for_tests(&h.client(), &old);    h.client().with_writer(|file| file.driver.run("DELETE FROM cotton_site", &[]).map(|_| ()).map_err(|e| e.to_string())).unwrap();    caught_up(&h, false);    let home = ask(&h, "sites.home", json!({}));    assert_eq!(home["loading"]["line"], "Loading your list…");    assert!(home.get("waiting_rows").is_none(), "{home}");    assert!(!home.to_string().contains("Ledger") && !home.to_string().contains("ledgerbank"), "{home}");    assert!(home.get("add").is_none(), "never an Add alone while loading");    // Caught up with its rows back: filled from them.    from_elsewhere(&h, json!({ "key": B, "label": "Ledger", "home": "https://ledgerbank.example/", "stay": true, "hidden": true, "position": 1, "trackers": true }));    caught_up(&h, true);    ask(&h, "sites.home", json!({}));    let now = crate::phone::sites::local_for_tests(&h.client());    assert!(now.known_hidden_filled, "filled once caught up");    assert!(now.known_hidden.contains(B));}/// Two copies' flags merged: hidden wins, and a copy whose flags are not filled leaves the merged ones not filled.#[test]fn a_carried_file_merges_hidden_as_hidden_wins() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let key = cotton_core::chat::seal::key_from_text(KEY).unwrap();    let folder = crate::phone::sites::local_folder_for_tests(&h.client()).unwrap();    caught_up(&h, false);    let mut own = cotton_core::sites::Local { migrated: true, known_hidden_filled: true, ..Default::default() };    own.known.insert(B.into(), ("Ledger".into(), "https://ledgerbank.example/".into()));    crate::phone::sites::write_local_as_for_tests(&h.client(), &own);    let mut other = cotton_core::sites::Local { known_hidden_filled: true, ..Default::default() };    other.known.insert(B.into(), ("Ledger".into(), "https://ledgerbank.example/".into()));    other.known_hidden.insert(B.into());    std::fs::write(folder.join("sites.carried.hidden-there.c1"), other.seal(&key, &[4; 12]).unwrap()).unwrap();    let home = ask(&h, "sites.home", json!({}));    assert!(!home.to_string().contains("Ledger"), "hidden on either copy is hidden: {home}");    assert!(crate::phone::sites::local_for_tests(&h.client()).known_hidden.contains(B));    // A carried copy an older build wrote: its flags unknown, so nothing waiting is drawn.    let mut older = cotton_core::sites::Local::default();    older.known.insert(A.into(), ("Work mail".into(), "https://mail.example/".into()));    std::fs::write(folder.join("sites.carried.older.c1"), older.seal(&key, &[5; 12]).unwrap()).unwrap();    let home = ask(&h, "sites.home", json!({}));    assert!(home.get("waiting_rows").is_none(), "{home}");    assert!(!crate::phone::sites::local_for_tests(&h.client()).known_hidden_filled);}/// The banner of sign-ins for sites no longer in the list never names a hidden site before the unlock.#[test]fn the_orphans_banner_never_names_a_hidden_site_before_the_unlock() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    ask(&h, "sites.add", json!({ "label": "News", "home": "news.example" }));    let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example", "hidden": true })));    ask(&h, "sites.open", json!({ "id": club }));    caught_up(&h, true);    ask(&h, "sites.home", json!({}));    removed_elsewhere(&h, &club);    let locked = ask(&h, "sites.home", json!({}));    assert!(locked.get("orphans").is_none(), "{locked}");    assert!(!locked.to_string().contains("Club"), "{locked}");    let open = ask(&h, "sites.home", json!({ "unlocked": true }));    assert_eq!(open["orphans"]["sites"], json!([{ "id": club, "label": "Club" }]), "{open}");}/// Orphans are never offered when something looks off: rows empty, or more than half of what this phone keeps.#[test]fn orphans_are_not_offered_when_most_of_the_list_is_missing() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let news = id(&ask(&h, "sites.add", json!({ "label": "News", "home": "news.example" })));    let club = id(&ask(&h, "sites.add", json!({ "label": "Club", "home": "club.example" })));    let bank = id(&ask(&h, "sites.add", json!({ "label": "Bank", "home": "ledgerbank.example" })));    for k in [&news, &club, &bank] {        ask(&h, "sites.open", json!({ "id": k }));    }    caught_up(&h, true);    ask(&h, "sites.home", json!({}));    removed_elsewhere(&h, &club);    removed_elsewhere(&h, &bank);    let home = ask(&h, "sites.home", json!({}));    assert!(home.get("orphans").is_none(), "two of three missing: nothing said: {home}");    removed_elsewhere(&h, &news);    assert!(ask(&h, "sites.home", json!({})).get("orphans").is_none(), "no rows at all: nothing said");}/// A site already signed in from build 1 never shows Sign in once because the wait kept a stale mark.#[test]fn a_signed_in_site_stays_signed_in_through_the_migration() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut book = cotton_core::sites::Book::default();    book.add(A.into(), "Work mail", "mail.example", true, false).unwrap();    book.settings.synced = true;    from_elsewhere(&h, json!({ "key": A, "label": "Work mail", "home": "https://mail.example/", "stay": true, "position": 0, "trackers": true }));    old_book(&h, &book);    caught_up(&h, true);    let home = ask(&h, "sites.home", json!({}));    assert_eq!(home["rows"][0]["sign_in_once"], false, "{home}");}/// A book that cannot be read from disk is retried, and said after three tries.#[test]fn a_book_that_cannot_be_read_is_said_after_three_tries() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let book = h.client().layout().client_dir().join("sites.c1");    std::fs::create_dir_all(&book).unwrap();    std::fs::write(book.with_extension("c1.owner"), h.client().current_database().unwrap()).unwrap();    caught_up(&h, true);    assert!(ask(&h, "sites.home", json!({})).get("book_stuck").is_none());    assert!(ask(&h, "sites.home", json!({})).get("book_stuck").is_none());    assert_eq!(ask(&h, "sites.home", json!({}))["book_stuck"]["leave"], "Leave them");}// ---- The owner's upgrade from build 1: "Keep my list on this phone only" was never on (coordinator, 27 Nov 2026)/// RULE: his phone's path at the upgrade, the strongest test. Build 1's book, synced: every site build/// 1 mirrored is a row at the book's key. After the upgrade every site is still there at the same key (the same/// sign-in), with its last page, page state and settings; no row he holds is changed or erased; no sign-in is queued/// for removal; a site the copy never held (removed on another phone since, or never synced) is written into the list/// at its key, never kept only here (the switch is gone, 27 Nov 2026); a site added on another phone since shows as it/// is; the book is set aside, never deleted; and opening again changes nothing.#[test]fn the_owners_upgrade_keeps_every_site_and_changes_no_row() {    const C: &str = "0a0a0a0a-1111-4222-8333-444444444443";    const D: &str = "0a0a0a0a-1111-4222-8333-444444444444";    const E: &str = "0a0a0a0a-1111-4222-8333-444444444445";    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut book = cotton_core::sites::Book::default();    book.add(A.into(), "Work mail", "mail.example", true, false).unwrap();    book.add(B.into(), "Club", "club.example", false, false).unwrap();    book.add(C.into(), "Bank", "ledgerbank.example", true, true).unwrap();    book.add(D.into(), "Old forum", "forum.example", true, false).unwrap();    book.leave_titled(A, Some("https://mail.example/inbox/77"), Some("Inbox (4)")).unwrap();    book.keep_state(A, Some("c3RhdGUtYQ")).unwrap();    book.leave_titled(C, Some("https://ledgerbank.example/accounts"), Some("Accounts")).unwrap();    book.settings.engine = "brave".into();    book.settings.synced = true;    // Build 1 mirrored A, B and C as rows at the book's keys; D was removed on another phone since (no row); E was    // added on another phone since (a row the book never held).    from_elsewhere(&h, json!({ "key": A, "label": "Work mail", "home": "https://mail.example/", "stay": true, "hidden": false, "pinned": false, "position": 0, "trackers": true }));    from_elsewhere(&h, json!({ "key": B, "label": "Club", "home": "https://club.example/", "stay": false, "hidden": false, "pinned": false, "position": 1, "trackers": true }));    from_elsewhere(&h, json!({ "key": C, "label": "Bank", "home": "https://ledgerbank.example/", "stay": true, "hidden": true, "pinned": false, "position": 2, "trackers": true }));    from_elsewhere(&h, json!({ "key": E, "label": "News", "home": "https://news.example/", "stay": true, "hidden": false, "pinned": false, "position": 3, "trackers": true }));    let before: Vec<Value> = rows(&h);    old_book(&h, &book);    caught_up(&h, true);    let home = ask(&h, "sites.home", json!({ "unlocked": true }));    let all: Vec<Value> = home["rows"].as_array().unwrap().iter().chain(home["hidden"]["rows"].as_array().into_iter().flatten()).cloned().collect();    let by = |id: &str| all.iter().find(|r| r["id"] == id).cloned().unwrap_or_else(|| panic!("{id} is in the list: {home}"));    // Every site, at its own key: the same sign-in.    for id in [A, B, C, D, E] {        let row = by(id);        assert_eq!(row["store_uuid"].as_str().map(str::to_string), Some(id.to_string()), "{id} keeps its sign-in: {row}");    }    assert_eq!(by(A)["line"], "mail.example · Inbox (4)", "its last page");    assert_eq!(ask(&h, "sites.state", json!({ "id": A }))["blob"], "c3RhdGUtYQ", "its page state");    assert_eq!(by(C)["line"], "ledgerbank.example · Accounts");    assert_eq!(by(E)["label"], "News", "added elsewhere: shown as it is");    // Removed elsewhere since: written into the list at its key, never dropped; he can remove it again.    let now: Vec<Value> = rows(&h);    assert_eq!(now.iter().filter(|r| r["key"] == D).count(), 1, "D a row again: {now:?}");    // Every row he held exactly as before.    let held: Vec<Value> = now.iter().filter(|r| r["key"] != D).cloned().collect();    assert_eq!(held, before, "no row he held changed or erased");    assert!(ask(&h, "sites.stores.gone", json!({}))["stores"].as_array().unwrap().is_empty(), "no sign-in queued for removal");    assert!(home.get("orphans").is_none() && home.get("book_stuck").is_none() && home.get("loading").is_none(), "{home}");    let settings = ask(&h, "sites.settings", json!({}));    let engine = settings["rows"].as_array().unwrap().iter().find(|r| r["id"] == "engine").unwrap().clone();    assert!(engine["choices"].as_array().unwrap().iter().any(|c| c["id"] == "brave" && c["chosen"] == true), "settings moved: {engine}");    assert!(!old_book_left(&h) && set_aside_left(&h), "the book set aside, not deleted");    // Opening again changes nothing.    let again = ask(&h, "sites.home", json!({ "unlocked": true }));    assert_eq!(again["rows"], home["rows"]);    assert_eq!(rows(&h), now);    assert!(ask(&h, "sites.stores.gone", json!({}))["stores"].as_array().unwrap().is_empty());}/// The files carried into a folder are taken in in a fixed order, merged field by field: a site kept only on this/// phone at sign-in keeps the store, last page and state the copy's own file carried for it.#[test]fn carried_files_merge_in_a_fixed_order_field_by_field() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let key = cotton_core::chat::seal::key_from_text(KEY).unwrap();    let folder = crate::phone::sites::local_folder_for_tests(&h.client()).unwrap();    let mut kept = cotton_core::sites::Local::default();    let mut entry = cotton_core::sites::Row { id: A.into(), label: String::new(), home: String::new(), stay: true, hidden: false, last: Some("https://mail.example/inbox".into()), pinned: false, trackers: true, login: None, title: Some("Inbox (4)".into()), state: Some("c3RhdGU".into()), sign_in_once: false, waiting: None, changed_at: 0, store: Some("earlier-store".into()) };    kept.entries.insert(A.into(), entry.clone());    let mut left = cotton_core::sites::Local::default();    entry = cotton_core::sites::Row { label: "Work mail".into(), home: "https://mail.example/".into(), last: None, title: None, state: None, store: None, ..entry };    left.entries.insert(A.into(), entry);    left.only.insert(A.into(), 1024.0);    // Named so that a plain directory order would read the left-here file first.    std::fs::write(folder.join("sites.carried.zz-from.c1"), kept.seal(&key, &[1; 12]).unwrap()).unwrap();    std::fs::write(folder.join("sites.left-here.aa-from.c1"), left.seal(&key, &[2; 12]).unwrap()).unwrap();    let home = ask(&h, "sites.home", json!({}));    let row = home["rows"].as_array().unwrap().iter().find(|r| r["id"] == A).expect("kept here").clone();    assert_eq!(row["label"], "Work mail");    assert_eq!(row["line"], "mail.example · Inbox (4)", "{row}");    assert_eq!(row["store"], "site-earlier-store", "its sign-in");    assert_eq!(ask(&h, "sites.state", json!({ "id": A }))["blob"], "c3RhdGU");    assert!(!folder.join("sites.carried.zz-from.c1").exists() && !folder.join("sites.left-here.aa-from.c1").exists(), "taken in once");}/// A list write while a sign-in finishes deletes only the carried files its own read took in: sites carried here after/// that read stay for the next one (review of SITES ROWS 5, item 1).#[test]fn a_write_racing_a_carry_keeps_the_file_carried_after_its_read() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let key = cotton_core::chat::seal::key_from_text(KEY).unwrap();    let folder = crate::phone::sites::local_folder_for_tests(&h.client()).unwrap();    let (local, read) = super::read_local(&folder, &key).unwrap();    assert!(read.is_empty());    // The sign-in completes between the refresh's read and its write.    let mut left = cotton_core::sites::Local::default();    let row = cotton_core::sites::Row { id: A.into(), label: "Club".into(), home: "https://club.example/".into(), stay: true, hidden: false, last: None, pinned: false, trackers: true, login: None, title: None, state: None, sign_in_once: false, waiting: None, changed_at: 0, store: Some("club-store".into()) };    left.entries.insert(A.into(), row);    left.only.insert(A.into(), 1024.0);    let carried = folder.join("sites.left-here.earlier.c1");    std::fs::write(&carried, left.seal(&key, &[3; 12]).unwrap()).unwrap();    super::write_local(&folder, &key, &local, &read).unwrap();    assert!(carried.exists(), "a file carried after the read is not the write's to delete");    let home = ask(&h, "sites.home", json!({}));    assert!(home["rows"].as_array().unwrap().iter().any(|r| r["id"] == A && r["store"] == "site-club-store"), "taken in by the next read: {home}");}/// A carried file that does not open with this phone's key is kept beside, never deleted (item 3).#[test]fn a_carried_file_under_another_key_is_kept_not_deleted() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let other = [7u8; 32];    let folder = crate::phone::sites::local_folder_for_tests(&h.client()).unwrap();    let mut left = cotton_core::sites::Local::default();    left.only.insert(A.into(), 1024.0);    let carried = folder.join("sites.carried.other-key.c1");    let bytes = left.seal(&other, &[4; 12]).unwrap();    std::fs::write(&carried, &bytes).unwrap();    ask(&h, "sites.add", json!({ "label": "News", "home": "news.example" }));    ask(&h, "sites.home", json!({}));    assert!(!carried.exists());    assert_eq!(std::fs::read(folder.join("sites.carried.other-key.c1.unread")).unwrap(), bytes, "kept whole beside");}/// A carried file that cannot be read now is left as it is and asked again; two that do not open with this key are/// each kept under a name of their own; the list says so once (review of SITES ROWS 6, item 4).#[test]fn unread_files_are_kept_apart_and_said_once() {    use std::os::unix::fs::PermissionsExt as _;    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let folder = crate::phone::sites::local_folder_for_tests(&h.client()).unwrap();    let mut left = cotton_core::sites::Local::default();    left.only.insert(A.into(), 1024.0);    let other = [7u8; 32];    std::fs::write(folder.join("sites.carried.one.c1"), left.seal(&other, &[5; 12]).unwrap()).unwrap();    std::fs::write(folder.join("sites.carried.one.c1.unread"), b"an earlier unread file").unwrap();    let busy = folder.join("sites.carried.two.c1");    std::fs::write(&busy, b"not readable now").unwrap();    std::fs::set_permissions(&busy, std::fs::Permissions::from_mode(0o000)).unwrap();    let home = ask(&h, "sites.home", json!({}));    std::fs::set_permissions(&busy, std::fs::Permissions::from_mode(0o600)).unwrap();    assert!(busy.exists(), "a read error leaves the file for next time");    assert_eq!(std::fs::read(folder.join("sites.carried.one.c1.unread")).unwrap(), b"an earlier unread file", "never written over");    assert!(folder.join("sites.carried.one.c1.unread-2").exists(), "the second kept under its own name");    assert!(home["unread"]["line"].as_str().is_some_and(|l| !l.is_empty()), "{home}");    std::fs::remove_file(&busy).unwrap();    assert!(ask(&h, "sites.home", json!({})).get("unread").is_none(), "said once");}/// A carried file taken in again after a kill (the merged file written, the carried one not yet removed) never brings/// back a site he removed (review of SITES ROWS 6, item 5).#[test]fn a_carried_file_taken_in_again_never_brings_back_a_removed_site() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let key = cotton_core::chat::seal::key_from_text(KEY).unwrap();    let folder = crate::phone::sites::local_folder_for_tests(&h.client()).unwrap();    let mut left = cotton_core::sites::Local::default();    let row = cotton_core::sites::Row { id: A.into(), label: "Club".into(), home: "https://club.example/".into(), stay: true, hidden: false, last: None, pinned: false, trackers: true, login: None, title: None, state: None, sign_in_once: false, waiting: None, changed_at: 0, store: None };    left.entries.insert(A.into(), row);    left.only.insert(A.into(), 1024.0);    let sealed = left.seal(&key, &[6; 12]).unwrap();    std::fs::write(folder.join("sites.left-here.earlier.c1"), &sealed).unwrap();    let (mut local, read) = super::read_local(&folder, &key).unwrap();    assert!(local.only.contains_key(A));    // He removes it; the merged file is written, and the app is killed before the carried file goes.    local.only.remove(A);    local.entries.remove(A);    local.gone.insert(A.into());    super::write_local(&folder, &key, &local, &[]).unwrap();    let _ = read;    let (again, _) = super::read_local(&folder, &key).unwrap();    assert!(!again.only.contains_key(A) && !again.entries.contains_key(A), "removed stays removed");}// ---- SITES NO SWITCH (owner, 27 Nov 2026): sites an earlier build kept only on this phone go into the list/// A site as an earlier build kept it only on this phone: whole, with its sign-in (`store`) and its page.fn kept_only(id: &str, label: &str, store: &str) -> cotton_core::sites::Row {    cotton_core::sites::Row { id: id.into(), label: label.into(), home: format!("https://{}.example/", label.to_lowercase()), stay: true, hidden: false, last: Some(format!("https://{}.example/board", label.to_lowercase())), pinned: false, trackers: true, login: None, title: Some("Board".into()), state: Some("c3RhdGU".into()), sign_in_once: false, waiting: None, changed_at: 0, store: Some(store.into()) }}fn with_only(h: &CottonHandle, rows: &[cotton_core::sites::Row], also: impl FnOnce(&mut cotton_core::sites::Local)) {    let mut local = crate::phone::sites::local_for_tests(&h.client());    for (i, r) in rows.iter().enumerate() {        local.entries.insert(r.id.clone(), r.clone());        local.only.insert(r.id.clone(), 1024.0 * (i as f64 + 1.0));    }    also(&mut local);    crate::phone::sites::write_local_as_for_tests(&h.client(), &local);}/// RULE (NO SWITCH 2): a site kept only here with no row anywhere is made a row at its own key, with its sign-in,/// page and state, and leaves the phone's list in the same turn: it is in one place, never both.#[test]fn a_site_kept_only_here_becomes_a_row_at_its_key() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    with_only(&h, &[kept_only(A, "Club", "club-store")], |_| {});    let home = ask(&h, "sites.home", json!({}));    assert_eq!(labels(&home["rows"]), ["Club"], "shown once: {home}");    assert_eq!(home["rows"][0]["id"], A);    assert_eq!(home["rows"][0]["store"], "site-club-store", "its sign-in");    assert_eq!(home["rows"][0]["line"], "club.example · Board");    assert_eq!(rows(&h).len(), 1);    assert_eq!(row_of(&rows(&h), A)["label"], "Club");    assert!(crate::phone::sites::local_for_tests(&h.client()).only.is_empty(), "out of the phone's list in the same turn");    assert_eq!(ask(&h, "sites.state", json!({ "id": A }))["blob"], "c3RhdGU", "its page state stays here");    // From now on an ordinary row: an edit goes to the row.    ask(&h, "sites.edit", json!({ "id": A, "label": "Chess club" }));    assert_eq!(row_of(&rows(&h), A)["label"], "Chess club");    assert_eq!(rows(&h).len(), 1, "made once");}/// RULE: where a live row for the site still stands, nothing is made: the row is the site, shown once.#[test]fn a_site_kept_only_here_with_its_row_standing_makes_nothing() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    from_elsewhere(&h, json!({ "key": A, "label": "Club", "home": "https://club.example/", "stay": true, "position": 0, "trackers": true }));    let before = updated(&h, A);    with_only(&h, &[kept_only(A, "Club", "club-store")], |_| {});    assert_eq!(labels(&ask(&h, "sites.home", json!({}))["rows"]), ["Club"]);    assert_eq!(rows(&h).len(), 1);    assert_eq!(updated(&h, A), before, "the row is not written");    assert!(crate::phone::sites::local_for_tests(&h.client()).only.is_empty());}/// RULE: a site whose key was removed (a create there is never sent) goes in under the key derived from its own,/// keeping its sign-in.#[test]fn a_site_kept_only_here_at_a_removed_key_goes_in_under_its_derived_key() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    from_elsewhere(&h, json!({ "key": A, "label": "Club", "home": "https://club.example/", "stay": true, "position": 0, "trackers": true }));    removed_elsewhere(&h, A);    with_only(&h, &[kept_only(A, "Club", "club-store")], |_| {});    let home = ask(&h, "sites.home", json!({}));    assert_eq!(labels(&home["rows"]), ["Club"], "{home}");    let derived = super::derived_key(A);    assert_ne!(derived, A);    assert_eq!(super::derived_key(A), derived, "the same every time");    assert_eq!(home["rows"][0]["id"], derived.as_str());    assert_eq!(home["rows"][0]["store"], "site-club-store", "the same sign-in");    assert_eq!(rows(&h).len(), 1);    assert_eq!(labels(&ask(&h, "sites.home", json!({}))["rows"]), ["Club"]);}/// RULE: a real kill between the create and the file write (injected): the next read finds the row standing at the/// same key, makes nothing again, and lets the site go from the phone's list. Both keys: its own and the derived one.#[test]fn killed_between_the_create_and_the_file_write_makes_it_once() {    for removed_before in [false, true] {        let dir = tempfile::tempdir().unwrap();        let h = sites_phone(&dir);        if removed_before {            from_elsewhere(&h, json!({ "key": A, "label": "Club", "home": "https://club.example/", "stay": true, "position": 0, "trackers": true }));            removed_elsewhere(&h, A);        }        with_only(&h, &[kept_only(A, "Club", "club-store")], |_| {});        crate::phone::sites::stop_retire_for_tests(1, true);        // The run dies after the create (the list is still drawn, as after any failed tidy): the file is not written.        assert_eq!(labels(&ask(&h, "sites.home", json!({}))["rows"]), ["Club"], "never twice, even right after the kill");        assert!(crate::phone::sites::local_for_tests(&h.client()).only.contains_key(A), "the file was not written");        assert_eq!(rows(&h).len(), 1, "the row was made");        let home = ask(&h, "sites.home", json!({}));        assert_eq!(labels(&home["rows"]), ["Club"], "{home}");        assert_eq!(rows(&h).len(), 1, "made once ({removed_before})");        assert!(crate::phone::sites::local_for_tests(&h.client()).only.is_empty());        assert_eq!(home["rows"][0]["store"], "site-club-store");    }}/// RULE (NO SWITCH 2, item 5): a site whose row is refused stays in the phone's list, said once in the log, and/// nothing else stops: the other site goes in, every later read and edit works, and it goes in once it is taken.#[test]fn a_refused_site_stays_here_and_stops_nothing() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    with_only(&h, &[kept_only(A, "Club", "club-store"), kept_only(B, "Bank", "bank-store")], |_| {});    crate::phone::sites::refuse_create_for_tests(Some(B));    let home = ask(&h, "sites.home", json!({}));    let mut shown_now = labels(&home["rows"]);    shown_now.sort();    assert_eq!(shown_now, ["Bank", "Club"], "both shown, each once: {home}");    let local = crate::phone::sites::local_for_tests(&h.client());    assert_eq!(local.only.keys().collect::<Vec<_>>(), [B], "only the refused one stays here");    assert_eq!(rows(&h).len(), 1, "Club went in");    let news = id(&ask(&h, "sites.add", json!({ "label": "News", "home": "news.example" })));    ask(&h, "sites.edit", json!({ "id": news, "label": "Daily news" }));    ask(&h, "sites.edit", json!({ "id": A, "label": "Chess club" }));    let mut now = shown(&h);    now.sort();    assert_eq!(now, ["Bank", "Chess club", "Daily news"]);    crate::phone::sites::refuse_create_for_tests(None);    ask(&h, "sites.home", json!({}));    assert!(crate::phone::sites::local_for_tests(&h.client()).only.is_empty(), "taken at the next read");    assert_eq!(rows(&h).len(), 3);    assert_eq!(row_of(&rows(&h), B)["label"], "Bank");}/// RULE: the copy switched part way (a sign-out, a database switch): nothing more is made, and the rest goes in once/// the copy is back.#[test]fn a_database_switch_part_way_makes_nothing_more() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    with_only(&h, &[kept_only(A, "Club", "club-store"), kept_only(B, "Bank", "bank-store")], |_| {});    crate::phone::sites::stop_retire_for_tests(1, false);    ask(&h, "sites.home", json!({}));    assert_eq!(rows(&h).len(), 1, "one made before the switch");    let local = crate::phone::sites::local_for_tests(&h.client());    assert_eq!(local.only.len(), 1, "the other waits: {:?}", local.only);    crate::phone::sites::go_on_retire_for_tests();    let home = ask(&h, "sites.home", json!({}));    assert_eq!(rows(&h).len(), 2);    assert_eq!(labels(&home["rows"]).len(), 2, "{home}");    assert!(crate::phone::sites::local_for_tests(&h.client()).only.is_empty());}/// RULE: nothing is decided while the pull is behind: a row it would bring may be the site's.#[test]fn a_site_kept_only_here_waits_for_the_pull() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    caught_up(&h, false);    with_only(&h, &[kept_only(A, "Club", "club-store")], |_| {});    assert_eq!(labels(&ask(&h, "sites.home", json!({}))["rows"]), ["Club"], "still shown");    assert!(rows(&h).is_empty(), "nothing made while behind");    caught_up(&h, true);    ask(&h, "sites.home", json!({}));    assert_eq!(rows(&h).len(), 1);}/// RULE (ROWS 8, low): Sites' own file that does not open is kept beside under a numbered name, never written over.#[test]fn an_unreadable_own_file_is_kept_under_a_numbered_name() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let folder = crate::phone::sites::local_folder_for_tests(&h.client()).unwrap();    std::fs::write(folder.join("sites.local.c1"), b"first unreadable").unwrap();    ask(&h, "sites.home", json!({}));    std::fs::write(folder.join("sites.local.c1"), b"second unreadable").unwrap();    ask(&h, "sites.home", json!({}));    assert_eq!(std::fs::read(folder.join("sites.local.c1.unreadable")).unwrap(), b"first unreadable");    assert_eq!(std::fs::read(folder.join("sites.local.c1.unreadable-2")).unwrap(), b"second unreadable");}/// RULE (ROWS 8, item 3): owed carries are one per pair of copies, each cleared only by its own carry: a carry that/// goes between two other copies never clears an earlier failure, and a second failure never writes over the first.#[test]fn two_owed_carries_are_each_tried_until_their_own_goes() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let layout = h.client().layout().clone();    let folder_of = |db: &str| {        let folder = layout.replica(db).parent().unwrap().to_path_buf();        std::fs::create_dir_all(&folder).unwrap();        folder    };    let (a, b, c, d, e, f) = ("db-invented-a", "db-invented-b", "db-invented-c", "db-invented-d", "db-invented-e", "db-invented-f");    for from in [a, c, e] {        std::fs::write(folder_of(from).join("sites.local.c1"), b"kept").unwrap();    }    for to in [b, d, f] {        folder_of(to);    }    crate::phone::sites::carry_fails_from_for_tests(&folder_of(a));    crate::phone::sites::carry_fails_from_for_tests(&folder_of(e));    assert!(super::carry(&layout, a, b).is_err());    assert!(super::carry(&layout, e, f).is_err(), "a second failure");    assert!(super::carry(&layout, c, d).is_ok(), "another pair goes");    let owed = super::carries_owed(&layout);    assert_eq!(owed, vec![(a.to_string(), b.to_string()), (e.to_string(), f.to_string())], "both still owed");    crate::phone::sites::carry_goes_from_for_tests(&folder_of(a));    assert!(super::retry_carry(&layout, None));    assert_eq!(super::carries_owed(&layout), vec![(e.to_string(), f.to_string())], "only its own cleared");    assert!(folder_of(b).join("sites.carried.db-invented-a.c1").exists());    crate::phone::sites::carry_goes_from_for_tests(&folder_of(e));    assert!(super::retry_carry(&layout, None));    assert!(super::carries_owed(&layout).is_empty());}/// RULE (review of SITES NO SWITCH, item 4): a carry chain a to b, then b to c: the owed (a, b) carry whose b is gone/// is redirected to the copy now in use, and goes there; it never fails at every launch against a folder gone.#[test]fn an_owed_carry_whose_copy_is_gone_goes_to_the_copy_in_use() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let layout = h.client().layout().clone();    let folder_of = |db: &str| layout.replica(db).parent().unwrap().to_path_buf();    let (a, b, c) = ("db-invented-chain-a", "db-invented-chain-b", "db-invented-chain-c");    for db in [a, b, c] {        std::fs::create_dir_all(folder_of(db)).unwrap();    }    std::fs::write(folder_of(a).join("sites.local.c1"), b"kept in a").unwrap();    std::fs::write(folder_of(b).join("sites.local.c1"), b"kept in b").unwrap();    crate::phone::sites::carry_fails_from_for_tests(&folder_of(a));    assert!(super::carry(&layout, a, b).is_err());    assert_eq!(super::carries_owed(&layout), vec![(a.to_string(), b.to_string())]);    // b goes whole into c, and its folder with it.    assert!(super::carry(&layout, b, c).is_ok());    crate::phone::personal_object::remove_database_folder(&layout, b, cotton_client::copy_keep::Ending::keep_into("a local database was adopted into the signed-in copy", c, &[]));    assert!(!folder_of(b).is_dir());    crate::phone::sites::carry_goes_from_for_tests(&folder_of(a));    assert!(!super::retry_carry(&layout, None), "with no copy in use it waits");    assert_eq!(super::carries_owed(&layout), vec![(a.to_string(), b.to_string())]);    assert!(super::retry_carry(&layout, Some(c)), "redirected to the copy in use");    assert!(super::carries_owed(&layout).is_empty(), "owed no more");    assert!(folder_of(c).join("sites.carried.db-invented-chain-a.c1").exists(), "a's file is in c");    assert!(folder_of(c).join("sites.carried.db-invented-chain-b.c1").exists(), "and b's");    assert!(!folder_of(a).is_dir(), "a's folder goes once carried");}/// RULE (review of NO SWITCH 2, item 3): a run killed after an owed carry went but before it was forgotten: still owed,/// the earlier copy's folder kept, and the next try carries it and lets it go. Nothing is stranded at any point.#[test]fn a_kill_after_an_owed_carry_strands_nothing() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let layout = h.client().layout().clone();    let folder_of = |db: &str| layout.replica(db).parent().unwrap().to_path_buf();    let (a, b, c) = ("db-invented-kill-a", "db-invented-kill-b", "db-invented-kill-c");    for db in [a, b, c] {        std::fs::create_dir_all(folder_of(db)).unwrap();    }    std::fs::write(folder_of(a).join("sites.local.c1"), b"kept in a").unwrap();    crate::phone::sites::carry_fails_from_for_tests(&folder_of(a));    assert!(super::carry(&layout, a, b).is_err());    crate::phone::sites::carry_goes_from_for_tests(&folder_of(a));    // b went meanwhile: the carry is redirected to c, and the run dies right after it.    crate::phone::personal_object::remove_database_folder(&layout, b, cotton_client::copy_keep::Ending::keep_into("a local database was adopted into the signed-in copy", c, &[]));    crate::phone::sites::kill_after_carry_for_tests();    super::retry_carry(&layout, Some(c));    assert!(folder_of(c).join("sites.carried.db-invented-kill-a.c1").exists(), "carried");    assert_eq!(super::carries_owed(&layout), vec![(a.to_string(), b.to_string())], "still owed");    assert!(folder_of(a).join("sites.local.c1").exists(), "a's folder kept");    assert!(super::retry_carry(&layout, Some(c)));    assert!(super::carries_owed(&layout).is_empty());    assert!(!folder_of(a).is_dir(), "let go once carried and forgotten");}/// RULE (review of NO SWITCH 2, item 4): a row at the key derived from a site this phone holds a sign-in for is drawn/// with that sign-in, never asking "Sign in once".#[test]fn a_row_at_a_derived_key_reuses_the_sign_in_held_here() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let mut local = crate::phone::sites::local_for_tests(&h.client());    local.entries.insert(A.into(), kept_only(A, "Club", "club-store"));    crate::phone::sites::write_local_as_for_tests(&h.client(), &local);    let derived = super::derived_key(A);    from_elsewhere(&h, json!({ "key": derived, "label": "Club", "home": "https://club.example/", "stay": true, "position": 0, "trackers": true }));    let home = ask(&h, "sites.home", json!({}));    let club = home["rows"].as_array().unwrap().iter().find(|r| r["id"] == derived.as_str()).unwrap_or_else(|| panic!("{home}")).clone();    assert_eq!(club["store"], "site-club-store", "the sign-in held here");    assert_eq!(club["sign_in_once"], false, "{club}");}/// RULE (review of NO SWITCH 2, item 6): a signed-out copy's stale left-here file is read once, at the sign-in that/// carries it, honouring what he removed in that copy, and deleted there so no later sign-in reads it again.#[test]fn a_stale_left_here_file_is_read_once_honouring_that_copys_removals() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let key = cotton_core::chat::seal::key_from_text(KEY).unwrap();    let layout = h.client().layout().clone();    let current = h.client().current_database().unwrap();    let old = layout.replica("db-invented-signed-out").parent().unwrap().to_path_buf();    std::fs::create_dir_all(&old).unwrap();    let mut own = cotton_core::sites::Local::default();    own.gone.insert(B.into());    std::fs::write(old.join("sites.local.c1"), own.seal(&key, &[5; 12]).unwrap()).unwrap();    let mut left = cotton_core::sites::Local::default();    for (k, label) in [(A, "Club"), (B, "Bank")] {        left.entries.insert(k.into(), kept_only(k, label, &format!("{}-store", label.to_lowercase())));        left.only.insert(k.into(), 1024.0);    }    std::fs::write(old.join("sites.left-here.c1"), left.seal(&key, &[6; 12]).unwrap()).unwrap();    assert!(super::carry(&layout, "db-invented-signed-out", &current).is_ok());    assert!(!old.join("sites.left-here.c1").exists(), "deleted where it stood once carried");    let mut now = shown(&h);    now.sort();    assert_eq!(now, ["Club"], "Bank was removed in that copy");    assert_eq!(rows(&h).len(), 1);    assert!(super::carry(&layout, "db-invented-signed-out", &current).is_ok());    assert_eq!(shown(&h), ["Club"], "not read again");}/// RULE (review of NO SWITCH 3): a site removed in one carried copy never comes back from another carried copy,/// whichever is read first: every carried removed list is taken before any entry.#[test]fn a_site_removed_in_one_carried_copy_never_comes_back_from_another() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    let key = cotton_core::chat::seal::key_from_text(KEY).unwrap();    let folder = crate::phone::sites::local_folder_for_tests(&h.client()).unwrap();    let mut a = cotton_core::sites::Local::default();    a.entries.insert(A.into(), kept_only(A, "Club", "club-store"));    a.only.insert(A.into(), 1024.0);    let mut b = cotton_core::sites::Local::default();    b.gone.insert(A.into());    // Named so the copy holding the site is read before the copy that removed it.    std::fs::write(folder.join("sites.carried.aa-copy.c1"), a.seal(&key, &[7; 12]).unwrap()).unwrap();    std::fs::write(folder.join("sites.carried.bb-copy.c1"), b.seal(&key, &[8; 12]).unwrap()).unwrap();    assert!(shown(&h).is_empty(), "removed in copy b: never back from copy a");    assert!(rows(&h).is_empty(), "nothing made");    let local = crate::phone::sites::local_for_tests(&h.client());    assert!(!local.only.contains_key(A) && !local.entries.contains_key(A));}/// RULE (review of NO SWITCH 3): a site still here at a key whose row came from another phone, before caught up:/// nothing is queued, the stale entry leaves `only`, and the row is drawn with the sign-in kept here.#[test]fn a_stale_entry_at_a_row_from_another_phone_queues_nothing_and_keeps_its_sign_in() {    let dir = tempfile::tempdir().unwrap();    let h = sites_phone(&dir);    from_elsewhere(&h, json!({ "key": A, "label": "Chess club", "home": "https://club.example/", "stay": true, "position": 0, "trackers": true }));    let before = updated(&h, A);    caught_up(&h, false);    with_only(&h, &[kept_only(A, "Club", "club-store")], |_| {});    let home = ask(&h, "sites.home", json!({}));    assert_eq!(labels(&home["rows"]), ["Chess club"], "the row is the site, shown once: {home}");    assert_eq!(home["rows"][0]["store"], "site-club-store", "with the sign-in kept here");    assert_eq!(home["rows"][0]["sign_in_once"], false);    assert!(crate::phone::sites::local_for_tests(&h.client()).only.is_empty(), "the stale entry is gone");    assert_eq!(updated(&h, A), before, "nothing written to the row");    assert_eq!(rows(&h).len(), 1);    // An edit now goes to the row.    ask(&h, "sites.edit", json!({ "id": A, "label": "Chess club B" }));    assert_eq!(row_of(&rows(&h), A)["label"], "Chess club B");}