Cotton code
295 lines · 16.7 KB · RustRaw
//! `voice.*` through the core's own dispatch, on a started phone: whole//! sessions from recorded engine output, the settings row, Story's names//! first, a command that opens a record, and the models this phone holds.use serde_json::{json, Value};use crate::handle::CottonHandle;fn phone() -> (tempfile::TempDir, CottonHandle) {    let manifest: Value = serde_json::from_str(include_str!("../../../../apps/cotton/App/CottonManifest/flavour.json")).expect("a manifest");    phone_of(manifest)}/// Cotton Story's flavour as a phone opens it (as `story_tests` does).fn story_phone() -> (tempfile::TempDir, CottonHandle) {    phone_of(json!({        "genesis": "personal",        "flavour": "story",        "name": "Cotton Story",        "databases": "single",        "database": "personal",        "business": { "server": { "real": "https://cottondb.com", "dev": "https://dev.example.invalid" } },        "fan": { "home": false, "tools": false, "opens": "story" },        "kit": "story",        "ground": "blank"    }))}fn phone_of(manifest: Value) -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let handle = CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::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(manifest),    })    .expect("an open core");    crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started");    (dir, handle)}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value {    crate::methods::dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}fn make(handle: &CottonHandle, table: &str, data: Value) -> String {    let made = ask(handle, "records.create", json!({"table": table, "data": data}));    made["id"].as_str().or_else(|| made["record"]["id"].as_str()).unwrap_or_else(|| panic!("a made id: {made}")).to_string()}/// The platform's side: its text, changed only by answers and the person.struct Field<'a> {    handle: &'a CottonHandle,    session: String,    text: String,}impl<'a> Field<'a> {    fn open(handle: &'a CottonHandle, plan: Value) -> (Field<'a>, Value) {        let planned = ask(handle, "voice.plan", plan);        let session = planned["session"].as_str().expect("a session").to_string();        (Field { handle, session, text: String::new() }, planned)    }    fn apply(&mut self, answer: &Value) {        for edit in answer["edits"].as_array().unwrap() {            let units: Vec<u16> = self.text.encode_utf16().collect();            let (from, to) = (edit["from"].as_u64().unwrap() as usize, edit["to"].as_u64().unwrap() as usize);            let mut next: Vec<u16> = units[..from].to_vec();            next.extend(edit["text"].as_str().unwrap().encode_utf16());            next.extend(&units[to..]);            self.text = String::from_utf16(&next).unwrap();        }        let whole = format!("{}{}{}", answer["settled"].as_str().unwrap_or_default(), answer["tentative"].as_str().unwrap_or_default(), answer["later"].as_str().unwrap_or_default());        if answer.get("settled").is_some() {            assert_eq!(self.text, whole, "the edits make the core's text: {answer}");        }    }    fn heard(&mut self, request: Value) -> Value {        let mut request = request;        request["session"] = json!(self.session);        let answer = ask(self.handle, "voice.heard", request);        self.apply(&answer);        answer    }    fn person(&mut self, word: &str, with: &str) -> Value {        let at = self.text.find(word).unwrap();        let from = self.text[..at].encode_utf16().count();        let to = from + word.encode_utf16().count();        self.text.replace_range(at..at + word.len(), with);        let answer = ask(self.handle, "voice.touched", json!({"session": self.session, "from": from, "to": to, "text": with}));        assert_eq!(answer["edits"], json!([]));        answer    }    fn end(&mut self) -> Value {        let answer = ask(self.handle, "voice.end", json!({"session": self.session}));        self.apply(&answer);        assert_eq!(answer["text"], json!(self.text));        answer    }}// RULE (voice plan, 17 Nov 2026): a dictation is one session: live partials revise the tentative words, a live final settles them, the second pass corrects the settled sentence, the person's edit in it is never changed, and the platform's text after every answer's edits is the core's.#[test]fn a_whole_dictation_from_recorded_engine_output() {    let (_dir, handle) = phone();    let (mut field, plan) = Field::open(&handle, json!({"surface": "note", "table": "note", "mode": "dictate", "platform": "android"}));    assert_eq!(plan["mode"], "dictate");    assert_eq!(plan["languages"], json!(["en"]));    assert!(plan["live"]["engine"].as_str().unwrap().starts_with("sherpa:"), "{plan}");    assert!(plan["second"]["engine"].as_str().unwrap().starts_with("sherpa:"), "{plan}");    assert_eq!(plan["lines"]["listening"], "Listening…");    assert_eq!(plan["lines"]["cotton_voice"], "Cotton Voice makes dictation better.");    // The catalogue's files are uploaded: a phone holding no model is offered the plan's, each by its link and checksum.    let downloads = plan["downloads"].as_array().expect("downloads");    assert!(!downloads.is_empty(), "{plan}");    for file in downloads {        assert!(file["url"].as_str().unwrap().starts_with("https://models.cottondb.com/v1/"), "{file}");        assert_eq!(file["sha256"].as_str().unwrap().len(), 64, "{file}");    }    let a = field.heard(json!({"pass": "live", "final": false, "text": "SEND IT TO", "from_ms": 0, "to_ms": 600}));    assert_eq!(a["tentative"], "Send it to");    field.heard(json!({"pass": "live", "final": false, "text": "SEND IT TO ROBBIE TOMOROW", "from_ms": 0, "to_ms": 1400}));    let a = field.heard(json!({"pass": "live", "final": true, "text": "SEND IT TO ROBBIE TOMOROW", "from_ms": 0, "to_ms": 1500}));    assert_eq!((a["settled"].as_str(), a["tentative"].as_str()), (Some("Send it to robbie tomorow"), Some("")));    assert_eq!(a["wait_ms"], 1500);    field.person("robbie", "Ravi");    let a = field.heard(json!({"pass": "second", "final": true, "text": "Send it to Robby tomorrow.", "from_ms": 0, "to_ms": 1500}));    assert_eq!(field.text, "Send it to Ravi tomorrow.");    assert!(a.get("wait_ms").is_none());    let done = field.end();    assert_eq!(done["words"], 5);}// RULE (voice plan): spoken punctuation per language and mixed-language sentences, by the person's languages from the settings row.#[test]fn the_settings_row_chooses_the_languages_and_their_punctuation() {    let (_dir, handle) = phone();    let defaults = ask(&handle, "voice.settings", json!({}));    assert_eq!(defaults["languages"], json!([{"code": "en", "script": "latn", "name": "English", "native_script": "latn"}]));    assert_eq!((defaults["passes"].as_str(), defaults["mobile_data"].as_str()), (Some("two"), Some("ask")));    assert_eq!(defaults["lines"]["title"], "Voice");    let set = ask(&handle, "voice.settings", json!({"set": {"languages": [{"code": "te"}, {"code": "en"}], "mobile_data": "never"}}));    assert_eq!(set["languages"][0], json!({"code": "te", "script": "telu", "name": "తెలుగు", "native_script": "telu"}));    assert_eq!(set["mobile_data"], "never");    let latin = ask(&handle, "voice.settings", json!({"set": {"languages": [{"code": "te", "script": "latn"}, {"code": "en"}]}}));    assert_eq!(latin["languages"][0]["script"], "latn");    let refused = crate::methods::dispatch(&handle, "voice.settings", &json!({"set": {"languages": ["en", "te", "hi", "ja"]}})).unwrap_err();    assert_eq!(refused.code, "bad_request");    let (mut field, plan) = Field::open(&handle, json!({"surface": "message", "mode": "dictate", "platform": "ios"}));    assert_eq!(plan["languages"], json!(["te", "en"]));    assert_eq!(plan["scripts"]["te"], "latn");    // Apple does not hear Telugu well: the catalogue's model is the live pass.    assert_eq!(plan["live"]["engine"], "sherpa:indicconformer-te-int8");    assert_eq!(plan["mobile_data"], "never");    field.heard(json!({"pass": "live", "final": true, "text": "meeting at five కామా సరే full stop"}));    field.heard(json!({"pass": "live", "final": true, "text": "రేపు కలుద్దాం కొత్త లైన్ bye"}));    assert_eq!(field.text, "Meeting at five, సరే. రేపు కలుద్దాం\nBye");    ask(&handle, "voice.settings", json!({"set": {"languages": ["hi"], "passes": "live"}}));    let (mut field, plan) = Field::open(&handle, json!({"surface": "note", "mode": "dictate", "platform": "ios"}));    assert_eq!(plan["live"]["engine"], "apple.speech");    assert_eq!(plan["second"], Value::Null);    field.heard(json!({"pass": "live", "final": true, "text": "मैं घर जा रहा हूँ पूर्ण विराम कल मिलते हैं"}));    assert_eq!(field.text, "मैं घर जा रहा हूँ। कल मिलते हैं");}// RULE (voice plan): a Story dialogue hands the engines its own story's character names first, and the session writes them in their casing.#[test]fn a_story_dialogue_prefers_its_character_names() {    let (_dir, handle) = story_phone();    let story = make(&handle, "story_story", json!({"title": "The Monsoon House"}));    let other = make(&handle, "story_story", json!({"title": "Another Story"}));    make(&handle, "story_character", json!({"story": story, "name": "Meera", "lines": 40}));    make(&handle, "story_character", json!({"story": story, "name": "Arjun", "lines": 90}));    make(&handle, "story_character", json!({"story": other, "name": "Zubin", "lines": 500}));    make(&handle, "story_place", json!({"story": story, "name": "Kochi"}));    let scene = make(&handle, "story_scene", json!({"story": story, "heading": "INT. VERANDA - NIGHT", "position": 1}));    let (mut field, plan) = Field::open(&handle, json!({"surface": "dialogue", "table": "story_scene", "column": "body", "record": scene, "mode": "dictate", "platform": "android"}));    let vocabulary: Vec<&str> = plan["vocabulary"].as_array().unwrap().iter().filter_map(Value::as_str).collect();    assert_eq!(&vocabulary[..3], ["Arjun", "Meera", "Kochi"], "{vocabulary:?}");    assert!(!vocabulary[..3].contains(&"Zubin"));    field.heard(json!({"pass": "live", "final": true, "text": "arjun turns to meera comma we leave for kochi tonight full stop"}));    assert_eq!(field.text, "Arjun turns to Meera, we leave for Kochi tonight.");}// RULE (voice plan): command mode sends the words to the universal search and answers the record to open, or Find with the words when none resolves.#[test]fn a_command_resolves_to_a_record() {    let (_dir, handle) = phone();    let note = make(&handle, "note", json!({"title": "Garden plan", "body": "tomatoes by the wall"}));    make(&handle, "note", json!({"title": "Kitchen list"}));    let (mut field, plan) = Field::open(&handle, json!({"surface": "search", "mode": "command", "platform": "android"}));    assert_eq!(plan["second"], Value::Null);    assert_eq!(plan["vocabulary"], json!([]));    assert_eq!(plan["lines"]["command_hint"], "Say what to open");    let partial = field.heard(json!({"pass": "live", "final": false, "text": "open the garden"}));    assert!(partial.get("command").is_none());    let a = field.heard(json!({"pass": "live", "final": true, "text": "open garden plan"}));    assert_eq!(a["command"]["kind"], "open", "{a}");    assert_eq!(a["command"]["id"], json!(note));    assert_eq!(a["command"]["table"], "note");    assert_eq!(a["command"]["title"], "Garden plan");    assert_eq!(a["command"]["says"], "Opening Garden plan");    let (mut field, _) = Field::open(&handle, json!({"surface": "search", "mode": "command", "platform": "android"}));    let a = field.heard(json!({"pass": "live", "final": true, "text": "show me the quarterly numbers"}));    assert_eq!(a["command"], json!({"kind": "search", "query": "the quarterly numbers", "says": "Finding “the quarterly numbers”"}));}// RULE (voice plan): voice.models is the catalogue joined with what this phone holds; voice.model records a change, kept on this device only.#[test]fn the_models_this_phone_holds() {    let (_dir, handle) = phone();    let models = ask(&handle, "voice.models", json!({}));    let rows = models["models"].as_array().unwrap();    assert!(!rows.is_empty());    assert!(rows.iter().all(|row| row["state"] == "absent" && row["engine"].as_str().unwrap().starts_with("sherpa:")));    assert_eq!(models["held_bytes"], 0);    let id = rows[0]["id"].as_str().unwrap().to_string();    let downloading = ask(&handle, "voice.model", json!({"model": id, "state": "downloading", "bytes_done": 1024}));    assert_eq!((downloading["state"].as_str(), downloading["bytes_done"].as_u64()), (Some("downloading"), Some(1024)));    let ready = ask(&handle, "voice.model", json!({"model": id, "state": "ready", "path": "/shared/voice/model"}));    assert_eq!(ready["path"], "/shared/voice/model");    let again = ask(&handle, "voice.models", json!({}));    let row = again["models"].as_array().unwrap().iter().find(|row| row["id"] == json!(id)).unwrap().clone();    assert_eq!(row["state"], "ready");    assert!(crate::methods::dispatch(&handle, "voice.model", &json!({"model": id, "state": "ready"})).is_err());    assert!(crate::methods::dispatch(&handle, "voice.model", &json!({"model": "no-such-model", "state": "ready", "path": "/x"})).is_err());    ask(&handle, "voice.model", json!({"model": id, "state": "absent"}));    let gone = ask(&handle, "voice.models", json!({}));    assert!(gone["models"].as_array().unwrap().iter().all(|row| row["state"] == "absent"));}#[test]fn a_session_must_be_planned_first() {    let (_dir, handle) = phone();    let error = crate::methods::dispatch(&handle, "voice.heard", &json!({"session": "v-nothing", "pass": "live", "text": "hi"})).unwrap_err();    assert_eq!(error.code, "not_found");    let error = crate::methods::dispatch(&handle, "voice.plan", &json!({"mode": "sing"})).unwrap_err();    assert_eq!(error.code, "bad_request");}/// The plan offers only files it can check, one entry per file.#[test]fn downloads_are_one_entry_per_checkable_file() {    let catalogue: Value = serde_json::from_str(super::CATALOGUE).unwrap();    for (id, entry) in catalogue["models"].as_object().unwrap() {        for file in entry["files"].as_array().unwrap() {            assert!(file["name"].is_string(), "{id}");        }    }    for (code, choice) in catalogue["languages"].as_object().unwrap() {        for role in ["live", "second"] {            if let Some(model) = choice[role].as_str() {                assert!(catalogue["models"].get(model).is_some(), "{code}'s {role} model {model} is in the catalogue");            }        }    }}/// A row says how its model is configured and whether the microphone is/// levelled before it, so no platform reads anything into a model's name.#[test]fn a_models_row_carries_its_configuration_and_its_levelling() {    let (_dir, handle) = phone();    let models = ask(&handle, "voice.models", json!({}));    let catalogue: Value = serde_json::from_str(super::CATALOGUE).unwrap();    let rows = models["models"].as_array().unwrap();    let row = |id: &str| rows.iter().find(|row| row["id"] == json!(id)).unwrap_or_else(|| panic!("{id} answered")).clone();    for (id, entry) in catalogue["models"].as_object().unwrap() {        assert!(entry["normalises_input"].is_boolean(), "{id} says whether it levels its own input");        let answered = row(id);        assert_eq!(answered["kind"], entry["kind"], "{id}");        assert_eq!(answered["files"], entry["files"], "{id}");        assert_eq!(answered["options"], entry["options"], "{id}'s options as the catalogue has them");        if entry["normalises_input"] == false {            assert_eq!(answered["level_input"], catalogue["levelling"], "{id} is levelled before");        } else {            assert!(answered["level_input"].is_null(), "{id} levels itself");        }    }    let live = catalogue["languages"]["en"]["live"].as_str().unwrap();    assert_eq!(row(live)["options"]["model_type"], "nemo_transducer", "English's live NeMo transducer");    assert_eq!(models["vad"], catalogue["vad"]);    assert_eq!(models["lid"], "whisper-tiny-int8");    assert_eq!(row("whisper-tiny-int8")["role"], "lid");    assert!(row(models["vad"].as_str().unwrap())["level_input"]["below_peak"].is_number());}