Cotton code
766 lines · 41.9 KB · RustRaw
//! `send.*` — Send on this phone (owner, 13 Nov 2026): a copy of a record to//! one of this person's people, SEALED ALL THE WAY (ruling R5, 15 Nov 2026)://! this phone lays what a record sends (cotton-rules `send`, over its own//! plain copy) and seals it to the receiver's sharing key; the receiving//! phone opens it, plans what lands and writes the rows ([`super::send_seal`]).//! The object decides only who may receive it and what fits, routes the box//! and copies the bytes (`apps/business/src/send/send.ts`). This keeps the//! chat thread's item for each send, so the thread draws it as the real card.//!//! ```text//! send.offer    { table, id }                       → { sendable, words?, title?, bytes?, records?, people: [{ number, name, trusted }] }  (people: the object's)//! send.make     { table, id, thread? | to? }        → { id, thread, message, title, bytes, state }//! send.inbox    {}                                  → { in: [...], out: [...], landed: [{ thread, message, id }] }//! send.keep     { id }                              → { state: kept|keeping, landed?, held?, copied? }//! send.decline  { id }                              → { ok }//! send.undo     { id } | { thread? | from?, day }   → { removed, state? }  (a send this person made: taken back, state undone)//! send.trust    { thread? | number?, trusted }      → { ok }//! send.picture  { id, key, dir }                    → { path }//! ```//!//! **The thread item** is an ordinary `message` row on the Cotton thread with//! that person (channel `cotton`, body empty), its `meta.cotton.send` the//! object's inbox item: `{ id, table, title, bytes, records, state, card://! { face, fields }, held, fits, words?, expires_at, landed? }`. The row's id//! is derived from the send's id, so every phone of the person writes the//! same row. A received item is `direction: in`; one this person sent is//! `out`, its `state` moving offered → delivered → kept | declined | expired.//!//! **Receipts are chat's.** Delivered is told always (sends flow only//! between people who accepted each other); kept and declined are told only//! while this person's Read receipts switch is on (`chat.settings`).use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_core::chat::{ids, CHANNEL};use cotton_core::records::page::bytes_words;use cotton_core::rules::shell_lines::{self, LineRow};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};use super::cotton_chat::{ask, bad, e164, ensure_thread, exists, iso, meta_value, namespace, not_connected, now_ms, one, person_of, preferences, read, refused, rows, text, thread_number, touch_thread, words, write, ws, MESSAGES, THREADS};use crate::handle::CottonHandle;use crate::methods::MethodError;use super::send_seal;use crate::shell::client::ClientController;/// Every method this family answers.pub const METHODS: [&str; 8] = ["send.decline", "send.inbox", "send.keep", "send.make", "send.offer", "send.picture", "send.trust", "send.undo"];pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    over(&handle.client(), method, request)}/// The same, over a named controller (the suite's phone).pub fn over(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "send.offer" => offer(client, request),        "send.make" => make(client, request),        "send.inbox" => inbox(client),        "send.keep" => keep(client, request),        "send.decline" => decline(client, request),        "send.undo" => undo(client, request),        "send.trust" => trust(client, request),        "send.picture" => picture(client, request),        other => Err(MethodError::new("unknown_method", format!("no method {other}"))),    }}/// Can this record be sent, what it is, how much travels, and to whom: the/// object names this person's people, everyone they accepted on Cotton/// (an app with no chat tool keeps no thread on the phone, and the threads are/// sealed where it does), each with its number, name and trust; a name this/// phone's People knows better wins./// The table a card's record is sent as: a photo on the media engine's deck (Photos) is the photo it is (R5).fn sent_as(table: &str) -> &str {    if table == "media" { "photo" } else { table }}fn offer(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let table = sent_as(text(request, "table")?);    let id = text(request, "id")?;    let mut answer = ask(client, "GET", "/v1/send/people", None).map_err(refused)?;    super::circle::open_sealed(client, &mut answer);    let people: Vec<Value> = answer["people"]        .as_array()        .into_iter()        .flatten()        .filter_map(|p| {            let number = p["number"].as_str()?;            let (_, known) = person_of(client, number);            let mut p = p.clone();            if let Some(name) = known {                p["name"] = json!(name);            }            Some(p)        })        .collect();    let defs = send_seal::definitions(client)?;    let tables = send_seal::tables_of(&defs);    if let Err(no) = cotton_core::cotton_rules::send::sendable(table, &tables) {        return Ok(json!({ "sendable": false, "words": no.words, "people": people }));    }    let from = cotton_core::cotton_rules::send::From { number: String::new(), name: None };    match send_seal::compose(client, &tables, table, id, "offer-preview", from) {        Ok(payload) => Ok(json!({ "sendable": true, "title": payload.title, "bytes": payload.bytes, "records": send_seal::counts(&payload), "people": people })),        Err(no) => Ok(json!({ "sendable": false, "words": no.message, "people": people })),    }}/// The send leaves, and the thread with that person carries it at once as this person's own item.fn make(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let table = sent_as(text(request, "table")?).to_string();    let id = text(request, "id")?.to_string();    let number = number_of(client, request, "to")?;    let (_, name) = person_of(client, &number);    let name = name.or_else(|| request["name"].as_str().map(str::to_string));    // Sealed on this phone to their sharing key: the object routes a box it cannot open.    let secret = send_seal::post_key(client)?;    let key = ask(client, "GET", &format!("/v1/send/key?number={}", enc(&number)), None).map_err(refused)?;    let receiver = key["key"].as_str().ok_or_else(not_connected)?.to_string();    let me = key["me"].as_str().unwrap_or_default().to_string();    let defs = send_seal::definitions(client)?;    let tables = send_seal::tables_of(&defs);    let send_id = send_seal::fresh_id();    let own_name = request["from_name"].as_str().map(str::to_string);    let payload = send_seal::compose(client, &tables, &table, &id, &send_id, cotton_core::cotton_rules::send::From { number: me, name: own_name })?;    let keys = send_seal::file_keys(client, &payload)?;    let boxed = send_seal::seal_payload(&secret, &receiver, &payload, &keys)?;    let files: Vec<Value> = payload.files.iter().map(|f| if f.folder { json!({ "key": f.key, "folder": true }) } else { json!({ "key": f.key }) }).collect();    let mut sent = ask(client, "POST", "/v1/send/make", Some(&json!({ "id": send_id, "to": number, "box": boxed, "table": table, "files": files }))).map_err(refused)?;    sent["title"] = json!(payload.title);    sent["card"] = send_seal::card_of(defs.iter().find(|d| d.id == table), &payload);    let ns = namespace(client)?;    let rows = lines(client);    let mut item = json!({ "id": send_id, "table": table, "record": id, "to": number, "title": sent["title"], "bytes": sent["bytes"], "state": "offered", "at": sent["at"], "card": sent["card"] });    item["shows"] = shows(&item, true, &rows);    let said = receipt(sent["title"].as_str().unwrap_or_default(), name.as_deref().unwrap_or(&number), &rows);    let at = iso(sent["at"].as_i64().unwrap_or_else(|| now_ms(client)));    let (n, it) = (ns.clone(), item.clone());    let preview = say(&rows, "preview.out", &[("title", it["title"].as_str().unwrap_or_default())]);    let landed = write(client, "send.make", move |ctx| land(ctx, &n, &number, name.as_deref(), &it, true, &at, &preview))?;    Ok(json!({ "id": send_id, "thread": landed["thread"], "message": landed["message"], "title": sent["title"], "bytes": sent["bytes"], "state": "offered", "card": sent["card"], "receipt": said }))}/// What arrived and what this person sent, each kept as its thread's item; the answer is the object's, with what landed new.fn inbox(client: &ClientController) -> Result<Value, MethodError> {    let secret = send_seal::post_key(client)?;    let mut answer = ask(client, "GET", "/v1/send/inbox", None).map_err(refused)?;    let ns = namespace(client)?;    let rows = lines(client);    let defs = send_seal::definitions(client)?;    let tables = send_seal::tables_of(&defs);    // Trusted people's offers are kept as they arrive, by this phone: only a phone opens them.    let mut kept_now = false;    for item in answer["in"].as_array().cloned().into_iter().flatten() {        if item["trusted"] == json!(true) && item["state"] == json!("offered") && item["fits"] != json!(false) {            if let Some(id) = item["id"].as_str() {                kept_now |= keep_sealed(client, &secret, &tables, &item, id).is_ok();            }        }    }    if kept_now {        answer = ask(client, "GET", "/v1/send/inbox", None).map_err(refused)?;    }    let mut landed = Vec::new();    let mut incoming = Vec::new();    for item in answer["in"].as_array().into_iter().flatten() {        let Some(peer) = item["from"].as_str().and_then(e164) else { continue };        // The box opens here or the offer is not drawn: a send that does not open is nobody's to keep.        let Ok(payload) = send_seal::open_payload(&secret, item, &tables) else { continue };        let (_, name) = person_of(client, &peer);        let name = name.or_else(|| payload.from.name.clone());        let at = iso(item["at"].as_i64().unwrap_or_else(|| now_ms(client)));        // The card's words, by the name this phone knows them by.        let mut item = item.clone();        if let Some(name) = &name {            item["name"] = json!(name);        }        let id = item["id"].as_str().unwrap_or_default().to_string();        // Kept while its bytes copied on the object's alarm: the rows are this phone's to write now.        if pending(client, &id) && item["state"] == json!("kept") {            if let Ok(root) = land_rows(client, &tables, &payload, name.clone(), &id) {                item["landed"] = root;            }        }        let arriving = send_seal::land_of(client, &tables, &payload, name.clone())?;        item["title"] = json!(payload.title);        item["records"] = send_seal::counts(&payload);        item["card"] = send_seal::card_of(defs.iter().find(|d| d.id == payload.root.table), &payload);        item["held"] = if item["state"] == json!("offered") { send_seal::held_root(client, &arriving, &payload).unwrap_or(Value::Null) } else { Value::Null };        if let Some(map) = item.as_object_mut() {            for gone in ["box", "files", "source_database"] {                map.remove(gone);            }        }        item["shows"] = shows(&item, false, &rows);        incoming.push(item.clone());        let (n, it) = (ns.clone(), item.clone());        let preview = say(&rows, "preview.in", &[("title", it["title"].as_str().unwrap_or_default())]);        let done = write(client, "send.inbox", move |ctx| land(ctx, &n, &peer, name.as_deref(), &it, false, &at, &preview))?;        if done["new"] == json!(true) {            landed.push(json!({ "thread": done["thread"], "message": done["message"], "id": item["id"] }));        }    }    // An offer the object no longer holds (declined on another phone, taken back, expired) is put away here too.    let held: Vec<String> = answer["in"].as_array().into_iter().flatten().filter_map(|i| i["id"].as_str().map(external)).collect();    let now = iso(now_ms(client));    write(client, "send.gone", move |ctx| {        let open = super::cotton_chat::rows(ctx, &format!("SELECT id, external_id, meta FROM {MESSAGES} WHERE workspace_id = ? AND direction = 'in' AND external_id LIKE 'send-%' AND trashed_at IS NULL"), &[ws(ctx)])?;        for row in open {            let external = row.get("external_id").and_then(Value::as_str).unwrap_or_default();            let state = meta_value(row.get("meta").unwrap_or(&Value::Null))["cotton"]["send"]["state"].as_str().map(str::to_string);            if held.iter().any(|h| h == external) || !matches!(state.as_deref(), Some("offered" | "keeping")) {                continue;            }            let mut patch = Map::new();            patch.insert("trashed_at".into(), json!(now));            update_row(ctx, MESSAGES, row.get("id").and_then(Value::as_str).unwrap_or_default(), patch).map_err(|f| f.to_string())?;        }        Ok(Value::Null)    })?;    for item in answer["out"].as_array().into_iter().flatten() {        let Some(id) = item["id"].as_str() else { continue };        let message = ids::message_id(&ns, ids::ME, &external(id));        let state = item["state"].clone();        let rows = rows.clone();        write(client, "send.state", move |ctx| set_fields(ctx, &message, &[("state", state.clone())], &rows))?;    }    let outgoing: Vec<Value> = answer["out"].as_array().into_iter().flatten().map(|item| {        let mut item = item.clone();        item["shows"] = shows(&item, true, &rows);        item    }).collect();    Ok(json!({ "in": incoming, "out": outgoing, "landed": landed }))}fn keep(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?.to_string();    let secret = send_seal::post_key(client)?;    let tables = send_seal::tables_of(&send_seal::definitions(client)?);    let inbox = ask(client, "GET", "/v1/send/inbox", None).map_err(refused)?;    let item = inbox["in"].as_array().into_iter().flatten().find(|i| i["id"].as_str() == Some(id.as_str())).cloned().ok_or_else(|| words("not_found", "That send is not here any more: it was declined, or it expired."))?;    let kept = keep_sealed(client, &secret, &tables, &item, &id)?;    let message = incoming_message(client, &id)?;    let state = kept["state"].clone();    let landed = kept.get("landed").cloned().unwrap_or(Value::Null);    let copied = kept.get("copied").cloned().unwrap_or(Value::Null);    let rows = lines(client);    let item = write(client, "send.keep", move |ctx| {        let mut fields = vec![("state", state.clone())];        if !landed.is_null() {            fields.push(("landed", landed.clone()));        }        if !copied.is_null() {            fields.push(("copied", copied.clone()));        }        set_fields(ctx, &message, &fields, &rows)    })?;    let mut kept = kept;    kept["shows"] = item["shows"].clone();    Ok(kept)}/// One arrival kept on this phone: its box opened, its landing planned over/// this phone's copy, the object asked to copy the bytes; once they have, the/// rows written here (sealed by this phone's sync) and the landed root told.fn keep_sealed(client: &ClientController, secret: &[u8; 32], tables: &cotton_core::cotton_rules::send::Tables, item: &Value, id: &str) -> Result<Value, MethodError> {    let (payload, file_keys) = send_seal::open_sent(secret, item, tables)?;    let peer = item["from"].as_str().unwrap_or_default();    let (_, name) = person_of(client, peer);    let name = name.or_else(|| payload.from.name.clone());    let land = send_seal::land_of(client, tables, &payload, name.clone())?;    let landing = send_seal::plan(client, &land)?;    // A file the sender sealed under their own key is opened with the key the box carried and sealed again here under this person's; the object copies only what it may as it lies.    // A photo enters as its bytes (CAPTURED): captured here, its copy and its record not asked of anyone else.    let mut captured: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();    let mut taken: std::collections::HashSet<String> = std::collections::HashSet::new();    for create in landing.creates.iter().filter(|c| send_seal::CAPTURED.contains(&c.table.as_str())) {        let key = create.data.get("key").and_then(Value::as_str).unwrap_or_default();        let Some(copy) = landing.copies.iter().find(|c| c.to == key) else { continue };        let id_here = send_seal::capture_sent(client, id, &copy.from, file_keys.get(&copy.from).and_then(Value::as_str), &create.data)?;        taken.insert(copy.from.clone());        captured.insert(create.id.clone(), id_here);    }    let mut copies = Vec::new();    for copy in landing.copies.iter().filter(|c| !taken.contains(&c.from)) {        let resealed = match file_keys.get(&copy.from).and_then(Value::as_str) {            Some(fk) => send_seal::reseal(client, id, copy, fk)?,            None => false,        };        if !resealed {            copies.push(copy.clone());        }    }    let (tell, _) = preferences(client);    let mut kept = ask(client, "POST", "/v1/send/keep", Some(&json!({ "id": id, "tell": tell, "copies": copies, "root": landing.root }))).map_err(refused)?;    match kept["state"].as_str() {        Some("kept") if kept["fresh"] == json!(true) => {            // A message lands in this person's thread with whoever sent it, as chat writes one (it has no thread of its own to travel with).            for create in landing.creates.iter().filter(|c| c.table == "message") {                let landed = land_message(client, peer, name.as_deref(), id, &create.id, &create.data)?;                captured.insert(create.id.clone(), landed);            }            let root = send_seal::write_rows_after(client, &landing, captured)?;            let _ = ask(client, "POST", "/v1/send/landed", Some(&json!({ "id": id, "root": root })));            kept["landed"] = root;        }        Some("keeping") => mark_pending(client, id, true),        _ => {}    }    Ok(kept)}/// A kept send's rows written once its bytes have: planned again over this phone's copy (what it already holds is not made again).fn land_rows(client: &ClientController, tables: &cotton_core::cotton_rules::send::Tables, payload: &cotton_core::cotton_rules::send::Payload, name: Option<String>, id: &str) -> Result<Value, MethodError> {    let land = send_seal::land_of(client, tables, payload, name)?;    let landing = send_seal::plan(client, &land)?;    let root = send_seal::write_rows(client, &landing)?;    let _ = ask(client, "POST", "/v1/send/landed", Some(&json!({ "id": id, "root": root })));    mark_pending(client, id, false);    Ok(root)}/// Sends this phone began keeping whose rows wait for their bytes.fn pending_set() -> &'static std::sync::Mutex<std::collections::HashSet<String>> {    static PENDING: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> = std::sync::OnceLock::new();    PENDING.get_or_init(|| std::sync::Mutex::new(std::collections::HashSet::new()))}fn mark_pending(_client: &ClientController, id: &str, on: bool) {    if let Ok(mut set) = pending_set().lock() {        if on {            set.insert(id.to_string());        } else {            set.remove(id);        }    }}fn pending(_client: &ClientController, id: &str) -> bool {    pending_set().lock().map(|s| s.contains(id)).unwrap_or(false)}/// Declined, the offer goes from the object and its item from the thread: nothing stays.fn decline(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?.to_string();    let (tell, _) = preferences(client);    ask(client, "POST", "/v1/send/decline", Some(&json!({ "id": id, "tell": tell }))).map_err(refused)?;    let message = incoming_message(client, &id)?;    let now = iso(now_ms(client));    write(client, "send.decline", move |ctx| {        if exists(ctx, MESSAGES, &message)? {            let mut patch = Map::new();            patch.insert("trashed_at".into(), json!(now));            update_row(ctx, MESSAGES, &message, patch).map_err(|f| f.to_string())?;        }        Ok(Value::Null)    })?;    Ok(json!({ "ok": true }))}/// Everything one send brought goes, or everything one person sent on a day.fn undo(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    if let Some(id) = request.get("id").and_then(Value::as_str) {        let id = id.to_string();        let answer = ask(client, "POST", "/v1/send/undo", Some(&json!({ "id": id }))).map_err(refused)?;        // A send this person made is taken back (the object answers its state); one they kept has what it brought removed.        let message = match answer.get("state") {            Some(_) => ids::message_id(&namespace(client)?, ids::ME, &external(&id)),            None => incoming_message(client, &id)?,        };        let mut answer = answer;        if answer.get("state").is_none() {            // What a kept send brought is this phone's to remove: its rows' send_id is sealed on the object.            let removed = remove_brought(client, |data| data.get("send_id").and_then(Value::as_str) == Some(id.as_str()))?;            answer["removed"] = json!(answer["removed"].as_u64().unwrap_or(0) + removed);        }        let rows = lines(client);        let item = write(client, "send.undo", move |ctx| set_fields(ctx, &message, &[("state", json!("undone"))], &rows))?;        answer["shows"] = item["shows"].clone();        return Ok(answer);    }    let from = number_of(client, request, "from")?;    let day = text(request, "day")?.to_string();    let mut answer = ask(client, "POST", "/v1/send/undo", Some(&json!({ "from": from, "day": day }))).map_err(refused)?;    let removed = remove_brought(client, |data| data.get("sent_by_number").and_then(Value::as_str) == Some(from.as_str()) && data.get("sent_at").and_then(Value::as_str).is_some_and(|at| at.starts_with(&day)))?;    answer["removed"] = json!(answer["removed"].as_u64().unwrap_or(0) + removed);    Ok(answer)}/// Every record a send brought that `brought` matches, removed on this phone/// (tables sealed on the object: the object cannot read their send_id).fn remove_brought(client: &ClientController, brought: impl Fn(&Map<String, Value>) -> bool) -> Result<u64, MethodError> {    let mut removed = 0;    for def in send_seal::definitions(client)?.into_iter().filter(|d| d.send.is_some() && d.seal.is_some()) {        let listed = super::records::call(client, "records.list", &json!({ "table": def.id, "page": 0, "limit": 500 }))?;        for record in listed["records"].as_array().into_iter().flatten() {            let data = record.get("data").and_then(Value::as_object).cloned().unwrap_or_default();            if !brought(&data) {                continue;            }            if let Some(id) = record["id"].as_str() {                super::records::call(client, "records.delete", &json!({ "table": def.id, "id": id }))?;                removed += 1;            }        }    }    Ok(removed)}fn trust(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let number = number_of(client, request, "number")?;    let trusted = request.get("trusted").and_then(Value::as_bool).ok_or_else(|| bad("trusted", "true or false"))?;    ask(client, "POST", "/v1/send/trust", Some(&json!({ "number": number, "trusted": trusted }))).map_err(refused)}/// A picture an offer names (its cover), fetched into `dir` for the card to draw before Keep.fn picture(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = text(request, "id")?;    let media = text(request, "key")?;    let dir = std::path::PathBuf::from(text(request, "dir")?);    let door = client.object_door().ok_or_else(not_connected)?;    let path = format!("/v1/send/{id}/media?key={}", enc(media));    let (status, bytes) = door.address.send_bytes(door.exchange.as_ref(), "GET", &path, cotton_client::transport::object::bearer(&door.credential), None).map_err(refused)?;    if status != 200 {        return Err(words("not_found", "The picture has gone."));    }    std::fs::create_dir_all(&dir).map_err(|e| MethodError::new("unwritable", e.to_string()))?;    let name = media.rsplit('/').next().unwrap_or("picture");    let file = dir.join(format!("send-{id}-{name}"));    // not a copy: a picture being sent.    std::fs::write(&file, bytes).map_err(|e| MethodError::new("unwritable", e.to_string()))?;    Ok(json!({ "path": file.to_string_lossy() }))}// ── what the shell draws ────────────────────────────────────────────────/// The database's lines, the kit's under them.fn lines(client: &ClientController) -> Vec<LineRow> {    client.with_file(|file| Ok(cotton_tools::presentation::line_rows(file.driver, file.workspace_id))).unwrap_or_default()}fn say(rows: &[LineRow], line: &str, fills: &[(&str, &str)]) -> String {    shell_lines::resolve("send", line, rows, fills).unwrap_or_default()}/// `shell.opened {step: send, table, id}`: the people the held card can be/// sent to, as the fan's tier of persons. The tier says what goes and its/// size (`says`); each person's row sends at a tap (`sends`: their number) and/// holds the trust act (`holds`), trusted ones marked (`detail`). With nobody/// to send to, the rows are empty and `empty` says so, with the door to Cotton/// chat's request where this app keeps chat; a record that cannot be sent/// says why in the object's words. Last, always, the Add a person row/// (`add`: its words, the number's hint and its ask), Account's Your people/// add step (`your_people`, one implementation). A person still waiting (added/// here, not yet adding back) is a row with `waiting` and its line in/// `detail`, sending nothing and holding nothing.pub fn step(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let rows = lines(client);    let offer = offer(client, request)?;    if offer["sendable"] != json!(true) {        return Ok(json!({ "step": { "kind": "send", "rows": [], "refused": offer["words"] } }));    }    let title = offer["title"].as_str().unwrap_or_default();    let size = bytes_words(offer["bytes"].as_f64().unwrap_or_default());    let people: Vec<Value> = offer["people"].as_array().into_iter().flatten().filter_map(|p| person_row(p, &size, &rows)).collect();    let mut step = json!({        "kind": "send", "says": say(&rows, "who.says", &[("title", title), ("size", &size)]), "title": title, "bytes": offer["bytes"], "rows": people,        "add": super::your_people::add_row(),    });    if step["rows"].as_array().is_some_and(Vec::is_empty) {        let mut empty = json!({ "words": say(&rows, "who.none", &[]) });        if let Some(path) = chat_door(client)? {            empty["door"] = json!({ "words": say(&rows, "who.door", &[]), "path": path });        }        step["empty"] = empty;    }    Ok(json!({ "step": step }))}/// One person of the Send tier: their name (else their number), initials,/// the size that goes (said before sending) and whether every send from/// them is kept, and the act a hold on them offers.fn person_row(person: &Value, size: &str, rows: &[LineRow]) -> Option<Value> {    let number = person["number"].as_str()?;    let name = person["name"].as_str().filter(|n| !n.trim().is_empty()).unwrap_or(number);    let trusted = person["trusted"] == json!(true);    let initials: String = name.split_whitespace().take(2).filter_map(|word| word.chars().find(|c| c.is_alphanumeric())).collect();    let initials = if initials.is_empty() { "+".to_string() } else { initials.to_uppercase() };    if person["waiting"] == json!(true) {        return Some(json!({ "value": number, "words": name, "number": number, "trusted": false, "initials": initials, "waiting": true, "detail": say(rows, "who.waiting", &[]) }));    }    let mut row = json!({        "value": number, "words": name, "number": number, "trusted": trusted,        "initials": initials,        "sends": { "to": number },        "holds": [trust_act(number, name, trusted, rows, "who")],    });    row["detail"] = json!(say(rows, if trusted { "who.trusted" } else { "who.size" }, &[("size", size)]));    Some(row)}/// Always keep from {name}, or its undoing: what `send.trust` is asked.fn trust_act(number: &str, name: &str, trusted: bool, rows: &[LineRow], set: &str) -> Value {    let line = if trusted { format!("{set}.untrust") } else { format!("{set}.trust") };    json!({ "id": "trust", "words": say(rows, &line, &[("name", name)]), "trust": { "number": number, "trusted": !trusted } })}/// Where Cotton chat's request is written, in an app that keeps chat: the/// thread table's own Plus. None in an app with no chat tool.fn chat_door(client: &ClientController) -> Result<Option<String>, MethodError> {    let keeps = super::tool_acts::app_kit(client)?.is_none_or(|kit| kit.keeps_table("thread"));    if !keeps {        return Ok(None);    }    let mut path = None;    client        .read_rows("send.door", &mut |ctx| {            let tables = cotton_tools::definitions::table_definitions(ctx).map_err(|failure| failure.to_string())?.definitions;            path = tables.into_iter().find(|table| table.id == "thread").and_then(|table| table.create).and_then(|create| create.path);            Ok(Value::Null)        })        .map_err(|why| MethodError::new("unreadable", why))?;    Ok(path)}/// What a send's card says under it, by its state and side: the line, the/// acts it offers (Keep with its size, Decline, Open, Remove, Undo, the/// trust act) and the copy's progress. The shell draws these and decides none.pub fn shows(item: &Value, out: bool, rows: &[LineRow]) -> Value {    let state = item["state"].as_str().unwrap_or("offered");    let size = bytes_words(item["bytes"].as_f64().unwrap_or_default());    let mut shows = Map::new();    let mut acts = Vec::new();    if out {        shows.insert("line".into(), json!(say(rows, &format!("state.{state}"), &[])));        if matches!(state, "offered" | "delivered") {            acts.push(json!({ "id": "undo", "words": say(rows, "receipt.undo", &[]) }));        }    } else {        let number = item["from"].as_str().unwrap_or_default();        let name = item["name"].as_str().filter(|n| !n.trim().is_empty()).unwrap_or(number);        shows.insert("from".into(), json!(say(rows, "card.from", &[("name", name)])));        let held = item["held"].is_object();        match state {            "offered" if held => {                shows.insert("line".into(), json!(say(rows, "card.held", &[])));                acts.push(json!({ "id": "open", "words": say(rows, "card.open", &[]), "opens": item["held"] }));                acts.push(json!({ "id": "decline", "words": say(rows, "card.decline", &[]) }));            }            "offered" => {                if item["fits"] == json!(false) {                    shows.insert("line".into(), item.get("words").cloned().unwrap_or(Value::Null));                } else {                    acts.push(json!({ "id": "keep", "words": say(rows, "card.keep", &[("size", &size)]), "primary": true }));                }                acts.push(json!({ "id": "decline", "words": say(rows, "card.decline", &[]) }));            }            "keeping" => {                let done = bytes_words(item["copied"]["done"].as_f64().unwrap_or_default());                let whole = item["copied"]["bytes"].as_f64().map(bytes_words).unwrap_or(size.clone());                shows.insert("line".into(), json!(say(rows, "card.keeping", &[("done", &done), ("size", &whole)])));                shows.insert("progress".into(), json!({ "done": item["copied"]["done"], "bytes": item["copied"]["bytes"] }));            }            "kept" => {                shows.insert("line".into(), json!(say(rows, "card.kept", &[])));                if item["landed"].is_object() {                    acts.push(json!({ "id": "open", "words": say(rows, "card.open", &[]), "opens": item["landed"] }));                }                acts.push(json!({ "id": "undo", "words": say(rows, "card.undo", &[]), "red": true }));            }            "undone" => {                shows.insert("line".into(), json!(say(rows, "card.undone", &[])));            }            _ => {}        }        if !number.is_empty() && state != "undone" {            acts.push(trust_act(number, name, item["trusted"] == json!(true), rows, "card"));        }    }    shows.insert("acts".into(), Value::Array(acts));    Value::Object(shows)}/// The fan card standing aside in an app with no chat tool (Books), where/// a send has no thread to arrive in: what was sent to this person.pub const SENT_CARD: &str = "sent";/// `SENT_CARD` for `shell.fan`, where this app keeps no chat and this/// phone holds something sent to its person (offered, copying or kept, not/// put away): its name and how many wait for an answer. None otherwise.pub fn sent_card(client: &ClientController) -> Option<Value> {    let keeps_chat = super::tool_acts::app_kit(client).ok().flatten().is_none_or(|kit| kit.keeps_table("message"));    if keeps_chat {        return None;    }    let held = read(client, "send.held", |ctx| {        let open = rows(ctx, &format!("SELECT meta FROM {MESSAGES} WHERE workspace_id = ? AND direction = 'in' AND external_id LIKE 'send-%' AND trashed_at IS NULL"), &[ws(ctx)])?;        let states: Vec<Value> = open.iter().map(|row| meta_value(row.get("meta").unwrap_or(&Value::Null))["cotton"]["send"]["state"].clone()).collect();        Ok(Value::Array(states))    })    .ok()?;    let states: Vec<&str> = held.as_array()?.iter().filter_map(Value::as_str).filter(|state| matches!(*state, "offered" | "keeping" | "kept")).collect();    if states.is_empty() {        return None;    }    let waiting = states.iter().filter(|state| **state == "offered").count();    Some(json!({ "id": SENT_CARD, "label": say(&lines(client), "sent_to_you", &[]), "default": false, "count": waiting, "read": { "table": "" }, "aside": true }))}/// "From {name}, {day}": where a record a send brought came from, read off/// its provenance columns (`sent_by`, else `sent_by_number`; `sent_at`'s day/// in `zone`). None for a record no send brought.pub fn from_line(data: &Map<String, Value>, zone: &str, rows: &[LineRow]) -> Option<String> {    let name = ["sent_by", "sent_by_number"].iter().find_map(|key| data.get(*key).and_then(Value::as_str).filter(|n| !n.trim().is_empty()))?;    let dates = cotton_core::records::page::Words::of_rows(rows).dates;    let day = data.get("sent_at").and_then(Value::as_str).and_then(|at| cotton_core::records::page::face_day_words(at.get(..10)?, zone, None, &dates))?;    Some(say(rows, "whole.from", &[("name", name), ("date", &day)]))}/// The receipt Send leaves: "Sent {title} to {name}", with its Undo.fn receipt(title: &str, name: &str, rows: &[LineRow]) -> Value {    json!({ "words": say(rows, "receipt.sent", &[("title", title), ("name", name)]), "undo": say(rows, "receipt.undo", &[]), "undone": say(rows, "receipt.undone", &[]) })}// ── the thread item ─────────────────────────────────────────────────────/// A send's external id on its thread row.fn external(id: &str) -> String {    format!("send-{id}")}/// One send as its thread's item: made once, its meta kept as the object/// says after, the thread's preview said as `preview`.#[allow(clippy::too_many_arguments)]fn land(ctx: &mut Ctx<'_>, ns: &str, number: &str, name: Option<&str>, item: &Value, out: bool, at: &str, preview: &str) -> Result<Value, String> {    let thread = ensure_thread(ctx, ns, number, name, None, None, true)?;    let id = item["id"].as_str().unwrap_or_default();    let author = if out { ids::ME } else { number };    let message = ids::message_id(ns, author, &external(id));    if exists(ctx, MESSAGES, &message)? {        let mut meta = meta_of(ctx, &message)?;        // The inbox is read on every launch and on a clock: an item the        // object says nothing new of is not written again (send-walk: each        // read rewrote every item, a sealed row's write that waits for ever).        if meta["cotton"]["send"] == *item {            return Ok(json!({ "thread": thread, "message": message, "new": false }));        }        let mut patch = Map::new();        meta["cotton"]["send"] = item.clone();        patch.insert("meta".into(), meta);        update_row(ctx, MESSAGES, &message, patch).map_err(|f| f.to_string())?;        return Ok(json!({ "thread": thread, "message": message, "new": false }));    }    let mut columns = Map::new();    columns.insert("thread_id".into(), json!(thread));    columns.insert("direction".into(), json!(if out { "out" } else { "in" }));    columns.insert("channel".into(), json!(CHANNEL));    columns.insert("origin".into(), json!("live"));    columns.insert("body".into(), json!(""));    columns.insert("external_id".into(), json!(external(id)));    columns.insert("sent_at".into(), json!(at));    if out {        columns.insert("send_state".into(), json!("sent"));    }    columns.insert("meta".into(), json!({ "cotton": { "send": item, "written_at": at } }));    insert_row(ctx, MESSAGES, &message, columns).map_err(|f| f.to_string())?;    touch_thread(ctx, &thread, at, Some(preview), false)?;    Ok(json!({ "thread": thread, "message": message, "new": true }))}/// A sent message kept: written into this person's thread with the sender (made when new), inbound, its words and/// its picture as the send carried them, and which send brought it in its meta. Answers its id.fn land_message(client: &ClientController, number: &str, name: Option<&str>, send: &str, sent_id: &str, data: &Map<String, Value>) -> Result<String, MethodError> {    let ns = namespace(client)?;    let number = number.to_string();    let name = name.map(str::to_string);    let external_id = format!("sent-{send}-{sent_id}");    let data = data.clone();    let send = send.to_string();    let at = iso(now_ms(client));    let landed = write(client, "send.keep", move |ctx| {        let thread = ensure_thread(ctx, &ns, &number, name.as_deref(), None, None, true)?;        let message = ids::message_id(&ns, &number, &external_id);        if exists(ctx, MESSAGES, &message)? {            return Ok(json!({ "message": message }));        }        let body = data.get("body").and_then(Value::as_str).unwrap_or_default().to_string();        let mut columns = Map::new();        columns.insert("thread_id".into(), json!(thread));        columns.insert("direction".into(), json!("in"));        columns.insert("channel".into(), json!(CHANNEL));        columns.insert("origin".into(), json!("live"));        columns.insert("body".into(), json!(body));        if let Some(media) = data.get("media").filter(|m| !m.is_null()) {            columns.insert("media".into(), media.clone());        }        columns.insert("external_id".into(), json!(external_id));        columns.insert("sent_at".into(), json!(at));        columns.insert("meta".into(), json!({ "cotton": { "sent": { "send_id": send, "from": number }, "written_at": at } }));        insert_row(ctx, MESSAGES, &message, columns).map_err(|f| f.to_string())?;        touch_thread(ctx, &thread, &at, Some(&body), false)?;        Ok(json!({ "message": message }))    })?;    Ok(landed["message"].as_str().unwrap_or_default().to_string())}fn meta_of(ctx: &mut Ctx<'_>, message: &str) -> Result<Value, String> {    let row = one(ctx, &format!("SELECT meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(message.to_string())])?;    Ok(row.map(|row| meta_value(row.get("meta").unwrap_or(&Value::Null))).unwrap_or_else(|| json!({ "cotton": {} })))}/// Fields of a thread item's send, set in one write (a second write in the/// same act would read the row as it stood), and what its card says with/// them; the item as it now stands.fn set_fields(ctx: &mut Ctx<'_>, message: &str, fields: &[(&str, Value)], rows: &[LineRow]) -> Result<Value, String> {    let Some(row) = one(ctx, &format!("SELECT direction FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(message.to_string())])? else {        return Ok(Value::Null);    };    let out = row.get("direction").and_then(Value::as_str) == Some("out");    let mut meta = meta_of(ctx, message)?;    if !meta["cotton"]["send"].is_object() {        meta["cotton"]["send"] = json!({});    }    for (field, value) in fields {        meta["cotton"]["send"][*field] = value.clone();    }    meta["cotton"]["send"]["shows"] = shows(&meta["cotton"]["send"], out, rows);    let item = meta["cotton"]["send"].clone();    if meta_of(ctx, message)?["cotton"]["send"] == item {        return Ok(item);    }    let mut patch = Map::new();    patch.insert("meta".into(), meta);    update_row(ctx, MESSAGES, message, patch).map_err(|f| f.to_string())?;    Ok(item)}/// The thread row of a send this person received, by the send's id.fn incoming_message(client: &ClientController, id: &str) -> Result<String, MethodError> {    let external = external(id);    let found = read(client, "send.item", move |ctx| Ok(one(ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND external_id = ? AND direction = 'in'"), &[ws(ctx), SqlValue::Text(external.clone())])?.and_then(|r| r.get("id").cloned()).unwrap_or(Value::Null)))?;    Ok(found.as_str().unwrap_or_default().to_string())}/// A number from `thread` or the named field.fn number_of(client: &ClientController, request: &Value, field: &str) -> Result<String, MethodError> {    if let Some(thread) = request.get("thread").and_then(Value::as_str) {        return thread_number(client, thread);    }    e164(text(request, field)?).ok_or_else(|| words("bad_number", "That isn't a phone number Cotton can use."))}fn enc(text: &str) -> String {    text.bytes()        .map(|b| match b {            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),            _ => format!("%{b:02X}"),        })        .collect()}#[cfg(test)]#[path = "cotton_send_tests.rs"]mod tests;