Cotton code
257 lines · 16.5 KB · RustRaw
//! Look on a phone that started its own database: choosing, reset and carry-over, for every app. Invented data only.use serde_json::{json, Value};use crate::handle::{CottonHandle, OpenConfig, OpenMode};use crate::methods::dispatch;fn phone(dir: &tempfile::TempDir) -> CottonHandle {    let handle = CottonHandle::open(OpenConfig {        mode: 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(json!({            "genesis": "personal", "flavour": "notes", "name": "Cotton Notes", "databases": "single", "database": "personal",            "business": { "server": { "real": "https://cottondb.com", "dev": "https://dev.example.invalid" } },            "fan": { "home": false, "tools": false, "opens": "notebook" }, "kit": "notes", "ground": "blank"        })),    })    .expect("an open core");    dispatch(&handle, "workspace.startLocal", &json!({ "deviceName": "An invented phone" })).expect("started on the phone");    handle}fn ask(handle: &CottonHandle, request: Value) -> Value {    dispatch(handle, "look", &request).unwrap_or_else(|error| panic!("look {request}: {error:?}"))}fn ids(answer: &Value, key: &str) -> Vec<String> {    answer[key].as_array().unwrap().iter().map(|v| v["id"].as_str().unwrap().to_string()).collect()}// Each app answers its papers, four inks, the five faces and its sizes, its defaults chosen; every choice is kept,// read back and synced in the app's own rows; reset puts every one back.#[test]fn choosing_and_reset_in_every_app() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    for (app, papers, ink, size) in [        ("notes", ["linen", "slate", "print", "dusk"], "blue", 17.0),        ("days", ["grey", "cream", "white", "night"], "blue", 1.0),        ("messages", ["warm", "mist", "print", "dusk"], "terracotta", 1.0),        ("story", ["grey", "cream", "white", "night"], "blue", 1.0),    ] {        let first = ask(&handle, json!({ "app": app }));        assert_eq!(ids(&first, "papers"), papers, "{app}");        assert_eq!(ids(&first, "faces"), ["own", "serif", "typewriter", "hyperlegible", "dyslexic"], "{app}");        assert_eq!(first["inks"].as_array().unwrap().len(), 4);        assert_eq!((first["ink"].as_str(), first["face"].as_str(), first["size"].as_f64()), (Some(ink), Some("own"), Some(size)), "{app}");        assert_eq!(first["default"], true);        assert!(!first["words"]["reset_ask"].as_str().unwrap().contains('{'), "{app}: the app's name filled");        assert_eq!(first["words"]["reset_title"], "Reset the look?");        // FEEDBACK-4 A1: Paper is two rows, one heading each, so the two chosen papers never read as two picked together.        assert_eq!((first["words"]["when_light"].as_str(), first["words"]["when_dark"].as_str()), (Some("When the phone is light"), Some("When the phone is dark")), "{app}");        let larger = first["sizes"].as_array().unwrap().last().unwrap()["value"].as_f64().unwrap();        let set = ask(&handle, json!({ "app": app, "light": papers[2], "dark": papers[3], "ink": "green", "face": "dyslexic", "size": larger }));        assert_eq!((set["light"].as_str(), set["dark"].as_str(), set["ink"].as_str(), set["face"].as_str()), (Some(papers[2]), Some(papers[3]), Some("green"), Some("dyslexic")), "{app}");        assert_eq!(set["size"].as_f64(), Some(larger));        assert_eq!(set["default"], false);        assert_eq!(set["face_name"], "OpenDyslexic");        // Read again, as the other phone would after a sync: the rows hold it.        let again = ask(&handle, json!({ "app": app }));        assert_eq!(again["light"], set["light"]);        assert_eq!(again["colours"], set["colours"]);        let reset = ask(&handle, json!({ "app": app, "reset": true }));        assert_eq!(reset["default"], true, "{app}");        assert_eq!(reset["colours"], first["colours"], "{app}: reset is the default look again");        assert!(dispatch(&handle, "look", &json!({ "app": app, "ink": "purple" })).is_err());        assert!(dispatch(&handle, "look", &json!({ "app": app, "size": 99 })).is_err());        assert!(dispatch(&handle, "look", &json!({ "app": app, "face": "comic" })).is_err());    }    // The names the iPhone first asked for write the same.    assert_eq!(ask(&handle, json!({ "app": "days", "light_paper": "cream", "dark_paper": "night" }))["dark"], "night");    ask(&handle, json!({ "app": "days", "reset": true }));    // One app's look is its own.    ask(&handle, json!({ "app": "days", "ink": "red" }));    assert_eq!(ask(&handle, json!({ "app": "story" }))["ink"], "blue");    assert!(dispatch(&handle, "look", &json!({ "app": "books" })).is_err());}// Secrets answers through the same `look` (the owner, 25 Nov 2026): four papers, five inks with Plum first and chosen,// the five faces with Red Hat Text its own, kept in its own rows and reset like the rest; its preview is its own rows.#[test]fn secrets_has_its_look() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let first = ask(&handle, json!({ "app": "keys" }));    assert_eq!(ids(&first, "papers"), ["lilac", "paper", "night", "coal"]);    assert_eq!(ids(&first, "inks"), ["plum", "jade", "garnet", "indigo", "graphite"]);    assert_eq!(ids(&first, "faces"), ["own", "serif", "typewriter", "hyperlegible", "dyslexic"]);    assert_eq!(first["faces"][0]["name"], "Red Hat Text");    assert_eq!((first["light"].as_str(), first["dark"].as_str(), first["ink"].as_str()), (Some("lilac"), Some("night"), Some("plum")));    assert_eq!(first["colours"]["light"]["accent"], "#7A3C9E");    assert_eq!(first["colours"]["dark"]["ground"], "#18131D");    assert_eq!(first["line"], "Lilac · Night");    assert_eq!(first["preview"]["secrets"][0]["title"], "Stripe test key");    assert!(first["words"]["reset_ask"].as_str().unwrap().contains("Secrets"));    let set = ask(&handle, json!({ "app": "keys", "light": "paper", "dark": "coal", "ink": "jade", "face": "hyperlegible", "size": 1.3 }));    assert_eq!((set["light"].as_str(), set["dark"].as_str(), set["ink"].as_str()), (Some("paper"), Some("coal"), Some("jade")));    assert_eq!(set["colours"]["light"]["accent"], "#11785A");    assert_eq!(ask(&handle, json!({ "app": "keys" }))["colours"], set["colours"], "kept in keys_look and keys_look_dark");    assert_eq!(ask(&handle, json!({ "app": "days" }))["ink"], "blue", "Days' look is its own");    assert!(dispatch(&handle, "look", &json!({ "app": "keys", "ink": "green" })).is_err());    let reset = ask(&handle, json!({ "app": "keys", "reset": true }));    assert_eq!(reset["colours"], first["colours"]);    assert_eq!(reset["default"], true);}// Words keeps its own rows: what a person chose in Words before Look reads the same in Look, and the other way.#[test]fn words_choices_carry_over() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let before = dispatch(&handle, "notes.settings", &json!({ "light_theme": "print", "dark_theme": "dusk", "ink": "red", "font": "mono", "font_size": 20 })).unwrap();    let look = ask(&handle, json!({ "app": "notes" }));    assert_eq!((look["light"].as_str(), look["dark"].as_str(), look["ink"].as_str()), (Some("print"), Some("dusk"), Some("red")));    assert_eq!((look["face"].as_str(), look["size"].as_f64()), (Some("typewriter"), Some(20.0)), "Mono reads as the typewriter face");    assert_eq!(look["colours"]["light"], before["light"]);    // Chosen in Look, read by notes.settings (and by a build before Look, through `font`).    ask(&handle, json!({ "app": "notes", "face": "serif", "size": 22 }));    let after = dispatch(&handle, "notes.settings", &json!({})).unwrap();    assert_eq!((after["font"].as_str(), after["face"].as_str(), after["font_size"].as_f64()), (Some("serif"), Some("serif"), Some(22.0)));    ask(&handle, json!({ "app": "notes", "face": "hyperlegible" }));    let after = dispatch(&handle, "notes.settings", &json!({})).unwrap();    assert_eq!((after["font"].as_str(), after["face"].as_str()), (Some("hyperlegible"), Some("hyperlegible")));    // The iPhone writes Look's ids through notes.settings too.    let typed = dispatch(&handle, "notes.settings", &json!({ "font": "dyslexic" })).unwrap();    assert_eq!(typed["font"], "dyslexic");    assert_eq!(ask(&handle, json!({ "app": "notes" }))["face"], "dyslexic");    // Reset leaves Type's own choices (line spacing) as they were.    dispatch(&handle, "notes.settings", &json!({ "line_height": 1.8 })).unwrap();    ask(&handle, json!({ "app": "notes", "reset": true }));    let after = dispatch(&handle, "notes.settings", &json!({})).unwrap();    assert_eq!((after["font"].as_str(), after["light_theme"].as_str(), after["line_height"].as_f64()), (Some("sans"), Some("linen"), Some(1.8)));}// Comms' text size, kept on the phone before Look, carries over until a size is chosen in Look.#[test]fn comms_text_size_carries_over() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let file = handle.client().layout().client_dir().join("chat-theme.json");    std::fs::write(&file, br#"{"text":"larger"}"#).unwrap();    assert_eq!(ask(&handle, json!({ "app": "messages" }))["size"].as_f64(), Some(1.3));    assert_eq!(ask(&handle, json!({ "app": "messages", "size": 0.9 }))["size"].as_f64(), Some(0.9));}/// The copy's `face_settings` as a server deployed before Look serves it: no `type_face` column.fn served_without_type_face(handle: &CottonHandle) {    let ws = crate::phone::cotton_chat::read(&handle.client(), "test.ws", |ctx| Ok(json!(ctx.workspace_id))).unwrap().as_str().unwrap().to_string();    handle        .client()        .with_writer(|replica| {            let row = replica                .driver                .all("SELECT definition FROM cotton_table_definitions WHERE workspace_id = ? AND id = 'face_settings'", &[rusqlite::types::Value::Text(ws.clone())])                .map_err(|e| e.to_string())?;            let mut definition: Value = serde_json::from_str(row[0].text("definition").unwrap()).unwrap();            definition["columns"].as_array_mut().unwrap().retain(|c| c["key"] != "type_face");            if let Some(clear) = definition["seal"]["clear"].as_array_mut() {                clear.retain(|c| c != "type_face");            }            replica                .driver                .run("UPDATE cotton_table_definitions SET definition = ? WHERE workspace_id = ? AND id = 'face_settings'", &[rusqlite::types::Value::Text(definition.to_string()), rusqlite::types::Value::Text(ws.clone())])                .map(|_| ())                .map_err(|e| e.to_string())        })        .unwrap();}// RULE (owner, 23 Nov 2026, Words 26, Days 23, Story 26, Comms 25 on his iPhone: "choosing a font changes nothing"):// on a server not yet deployed with Look's `type_face` column, the copy refused the whole write ("no column// type_face") while the size, the papers and the inks, in columns of before, went. A face chosen there now stands on// this phone, read back as chosen, and every other choice is still kept; once the server has the column the face is// written into the synced row.#[test]fn a_face_is_kept_on_a_server_of_before() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    served_without_type_face(&handle);    for app in ["notes", "days", "messages", "story"] {        let set = ask(&handle, json!({ "app": app, "face": "serif" }));        assert_eq!(set["face"], "serif", "{app}: the face chosen stands");        assert_eq!(set["face_name"], "Literata", "{app}");        let again = ask(&handle, json!({ "app": app }));        assert_eq!(again["face"], "serif", "{app}: read back");        let both = ask(&handle, json!({ "app": app, "face": "typewriter", "ink": "green" }));        assert_eq!((both["face"].as_str(), both["ink"].as_str()), (Some("typewriter"), Some("green")), "{app}: the ink goes with it");        let reset = ask(&handle, json!({ "app": app, "reset": true }));        assert_eq!(reset["face"], "own", "{app}: reset");    }    // Words' own settings write the face too (`notes.settings { font }`): taken there as well, and Look reads it.    let settings = dispatch(&handle, "notes.settings", &json!({ "font": "serif" })).unwrap_or_else(|e| panic!("notes.settings: {e:?}"));    assert_eq!(settings["face"], "serif", "{settings}");    assert_eq!(ask(&handle, json!({ "app": "notes" }))["face"], "serif");}// Post answers through the same `look` (the owner, 25 Nov 2026): four papers, five inks with Franking green first and// chosen, the five faces with Instrument Sans its own, kept in its own rows and reset like the rest.#[test]fn post_has_its_look() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let first = ask(&handle, json!({ "app": "mail" }));    assert_eq!(ids(&first, "papers"), ["sage", "paper", "night", "coal"]);    assert_eq!(ids(&first, "inks"), ["franking", "teal", "oxblood", "ink_blue", "graphite"]);    assert_eq!(ids(&first, "faces"), ["own", "serif", "typewriter", "hyperlegible", "dyslexic"]);    assert_eq!(first["faces"][0]["name"], "Instrument Sans");    assert_eq!((first["light"].as_str(), first["dark"].as_str(), first["ink"].as_str()), (Some("sage"), Some("night"), Some("franking")));    assert_eq!(first["colours"]["light"]["accent"], "#1E6B4A");    assert_eq!(first["colours"]["dark"]["ground"], "#131915");    assert_eq!(first["line"], "Sage · Night");    // The row as the screen stands (Post on his phone, 26 Nov 2026: "Sage · Night" on a light screen).    assert_eq!(first["lines"]["light"], "Sage · Night when your phone is dark");    assert_eq!(first["lines"]["dark"], "Night · Sage when your phone is light");    assert_eq!(first["preview"]["rows"][0]["from"], "Priya Nair");    assert!(first["words"]["reset_ask"].as_str().unwrap().contains("Post"));    let set = ask(&handle, json!({ "app": "mail", "light": "paper", "dark": "coal", "ink": "teal", "face": "serif", "size": 1.15 }));    assert_eq!(set["colours"]["light"]["accent"], "#0E6A70");    assert_eq!(ask(&handle, json!({ "app": "mail" }))["colours"], set["colours"], "kept in mail_look and mail_look_dark");    assert_eq!(ask(&handle, json!({ "app": "keys" }))["ink"], "plum", "Secrets' look is its own");    assert!(dispatch(&handle, "look", &json!({ "app": "mail", "ink": "plum" })).is_err());    let reset = ask(&handle, json!({ "app": "mail", "reset": true }));    assert_eq!(reset["colours"], first["colours"]);}// Sites answers through the same `look` (the owner, 25 Nov 2026): four papers, five inks with Cranberry first and// chosen, Instrument Sans its own face, its preview two sites and the bar with the thread, kept in sites_look and// sites_look_dark and reset like the rest.#[test]fn sites_has_its_look() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let first = ask(&handle, json!({ "app": "sites" }));    assert_eq!(ids(&first, "papers"), ["rose", "paper", "night", "black"]);    assert_eq!(ids(&first, "inks"), ["cranberry", "petrol", "indigo", "ochre", "graphite"]);    assert_eq!(first["faces"][0]["name"], "Instrument Sans");    assert_eq!((first["light"].as_str(), first["dark"].as_str(), first["ink"].as_str()), (Some("rose"), Some("night"), Some("cranberry")));    assert_eq!(first["colours"]["light"]["accent"], "#9A2C4C");    assert_eq!(first["colours"]["dark"]["ground"], "#171213");    assert_eq!(first["line"], "Rose · Night");    assert_eq!(first["preview"]["rows"][0]["label"], "Work mail");    assert_eq!(first["preview"]["rows"][1]["line"], "club.example · forgets when closed");    assert_eq!(first["preview"]["bar"]["thread"], true);    assert!(first["words"]["reset_ask"].as_str().unwrap().contains("Sites"));    let set = ask(&handle, json!({ "app": "sites", "light": "paper", "dark": "black", "ink": "petrol", "face": "serif", "size": 1.15 }));    assert_eq!(set["colours"]["light"]["accent"], "#0E6372");    assert_eq!(set["colours"]["dark"]["ground"], "#000000");    assert_eq!(ask(&handle, json!({ "app": "sites" }))["colours"], set["colours"], "kept in sites_look and sites_look_dark");    assert_eq!(ask(&handle, json!({ "app": "mail" }))["ink"], "franking", "Post's look is its own");    assert!(dispatch(&handle, "look", &json!({ "app": "sites", "ink": "franking" })).is_err());    let reset = ask(&handle, json!({ "app": "sites", "reset": true }));    assert_eq!(reset["colours"], first["colours"]);}