Cotton code
373 lines · 26.3 KB · RustRaw
//! The one Share sheet over a scripted object: its people are the Circle (both accepted first, those waiting after//! and not pickable), nothing is picked for him, the plan says what will happen, and Secrets gives only to someone//! whose safety number was compared. Every number and name is invented.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange};use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use super::{can, over, App};use crate::handle::CottonHandle;use crate::phone::circle::Member;use crate::phone::passwords::tests::phone;use crate::phone::personal_object::ObjectDoor;const ASHA: &str = "+15550100021";const RAVI: &str = "+15550100022";const LATA: &str = "+15550100023";fn with_door(handle: &CottonHandle, replies: impl IntoIterator<Item = Reply>) -> Arc<ScriptedExchange> {    let exchange = ScriptedExchange::new(replies);    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: exchange.clone(), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".to_string() };    handle.client().set_object_door(Some(Arc::new(door)));    exchange}fn contact(handle: &CottonHandle, id: &str, name: &str, number: &str) {    let ws = crate::phone::cotton_chat::read(&handle.client(), "test.ws", |ctx| Ok(json!(ctx.workspace_id))).unwrap().as_str().unwrap().to_string();    let t = |s: &str| SqlValue::Text(s.to_string());    let run = |sql: &str, params: &[SqlValue]| handle.client().with_writer(|r| r.driver.run(sql, params).map(|_| ()).map_err(|e| e.to_string())).expect(sql);    run("INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, '2026-11-01', '2026-11-01')", &[t(id), t(&ws), t(name)]);    run("INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, position, created_at, updated_at) VALUES (?, ?, ?, 'phone', ?, ?, 'manual', 0, '2026-11-01', '2026-11-01')", &[t(&format!("{id}-h")), t(&ws), t(id), t(number), t(number)]);}fn circle() -> Reply {    Reply::ok(&json!({ "people": [{ "number": ASHA, "name": null, "waiting": false }, { "number": RAVI, "name": null, "waiting": false }, { "number": LATA, "name": null, "waiting": true }], "asking": [], "blocked": [] }).to_string())}fn album() -> Value {    json!({ "app": "albums", "thing": { "kind": "album", "name": "Mum's 70th" } })}// RULE: the sheet's people are the Circle, both-accepted first then waiting (can false, said why); nothing is on;// Albums offers its one role and its foot; the button names no one until someone is picked.#[test]fn the_sheet_lists_the_circle_and_picks_no_one() {    let (_dir, handle) = phone();    contact(&handle, "p-asha", "Asha Menon", ASHA);    contact(&handle, "p-ravi", "Ravi Shah", RAVI);    contact(&handle, "p-lata", "Lata Kumar", LATA);    with_door(&handle, [circle()]);    let sheet = over(&handle, "share.sheet", &album()).unwrap();    assert_eq!(sheet["title"], "Share \u{201c}Mum's 70th\u{201d}");    let rows: Vec<(String, bool, bool)> = sheet["people"].as_array().unwrap().iter().map(|p| (p["words"].as_str().unwrap().to_string(), p["can"].as_bool().unwrap(), p["on"].as_bool().unwrap())).collect();    assert_eq!(rows, [("Asha Menon".into(), true, false), ("Ravi Shah".into(), true, false), ("Lata Kumar".into(), false, false)]);    assert_eq!(sheet["people"][2]["detail"], "Waiting for Lata to accept you");    assert_eq!(sheet["roles"], json!([{ "id": "add", "words": "See and add", "on": true }]));    assert_eq!(sheet["until"], Value::Null);    assert!(sheet.get("link").is_none(), "a new album has no link yet");    assert_eq!(sheet["go"]["words"], "Pick someone");    assert_eq!(sheet["go"]["call"]["method"], "share.do");}// RULE: the plan says what will happen to whom and names the button; picking someone waiting is refused in words.#[test]fn the_plan_says_what_happens_and_refuses_someone_waiting() {    let (_dir, handle) = phone();    contact(&handle, "p-asha", "Asha Menon", ASHA);    contact(&handle, "p-ravi", "Ravi Shah", RAVI);    contact(&handle, "p-lata", "Lata Kumar", LATA);    with_door(&handle, [circle(), circle()]);    let mut request = album();    request["people"] = json!(["p-asha", RAVI]);    request["role"] = json!("add");    let plan = over(&handle, "share.plan", &request).unwrap();    assert_eq!(plan["lines"], json!(["Asha and Ravi can see the photos and add their own. They get a notice."]));    assert_eq!(plan["go"]["words"], "Share with 2");    assert_eq!(plan["go"]["call"]["request"]["people"], json!(["p-asha", RAVI]));    request["people"] = json!(["p-lata"]);    assert_eq!(over(&handle, "share.plan", &request).unwrap()["error"], "Waiting for Lata to accept you");}// RULE: Secrets gives a copy only to someone whose safety number was compared: anyone else is not pickable, said why,// with the check one tap away; someone waiting is not pickable either.#[test]fn secrets_gives_only_to_someone_checked() {    let app = App::Secrets { id: "s-1".into() };    let member = |accepted: bool, checked: bool| Member { person: Some("p-priya".into()), name: "Priya".into(), number: ASHA.into(), accepted, checked };    assert_eq!(can(&app, &member(true, true)).0, true);    let (ok, detail, call) = can(&app, &member(true, false));    assert!(!ok);    assert_eq!(detail.as_deref(), Some("Not checked: you check Priya's safety number first"));    assert_eq!(call, Some(json!({ "method": "circle.check", "request": { "person": "p-priya" } })));    assert_eq!(can(&app, &member(false, false)).1.as_deref(), Some("Waiting for Priya to accept you"));    // Albums asks no check: being in the Circle is enough.    assert!(can(&App::Albums { space: None, album: None, name: Some("x".into()) }, &member(true, false)).0);}// RULE: an app with no sheet, a sheet with nothing named, and signing out are each said in words.#[test]fn refusals_are_said_in_words() {    let (_dir, handle) = phone();    assert_eq!(over(&handle, "share.sheet", &album()).unwrap()["signedOut"]["title"], "Sign in to share");    with_door(&handle, []);    assert_eq!(over(&handle, "share.sheet", &json!({ "app": "post", "thing": { "kind": "mail", "id": "m" } })).unwrap()["error"], "This can't be shared from here yet.");    assert_eq!(over(&handle, "share.sheet", &json!({ "app": "albums", "thing": { "kind": "album" } })).unwrap()["error"], "Name the album to share.");    assert_eq!(over(&handle, "share.role", &json!({ "app": "albums", "thing": { "kind": "album", "space": "sp", "album": "a" }, "person": ASHA, "role": "see" })).unwrap()["error"], "Albums shares one way: they can see and add.");}// ── Days: one event, shared by inviting ──────────────────────────────────fn hold_key(handle: &CottonHandle) -> String {    let mut bytes = [0u8; 32];    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut bytes);    let client = handle.client();    let database = client.current_database().expect("a database");    client.data_keys().hold(&database, &cotton_core::seal::DataKey::from_bytes(bytes));    crate::phone::send_seal::sharing(&client).expect("a sharing key").1}// RULE (CONTACT KINDS 3): Days shares one event: the sheet names it and offers one role; share.do puts the picked// Circle member on its guest list and the invitation goes sealed to their phone at once; share.with shows them// waiting for an answer; share.stop takes them off, keeping everyone else on it.#[test]fn days_shares_an_event_by_inviting_from_the_circle() {    use crate::phone::days::tests::{ask, phone, zone, TODAY, ZONE};    let dir = tempfile::TempDir::new().unwrap();    let handle = phone(&dir);    zone(&handle);    hold_key(&handle);    let id = ask(&handle, "days.add", json!({ "words": "Dinner Saturday 7pm", "timezone": ZONE, "today": TODAY, "where": "days" }))["id"].as_str().unwrap().to_string();    let thing = json!({ "kind": "event", "id": id });    with_door(&handle, [circle()]);    let sheet = over(&handle, "share.sheet", &json!({ "app": "days", "thing": thing })).unwrap();    assert_eq!(sheet["title"], "Share \u{201c}Dinner\u{201d}", "{sheet}");    assert_eq!(sheet["roles"], json!([{ "id": "invite", "words": "Invited", "on": true }]));    assert_eq!(sheet["go"]["call"]["request"]["role"], "invite");    assert!(sheet["people"].as_array().unwrap().iter().all(|p| p["has"] == false));    let other_dir = tempfile::TempDir::new().unwrap();    let other_key = hold_key(&phone(&other_dir));    let ok = || Reply::ok(r#"{"ok":true}"#);    let out = with_door(&handle, [circle(), ok(), Reply::ok(r#"{"notes":[]}"#), Reply::ok(r#"{"available":true,"accounts":[]}"#), Reply::ok(&json!({ "key": other_key }).to_string()), ok(), ok(), Reply::ok(r#"{"held":[]}"#)]);    let done = over(&handle, "share.do", &json!({ "app": "days", "thing": thing, "people": [ASHA], "role": "invite", "timezone": ZONE })).unwrap();    assert!(done["error"].is_null(), "{done}");    let paths: Vec<String> = out.seen().iter().map(|s| s.path.clone()).collect();    assert!(paths.iter().any(|p| p == "/v1/invite/send"), "{paths:?}");    let rows = done["with"]["rows"].as_array().unwrap();    assert_eq!(rows.len(), 2, "{done}");    assert_eq!(rows[1]["number"], ASHA);    assert_eq!(rows[1]["detail"], "Invited, no answer yet");    assert_eq!(rows[1]["acts"][0]["call"]["method"], "share.stop");    let item = ask(&handle, "days.item", json!({ "table": "event", "id": id, "timezone": ZONE, "today": TODAY }));    assert_eq!(item["people"]["rows"].as_array().unwrap().iter().filter(|r| r["via"] == "cotton").count(), 1, "{item}");    // A second person keeps the first on the list.    with_door(&handle, [circle()]);    let both = over(&handle, "share.do", &json!({ "app": "days", "thing": thing, "people": [RAVI], "role": "invite", "timezone": ZONE })).unwrap();    assert_eq!(both["with"]["rows"].as_array().unwrap().len(), 3, "{both}");    assert_eq!(over(&handle, "share.role", &json!({ "app": "days", "thing": thing, "person": ASHA, "role": "see" })).unwrap()["error"], "Days shares one way: they're invited and answer.");    with_door(&handle, []);    let stopped = over(&handle, "share.stop", &json!({ "app": "days", "thing": thing, "person": ASHA, "timezone": ZONE })).unwrap();    let left: Vec<&Value> = stopped["rows"].as_array().unwrap().iter().skip(1).map(|r| &r["number"]).collect();    assert_eq!(left, [&json!(RAVI)], "{stopped}");    assert_eq!(over(&handle, "share.sheet", &json!({ "app": "days", "thing": { "kind": "event" } })).unwrap()["error"], "Pick the event to share.");}// ── Cinemas: a film list, shared as a shared list ───────────────────────const ME: &str = "+15550100020";fn cinemas_phone() -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let manifest = json!({        "genesis": "personal", "flavour": "cinemas", "name": "Cotton Cinemas", "ground": "velvet",        "databases": "single", "database": "personal", "fan": {"home": false, "tools": false, "opens": "cinemas"}, "kit": "cinemas",    });    let handle = CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(manifest),    })    .expect("an open core");    crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started");    (dir, handle)}fn film(handle: &CottonHandle, title: &str) -> String {    let data = json!({ "title": title, "kind": "film", "status": "want_to_watch", "year": "1999" }).as_object().unwrap().clone();    let answer = handle.client().write_rows("test.cinemas", &mut |ctx| Ok(json!({ "id": crate::phone::songs::made(ctx, "film", data.clone())? }))).expect("made");    crate::authoring::own_answer(answer)["id"].as_str().unwrap().to_string()}/// The list as the object answers who is on it (the sheet reads only its members and item ids).fn standing(members: &[&str], items: &[&str]) -> Reply {    let members: serde_json::Map<String, Value> = members.iter().map(|n| (n.to_string(), json!("k"))).collect();    let items: serde_json::Map<String, Value> = items.iter().map(|i| (i.to_string(), json!("sealed"))).collect();    Reply::ok(&json!({ "me": ME, "owner": ME, "id": "x", "state": { "membership": { "members": members }, "items": items } }).to_string())}// RULE (CONTACT KINDS 3; coordinator 28 Nov: Cinemas on shared lists): the first share founds the list with the// people picked and every title on it in one post, sealed (no title readable in what is posted); share.with shows who// sees it; share.stop takes one off with a new key. Words and Sites say plainly that they can't share yet.#[test]fn cinemas_shares_a_film_list_as_a_shared_list() {    let (_dir, handle) = cinemas_phone();    hold_key(&handle);    let (ferry, salt) = (film(&handle, "Night Ferry"), film(&handle, "The Salt Road"));    let made = crate::methods::dispatch(&handle, "groups.create", &json!({ "table": "film", "name": "Rainy Sundays", "records": [ferry, salt] })).unwrap();    let id = made.pointer("/group/id").or_else(|| made.get("id")).and_then(Value::as_str).unwrap().to_string();    let thing = json!({ "kind": "list", "id": id });    let no_list = || Reply::json(404, r#"{"code":"no_list","message":"That list is not there."}"#);    with_door(&handle, [circle(), no_list()]);    let sheet = over(&handle, "share.sheet", &json!({ "app": "cinemas", "thing": thing })).unwrap();    assert_eq!(sheet["title"], "Share \u{201c}Rainy Sundays\u{201d}", "{sheet}");    assert_eq!(sheet["roles"], json!([{ "id": "see", "words": "See the list", "on": true }]));    let (_other_dir, other) = cinemas_phone();    let asha_key = hold_key(&other);    let ok = || Reply::ok(r#"{"ok":true}"#);    let out = with_door(&handle, [circle(), ok(), Reply::ok(r#"{"notes":[]}"#), no_list(), Reply::ok(&json!({ "key": asha_key, "me": ME }).to_string()), Reply::ok(r#"{"notes":[]}"#), ok(), ok(), standing(&[ME, ASHA], &[&ferry, &salt])]);    let done = over(&handle, "share.do", &json!({ "app": "cinemas", "thing": thing, "people": [ASHA], "role": "see" })).unwrap();    assert!(done["error"].is_null(), "{done} {:?}", out.seen().iter().map(|s| s.path.clone()).collect::<Vec<_>>());    let posted = out.seen().into_iter().find(|s| s.path == "/v1/shared/lists").expect("the list posted");    let posted: Value = serde_json::from_slice(&posted.body).unwrap();    assert!(posted["id"].as_str().unwrap().starts_with("cinemas-"));    assert!(posted["state"]["membership"]["members"].get(ASHA).is_some());    assert!(posted["state"]["items"].get(&ferry).is_some() && posted["state"]["items"].get(&salt).is_some(), "{posted}");    assert!(!posted.to_string().contains("Night Ferry"), "a title went out readable");    let rows = done["with"]["rows"].as_array().unwrap();    assert_eq!((rows.len(), rows[1]["number"].clone(), rows[1]["detail"].clone()), (2, json!(ASHA), json!("Sees the list")));    // A title put on the list afterwards reaches them with no share again: the list read, the title sealed and posted.    let third = film(&handle, "Monsoon Ferry");    let live = |state: &Value| Reply::ok(&json!({ "me": ME, "owner": ME, "id": posted["id"], "state": state }).to_string());    let out = with_door(&handle, [live(&posted["state"]), live(&posted["state"]), ok()]);    crate::methods::dispatch(&handle, "groups.update", &json!({ "id": id, "add": [third] })).unwrap();    let put: Value = serde_json::from_slice(&out.seen().into_iter().find(|s| s.path == "/v1/shared/list/item").expect("the new title posted").body).unwrap();    assert_eq!(put["item"], json!(third));    assert!(!put.to_string().contains("Monsoon"), "a title went out readable");    // A list never shared asks once and sends nothing.    let quiet = crate::methods::dispatch(&handle, "groups.create", &json!({ "table": "film", "name": "Quiet", "records": [ferry] })).unwrap();    let quiet = quiet.pointer("/group/id").or_else(|| quiet.get("id")).and_then(Value::as_str).unwrap().to_string();    let out = with_door(&handle, [no_list()]);    crate::methods::dispatch(&handle, "groups.update", &json!({ "id": quiet, "add": [salt] })).unwrap();    assert_eq!(out.seen().len(), 1);    // Stop: the list read where it lives, Asha taken off with a new key, the state posted.    let live = Reply::ok(&json!({ "me": ME, "owner": ME, "id": posted["id"], "state": posted["state"] }).to_string());    let live_again = Reply::ok(&json!({ "me": ME, "owner": ME, "id": posted["id"], "state": posted["state"] }).to_string());    let out = with_door(&handle, [live, live_again, ok(), standing(&[ME], &[&ferry, &salt])]);    let stopped = over(&handle, "share.stop", &json!({ "app": "cinemas", "thing": thing, "person": ASHA })).unwrap();    assert!(stopped["error"].is_null(), "{stopped} {:?}", out.seen().iter().map(|s| s.path.clone()).collect::<Vec<_>>());    let state: Value = serde_json::from_slice(&out.seen().into_iter().find(|s| s.path == "/v1/shared/list/state").expect("the new state").body).unwrap();    assert!(state["state"]["membership"]["members"].get(ASHA).is_none());    assert_eq!(stopped["rows"].as_array().unwrap().len(), 1);    for app in ["words", "sites"] {        let said = over(&handle, "share.sheet", &json!({ "app": app, "thing": { "kind": "note", "id": "n" } })).unwrap();        assert!(said["error"].as_str().unwrap().ends_with("can't share yet. It's coming."), "{said}");    }}// RULE (CIRCLE GAPS 2): on a member's phone a Cinemas list shared with him stands on Cinemas home under its own line// (as last read: home never waits on the network), opens to who shared it, the list's name and its titles (sealed// to him, opened here), and Leave takes him off the list where it lives.#[test]fn a_cinemas_list_shared_with_him_is_listed_opened_and_left() {    let (_dir, handle) = cinemas_phone();    hold_key(&handle);    let (ferry, salt) = (film(&handle, "Night Ferry"), film(&handle, "The Salt Road"));    let made = crate::methods::dispatch(&handle, "groups.create", &json!({ "table": "film", "name": "Rainy Sundays", "records": [ferry, salt] })).unwrap();    let id = made.pointer("/group/id").or_else(|| made.get("id")).and_then(Value::as_str).unwrap().to_string();    let thing = json!({ "kind": "list", "id": id });    let no_list = || Reply::json(404, r#"{"code":"no_list","message":"That list is not there."}"#);    let ok = || Reply::ok(r#"{"ok":true}"#);    let (_other_dir, other) = cinemas_phone();    let asha_key = hold_key(&other);    let out = with_door(&handle, [circle(), ok(), Reply::ok(r#"{"notes":[]}"#), no_list(), Reply::ok(&json!({ "key": asha_key, "me": ME }).to_string()), Reply::ok(r#"{"notes":[]}"#), ok(), ok(), standing(&[ME, ASHA], &[&ferry, &salt])]);    over(&handle, "share.do", &json!({ "app": "cinemas", "thing": thing, "people": [ASHA], "role": "see" })).unwrap();    let posted: Value = serde_json::from_slice(&out.seen().into_iter().find(|s| s.path == "/v1/shared/lists").expect("the list posted").body).unwrap();    let list = posted["id"].as_str().unwrap().to_string();    assert!(!posted.to_string().contains("Rainy"), "the list's name went out readable");    // Asha's phone: the founder is one of her contacts.    other.client().write("create_person", json!({ "fullName": "Mira Example", "phones": [ME] }).as_object().unwrap()).expect("create_person");    let lists = || Reply::ok(&json!({ "me": ASHA, "lists": [{ "owner": ME, "id": list }, { "owner": ASHA, "id": "cinemas-hers" }, { "owner": ME, "id": "groceries" }] }).to_string());    let live = || Reply::ok(&json!({ "me": ASHA, "owner": ME, "id": list, "state": posted["state"] }).to_string());    let home = crate::methods::dispatch(&other, "cinemas.home", &json!({})).unwrap();    assert!(home["received"].is_null(), "nothing read yet: {}", home["received"]);    with_door(&other, [lists(), live()]);    super::super::cinemas_shared::refresh_now(&other.client()).unwrap();    let home = crate::methods::dispatch(&other, "cinemas.home", &json!({})).unwrap();    let line = &home["received"];    assert_eq!(line["title"], "Shared with you", "{line}");    assert_eq!(line["rows"].as_array().unwrap().len(), 1, "only a Cinemas list someone else made: {line}");    assert_eq!(line["rows"][0]["words"], "Rainy Sundays");    assert_eq!(line["rows"][0]["detail"], "From Mira Example · 2 titles");    assert_eq!(line["rows"][0]["call"], json!({ "method": "cinemas.shared", "request": { "owner": ME, "id": list } }));    with_door(&other, [live()]);    let opened = crate::methods::dispatch(&other, "cinemas.shared", &json!({ "owner": ME, "id": list })).unwrap();    assert_eq!(opened["title"], "Rainy Sundays");    assert_eq!(opened["from"], json!({ "number": ME, "name": "Mira Example" }));    let mut titles: Vec<&str> = opened["items"].as_array().unwrap().iter().map(|i| i["title"].as_str().unwrap()).collect();    titles.sort();    assert_eq!(titles, ["Night Ferry", "The Salt Road"]);    assert_eq!(opened["leave"]["call"]["method"], "cinemas.shared.leave");    assert_eq!(opened["leave"]["red"], true);    let out = with_door(&other, [lists(), live(), ok()]);    let left = crate::methods::dispatch(&other, "cinemas.shared.leave", &json!({ "owner": ME, "id": list })).unwrap();    assert_eq!(left["said"], "You left the list");    let asked: Value = serde_json::from_slice(&out.seen().into_iter().find(|s| s.path == "/v1/shared/list/item").expect("the ask to leave").body).unwrap();    assert_eq!((asked["owner"].clone(), asked["item"].clone()), (json!(ME), json!(format!("leave:{ASHA}"))));    assert!(crate::methods::dispatch(&other, "cinemas.home", &json!({})).unwrap()["received"].is_null(), "gone from home at once");    // The founder's phone, reading who sees the list, takes her off with a new key and takes the ask away.    let mut items = posted["state"]["items"].clone();    items[format!("leave:{ASHA}")] = asked["sealed"].clone();    let mut asking = posted["state"].clone();    asking["items"] = items;    let founder_live = |state: &Value| Reply::ok(&json!({ "me": ME, "owner": ME, "id": list, "state": state }).to_string());    let out = with_door(&handle, [founder_live(&asking), founder_live(&asking), ok(), founder_live(&asking), ok(), standing(&[ME], &[&ferry, &salt])]);    let with = over(&handle, "share.with", &json!({ "app": "cinemas", "thing": thing })).unwrap();    let paths: Vec<String> = out.seen().iter().map(|s| s.path.clone()).collect();    let state: Value = serde_json::from_slice(&out.seen().into_iter().find(|s| s.path == "/v1/shared/list/state").expect("the new state").body).unwrap();    assert!(state["state"]["membership"]["members"].get(ASHA).is_none(), "{state}");    assert!(paths.iter().filter(|p| *p == "/v1/shared/list/item").count() == 1, "the ask taken away: {paths:?}");    assert_eq!(with["rows"].as_array().unwrap().len(), 1, "{with}");}// RULE (CIRCLE GAPS 3): share.by_person covers Days and Cinemas: his event with her on the guest list by Cotton and// his film list she sees are his; an invitation she sent and a list she shared are hers. Words and Sites add nothing.#[test]fn by_person_covers_days_events_and_cinemas_lists() {    let (_dir, handle) = cinemas_phone();    hold_key(&handle);    let ws = crate::phone::cotton_chat::read(&handle.client(), "test.ws", |ctx| Ok(json!(ctx.workspace_id))).unwrap().as_str().unwrap().to_string();    let t = |s: &str| SqlValue::Text(s.to_string());    let run = |sql: &str, params: &[SqlValue]| handle.client().with_writer(|r| r.driver.run(sql, params).map(|_| ()).map_err(|e| e.to_string())).expect(sql);    for (id, title) in [("ev-mine", "Dinner at ours"), ("ev-hers", "Asha's birthday"), ("ev-other", "Team lunch")] {        run("INSERT INTO cotton_events (id, title, starts_at, created_at, updated_at) VALUES (?, ?, '2026-12-01T19:00:00.000Z', '2026-11-01', '2026-11-01')", &[t(id), t(title)]);    }    let _ = &ws;    for (id, event, phone, role) in [("g1", "ev-mine", ASHA, ""), ("g2", "ev-hers", ASHA, "organizer"), ("g3", "ev-hers", ME, ""), ("g4", "ev-other", RAVI, "")] {        run("INSERT INTO cotton_event_attendees (id, event_id, phone, display_name, via, role, created_at, updated_at) VALUES (?, ?, ?, 'x', 'cotton', NULLIF(?, ''), '2026-11-01', '2026-11-01')", &[t(id), t(event), t(phone), t(role)]);    }    let ferry = film(&handle, "Night Ferry");    let made = crate::methods::dispatch(&handle, "groups.create", &json!({ "table": "film", "name": "Rainy Sundays", "records": [ferry] })).unwrap();    let group = made.pointer("/group/id").or_else(|| made.get("id")).and_then(Value::as_str).unwrap().to_string();    let mine_list = format!("cinemas-{group}");    let lists = Reply::ok(&json!({ "me": ME, "lists": [{ "owner": ME, "id": mine_list }, { "owner": ASHA, "id": "cinemas-hers" }, { "owner": RAVI, "id": "cinemas-ravis" }] }).to_string());    let no_list = || Reply::json(404, r#"{"code":"no_list","message":"That list is not there."}"#);    // Albums and Secrets ask first (nothing here), then the shared lists: his own read for its members, hers read for its name.    let out = with_door(&handle, [no_list(), no_list(), Reply::ok(r#"{"notes":[]}"#), Reply::ok(r#"{"shares":[]}"#), lists, standing(&[ME, ASHA], &[&ferry]), no_list()]);    let shared = over(&handle, "share.by_person", &json!({ "person": ASHA })).unwrap();    let seen: Vec<String> = out.seen().iter().map(|s| s.path.clone()).collect();    let row = |side: &str, app: &str| shared[side].as_array().unwrap().iter().filter(|r| r["app"] == app).map(|r| r["detail"].as_str().unwrap_or_default().to_string()).collect::<Vec<_>>();    assert_eq!(row("mine", "days"), ["Dinner at ours"], "{shared} {seen:?}");    assert_eq!(row("theirs", "days"), ["Asha's birthday"], "{shared}");    assert_eq!(row("mine", "cinemas"), ["Rainy Sundays · sees the list"], "{shared} {seen:?}");    assert_eq!(row("theirs", "cinemas").len(), 1, "{shared} {seen:?}");    assert!(!shared.to_string().contains("Team lunch") && !shared.to_string().contains("ravis"), "{shared}");    assert!(!shared.to_string().contains("\"words\"") || shared["mine"].as_array().unwrap().iter().chain(shared["theirs"].as_array().unwrap()).all(|r| r["app"] != "words" && r["app"] != "sites"));}