Cotton code
254 lines · 16.0 KB · RustRaw
//! The Messages face's reads over a phone's own rows: the stream's order,//! its quiet count, search, and one chat's slips. Every number and word is//! invented.use cotton_core::chat::payload::{LinkPreview, Payload, Picture};use cotton_core::chat::seal;use cotton_core::vault::wrap::public_of;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::phone::cotton_chat::over;use crate::phone::passwords::tests::phone;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange};use crate::phone::personal_object::ObjectDoor;const ME: &str = "+15550100002";const ASHA: &str = "+15550100001";const BIMAL: &str = "+15550100003";fn scalar(seed: u8) -> [u8; 32] {    let mut bytes = [seed; 32];    bytes[0] = seed.wrapping_mul(7).wrapping_add(1);    bytes}fn private(seed: u8) -> String {    seal::key_text(&scalar(seed))}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 hold_definitions(handle: &CottonHandle) {    let thread: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/thread.json")).expect("the thread definition");    handle.client().with_writer(|replica| cotton_client::transport::object::hold_defined_columns(&replica.driver, [&thread]).map(|_| ())).unwrap();}/// Each sender's phone is its own scalar (2 is this phone); `items` land through the inbox.fn land(handle: &CottonHandle, items: Vec<(u8, &str, &str, bool, i64)>) -> Value {    land_with(handle, items, 0)}/// As [`land`], each message carrying `pictures` pictures.fn land_with(handle: &CottonHandle, items: Vec<(u8, &str, &str, bool, i64)>, pictures: usize) -> Value {    let mut boxed = Vec::new();    let mut replies = Vec::new();    for (i, (seed, from, words, request, at)) in items.iter().enumerate() {        let carried = (0..pictures)            .map(|n| Picture { file: format!("file{n}"), key: "a".repeat(43), sha256: "0".repeat(64), mime: "image/jpeg".into(), width: Some(4), height: Some(3), bytes: 10, ..Picture::default() })            .collect();        let payload = Payload::message(&format!("msg{i:013}"), from, ME, *at, Some(words.to_string()), None, carried);        boxed.push(json!({ "id": payload.id, "kind": "message", "peer": from, "out": false, "request": request, "box": seal::seal(&scalar(*seed), &public_of(&scalar(2)), &payload.bytes()).unwrap(), "at": at }));    }    replies.push(Reply::ok(&json!({ "me": ME, "items": boxed }).to_string()));    for (seed, ..) in &items {        replies.push(Reply::ok(&json!({ "me": ME, "devices": [{ "device": format!("handle{seed:016}"), "key": seal::key_text(&public_of(&scalar(*seed))) }], "own": [] }).to_string()));    }    // The ack, then each accepted sender's delivered tick.    for _ in 0..=items.len() {        replies.push(Reply::ok(r#"{"ok":true,"id":"x","at":1}"#));    }    let exchange = ScriptedExchange::new(replies);    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange, credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".into() };    handle.client().set_object_door(Some(std::sync::Arc::new(door)));    answer(handle, "chat.incoming", json!({ "privateKey": private(2) }))}fn thread_of(landed: &Value) -> String {    landed["landed"][0]["thread"].as_str().expect("a landed message").to_string()}// RULE: a stranger's chat carries the request card's words until it is answered; accepted, it carries none.#[test]fn a_request_carries_its_card_until_answered() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let thread = thread_of(&land(&handle, vec![(1, ASHA, "we met at the station", true, 1_000)]));    let slips = answer(&handle, "chat.slips", json!({ "thread": thread }));    assert_eq!(slips["request"]["accept"], "Accept");    assert_eq!(slips["request"]["refuse"], "Delete");    assert_eq!(slips["request"]["block"], "Block");    assert_eq!(slips["request"]["title"], "Someone you don't know wants to message you");    assert_eq!((slips["cotton"].as_bool(), slips["number"].as_str()), (Some(true), Some(ASHA)));    answer(&handle, "chat.accept", json!({ "thread": thread }));    assert!(answer(&handle, "chat.slips", json!({ "thread": thread })).get("request").is_none());}// RULE: a chat's slips run oldest to newest; my own slips say their delivery state in the chat set's words, theirs say none; a chat not here is refused by name.#[test]fn slips_run_in_order_and_say_my_state() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let thread = thread_of(&land(&handle, vec![(1, ASHA, "hello", false, 1_000)]));    // No door answers: my reply waits.    handle.client().set_object_door(Some(std::sync::Arc::new(ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").unwrap(), exchange: ScriptedExchange::new([]), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".into() })));    answer(&handle, "chat.send", json!({ "thread": thread, "body": "hi back", "privateKey": private(2) }));    let slips = answer(&handle, "chat.slips", json!({ "thread": thread }));    let all = slips["slips"].as_array().unwrap();    assert_eq!(all.len(), 2);    assert_eq!((all[0]["body"].as_str(), all[0]["out"].as_bool()), (Some("hello"), Some(false)));    assert!(all[0].get("state").is_none());    assert_eq!((all[1]["body"].as_str(), all[1]["state"].as_str(), all[1]["failed"].as_bool()), (Some("hi back"), Some("Waiting to send"), Some(false)));    assert!(!all[1]["when"].as_str().unwrap().is_empty());    assert!(!all[0]["day"].as_str().unwrap().is_empty());    assert_eq!(slips["words"], json!({ "write": "Write a message", "send": "Send", "picture": "Picture" }));    assert_eq!(over(&handle.client(), "chat.slips", &json!({ "thread": "nope" })).err().unwrap().code, "not_found");}// RULE: slips from several people land each in their own chat, in the sender's object's order.#[test]fn each_chat_holds_only_its_own_slips() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let landed = land(&handle, vec![(1, ASHA, "one", false, 1_000), (3, BIMAL, "two", false, 2_000), (1, ASHA, "three", false, 3_000)]);    let asha = thread_of(&landed);    let bodies: Vec<String> = answer(&handle, "chat.slips", json!({ "thread": asha }))["slips"].as_array().unwrap().iter().map(|s| s["body"].as_str().unwrap().to_string()).collect();    assert_eq!(bodies, ["one", "three"]);}// RULE: a chat whose person this phone blocked says so with Unblock where the typing line stands; unblocked, it says nothing.#[test]fn a_blocked_chat_says_so_with_unblock() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let thread = thread_of(&land(&handle, vec![(1, ASHA, "hello", false, 1_000)]));    assert!(answer(&handle, "chat.slips", json!({ "thread": thread })).get("blocked").is_none());    // The object hears the block and the unblock.    let door = |replies: Vec<Reply>| ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").unwrap(), exchange: ScriptedExchange::new(replies), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".into() };    handle.client().set_object_door(Some(std::sync::Arc::new(door(vec![Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]))));    answer(&handle, "chat.block", json!({ "thread": thread }));    let slips = answer(&handle, "chat.slips", json!({ "thread": thread }));    assert_eq!(slips["blocked"], json!({ "line": "You blocked them. They can't write to you or call you.", "unblock": "Unblock" }));    assert_eq!(slips["slips"].as_array().unwrap().len(), 1, "a block keeps the past");    answer(&handle, "chat.unblock", json!({ "thread": thread }));    assert!(answer(&handle, "chat.slips", json!({ "thread": thread })).get("blocked").is_none());}// RULE: a slip that carries pictures says how many; one that carries none says nothing of pictures.#[test]fn a_slip_says_how_many_pictures_it_carries() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let thread = thread_of(&land_with(&handle, vec![(1, ASHA, "look", false, 1_000)], 2));    let slips = answer(&handle, "chat.slips", json!({ "thread": thread }));    assert_eq!(slips["slips"][0]["pictures"], 2);    let other = thread_of(&land(&handle, vec![(3, BIMAL, "words only", false, 2_000)]));    assert!(answer(&handle, "chat.slips", json!({ "thread": other }))["slips"][0].get("pictures").is_none());}// RULE: Your people's Block blocks the person's chat on this phone too: it says so, with Unblock.#[test]fn your_peoples_block_blocks_their_chat_here() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let thread = thread_of(&land(&handle, vec![(1, ASHA, "hello", false, 1_000)]));    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").unwrap(), exchange: ScriptedExchange::new([Reply::ok(r#"{"ok":true}"#)]), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".into() };    handle.client().set_object_door(Some(std::sync::Arc::new(door)));    crate::phone::your_people::over(&handle.client(), "people.block", &json!({ "number": ASHA, "name": "Asha" })).unwrap();    assert_eq!(answer(&handle, "chat.slips", json!({ "thread": thread }))["blocked"]["unblock"], "Unblock");}// RULE: Your people's Unblock lets the person's chat on this phone take words again.#[test]fn your_peoples_unblock_unblocks_their_chat_here() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let thread = thread_of(&land(&handle, vec![(1, ASHA, "hello", false, 1_000)]));    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").unwrap(), exchange: ScriptedExchange::new([Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".into() };    handle.client().set_object_door(Some(std::sync::Arc::new(door)));    crate::phone::your_people::over(&handle.client(), "people.block", &json!({ "number": ASHA, "name": "Asha" })).unwrap();    crate::phone::your_people::over(&handle.client(), "people.unblock", &json!({ "number": ASHA, "name": "Asha" })).unwrap();    assert!(answer(&handle, "chat.slips", json!({ "thread": thread })).get("blocked").is_none());}/// Payloads from ASHA (seed 1) delivered through the inbox.fn deliver(handle: &CottonHandle, payloads: Vec<Payload>) -> Value {    let boxed: Vec<Value> = payloads        .iter()        .map(|p| json!({ "id": p.id, "kind": p.kind.as_str(), "peer": ASHA, "out": false, "request": false, "box": seal::seal(&scalar(1), &public_of(&scalar(2)), &p.bytes()).unwrap(), "at": p.at }))        .collect();    let mut replies = vec![Reply::ok(&json!({ "me": ME, "items": boxed }).to_string())];    replies.push(Reply::ok(&json!({ "me": ME, "devices": [{ "device": format!("handle{:016}", 1), "key": seal::key_text(&public_of(&scalar(1))) }], "own": [] }).to_string()));    for _ in 0..4 {        replies.push(Reply::ok(r#"{"ok":true,"id":"x","at":1}"#));    }    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: ScriptedExchange::new(replies), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".into() };    handle.client().set_object_door(Some(std::sync::Arc::new(door)));    answer(handle, "chat.incoming", json!({ "privateKey": private(2) }))}// RULE (Cotton Chat): a change from the other person lands on the message it names: their reaction under it,// their edit and delete only of their own message.#[test]fn a_change_lands_on_the_message_it_names() {    use cotton_core::chat::payload::{Change, What};    let (_dir, handle) = phone();    hold_definitions(&handle);    let landed = land(&handle, vec![(1, ASHA, "the kite is red", false, 1_000)]);    let thread = thread_of(&landed);    let message = landed["landed"][0]["message"].as_str().unwrap().to_string();    let change = |id: &str, what: What, emoji: Option<&str>, body: Option<&str>| Payload::change(id, ASHA, ME, 2_000, Change { what, message: "msg0000000000000".into(), emoji: emoji.map(str::to_string) }, body.map(str::to_string));    let got = deliver(&handle, vec![change("chg0000000000001", What::React, Some("❤️"), None), change("chg0000000000002", What::Edit, None, Some("the kite is blue"))]);    assert_eq!(got["changed"].as_array().map(Vec::len), Some(2), "{got}");    let page = answer(&handle, "chat.thread", json!({ "thread": thread }));    let bubble = page["items"].as_array().unwrap().iter().find(|i| i["message"] == json!(message)).unwrap().clone();    assert_eq!(bubble["reactions"], json!([{ "emoji": "❤️", "count": 1, "mine": false }]));    assert_eq!((bubble["text"].as_str(), bubble["edited"].as_str()), (Some("the kite is blue"), Some("edited")));    deliver(&handle, vec![change("chg0000000000003", What::Unreact, None, None), change("chg0000000000004", What::Delete, None, None)]);    let page = answer(&handle, "chat.thread", json!({ "thread": thread }));    let bubble = page["items"].as_array().unwrap().iter().find(|i| i["message"] == json!(message)).unwrap().clone();    assert!(bubble.get("reactions").is_none());    assert_eq!(bubble["kind"], "deleted");}// RULE (FEEDBACK1 item 5, 22 Nov 2026): a voice message's transcript arrives after it, as its writer's change, and// stands under its player.#[test]fn a_voice_messages_transcript_lands_after_it() {    use cotton_core::chat::payload::{Change, What};    let (_dir, handle) = phone();    hold_definitions(&handle);    let voice = Picture { file: "file0".into(), key: "a".repeat(43), sha256: "0".repeat(64), mime: "audio/mp4".into(), bytes: 10, kind: Some("voice".into()), duration_ms: Some(2_400), ..Picture::default() };    let landed = deliver(&handle, vec![Payload::message("msg0000000000000", ASHA, ME, 1_000, None, None, vec![voice])]);    let thread = thread_of(&landed);    let message = landed["landed"][0]["message"].as_str().unwrap().to_string();    let bubble = |handle: &CottonHandle| answer(handle, "chat.thread", json!({ "thread": thread }))["items"].as_array().unwrap().iter().find(|i| i["message"] == json!(message)).cloned().expect("the bubble");    assert!(bubble(&handle)["media"][0].get("transcript").is_none(), "no words until they come");    let words = Payload::change("chg0000000000001", ASHA, ME, 2_000, Change { what: What::Transcript, message: "msg0000000000000".into(), emoji: None }, Some("Running late, start without me".into()));    let got = deliver(&handle, vec![words]);    assert_eq!(got["changed"].as_array().map(Vec::len), Some(1), "{got}");    assert_eq!(bubble(&handle)["media"][0]["transcript"], "Running late, start without me");}/// RULE (FEEDBACK-4 B4): a card their phone fetched comes with their message and is drawn, picture and all; a card/// not of the words it came with is dropped, the message kept.#[test]fn their_link_card_is_drawn_when_it_is_of_their_words() {    let (_dir, handle) = phone();    let landed = land(&handle, vec![(1, ASHA, "hello", false, 500)]);    let thread = thread_of(&landed);    let card = |url: &str| Some(LinkPreview { url: url.into(), title: Some("Hill walks".into()), site: Some("Example".into()), ..LinkPreview::default() });    let mut with = Payload::message("msg0000000000001", ASHA, ME, 1_000, Some("walks: https://example.org/walks".into()), None, vec![]);    with.preview = card("https://example.org/walks");    let mut odd = Payload::message("msg0000000000002", ASHA, ME, 2_000, Some("nothing linked".into()), None, vec![]);    odd.preview = card("https://example.org/other");    deliver(&handle, vec![with, odd]);    let page = answer(&handle, "chat.thread", json!({ "thread": thread }));    let said = |words: &str| page["items"].as_array().unwrap().iter().find(|i| i["text"] == json!(words)).cloned().unwrap_or_else(|| panic!("{words}: {page}"));    assert_eq!(said("walks: https://example.org/walks")["link"]["title"], "Hill walks");    assert_eq!(said("walks: https://example.org/walks")["link"]["site"], "Example");    assert!(said("nothing linked")["link"].is_null());}