Cotton code
647 lines · 41.2 KB · RustRaw
//! `send.*` on a phone over a scripted object: what each method asks of the//! object, and the thread item it leaves. Every number, title and id is//! invented.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange, Seen};use serde_json::{json, Value};use super::over;use crate::handle::CottonHandle;use crate::phone::personal_object::ObjectDoor;const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential";const THEM: &str = "+15550100001";const SEND: &str = "0123456789abcdef0123456789abcdef";/// A Books phone (Books draws the book table, so its records are the person's own here).fn phone() -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let manifest = json!({        "genesis": "personal", "flavour": "books", "name": "Cotton Books", "databases": "single", "database": "personal",        "fan": {"home": false, "tools": false, "opens": "books"}, "kit": "books",    });    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 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: CREDENTIAL.to_string() };    handle.client().set_object_door(Some(Arc::new(door)));    exchange}fn answer(handle: &CottonHandle, method: &str, request: Value) -> Value {    over(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn body(seen: &Seen) -> Value {    serde_json::from_slice(&seen.body).expect("a JSON body")}fn messages(handle: &CottonHandle) -> Vec<serde_json::Map<String, Value>> {    handle        .client()        .with_writer(|replica| Ok(replica.driver.all("SELECT * FROM cotton_msg_messages ORDER BY sent_at", &[]).map_err(|e| e.to_string())?.iter().map(crate::phone::passwords::json_row).collect::<Vec<_>>()))        .unwrap()}fn meta(row: &serde_json::Map<String, Value>) -> Value {    match &row["meta"] {        Value::String(text) => serde_json::from_str(text).unwrap(),        other => other.clone(),    }}/// The chat with them, known on Cotton here (chat.start asks the server nothing), the test's own door kept.fn thread_with(handle: &CottonHandle) -> String {    let held = handle.client().object_door();    crate::phone::chat_people::hold_on_cotton(&handle.client(), THEM);    let found = cotton_client::transport::scripted::ScriptedExchange::new([]);    let door = crate::phone::personal_object::ObjectDoor { address: cotton_client::transport::object::ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: found, credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".to_string() };    handle.client().set_object_door(Some(std::sync::Arc::new(door)));    let thread = crate::phone::cotton_chat::over(&handle.client(), "chat.start", &json!({ "number": THEM })).unwrap()["thread"].as_str().unwrap().to_string();    handle.client().set_object_door(held);    thread}/// A data key held on this phone, so it holds its person's sharing key.fn hold_key(handle: &CottonHandle) {    hold_key_on(&handle.client());}fn hold_key_on(client: &crate::shell::client::ClientController) {    let mut bytes = [0u8; 32];    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut bytes);    let database = client.current_database().expect("a database");    client.data_keys().hold(&database, &cotton_core::seal::DataKey::from_bytes(bytes));}/// The sender's sharing secret in these tests: another person's phone.const SENDER_SECRET: [u8; 32] = [21; 32];/// What a sender's phone lays for one book (the rule's own shape), with no file.fn payload(id: &str) -> Value {    json!({        "format": "cotton.send", "version": 1, "id": id, "from": { "number": THEM, "name": "Test Sender" },        "made_at": "2026-11-13T08:00:00.000Z", "source_database": "22222222-2222-4222-8222-222222222222",        "root": { "table": "book", "id": "b-them" }, "title": "The Synthetic Garden",        "records": [{ "table": "book", "id": "b-them", "data": { "title": "The Synthetic Garden", "author": "A. Example" }, "role": "root" }],        "files": [], "bytes": 0    })}/// A box sealed to this phone's sharing key, as the sender's phone seals it.fn boxed_for(client: &crate::shell::client::ClientController, id: &str) -> String {    let (_, public) = super::send_seal::sharing(client).expect("the sharing key");    let key = cotton_core::seal::share::key_from_text(&public).unwrap();    cotton_core::seal::share::seal_to_person(&SENDER_SECRET, &key, &format!("send:{id}"), &serde_json::to_vec(&payload(id)).unwrap()).unwrap()}fn inbox_with(handle: &CottonHandle, state: &str) -> Reply {    inbox_for(&handle.client(), state)}fn inbox_for(client: &crate::shell::client::ClientController, state: &str) -> Reply {    let item = json!({ "id": SEND, "from": THEM, "table": "book", "bytes": 0, "state": state, "at": 1763000000000i64, "expires_at": 1764209600000i64, "fits": true, "trusted": false, "box": boxed_for(client, SEND), "files": [], "source_database": "22222222-2222-4222-8222-222222222222" });    Reply::ok(&json!({ "me": "+15550100002", "in": [item], "out": [] }).to_string())}fn ok() -> Reply {    Reply::ok(r#"{"ok":true}"#)}/// A book of this person's own, as their copy holds it.fn own_book(handle: &CottonHandle) -> String {    let made = crate::phone::records::call(&handle.client(), "records.create", &json!({ "table": "book", "data": { "title": "The Synthetic Garden", "author": "A. Example", "rating": 4 } })).expect("a book");    made["record"]["id"].as_str().or_else(|| made["id"].as_str()).expect("its id").to_string()}// RULE (R5): a send is laid and sealed on this phone to the receiver's sharing key; the object is posted only the box and its outside (no title, no record), and the thread carries it at once as this person's own item.#[test]fn making_a_send_seals_it_on_the_phone_and_puts_it_on_the_thread() {    let (_dir, handle) = phone();    hold_key(&handle);    let book = own_book(&handle);    let friend_secret = [33u8; 32];    let friend = cotton_core::seal::share::key_text(&cotton_core::vault::wrap::public_of(&friend_secret));    let exchange = with_door(&handle, [ok(), Reply::ok(&json!({ "key": friend, "me": "+15550100002" }).to_string()), Reply::ok(&json!({ "id": SEND, "at": 1763000000000i64, "bytes": 0, "state": "offered" }).to_string())]);    let thread = thread_with(&handle);    let made = answer(&handle, "send.make", json!({ "table": "book", "id": book, "thread": thread }));    assert_eq!(made["thread"], json!(thread));    assert_eq!(made["title"], "The Synthetic Garden", "the phone knows what it sent");    let seen = exchange.seen();    assert_eq!((seen[0].method.as_str(), seen[0].path.as_str()), ("POST", "/v1/send/key"));    assert_eq!(seen[1].path, format!("/v1/send/key?number=%2B{}", &THEM[1..]));    assert_eq!((seen[2].method.as_str(), seen[2].path.as_str()), ("POST", "/v1/send/make"));    let posted = body(&seen[2]);    let text = posted.to_string();    assert!(!text.contains("Synthetic") && !text.contains("Example"), "the object is handed no value: {text}");    assert_eq!(posted["table"], "book");    let id = posted["id"].as_str().unwrap();    // Only the friend's sharing key opens it, as the send it says it is, and the sender's own rating never travels.    let opened = cotton_core::seal::share::open_from_person(&friend_secret, posted["box"].as_str().unwrap(), &format!("send:{id}")).expect("it opens for the friend");    let envelope: Value = serde_json::from_slice(&opened.payload).unwrap();    assert_eq!(envelope["file_keys"], json!({}), "a book with no file carries no file key");    let sent = &envelope["send"];    assert_eq!((sent["title"].as_str(), sent["root"]["id"].as_str()), (Some("The Synthetic Garden"), Some(book.as_str())));    assert!(sent["records"][0]["data"].get("rating").is_none());    assert!(cotton_core::seal::share::open_from_person(&[34u8; 32], posted["box"].as_str().unwrap(), &format!("send:{id}")).is_err());    let rows = messages(&handle);    assert_eq!(rows.len(), 1);    assert_eq!((rows[0]["direction"].as_str(), rows[0]["channel"].as_str()), (Some("out"), Some("cotton")));    assert_eq!(meta(&rows[0])["cotton"]["send"]["state"], "offered");}// RULE (R5): an arrival is opened on this phone with its sharing key and lands once as the thread's item with its card; Keep plans over this phone's copy, asks the object only to copy bytes, writes the rows here and tells the landed root.#[test]fn an_arrival_opens_here_lands_with_its_card_and_keep_writes_the_rows_on_the_phone() {    let (_dir, handle) = phone();    hold_key(&handle);    let exchange = with_door(&handle, [ok(), inbox_with(&handle, "offered"), inbox_with(&handle, "offered"), inbox_with(&handle, "offered"), Reply::ok(&json!({ "state": "kept", "fresh": true, "landed": { "table": "book", "id": "planned" } }).to_string()), ok()]);    let first = answer(&handle, "send.inbox", json!({}));    assert_eq!(first["landed"].as_array().unwrap().len(), 1);    assert_eq!(first["in"][0]["title"], "The Synthetic Garden");    assert!(first["in"][0].get("box").is_none(), "the box is not kept on the item");    let again = answer(&handle, "send.inbox", json!({}));    assert!(again["landed"].as_array().unwrap().is_empty(), "an item lands once");    let rows = messages(&handle);    assert_eq!(rows.len(), 1);    assert_eq!(meta(&rows[0])["cotton"]["send"]["card"]["face"], "book.hardback");    let kept = answer(&handle, "send.keep", json!({ "id": SEND }));    assert_eq!(kept["state"], "kept");    let seen = exchange.seen();    let keep = seen.iter().find(|s| s.path == "/v1/send/keep").unwrap();    let asked = body(keep);    // `tell` follows the person's read-receipts switch, off until they turn it on (fb599d0b6).    assert_eq!((asked["id"].as_str(), asked["tell"].as_bool(), asked["copies"].as_array().map(Vec::len)), (Some(SEND), Some(false), Some(0)));    assert_eq!(asked["root"]["table"], "book");    assert!(!asked.to_string().contains("Synthetic"), "Keep hands the object no value");    let books = crate::phone::records::call(&handle.client(), "records.list", &json!({ "table": "book" })).unwrap();    let landed = &books["records"][0];    assert_eq!(landed["data"]["title"], "The Synthetic Garden");    assert_eq!((landed["data"]["sent_by_number"].as_str(), landed["data"]["send_id"].as_str()), (Some(THEM), Some(SEND)));    let told = seen.iter().find(|s| s.path == "/v1/send/landed").expect("the landed root is told");    assert_eq!(body(told)["root"]["id"], landed["id"]);    let item = &meta(&messages(&handle)[0])["cotton"]["send"];    assert_eq!((item["state"].as_str(), item["landed"]["id"].as_str()), (Some("kept"), landed["id"].as_str()));}// RULE (R5): a box that does not open with this phone's sharing key is never drawn as an offer.#[test]fn an_arrival_sealed_to_someone_else_is_not_drawn() {    let (_dir, handle) = phone();    hold_key(&handle);    let other = cotton_core::seal::share::key_text(&cotton_core::vault::wrap::public_of(&[44u8; 32]));    let boxed = cotton_core::seal::share::seal_to_person(&SENDER_SECRET, &cotton_core::seal::share::key_from_text(&other).unwrap(), &format!("send:{SEND}"), &serde_json::to_vec(&payload(SEND)).unwrap()).unwrap();    let item = json!({ "id": SEND, "from": THEM, "table": "book", "bytes": 0, "state": "offered", "at": 1763000000000i64, "fits": true, "trusted": false, "box": boxed });    with_door(&handle, [ok(), Reply::ok(&json!({ "me": "+15550100002", "in": [item], "out": [] }).to_string())]);    let read = answer(&handle, "send.inbox", json!({}));    assert!(read["in"].as_array().unwrap().is_empty());    assert!(messages(&handle).is_empty());}// RULE: a declined send leaves nothing on the thread.#[test]fn declining_puts_the_item_away() {    let (_dir, handle) = phone();    hold_key(&handle);    let exchange = with_door(&handle, [ok(), inbox_with(&handle, "offered"), ok()]);    answer(&handle, "send.inbox", json!({}));    answer(&handle, "send.decline", json!({ "id": SEND }));    assert_eq!(exchange.seen()[2].path, "/v1/send/decline");    assert!(messages(&handle)[0]["trashed_at"].is_string());}// RULE: the offer names the people the object holds as this person's, with their names and trust, even on a phone that keeps no chat; what goes is laid on this phone.#[test]fn the_offer_names_the_objects_people_without_a_thread_on_this_phone() {    let (_dir, handle) = phone();    hold_key(&handle);    let book = own_book(&handle);    let exchange = with_door(&handle, [Reply::ok(&json!({ "people": [{ "number": THEM, "name": "Test Friend", "trusted": true }] }).to_string())]);    let offered = answer(&handle, "send.offer", json!({ "table": "book", "id": book }));    assert_eq!(exchange.seen()[0].path, "/v1/send/people");    assert_eq!(offered["people"], json!([{ "number": THEM, "name": "Test Friend", "trusted": true }]));    assert_eq!((offered["sendable"].as_bool(), offered["title"].as_str()), (Some(true), Some("The Synthetic Garden")));}// RULE: an offer the object no longer holds (declined elsewhere, taken back, expired) is put away on this phone too; a kept one stays.#[test]fn an_offer_gone_from_the_object_is_put_away() {    let (_dir, handle) = phone();    hold_key(&handle);    let empty = Reply::ok(&json!({ "me": "+15550100002", "in": [], "out": [] }).to_string());    with_door(&handle, [ok(), inbox_with(&handle, "offered"), empty]);    answer(&handle, "send.inbox", json!({}));    assert!(messages(&handle)[0]["trashed_at"].is_null());    answer(&handle, "send.inbox", json!({}));    assert!(messages(&handle)[0]["trashed_at"].is_string());}// RULE: the sender's own item carries the card this phone laid, and their Undo takes the send back, the item saying so.#[test]fn the_senders_item_draws_its_card_and_undo_takes_it_back() {    let (_dir, handle) = phone();    hold_key(&handle);    let book = own_book(&handle);    let friend = cotton_core::seal::share::key_text(&cotton_core::vault::wrap::public_of(&[33u8; 32]));    let exchange = with_door(&handle, [ok(), Reply::ok(&json!({ "key": friend, "me": "+15550100002" }).to_string()), Reply::ok(&json!({ "id": SEND, "at": 1763000000000i64, "bytes": 0, "state": "offered" }).to_string()), Reply::ok(&json!({ "removed": 0, "state": "undone" }).to_string())]);    let thread = thread_with(&handle);    let made = answer(&handle, "send.make", json!({ "table": "book", "id": book, "thread": thread }));    assert_eq!(made["card"]["face"], "book.hardback");    assert_eq!(meta(&messages(&handle)[0])["cotton"]["send"]["card"]["face"], "book.hardback");    let sent = body(&exchange.seen()[2])["id"].as_str().unwrap().to_string();    let undone = answer(&handle, "send.undo", json!({ "id": sent }));    assert_eq!(undone["state"], "undone");    assert_eq!(body(&exchange.seen()[3]), json!({ "id": sent }));    assert_eq!(meta(&messages(&handle)[0])["cotton"]["send"]["state"], "undone");}/// The object's people, then its weight of the book's file (12 MB): what the Send step asks.fn offer_reply(handle: &CottonHandle, people: Value) -> [Reply; 2] {    let key = format!("{}/{FILE}", handle.client().current_database().unwrap());    [Reply::ok(&json!({ "people": people }).to_string()), Reply::ok(&json!({ "files": [{ "key": key, "folder": false, "bytes": 12_000_000 }] }).to_string())]}const FILE: &str = "books/0000000000000000000000000000000000000000000000000000000000000000.epub";/// A book of this person's own with a file, so the step has a size to say.fn step_book(handle: &CottonHandle) -> String {    hold_key(handle);    let database = handle.client().current_database().unwrap();    let made = crate::phone::records::call(&handle.client(), "records.create", &json!({ "table": "book", "data": { "title": "The Synthetic Garden", "author": "A. Example", "file": format!("{database}/{FILE}") } })).expect("a book");    made["record"]["id"].as_str().or_else(|| made["id"].as_str()).expect("its id").to_string()}fn step(handle: &CottonHandle, book: &str) -> Value {    crate::phone::opened::call(&handle.client(), &json!({ "table": "book", "id": book, "step": "send" })).unwrap_or_else(|e| panic!("{} {}", e.code, e.message))["step"].clone()}// RULE: the Send step is the person's people as the object names them, each a person's row that sends at a tap and holds the trust act, the trusted marked; the tier says what goes and its size.#[test]fn the_send_step_is_a_tier_of_people_saying_what_goes_and_its_size() {    let (_dir, handle) = phone();    let book = step_book(&handle);    with_door(&handle, offer_reply(&handle, json!([{ "number": THEM, "name": "Test Friend", "trusted": false }, { "number": "+15550100003", "name": "Second Test", "trusted": true }])));    let step = step(&handle, &book);    assert_eq!(step["kind"], "send", "{step}");    assert_eq!(step["says"], "The Synthetic Garden · 12 MB", "{step}");    assert_eq!(step["says"], "The Synthetic Garden · 12 MB");    let rows = step["rows"].as_array().unwrap();    assert_eq!((rows[0]["value"].as_str(), rows[0]["words"].as_str(), rows[0]["initials"].as_str()), (Some(THEM), Some("Test Friend"), Some("TF")));    assert_eq!(rows[0]["sends"], json!({ "to": THEM }));    assert_eq!(rows[0]["detail"], "12 MB", "the size is said before sending");    assert_eq!(rows[0]["holds"][0], json!({ "id": "trust", "words": "Always keep from Test Friend", "trust": { "number": THEM, "trusted": true } }));    assert_eq!(rows[1]["detail"], "Always kept · 12 MB");    assert_eq!(rows[1]["holds"][0]["words"], "Stop always keeping from Second Test");    assert!(step.get("empty").is_none());}// RULE: with nobody to send to the tier says so in the kit's words, offering Cotton chat's request where the app keeps chat and only the words where it does not (Books).#[test]fn with_no_people_the_send_step_says_so_and_opens_chat_only_where_the_app_keeps_it() {    let (_dir, handle) = phone();    let book = step_book(&handle);    with_door(&handle, offer_reply(&handle, json!([])).into_iter().chain(offer_reply(&handle, json!([]))));    let messages = cotton_core::kit::AppKit::named("messages").expect("the messages kit");    cotton_core::kit::AppKit::keep(Some(&messages), handle.client().layout().root()).unwrap();    // Messages' threads as the object syncs their definition, with its New Cotton message door.    handle.client().with_writer(|file| {        let raw = include_str!("../../../cotton-core/kits/personal/tables/thread.json");        file.driver.run("INSERT OR REPLACE INTO cotton_table_definitions (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at) VALUES ('thread', ?1, ?2, 0, 0, '2026-11-13', '2026-11-13')",            &[rusqlite::types::Value::Text(file.workspace_id.to_string()), rusqlite::types::Value::Text(raw.to_string())]).map_err(|error| error.to_string())?;        Ok(())    }).expect("Messages' threads");    let whole = step(&handle, &book);    assert!(whole["rows"].as_array().unwrap().is_empty());    assert_eq!(whole["empty"]["words"], "No one to send to yet. Send is for people you have both accepted on Cotton.");    assert_eq!(whole["empty"]["door"], json!({ "words": "Ask someone on Cotton", "path": "/messages/new" }));    let books = cotton_core::kit::AppKit::named("books").expect("the books kit");    cotton_core::kit::AppKit::keep(Some(&books), handle.client().layout().root()).unwrap();    let in_books = step(&handle, &book);    assert_eq!(in_books["empty"]["words"], whole["empty"]["words"]);    assert!(in_books["empty"].get("door").is_none(), "Books keeps no chat: the words alone");}// RULE: a received card says who it is from and offers Keep with its size and Decline; one that will not fit says why in the object's words and offers no Keep; one already held says so and opens it; while copying it says how far; kept it opens what landed and can be removed; each offers the trust act on its sender.#[test]fn a_received_card_says_its_state_and_offers_its_acts() {    let rows = Vec::new();    let base = json!({ "id": SEND, "from": THEM, "name": "Test Friend", "bytes": 12_000_000, "state": "offered", "fits": true, "held": null, "trusted": false });    let ids = |shows: &Value| shows["acts"].as_array().unwrap().iter().map(|a| a["id"].as_str().unwrap().to_string()).collect::<Vec<_>>();    let offered = super::shows(&base, false, &rows);    assert_eq!(offered["from"], "From Test Friend");    assert_eq!(ids(&offered), ["keep", "decline", "trust"]);    assert_eq!(offered["acts"][0]["words"], "Keep · 12 MB");    let mut full = base.clone();    full["fits"] = json!(false);    full["words"] = json!("This needs 12 MB and your Cotton has 1 MB free.");    let full = super::shows(&full, false, &rows);    assert_eq!((full["line"].as_str(), ids(&full)), (Some("This needs 12 MB and your Cotton has 1 MB free."), vec!["decline".to_string(), "trust".to_string()]));    let mut held = base.clone();    held["held"] = json!({ "table": "book", "id": "mine-1" });    let held = super::shows(&held, false, &rows);    assert_eq!((held["line"].as_str(), held["acts"][0]["opens"]["id"].as_str()), (Some("Already in your Cotton"), Some("mine-1")));    let mut keeping = base.clone();    keeping["state"] = json!("keeping");    keeping["copied"] = json!({ "bytes": 12_000_000, "done": 3_000_000 });    assert_eq!(super::shows(&keeping, false, &rows)["line"], "Copying 3 MB of 12 MB");    let mut kept = base.clone();    kept["state"] = json!("kept");    kept["trusted"] = json!(true);    kept["landed"] = json!({ "table": "book", "id": "new-1" });    let kept = super::shows(&kept, false, &rows);    assert_eq!(ids(&kept), ["open", "undo", "trust"]);    assert_eq!(kept["acts"][2]["words"], "Stop always keeping from Test Friend");}// RULE: the sender's card says Sent, Delivered, Kept, Declined, Not kept in time or Taken back as far as the object says, offering Undo until it is kept or closed.#[test]fn a_sent_card_says_how_far_it_went() {    let rows = Vec::new();    for (state, line, undo) in [("offered", "Sent", true), ("delivered", "Delivered", true), ("kept", "Kept", false), ("declined", "Declined", false), ("expired", "Not kept in time", false), ("undone", "Taken back", false)] {        let shows = super::shows(&json!({ "id": SEND, "state": state, "bytes": 10 }), true, &rows);        assert_eq!(shows["line"], line, "{state}");        assert_eq!(shows["acts"].as_array().unwrap().iter().any(|a| a["id"] == "undo"), undo, "{state}");    }}// RULE: an app with no chat tool (Books) has a Sent to you card while this phone holds something sent, counting what waits for an answer; an app with chat has none (sends arrive in the thread), nor one with nothing sent.#[test]fn an_app_without_chat_shows_what_was_sent_on_a_card_of_its_own() {    let (_dir, handle) = phone();    hold_key(&handle);    let reply = inbox_with(&handle, "offered");    with_door(&handle, [ok(), reply]);    let messages = cotton_core::kit::AppKit::named("messages").expect("the messages kit");    cotton_core::kit::AppKit::keep(Some(&messages), handle.client().layout().root()).unwrap();    assert!(super::sent_card(&handle.client()).is_none(), "nothing sent yet");    answer(&handle, "send.inbox", json!({}));    assert!(super::sent_card(&handle.client()).is_none(), "Messages keeps chat: the send is on its thread");    let books = cotton_core::kit::AppKit::named("books").expect("the books kit");    cotton_core::kit::AppKit::keep(Some(&books), handle.client().layout().root()).unwrap();    let card = super::sent_card(&handle.client()).expect("Books shows what was sent");    assert_eq!((card["id"].as_str(), card["label"].as_str(), card["count"].as_u64(), card["aside"].as_bool()), (Some("sent"), Some("Sent to you"), Some(1), Some(true)));}// RULE: a record a send brought says whom from and on what day; one of the person's own says nothing.#[test]fn a_kept_record_says_where_it_came_from() {    let data = json!({ "title": "The Synthetic Garden", "sent_by": "Test Friend", "sent_by_number": THEM, "sent_at": "2026-11-13T09:30:00.000Z" });    let from = super::from_line(data.as_object().unwrap(), "Asia/Kolkata", &[]).expect("a kept send says where from");    assert!(from.starts_with("From Test Friend, ") && from.contains("13 Nov"), "{from}");    assert!(super::from_line(json!({ "title": "Mine" }).as_object().unwrap(), "Asia/Kolkata", &[]).is_none());}// RULE: an inbox read that says nothing new of an item writes nothing: the inbox is read at every launch and on a clock, and each rewrite was a write owed to the object (send-walk, 13 Nov 2026: a Books phone held 60 such writes, sealed rows that could not go).#[test]fn an_inbox_read_saying_nothing_new_writes_nothing() {    let (_dir, client, _) = crate::shell::client::phone_tests::attached_on_a_clock_in("local");    hold_key_on(&client);    let exchange = ScriptedExchange::new([ok(), inbox_for(&client, "offered"), inbox_for(&client, "offered"), inbox_for(&client, "kept"), inbox_for(&client, "kept")]);    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange, credential: CREDENTIAL.to_string() };    client.set_object_door(Some(Arc::new(door)));    let queued = || -> i64 {        client            .with_file(|file| file.driver.get("SELECT COUNT(*) AS n FROM _outbox", &[]).map_err(|e| e.to_string()).map(|row| row.and_then(|row| row.int("n")).unwrap_or(0)))            .expect("the outbox")    };    let read = || over(&client, "send.inbox", &json!({})).unwrap_or_else(|e| panic!("{} {}", e.code, e.message));    read();    let landed = queued();    assert!(landed > 0, "the landing is a write owed to the object");    read();    assert_eq!(queued(), landed, "the same offer again writes nothing");    read();    let moved = queued();    assert!(moved > landed, "an item the object moved is written");    read();    assert_eq!(queued(), moved, "the same kept item again writes nothing");}// RULE: the Send step ends with Add a person, also with nobody to send to; a person still waiting (added here, not adding back) says so in the kit's words and neither sends nor holds an act.#[test]fn the_send_step_offers_add_a_person_and_shows_who_is_waiting() {    let (_dir, handle) = phone();    let book = step_book(&handle);    with_door(&handle, offer_reply(&handle, json!([{ "number": THEM, "name": "Test Friend", "trusted": false, "waiting": true }, { "number": "+15550100003", "name": null, "trusted": false, "waiting": false }])).into_iter().chain(offer_reply(&handle, json!([]))));    let step = step(&handle, &book);    assert_eq!(step["add"], json!({ "words": "Add a person", "hint": "Their phone number, starting with +", "ask": { "kind": "people_add" } }), "Account's Your people add step, one implementation");    let rows = step["rows"].as_array().unwrap();    assert_eq!(rows[0], json!({ "value": THEM, "words": "Test Friend", "number": THEM, "trusted": false, "initials": "TF", "waiting": true, "detail": "They have not added you yet" }));    assert_eq!(rows[1]["sends"], json!({ "to": "+15550100003" }));    assert!(rows[1].get("waiting").is_none());    let empty = super::super::opened::call(&handle.client(), &json!({ "table": "book", "id": book, "step": "send" })).unwrap()["step"].clone();    assert!(empty["rows"].as_array().unwrap().is_empty());    assert_eq!(empty["add"]["words"], "Add a person", "Add a person stands with nobody to send to");}// RULE (R5 with R6): a book file the sender sealed under their own per-file key travels with that key inside the box; Keep opens the bytes with it on this phone and seals them again under this person's own key for where they land, so the object copies nothing it could read and the receiver's file opens with the receiver's key alone.#[test]fn a_file_sealed_by_the_sender_is_opened_and_sealed_again_under_the_receivers_key_at_keep() {    use cotton_core::seal::file;    let (_dir, handle) = phone();    hold_key(&handle);    let client = handle.client();    let theirs_db = "22222222-2222-4222-8222-222222222222";    let sha = "ab".repeat(32);    let from = format!("{theirs_db}/books/{sha}.epub");    // The sender's phone sealed the book under its own per-file key.    let sender_fk = file::FileKey::from_bytes([55; 32]);    let plain = b"a synthetic epub's bytes".repeat(40);    let mut sealed = Vec::new();    file::seal_file(&sender_fk, &from, &mut plain.as_slice(), &mut sealed).unwrap();    let mut sent = payload(SEND);    sent["records"][0]["data"]["file"] = json!(from);    sent["files"] = json!([{ "key": from, "bytes": sealed.len() }]);    sent["bytes"] = json!(sealed.len());    let (_, public) = super::send_seal::sharing(&client).unwrap();    let envelope = json!({ "send": sent, "file_keys": { from.clone(): sender_fk.text() } });    let boxed = cotton_core::seal::share::seal_to_person(&SENDER_SECRET, &cotton_core::seal::share::key_from_text(&public).unwrap(), &format!("send:{SEND}"), &serde_json::to_vec(&envelope).unwrap()).unwrap();    let item = json!({ "id": SEND, "from": THEM, "table": "book", "bytes": sealed.len(), "state": "offered", "at": 1763000000000i64, "fits": true, "trusted": false, "box": boxed });    let inbox = Reply::ok(&json!({ "me": "+15550100002", "in": [item], "out": [] }).to_string());    let exchange = with_door(&handle, [ok(), inbox, Reply::new(200, sealed.clone()).with_header("content-type", "application/vnd.cotton.f1"), Reply::ok(r#"{"stored":true}"#), Reply::ok(&json!({ "state": "kept", "fresh": true, "landed": { "table": "book", "id": "planned" } }).to_string()), ok()]);    let kept = answer(&handle, "send.keep", json!({ "id": SEND }));    assert_eq!(kept["state"], "kept");    let seen = exchange.seen();    assert!(seen[2].path.starts_with(&format!("/v1/send/{SEND}/media?key=")) && seen[2].path.ends_with("&whole=1"), "{}", seen[2].path);    let put = &seen[3];    assert_eq!(put.method, "PUT");    let database = client.current_database().unwrap();    let to = format!("{database}/books/{sha}.epub");    assert_eq!(put.path, format!("/v1/media/{to}"));    assert!(!put.body.windows(9).any(|w| w == b"synthetic"), "the bytes go up sealed");    // They open with this person's own key for where they land, and with the sender's no more.    use cotton_client::seal::DataKeyStore as _;    let dk = client.data_keys().data_key(&database).unwrap().unwrap();    let mine = file::person_file_key(&cotton_core::seal::keys::file_root(&dk, &database).unwrap(), &to);    let mut opened = Vec::new();    file::open_file(&mine, &to, &mut put.body.as_slice(), &mut opened).expect("it opens with the receiver's key");    assert_eq!(opened, plain);    assert!(file::open_file(&sender_fk, &from, &mut put.body.as_slice(), &mut Vec::new()).is_err());    // The object is asked to copy nothing: the file is stored already.    let keep = seen.iter().find(|s| s.path == "/v1/send/keep").unwrap();    assert_eq!(body(keep)["copies"], json!([]));}/// RULE (R5, walk send-sealed run 6): the phone posts its person's sharing key the moment it holds the data key/// (`seal.status`, read every pass), once a launch, so one of their people who sends before this phone ever opens/// Send seals to the real key, never to a made-up one nobody can open.#[test]fn the_sharing_key_is_posted_once_the_data_key_is_held() {    let (_dir, handle) = phone();    let exchange = with_door(&handle, [ok(), ok()]);    crate::methods::dispatch(&handle, "seal.status", &json!({})).expect("a status");    assert!(exchange.seen().iter().all(|s| s.path != "/v1/send/key"), "no key held, nothing posted");    hold_key(&handle);    crate::methods::dispatch(&handle, "seal.status", &json!({})).expect("a status");    crate::methods::dispatch(&handle, "seal.status", &json!({})).expect("a status");    let posts: Vec<_> = exchange.seen().into_iter().filter(|s| s.method == "POST" && s.path == "/v1/send/key").collect();    assert_eq!(posts.len(), 1, "posted once a launch");    let (_, public) = crate::phone::send_seal::sharing(&handle.client()).expect("the sharing key");    assert_eq!(body(&posts[0])["key"], json!(public), "its public half, never the secret");}/// A phone of `kit` (the app that draws the table a landing writes).fn phone_of(kit: &str, flavour: &str, name: &str) -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let manifest = json!({        "genesis": "personal", "flavour": flavour, "name": name, "databases": "single", "database": "personal",        "fan": {"home": false, "tools": false, "opens": flavour}, "kit": kit,    });    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)}/// RULE (R5): a landing writes a table this build stores (a todo, a note, a photo, a message) as it/// writes a kit's own (a book): its columns, the row the person's own; the provenance its own write keeps no column/// for stays on the phone's send item.#[test]fn a_landing_writes_a_table_this_build_stores_with_its_provenance() {    for (kit, flavour, name, table, data) in [        ("todos", "todos", "Cotton Todos", "todo", json!({"title": "Invented Wexhollow errand", "priority": 1})),        ("notes", "notes", "Cotton Notes", "note", json!({"kind": "note", "title": "Invented Drusket note", "body": "Words", "words": 1, "journal_date": null, "published_at": null})),    ] {        let (_dir, handle) = phone_of(kit, flavour, name);        let mut row = data.clone();        for (k, v) in [("sent_by", json!("Invented Sender")), ("sent_by_number", json!(THEM)), ("sent_at", json!("2026-11-15T10:00:00.000Z")), ("send_id", json!(SEND))] {            row[k] = v;        }        let landing: cotton_core::cotton_rules::send::Landing = serde_json::from_value(json!({            "creates": [{"table": table, "id": "sent-root", "data": row}], "copies": [], "held": [], "bytes": 0, "root": {"table": table, "id": "sent-root"},        }))        .expect("a landing");        let root = crate::phone::send_seal::write_rows(&handle.client(), &landing).unwrap_or_else(|e| panic!("{table}: {} {}", e.code, e.message));        let id = root["id"].as_str().expect("an id").to_string();        let got = crate::methods::dispatch(&handle, "records.get", &json!({"table": table, "id": id})).unwrap_or_else(|e| panic!("{table}: {} {}", e.code, e.message));        let text = got.to_string();        assert!(text.contains("Invented"), "{table} landed with its words: {text}");    }}/// A box of `payload` sealed to this phone's sharing key, with no file keys (files as they lie).fn boxed_payload(client: &crate::shell::client::ClientController, id: &str, payload: &Value) -> String {    let (_, public) = super::send_seal::sharing(client).expect("the sharing key");    let key = cotton_core::seal::share::key_from_text(&public).unwrap();    cotton_core::seal::share::seal_to_person(&SENDER_SECRET, &key, &format!("send:{id}"), &serde_json::to_vec(&json!({ "send": payload, "file_keys": {} })).unwrap()).unwrap()}/// The inbox answering one offer of `table` carrying `payload`.fn inbox_of(client: &crate::shell::client::ClientController, table: &str, payload: &Value, files: Value, bytes: u64) -> Reply {    let item = json!({ "id": SEND, "from": THEM, "table": table, "bytes": bytes, "state": "offered", "at": 1763000000000i64, "expires_at": 1764209600000i64, "fits": true, "trusted": false, "box": boxed_payload(client, SEND, payload), "files": files, "source_database": "22222222-2222-4222-8222-222222222222" });    Reply::ok(&json!({ "me": "+15550100002", "in": [item], "out": [] }).to_string())}fn sent_payload(table: &str, data: Value, files: Value, bytes: u64) -> Value {    json!({        "format": "cotton.send", "version": 1, "id": SEND, "from": { "number": THEM, "name": "Test Sender" },        "made_at": "2026-11-13T08:00:00.000Z", "source_database": "22222222-2222-4222-8222-222222222222",        "root": { "table": table, "id": "r-them" }, "title": "Invented",        "records": [{ "table": table, "id": "r-them", "data": data, "role": "root" }], "files": files, "bytes": bytes    })}/// RULE (R5): a photo enters as its bytes: kept, it is fetched through the send and brought in by/// this phone's own capture (a photo row of this person's, its bytes sealed under their key), never written as a/// record, and the object is asked to copy nothing.#[test]fn a_sent_photo_is_kept_by_capturing_its_bytes() {    let (_dir, handle) = phone_of("photos", "photos", "Cotton Photos");    hold_key(&handle);    let key = "22222222-2222-4222-8222-222222222222/photos/invented.png";    let files = json!([{ "key": key, "bytes": 3 }]);    let payload = sent_payload("photo", json!({ "key": key, "content_type": "image/png", "original_filename": "invented.png", "caption": "Invented Plimzat view" }), files.clone(), 3);    let client = handle.client();    let exchange = with_door(&handle, [ok(), inbox_of(&client, "photo", &payload, json!([key]), 3), inbox_of(&client, "photo", &payload, json!([key]), 3), Reply::ok("png"), Reply::ok(&json!({ "state": "kept", "fresh": true }).to_string()), ok()]);    answer(&handle, "send.inbox", json!({}));    let kept = answer(&handle, "send.keep", json!({ "id": SEND }));    assert_eq!(kept["state"], "kept", "{kept}");    let seen = exchange.seen();    assert!(seen.iter().any(|s| s.path.starts_with(&format!("/v1/send/{SEND}/media?key=")) && s.path.ends_with("&whole=1")), "the bytes come through the send");    let keep = seen.iter().find(|s| s.path == "/v1/send/keep").expect("kept");    assert_eq!(body(keep)["copies"], json!([]), "the object copies nothing: the phone brought the picture in");    let photos = crate::methods::dispatch(&handle, "records.list", &json!({ "table": "photo" })).expect("photos");    let landed = photos["records"].as_array().expect("records");    assert_eq!(landed.len(), 1, "{photos}");    assert_eq!(landed[0]["data"]["caption"], "Invented Plimzat view");    assert_ne!(landed[0]["data"]["key"], json!(key), "its bytes are this person's own now");}/// RULE (R5): a sent message lands in this person's thread with whoever sent it, inbound, with its/// words, and which send brought it in its meta.#[test]fn a_sent_message_is_kept_into_the_thread_with_its_sender() {    let (_dir, handle) = phone_of("messages", "messages", "Cotton Messages");    hold_key(&handle);    let payload = sent_payload("message", json!({ "body": "Invented Qvornek words" }), json!([]), 0);    let client = handle.client();    with_door(&handle, [ok(), inbox_of(&client, "message", &payload, json!([]), 0), inbox_of(&client, "message", &payload, json!([]), 0), Reply::ok(&json!({ "state": "kept", "fresh": true }).to_string()), ok()]);    answer(&handle, "send.inbox", json!({}));    let kept = answer(&handle, "send.keep", json!({ "id": SEND }));    assert_eq!(kept["state"], "kept", "{kept}");    let rows = messages(&handle);    let landed = rows.iter().find(|r| r.get("body").and_then(Value::as_str) == Some("Invented Qvornek words")).expect("the message landed");    let item = rows.iter().find(|r| r.get("external_id").and_then(Value::as_str) == Some(&format!("send-{SEND}"))).expect("the send's item");    assert_eq!(landed.get("thread_id"), item.get("thread_id"), "in the thread with its sender");    assert_eq!(landed.get("direction").and_then(Value::as_str), Some("in"));    assert_eq!(meta(landed)["cotton"]["sent"]["send_id"], SEND);}/// RULE (R5): a photo on Photos' deck (the media engine's card) is offered as the photo it is.#[test]fn a_photo_on_the_deck_is_offered_as_its_photo() {    let (dir, handle) = phone_of("photos", "photos", "Cotton Photos");    hold_key(&handle);    let picked = dir.path().join("picked.png");    std::fs::write(&picked, b"png").expect("a synthetic file");    let kept = crate::methods::dispatch(&handle, "capture.media", &json!({ "path": picked.to_string_lossy(), "mime": "image/png", "filename": "picked.png", "kind": "photo" })).expect("captured");    let id = kept["recordId"].as_str().expect("the photo").to_string();    with_door(&handle, [Reply::ok(&json!({ "people": [{ "number": THEM, "trusted": false }] }).to_string()), Reply::ok(&json!({ "files": [{ "key": kept["key"], "folder": false, "bytes": 3 }] }).to_string())]);    let offer = answer(&handle, "send.offer", json!({ "table": "media", "id": id }));    assert_eq!(offer["sendable"], true, "{offer}");    assert_eq!(offer["records"], json!({ "photo": 1 }), "{offer}");}