Cotton code
538 lines · 21.8 KB · RustRaw
//! The eight settings reads and the writes the tool surface owes no verb.//!//! Everything here runs against `shell::client::phone_tests::attached` — the//! one place a paired phone is assembled, a synthetic file at the build's own//! schema version with a fixed//! clock and a seeded RNG, so these cases and the 4p write cases are looking at//! the same device. Every fixture is invented: a workspace of zeroes, a word//! nobody said, a place nobody lives//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).use serde_json::{json, Map, Value};use crate::shell::client::phone_tests::attached;use crate::shell::client::ClientController;fn read(client: &ClientController, name: &str) -> Value {    read_with(client, name, &Map::new())}fn read_with(client: &ClientController, name: &str, args: &Map<String, Value>) -> Value {    let entry = super::reads::read_for(name).unwrap_or_else(|| panic!("{name} is declared"));    // The ONE dispatch `cotton_call` uses, so a test cannot drift from it.    super::answer_read(client, entry, args)        .unwrap_or_else(|reason| panic!("{name} answered: {reason}"))}/// One statement against the replica, for seeding a fixture row.fn exec(client: &ClientController, sql: &str, params: &[&str]) {    client        .with_writer(|replica| {            let bound: Vec<rusqlite::types::Value> = params                .iter()                .map(|value| rusqlite::types::Value::Text((*value).to_string()))                .collect();            replica                .driver                .run(sql, &bound)                .map_err(|error| error.to_string())?;            crate::fixture::receipted(replica.driver, sql);            Ok(())        })        .expect("the seed");}fn workspace(client: &ClientController) -> String {    client        .with_writer(|replica| Ok(replica.workspace_id.to_string()))        .expect("the workspace id")}/// Run one of the five writes the way `methods::dispatch` runs it, minus the/// handle.fn write(    client: &ClientController,    label: &str,    body: &mut dyn FnMut(&mut cotton_tools::mcp::dispatch::Ctx<'_>) -> Result<Value, String>,) -> Value {    client        .write_rows(label, body)        .unwrap_or_else(|reason| panic!("{label} refused: {reason}"))}fn term(client: &ClientController, term: &str, source: &str) -> Value {    let input = super::settings_writes::VoiceTerm {        term: term.to_string(),        source: source.to_string(),    };    write(client, "settings.voiceTerm", &mut |ctx| {        super::settings_writes::upsert_term(ctx, &input)    })}// ── read.account ──────────────────────────────────────────────────────────#[test]fn a_workspace_that_nobody_has_named_answers_no_owner_name_rather_than_personal() {    let (_dir, client) = attached();    let id = workspace(&client);    exec(        &client,        "UPDATE cotton_workspaces SET name = ? WHERE id = ?",        &["Personal", &id],    );    let answer = read(&client, "read.account");    assert_eq!(        answer["ownerName"],        Value::Null,        "the placeholder is not a name, and a screen drawing it would tell the person that is \         what they are called"    );}#[test]fn a_workspace_somebody_named_answers_the_name() {    let (_dir, client) = attached();    let id = workspace(&client);    exec(        &client,        "UPDATE cotton_workspaces SET name = ? WHERE id = ?",        &["A Person", &id],    );    assert_eq!(        read(&client, "read.account")["ownerName"],        json!("A Person")    );}// ── read.dictationStats ───────────────────────────────────────────────────#[test]fn the_corpus_line_is_two_aggregates_and_an_empty_file_is_two_zeroes() {    let (_dir, client) = attached();    assert_eq!(        read(&client, "read.dictationStats"),        json!({ "count": 0, "words": 0 })    );    let id = workspace(&client);    for (row, words) in [("d1", "7"), ("d2", "11")] {        exec(            &client,            "INSERT INTO cotton_dictations (id, workspace_id, text, source, words, spoken_at,                created_at)             VALUES (?, ?, 'a take nobody said', 'take', ?, ?, ?)",            &[                row,                &id,                words,                "2026-01-01T00:00:00.000Z",                "2026-01-01T00:00:00.000Z",            ],        );    }    // The screen draws the line only when the count is over zero — the figure    // is this read's and the silence is the screen's.    assert_eq!(        read(&client, "read.dictationStats"),        json!({ "count": 2, "words": 18 })    );}// ── read.voiceVocabulary and the two writes over it ───────────────────────#[test]fn a_typed_word_lands_and_the_list_is_alphabetical_to_a_person_rather_than_to_a_byte() {    let (_dir, client) = attached();    for word in ["nilgiri", "Anand", "bakery"] {        term(&client, word, "manual");    }    let terms = read(&client, "read.voiceVocabulary");    let words: Vec<&str> = terms["terms"]        .as_array()        .expect("a list")        .iter()        .map(|row| row["term"].as_str().expect("a word"))        .collect();    assert_eq!(words, ["Anand", "bakery", "nilgiri"]);}#[test]fn a_learned_word_never_re_cases_one_the_person_typed() {    let (_dir, client) = attached();    term(&client, "Nilgiri", "manual");    let answer = term(&client, "nilgiri", "auto");    assert_eq!(answer["answer"]["changed"], json!(false));    let terms = read(&client, "read.voiceVocabulary");    assert_eq!(terms["terms"].as_array().expect("a list").len(), 1);    assert_eq!(terms["terms"][0]["term"], json!("Nilgiri"));    assert_eq!(terms["terms"][0]["source"], json!("manual"));}#[test]fn a_word_dictation_learned_is_promoted_when_the_person_types_it_and_takes_their_spelling() {    let (_dir, client) = attached();    term(&client, "nilgiri", "auto");    let answer = term(&client, "Nilgiri", "manual");    assert_eq!(answer["answer"]["changed"], json!(true));    let terms = read(&client, "read.voiceVocabulary");    assert_eq!(        terms["terms"].as_array().expect("a list").len(),        1,        "one word, not two"    );    assert_eq!(terms["terms"][0]["term"], json!("Nilgiri"));    assert_eq!(terms["terms"][0]["source"], json!("manual"));}#[test]fn a_term_is_trimmed_and_its_inner_whitespace_collapsed_but_never_re_cased() {    assert_eq!(        super::settings_writes::normalize("  Anand   Bakery \n"),        "Anand Bakery"    );    assert_eq!(super::settings_writes::normalize("MiXeD"), "MiXeD");    assert_eq!(super::settings_writes::normalize("   "), "");}#[test]fn forgetting_a_word_that_is_already_gone_is_a_success_because_a_rename_adds_first() {    let (_dir, client) = attached();    let answer = write(&client, "settings.forgetVoiceTerm", &mut |ctx| {        super::settings_writes::forget_term(ctx, "no-such-word")    });    assert_eq!(answer["answer"]["removed"], json!(false));    assert_eq!(answer["queued"], json!(0), "nothing was written");}#[test]fn forgetting_a_word_takes_it_out_and_queues_the_delete_for_the_other_devices() {    let (_dir, client) = attached();    let added = term(&client, "Nilgiri", "manual");    let id = added["answer"]["id"].as_str().expect("an id").to_string();    let answer = write(&client, "settings.forgetVoiceTerm", &mut |ctx| {        super::settings_writes::forget_term(ctx, &id)    });    assert_eq!(answer["answer"]["removed"], json!(true));    assert_eq!(answer["queued"], json!(1));    assert_eq!(        answer["tables"],        json!(["cotton_voice_vocabulary"]),        "`tables` IS the invalidation"    );    assert!(read(&client, "read.voiceVocabulary")["terms"]        .as_array()        .expect("a list")        .is_empty());}// ── read.find ─────────────────────────────────────────────────────────────#[test]fn find_answers_hits_grouped_by_the_engines_own_sections_with_their_totals() {    let (_dir, client) = attached();    client        .write(            "create_todo",            &super::super::shell::client::phone_tests::args(&[(                "title",                json!("Mend the nilgiri fence"),            )]),        )        .expect("a todo");    let answer = read_with(        &client,        "read.find",        &super::super::shell::client::phone_tests::args(&[("query", json!("nilgiri"))]),    );    let hits = answer["hits"].as_array().expect("a list");    assert_eq!(hits.len(), 1);    assert_eq!(hits[0]["kind"], json!("todo"));    assert_eq!(hits[0]["title"], json!("Mend the nilgiri fence"));    // `totals` is a map keyed by SECTION, in lane order — which is what the    // section headings and the "See all" counts are drawn from.    assert_eq!(answer["totals"]["todo"], json!(1));}/// Seven todos and five people the word "nilgiri" finds.fn nilgiri_file() -> (tempfile::TempDir, std::sync::Arc<ClientController>) {    let (dir, client) = attached();    let args = super::super::shell::client::phone_tests::args;    for n in 0..7 {        client.write("create_todo", &args(&[("title", json!(format!("Mend the nilgiri fence {n}")))])).expect("a todo");    }    for n in 0..5 {        client.write("create_person", &args(&[("fullName", json!(format!("Nilgiri Walker {n}")))])).expect("a person");    }    (dir, client)}fn find_with(client: &ClientController, pairs: &[(&str, Value)]) -> Value {    read_with(client, "read.find", &super::super::shell::client::phone_tests::args(pairs))}fn ids_of(answer: &Value, kind: &str) -> Vec<String> {    answer["hits"]        .as_array()        .expect("a list")        .iter()        .filter(|hit| hit["kind"] == json!(kind))        .map(|hit| hit["id"].as_str().expect("an id").to_string())        .collect()}/// RULE: search's section totals are exact counts — summed, they equal every hit the whole set holds — because a first page names the rest it did not read (architect, 15 Oct 2026).#[test]fn the_section_totals_of_a_first_page_sum_to_the_whole_set() {    let (_dir, client) = nilgiri_file();    let first = find_with(&client, &[("query", json!("nilgiri")), ("limit", json!(3))]);    let whole = find_with(&client, &[("query", json!("nilgiri"))]);    let sum: i64 = first["totals"].as_object().expect("totals").values().filter_map(Value::as_i64).sum();    assert_eq!(first["hits"].as_array().expect("a list").len(), 6, "three a kind");    assert_eq!(sum, whole["hits"].as_array().expect("a list").len() as i64);    assert_eq!(first["totals"], whole["totals"]);}/// RULE: an expanded search section pages through its kind to its last hit — nothing a total counts is out of reach (architect, 15 Oct 2026: nothing is hidden, nothing is read all at once).#[test]fn an_expanded_section_pages_to_its_last_hit() {    let (_dir, client) = nilgiri_file();    let whole = find_with(&client, &[("query", json!("nilgiri"))]);    let mut paged = ids_of(&find_with(&client, &[("query", json!("nilgiri")), ("limit", json!(3))]), "todo");    loop {        let page = find_with(            &client,            &[("query", json!("nilgiri")), ("kind", json!("todo")), ("offset", json!(paged.len())), ("limit", json!(2))],        );        assert_eq!(page["totals"]["todo"], json!(7), "each page carries the kind's whole count");        let ids = ids_of(&page, "todo");        assert!(ids_of(&page, "person").is_empty(), "a page reads its kind alone");        let short = ids.len() < 2;        paged.extend(ids);        if short {            break;        }    }    assert_eq!(paged, ids_of(&whole, "todo"), "every hit, in the whole set's order");}/// RULE: a keystroke's search stops the one before it on its channel of the same file — between statements and inside the one running, on whichever connection it runs — so fast typing never queues stale SQL (architect, 15 Oct 2026); a search on another file never stops it.#[test]fn a_newer_search_on_the_channel_stops_the_one_in_flight() {    let dir = tempfile::tempdir().expect("a dir");    // Two connections to one file, as a read pool holds them.    let older = cotton_store::driver::Driver::open(dir.path().join("a.db")).expect("a file");    let newer = cotton_store::driver::Driver::open(dir.path().join("a.db")).expect("the same file again");    let elsewhere = cotton_store::driver::Driver::open(dir.path().join("b.db")).expect("another file");    let flight = super::reads::FindFlight::begin("guard", &older);    // A statement that runs until it is interrupted, and says when it began.    let began = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));    let said = began.clone();    older        .connection()        .create_scalar_function("began", 0, rusqlite::functions::FunctionFlags::SQLITE_UTF8, move |_| {            said.store(true, std::sync::atomic::Ordering::SeqCst);            Ok(1)        })        .expect("a function");    let running = std::thread::spawn(move || {        older            .all("WITH RECURSIVE n(i) AS (SELECT began() UNION ALL SELECT i + 1 FROM n) SELECT count(*) FROM n", &[])            .map(|_| ())            .map_err(|error| error.to_string())    });    while !began.load(std::sync::atomic::Ordering::SeqCst) {        std::thread::yield_now();    }    // The same channel on another file (another database, another core in the process) leaves it running.    let _elsewhere = super::reads::FindFlight::begin("guard", &elsewhere);    assert!(!flight.cancelled(), "a search on another file never stops this one");    let _newer = super::reads::FindFlight::begin("guard", &newer);    let running = running.join().expect("the statement returns");    assert!(running.is_err(), "the running statement is interrupted");    assert!(flight.cancelled(), "and the older search refuses its next statement");    // Another channel is left alone.    let other = super::reads::FindFlight::begin("other", &newer);    let _again = super::reads::FindFlight::begin("guard", &newer);    assert!(!other.cancelled());}#[test]fn a_query_nothing_matches_answers_an_empty_list_rather_than_refusing() {    let (_dir, client) = attached();    let answer = read_with(        &client,        "read.find",        &super::super::shell::client::phone_tests::args(&[("query", json!("nothingatall"))]),    );    assert!(answer["hits"].as_array().expect("a list").is_empty());}#[test]fn a_blank_query_answers_nothing_because_the_engine_refuses_one() {    // The engine's own rule, and the reason Find has a two-character floor in    // the screen above it: an empty search is not a search.    let (_dir, client) = attached();    let answer = read_with(        &client,        "read.find",        &super::super::shell::client::phone_tests::args(&[("query", json!("   "))]),    );    assert!(answer["hits"].as_array().expect("a list").is_empty());}// ── read.syncStatus, extended ─────────────────────────────────────────────#[test]fn the_sync_answer_carries_the_media_ledgers_counts_so_one_call_draws_both_cards() {    let (_dir, client) = attached();    let answer = read(&client, "read.syncStatus");    assert_eq!(answer["connected"], json!(true));    assert_eq!(        answer["media"]["counts"],        json!({ "pending": 0, "synced": 0, "failed": 0, "deletePending": 0 })    );    assert!(answer["media"]["failed"]        .as_array()        .expect("a list")        .is_empty());}#[test]fn a_file_that_could_not_be_backed_up_is_named_with_the_reason_it_could_not() {    let (_dir, client) = attached();    exec(        &client,        "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path,            state, attempts, last_error, created_at, updated_at)         VALUES (?, ?, 'sha', 'image/jpeg', 3, '/nowhere', 'failed', 4, ?, ?, ?)",        &[            "media/2026/01/aaaa.jpg",            &workspace(&client),            "the server would not take it",            "2026-01-01T00:00:00.000Z",            "2026-01-01T00:00:00.000Z",        ],    );    let media = &read(&client, "read.syncStatus")["media"];    assert_eq!(media["counts"]["failed"], json!(1));    assert_eq!(media["failed"][0]["key"], json!("media/2026/01/aaaa.jpg"));    assert_eq!(        media["failed"][0]["lastError"],        json!("the server would not take it"),        "the card prints the file's own reason, not a generic one"    );}// ── read.home over a stored arrangement ───────────────────────────────────//// The app never edits Home (owner, 16 Oct 2026): the arrangement is set over// MCP only, so these cases seed the row through the one writer that remains,// `cotton_tools::home_arrangement` — the row `arrange_tools` writes — and// check what `read.home` answers from it.use cotton_core::rules::home_arrangement::HomeArrangement;fn arrangement(project_slugs: &[&str], view_ids: &[&str]) -> HomeArrangement {    let said = |entries: &[&str]| -> Vec<String> {        entries.iter().map(|entry| (*entry).to_string()).collect()    };    HomeArrangement {        project_slugs: said(project_slugs),        tools: Vec::new(),        view_ids: said(view_ids),    }}/// Store the arrangement with the database's tools as it holds them now, the/// way the MCP writer stores it.fn save(client: &ClientController, record: &HomeArrangement) -> Value {    let personal = super::reads::personal_database(client).expect("the held databases");    write(client, "home arrangement fixture", &mut |ctx| {        let workspace_id = ctx.workspace_id.to_string();        let personal = personal.as_deref() == Some(workspace_id.as_str());        let saved = super::reads::home_arrangement(ctx.db(), &workspace_id)?;        let tools = cotton_tools::home_arrangement::tools(ctx.db(), &workspace_id, saved.as_ref(), personal)?;        let record = HomeArrangement { tools, ..record.clone() };        cotton_tools::home_arrangement::save(ctx, &record).map_err(|failure| failure.to_string())?;        Ok(json!({ "changed": true }))    })}fn listed(value: &Value) -> Vec<String> {    serde_json::from_value(value.clone()).expect("a list of strings")}#[test]fn read_home_answers_the_stored_arrangement() {    let (_dir, client) = attached();    save(&client, &arrangement(&[], &["tool/passwords", "tool/todos"]));    let home = read(&client, "read.home");    assert_eq!(home["arrangement"]["manual"], Value::Bool(true));    assert_eq!(home["arrangement"]["viewIds"], json!(["tool/passwords", "tool/todos"]));    let mut tiles: Vec<String> =        home["arrangement"]["tiles"].as_array().unwrap().iter().map(|tile| tile["id"].as_str().unwrap().to_string()).collect();    tiles.sort();    assert_eq!(tiles, ["tool/passwords", "tool/todos"]);    // The kit's tools and the shell's Bin.    assert_eq!(listed(&home["arrangement"]["tools"]).len(), cotton_core::kit::ids().len() + 1);}// RULE: an installed data tool is one of the database's tools and its tile takes its alphabetical place by its definition's name (owner, 17 Oct 2026: the stored order is never read), through real writes and reads; a stored view naming no tool here cannot invent a tile.#[test]fn data_tool_arrangement_survives_real_read_write_round_trip() {    let (_dir, client) = attached();    let tool = json!({        "id": "classroom", "name": "Classroom", "picture": "tool-classroom",        "tables": ["lesson"], "instructions": "Synthetic teaching tool.",        "automations": [], "author": { "device": "example", "name": "Example Teacher" },        "signature": null    });    exec(&client,        "INSERT INTO cotton_tool_definitions (id, workspace_id, definition, created_at, updated_at) VALUES (?, ?, ?, '2026-10-01T09:00:00Z', '2026-10-01T09:00:00Z')",        &["classroom", &workspace(&client), &tool.to_string()]);    save(&client, &arrangement(&[], &["tool/classroom", "tool/notebook", "tool/unknown-tool"]));    let home = read(&client, "read.home");    assert_eq!(home["arrangement"]["viewIds"], json!(["tool/classroom", "tool/notebook"]));    let tools = listed(&home["arrangement"]["tools"]);    assert!(tools.contains(&"classroom".to_string()) && !tools.contains(&"unknown-tool".to_string()), "{tools:?}");    // The kit's tools, the shell's Bin and classroom.    assert_eq!(tools.len(), cotton_core::kit::ids().len() + 2);    save(&client, &arrangement(&[], &["tool/notebook", "tool/classroom"]));    let again = read(&client, "read.home");    assert_eq!(again["arrangement"]["viewIds"], json!(["tool/classroom", "tool/notebook"]), "the stored order is never read");}#[test]fn everything_counts_passwords_as_the_passwords_list_reads_them() {    let (_dir, client) = attached();    let workspace_id = workspace(&client);    let at = "2026-01-02T00:00:00.000Z";    for (id, kind, trashed) in [        ("sec-login", "login", ""),        ("sec-note", "note", ""),        ("sec-document", "document", ""),        ("sec-binned", "login", at),    ] {        exec(            &client,            "INSERT INTO cotton_secrets (id, workspace_id, kind, name, value_enc, hint, trashed_at, created_at, updated_at)             VALUES (?, ?, ?, ?, 'sealed-not-a-real-value', 'wxyz', NULLIF(?, ''), ?, ?)",            &[id, &workspace_id, kind, id, trashed, at, at],        );    }    let listed = read(&client, "read.secrets")["secrets"].as_array().expect("a list").len();    let counted = client        .with_writer(|replica| super::vault::listed_count(replica.driver, replica.workspace_id))        .expect("the count");    assert_eq!(listed, 2, "a login and a note; never a document's password or a binned one");    assert_eq!(counted, listed as i64);}