Cotton code
246 lines · 9.0 KB · RustRaw
//! The `countWords` and snapshot-building rules this read carries.//!//! There is no parser here and there should not be: reading a snapshot back//! off `UserDefaults` is the SWIFT side's job, and this read never does it —//! it takes pending ids and their finished times as arguments instead.//!//! Every fixture is synthetic.use super::*;/// Friday 21 August 2026, 10:00 UTC — the frozen `NOW` every case here uses.const NOW: i64 = 1_787_306_400_000;const NOW_ISO: &str = "2026-08-21T10:00:00.000Z";fn take(id: &str, minutes_ago: i64) -> TakeRow {    TakeRow {        id: id.to_string(),        text: format!("take {id}"),        words: 2,        created_at: iso(NOW - minutes_ago * 60_000),    }}/// The instant as the TypeScript's `toISOString()` writes it.fn iso(at_ms: i64) -> String {    let parts =        cotton_core::transforms::zoned_clock::zoned_parts(at_ms, "UTC").expect("UTC is readable");    format!(        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",        parts.year,        parts.month,        parts.day,        parts.hour,        parts.minute,        parts.second,        at_ms.rem_euclid(1000)    )}fn build(takes: &[TakeRow], pending: &[&str]) -> KeyboardSnapshot {    let pending: Vec<PendingTake> = pending        .iter()        .map(|id| PendingTake {            id: (*id).to_string(),            created_at: takes                .iter()                .find(|take| take.id == *id)                .expect("standing take")                .created_at                .clone(),        })        .collect();    build_keyboard_snapshot(takes, &pending, NOW)}#[test]fn words_are_whitespace_runs_and_nothing_cleverer() {    assert_eq!(count_words("  hello   there\nworld "), 3);    assert_eq!(count_words(""), 0);    assert_eq!(count_words("   "), 0);}/// A pending flag is CARRIED, never invented, and only inside the window.#[test]fn a_pending_flag_is_carried_forward_within_the_window_only() {    let takes = vec![take("fresh", 5), take("stale", 20), take("done", 1)];    let snapshot = build(&takes, &["fresh", "stale"]);    let pending: std::collections::BTreeMap<&str, bool> = snapshot        .takes        .iter()        .map(|take| (take.id.as_str(), take.pending))        .collect();    assert!(        pending["fresh"],        "five minutes is inside the ten-minute window"    );    assert!(        !pending["stale"],        "twenty minutes is past it, whatever the previous snapshot said"    );    assert!(        !pending["done"],        "a take the previous snapshot did not hold as pending is not made pending here"    );}/// **The boundary the TypeScript pins**: a take exactly ten minutes old is no/// longer auto-insertable. Inserting a forgotten take into tomorrow's first/// text field is the bug the window exists to prevent, and `<=` here would/// reopen it by one millisecond.#[test]fn a_take_exactly_at_the_window_edge_is_no_longer_pending() {    let edge = TakeRow {        id: "edge".to_string(),        text: "x".to_string(),        words: 1,        created_at: iso(NOW - TAKE_PENDING_WINDOW_MS),    };    assert!(!build(std::slice::from_ref(&edge), &["edge"]).takes[0].pending);    let inside = TakeRow {        created_at: iso(NOW - TAKE_PENDING_WINDOW_MS + 1),        ..edge    };    assert!(build(&[inside], &["edge"]).takes[0].pending);}/// An instant that cannot be read is not carried: a take whose age cannot be/// computed is not inside any window, which is also what the TypeScript's `NaN`/// comparison answers.#[test]fn a_take_with_an_unreadable_instant_is_not_carried() {    let broken = TakeRow {        id: "broken".to_string(),        text: "x".to_string(),        words: 1,        created_at: "not-an-instant".to_string(),    };    assert!(!build(&[broken], &["broken"]).takes[0].pending);}#[test]fn the_tray_is_capped_at_five() {    let takes: Vec<TakeRow> = (0..MAX_SNAPSHOT_TAKES + 3)        .map(|index| take(&index.to_string(), index as i64))        .collect();    assert_eq!(build(&takes, &[]).takes.len(), MAX_SNAPSHOT_TAKES);}/// The snapshot speaks for the instant it was asked about, and the takes travel/// whole — the text, the count the writer made, and the instant it finished.#[test]fn the_snapshot_states_its_own_instant_and_carries_each_take_whole() {    let snapshot = build(&[take("t1", 1)], &[]);    assert_eq!(snapshot.as_of, NOW_ISO);    assert_eq!(snapshot.takes[0].id, "t1");    assert_eq!(snapshot.takes[0].text, "take t1");    assert_eq!(snapshot.takes[0].words, 2);}/// Every field travels under the name the extension decodes. A renamed one is a/// keyboard whose tray is silently empty for ever.#[test]fn every_field_travels_under_the_name_the_extension_decodes() {    let written =        serde_json::to_value(build(&[take("t1", 1)], &["t1"])).expect("serialisable");    let take = &written["takes"][0];    let keys: Vec<&str> = take        .as_object()        .expect("an object")        .keys()        .map(String::as_str)        .collect();    assert_eq!(keys, ["id", "text", "words", "createdAt", "pending"]);    assert_eq!(take["pending"], true);    let keys: Vec<&str> = written        .as_object()        .expect("an object")        .keys()        .map(String::as_str)        .collect();    assert_eq!(keys, ["asOf", "takes"]);}// ── The read, over a real file ────────────────────────────────────────────mod over_a_file {    use super::*;    use crate::shell::client::phone_tests::attached;    #[test]    fn newest_five_takes_survive_interleaved_typed_rows_and_creation_order() {        let (_dir, client) = attached();        let written = client.with_writer(|replica| {            use rusqlite::types::Value as Sql;            for index in 0..14 {                let source = if index % 2 == 0 { "take" } else { "typed" };                let at = format!("2026-08-21T09:{:02}:00.000Z", 40 + index);                let created = format!("2026-08-21T08:{:02}:00.000Z", 59 - index);                replica.driver.run("INSERT INTO cotton_dictations (id,workspace_id,text,source,words,spoken_at,created_at) VALUES (?,?,?,?,?,?,?)", &[                    Sql::Text(format!("dictation-{index}")), Sql::Text(replica.workspace_id.to_string()),                    Sql::Text("Synthetic take".into()), Sql::Text(source.into()), Sql::Integer(7), Sql::Text(at), Sql::Text(created),                ]).map_err(|error| error.to_string())?;            }            keyboard_snapshot(replica, serde_json::json!({"now":NOW_ISO,"pending":[{"id":"dictation-12","createdAt":"2026-08-21T09:52:00.000Z"},{"id":"dictation-0","createdAt":"2026-08-21T09:40:00.000Z"}]}).as_object().expect("args"))        }).expect("snapshot");        let takes = written["takes"].as_array().expect("takes");        assert_eq!(            takes                .iter()                .map(|take| take["id"].as_str().expect("id"))                .collect::<Vec<_>>(),            [                "dictation-12",                "dictation-10",                "dictation-8",                "dictation-6",                "dictation-4"            ]        );        assert_eq!(takes[0]["createdAt"], "2026-08-21T09:52:00.000Z");        assert_eq!(takes[0]["words"], 7);        assert_eq!(takes[0]["pending"], true);        assert_eq!(takes[1]["pending"], false);    }    fn read(args: serde_json::Value) -> Result<Value, String> {        let (_dir, client) = attached();        let args = args.as_object().cloned().unwrap_or_default();        client.with_writer(|replica| keyboard_snapshot(replica, &args))    }    #[test]    fn an_empty_corpus_answers_a_snapshot_with_no_takes() {        let written = read(serde_json::json!({ "now": NOW_ISO })).expect("the snapshot");        assert_eq!(written["asOf"], NOW_ISO);        assert_eq!(written["takes"], serde_json::json!([]));    }    /// RULE: the keyboard is voice only — the snapshot carries no typed-capture switch, whatever the caller sends.    #[test]    fn the_snapshot_carries_no_typed_capture_switch() {        let written = read(serde_json::json!({ "now": NOW_ISO, "typedCapture": true }))            .expect("the snapshot");        assert!(written.get("settings").is_none(), "{written}");    }    #[test]    fn a_missing_or_unreadable_clock_is_refused_by_name() {        let refusal = read(serde_json::json!({})).expect_err("a refusal");        assert!(refusal.contains("`now`"), "{refusal}");        let refusal = read(serde_json::json!({ "now": "nope" })).expect_err("a refusal");        assert!(refusal.contains("not an instant"), "{refusal}");    }}#[test]fn pending_window_uses_previous_finished_time_not_fresh_spoken_time() {    let fresh = take("synthetic", 20);    let pending = [PendingTake {        id: fresh.id.clone(),        created_at: "2026-08-21T09:59:00.000Z".into(),    }];    let snapshot = build_keyboard_snapshot(&[fresh], &pending, NOW);    assert!(snapshot.takes[0].pending);    assert_eq!(snapshot.as_of, NOW_ISO);}