Cotton code
265 lines · 13.8 KB · RustRaw
//! RULE (owner, 22 Nov 2026, MAC-PANEL.md): three screens never mixed; one plain headline; a row is a problem only//! when the person must act; a source never set up is offered as Add; no internal words.use chrono::{TimeZone, Utc};use serde_json::Value;use super::*;fn now() -> DateTime<Utc> {    Utc.with_ymd_and_hms(2026, 11, 22, 16, 0, 0).unwrap()}fn row<'a>(key: SourceKey, probe: &'a Probe) -> RowFacts<'a> {    RowFacts { key, paused: false, running: false, progress: None, probe, total: 0, last_brought_at: None, last_error: None, let_go: false, again: false, history: None }}fn facts(rows: Vec<RowFacts<'_>>) -> PanelFacts<'_> {    PanelFacts { signed_in: true, vault: Some("open"), phone: Some("+15550100000"), rows, now: now() }}// " pass" with its space: "app password" is the person's word.const INTERNAL: [&str; 9] = ["vault", " pass ", "cursor", "let in", "pushing", "hourly", "object", "seal", "imports only"];fn clean(panel: &Value) {    let said = panel.to_string().to_lowercase();    for word in INTERNAL {        assert!(!said.contains(word), "the panel says \"{word}\": {said}");    }}#[test]fn the_three_screens_never_mix() {    let ready = Probe::ready();    let mut signed_out = facts(vec![row(SourceKey::Whatsapp, &ready)]);    signed_out.signed_in = false;    let p = panel(&signed_out);    assert_eq!(p["screen"], "signIn");    assert!(p.get("rows").is_none());    let mut waiting = facts(vec![row(SourceKey::Whatsapp, &ready)]);    waiting.vault = Some("waiting");    let p = panel(&waiting);    assert_eq!(p["screen"], "step");    assert!(p.get("rows").is_none() && p.get("headline").is_none());    assert_eq!(panel(&facts(vec![row(SourceKey::Whatsapp, &ready)]))["screen"], "working");}#[test]fn all_brought_in_reads_up_to_date_with_what_and_when() {    let ready = Probe::ready();    let mut mail = row(SourceKey::Mail, &ready);    mail.total = 41_380;    mail.last_brought_at = Some("2026-11-22T15:56:00Z");    let mut wa = row(SourceKey::Whatsapp, &ready);    wa.total = 1;    wa.last_brought_at = Some("2026-11-22T15:59:40Z");    let p = panel(&facts(vec![wa, mail]));    clean(&p);    assert_eq!(p["headline"]["line"], "Everything is up to date");    assert_eq!(p["headline"]["sub"], "Last brought in just now");    assert_eq!(p["rows"][0]["line"], "1 message · just now");    assert_eq!(p["rows"][1]["line"], "41,380 emails · 4 min ago");    assert_eq!(p["rows"][1]["kind"], "ok");}#[test]fn a_source_never_set_up_is_offered_and_a_dropped_one_needs_the_person() {    let unset = Probe::needs(Need::Credentials);    let fresh_pair = Probe::needs(Need::Pair { by: None, code: None, qr: None, passkey: None, confirm: None });    let disk = Probe::needs(Need::FullDiskAccess);    let p = panel(&facts(vec![row(SourceKey::Whatsapp, &fresh_pair), row(SourceKey::Mail, &unset), row(SourceKey::Photos, &disk)]));    clean(&p);    for i in 0..3 {        assert_eq!(p["rows"][i]["kind"], "add", "{}", p["rows"][i]);        assert_eq!(p["rows"][i]["act"], "Add");    }    assert_eq!(p["headline"]["line"], "Choose what to bring in");    assert_eq!(p["headline"]["needs"], false);    let mut unlinked = Probe::needs(Need::Pair { by: None, code: None, qr: None, passkey: None, confirm: None });    unlinked.detail = Some("Unlinked by WhatsApp on 22 Nov: removed from the phone. Link it again.".into());    let mut wa = row(SourceKey::Whatsapp, &unlinked);    wa.total = 18_204;    let ready = Probe::ready();    let p = panel(&facts(vec![wa, row(SourceKey::Calls, &ready)]));    clean(&p);    assert_eq!(p["rows"][0]["kind"], "problem");    assert_eq!(p["rows"][0]["act"], "Link");    assert_eq!(p["headline"]["line"], "WhatsApp needs you");    assert_eq!(p["headline"]["needs"], true);}#[test]fn a_refusal_the_app_retries_and_the_wait_for_the_key_are_never_problems() {    let ready = Probe::ready();    let mut wa = row(SourceKey::Whatsapp, &ready);    wa.last_error = Some("the object refused (400 bad_batch): synthetic");    let mut mail = row(SourceKey::Mail, &ready);    mail.last_error = Some(WAITS_FOR_THE_VAULT);    let p = panel(&facts(vec![wa, mail]));    clean(&p);    assert_eq!(p["rows"][0]["kind"], "ok");    assert_eq!(p["rows"][0]["line"], "Couldn't bring in new ones just now. Trying again by itself.");    assert_eq!(p["rows"][1]["kind"], "ok");    assert_eq!(p["headline"]["needs"], false);}#[test]fn bringing_in_counts_against_the_total_and_offline_says_nothing_is_lost() {    let ready = Probe::ready();    let mut wa = row(SourceKey::Whatsapp, &ready);    wa.running = true;    wa.progress = Some(Progress { sent: 240, brought: 240, uploaded: 0, total: Some(1300) });    let p = panel(&facts(vec![wa]));    assert_eq!(p["headline"]["line"], "Bringing in 240 of 1,300 messages");    assert_eq!(p["headline"]["progress"]["total"], 1300);    assert_eq!(p["rows"][0]["kind"], "bringing");    let mut mail = row(SourceKey::Mail, &ready);    mail.last_error = Some("the object could not be reached: timed out");    let p = panel(&facts(vec![mail]));    clean(&p);    assert_eq!(p["headline"]["line"], "Can't reach Cotton right now");    assert!(p["headline"]["sub"].as_str().unwrap().starts_with("Nothing is lost"));}#[test]fn a_paused_source_says_paused_and_is_no_problem() {    let ready = Probe::ready();    let mut photos = row(SourceKey::Photos, &ready);    photos.paused = true;    let p = panel(&facts(vec![photos]));    assert_eq!(p["rows"][0]["kind"], "paused");    assert_eq!(p["rows"][0]["paused"], true);    assert_eq!(p["rows"][0]["line"], "Paused");}#[test]fn a_source_the_person_let_go_is_offered_again_never_a_problem() {    // WhatsApp unlinked on the panel: the helper then reports the number unlinked, which alone reads as a problem.    let unlinked = Probe {        ready: false,        need: Some(Need::Pair { by: None, code: None, qr: None, passkey: None, confirm: None }),        detail: Some("Unlinked on 22 Nov".to_string()),    };    let mut whatsapp = row(SourceKey::Whatsapp, &unlinked);    whatsapp.total = 18204;    whatsapp.let_go = true;    let p = panel(&facts(vec![whatsapp]));    assert_eq!(p["rows"][0]["kind"], "add");    assert_eq!(p["headline"]["needs"], false);    let mut dropped = row(SourceKey::Whatsapp, &unlinked);    dropped.total = 18204;    assert_eq!(panel(&facts(vec![dropped]))["rows"][0]["kind"], "problem", "WhatsApp dropping it is still a problem");}#[test]fn the_pages_words_come_with_the_working_panel() {    let ready = Probe::ready();    let p = panel(&facts(vec![row(SourceKey::Mail, &ready)]));    for key in ["back", "new_now", "again", "unlink_ask_title", "remove_ask_title", "mail_test", "disk_open"] {        assert!(p["page"][key].as_str().is_some_and(|w| !w.is_empty()), "no page word {key}");    }    assert!(p["account"]["quitLine"].as_str().is_some_and(|w| w.contains("open Cotton again")));    clean(&p);}/// Writes the panel's screens as whole statuses (the shape `App::status` answers) to `$PANEL_SNAPSHOTS`, for the/// Swift panel to draw with `-CottonCannedStatusFile` (the Mac import's check of build 4). Invented data only./// RULE (walk 23 Nov 2026): looking at the link step and backing out links nothing and is no problem: no orange/// headline, no red "Linking…", no dot. A number linked before and lost stays a problem while it is linked again.#[test]fn a_first_link_under_way_or_backed_out_of_is_still_an_offer() {    let ready = Probe::ready();    let qr = Probe::needs(Need::Pair { by: Some("qr".into()), code: None, qr: Some("2@abc".into()), passkey: None, confirm: None });    let first = panel(&facts(vec![row(SourceKey::Whatsapp, &qr), RowFacts { total: 12, last_brought_at: Some("2026-11-22T15:59:00Z"), ..row(SourceKey::Calls, &ready) }]));    assert_eq!(first["rows"][0]["kind"], "add");    assert_eq!(first["rows"][0]["act"], say("act.add", &[]));    assert_eq!(first["headline"]["needs"], false);    let relink = panel(&facts(vec![RowFacts { total: 2208, last_brought_at: Some("2026-11-22T15:00:00Z"), ..row(SourceKey::Whatsapp, &qr) }]));    assert_eq!(relink["rows"][0]["kind"], "problem");    assert_eq!(relink["rows"][0]["line"], say("row.linking", &[]));    assert_eq!(relink["headline"]["needs"], true);}/// RULE (walk 23 Nov 2026): the page says "Bringing everything in again" only while that is asked or under way.#[test]fn bring_everything_in_again_is_said_until_its_run_ends() {    let ready = Probe::ready();    let asked = panel(&facts(vec![RowFacts { again: true, running: true, ..row(SourceKey::Calls, &ready) }]));    assert_eq!(asked["rows"][0]["again"], true);    let done = panel(&facts(vec![RowFacts { total: 12, last_brought_at: Some("2026-11-22T15:59:00Z"), ..row(SourceKey::Calls, &ready) }]));    assert_eq!(done["rows"][0]["again"], false);}#[test]#[ignore]fn panel_snapshots() {    let dir = std::path::PathBuf::from(std::env::var("PANEL_SNAPSHOTS").expect("PANEL_SNAPSHOTS"));    std::fs::create_dir_all(&dir).unwrap();    let ready = Probe::ready();    let pair = Probe::needs(Need::Pair { by: None, code: None, qr: None, passkey: None, confirm: None });    let pair_code = Probe::needs(Need::Pair { by: Some("code".into()), code: Some("K4P9-WX2M".into()), qr: None, passkey: None, confirm: None });    let unlinked = Probe { ready: false, need: pair.need.clone(), detail: Some("WhatsApp unlinked this Mac on 22 Nov.".into()) };    let creds = Probe::needs(Need::Credentials);    let refused = Probe { ready: false, need: Some(Need::Credentials), detail: Some("Gmail no longer accepts the app password for asha@example.com.".into()) };    let disk = Probe::needs(Need::FullDiskAccess);    let at = |minutes: i64| (now() - chrono::Duration::minutes(minutes)).to_rfc3339();    let (a0, a4, a60) = (at(0), at(4), at(60));    let write = |name: &str, rows: Vec<RowFacts<'_>>, vault: &str, signed_in: bool| {        let facts = PanelFacts { signed_in, vault: Some(vault), phone: Some("+91 98765 43210"), rows, now: now() };        let sources: Vec<Value> = facts            .rows            .iter()            .map(|r| {                serde_json::json!({                    "source": r.key.as_str(), "schedule": "", "phase": if r.paused { "paused" } else if r.running { "running" } else if r.probe.ready { "idle" } else { "needs" },                    "probe": r.probe, "progress": r.progress, "lastBrought": 0, "lastBroughtAt": r.last_brought_at, "total": r.total, "error": r.last_error,                })            })            .collect();        let status = serde_json::json!({            "panel": panel(&facts), "signedIn": signed_in, "signedOut": false, "phone": "+91 98765 43210", "sources": sources,            "vault": { "state": vault, "detail": "" },        });        std::fs::write(dir.join(format!("{name}.json")), serde_json::to_vec_pretty(&status).unwrap()).unwrap();    };    fn ok<'a>(key: SourceKey, probe: &'a Probe, total: i64, when: &'a str) -> RowFacts<'a> {        RowFacts { total, last_brought_at: Some(when), ..row(key, probe) }    }    let (w0, w4, w60) = (a0.as_str(), a4.as_str(), a60.as_str());    write("working", vec![ok(SourceKey::Whatsapp, &ready, 18204, w0), ok(SourceKey::Mail, &ready, 41380, w4), ok(SourceKey::Photos, &ready, 12906, w60), ok(SourceKey::Calls, &ready, 2311, w60)], "open", true);    let mut running = ok(SourceKey::Whatsapp, &ready, 18204, w0);    running.running = true;    running.progress = Some(Progress { sent: 240, brought: 240, uploaded: 12, total: Some(1300) });    let mut paused = ok(SourceKey::Photos, &ready, 12906, w60);    paused.paused = true;    write("bringing", vec![running, ok(SourceKey::Mail, &ready, 41380, w4), paused, ok(SourceKey::Calls, &ready, 2311, w60)], "open", true);    write("whatsapp_needs", vec![ok(SourceKey::Whatsapp, &unlinked, 18204, w0), ok(SourceKey::Mail, &ready, 41380, w4), ok(SourceKey::Photos, &ready, 12906, w60), ok(SourceKey::Calls, &ready, 2311, w60)], "open", true);    write("mail_needs", vec![ok(SourceKey::Whatsapp, &ready, 18204, w0), ok(SourceKey::Mail, &refused, 41380, w4), ok(SourceKey::Photos, &ready, 12906, w60), ok(SourceKey::Calls, &ready, 2311, w60)], "open", true);    let mut retrying = ok(SourceKey::Mail, &ready, 41380, w60);    retrying.last_error = Some("The mail server kept closing the connection while Cotton was reading.");    write("mail_retrying", vec![ok(SourceKey::Whatsapp, &ready, 18204, w0), retrying, ok(SourceKey::Photos, &ready, 12906, w60), ok(SourceKey::Calls, &ready, 2311, w60)], "open", true);    write("first_look", vec![row(SourceKey::Whatsapp, &pair), row(SourceKey::Mail, &creds), row(SourceKey::Photos, &disk), row(SourceKey::Calls, &disk)], "open", true);    write("whatsapp_link", vec![row(SourceKey::Whatsapp, &pair_code), row(SourceKey::Mail, &creds), row(SourceKey::Photos, &disk), row(SourceKey::Calls, &disk)], "open", true);    let mut offline = ok(SourceKey::Whatsapp, &ready, 18204, w0);    offline.last_error = Some("the object could not be reached: timed out");    write("offline", vec![offline, ok(SourceKey::Mail, &ready, 41380, w60)], "open", true);    write("step", vec![row(SourceKey::Whatsapp, &ready)], "waiting", true);    write("sign_in", vec![row(SourceKey::Whatsapp, &ready)], "waiting", false);}#[test]fn a_problem_headline_says_what_happened_and_that_nothing_is_lost_the_row_what_to_do() {    let unlinked = Probe {        ready: false,        need: Some(Need::Pair { by: None, code: None, qr: None, passkey: None, confirm: None }),        detail: Some("WhatsApp unlinked this Mac on 22 Nov.".to_string()),    };    let mut whatsapp = row(SourceKey::Whatsapp, &unlinked);    whatsapp.total = 18204;    let p = panel(&facts(vec![whatsapp]));    assert_eq!(p["headline"]["line"], "WhatsApp needs you");    assert_eq!(p["headline"]["sub"], "WhatsApp unlinked this Mac on 22 Nov. What's already in Cotton is safe.");    assert_ne!(p["headline"]["sub"], p["rows"][0]["line"], "the headline does not repeat the row");}