//! Whole sessions driven from recorded engine output, every answer applied //! the way a platform applies it: the platform's text must equal the core's //! after every call, so the edits are proven, not only the text. use super::*; use crate::voice::format::Rules; /// What a platform holds: the text it shows, changed only by the answers' /// edits and by the person's own typing. struct Phone { session: Session, text: String, } impl Phone { fn new(codes: &[&str], vocabulary: &[&str]) -> Phone { let rules = Rules::of(codes, vocabulary.iter().map(|s| s.to_string()).collect()); Phone { session: Session::new(rules, false, true), text: String::new() } } fn check(&mut self, answer: &Answer) { self.text = apply(&self.text, &answer.edits); assert_eq!(self.text, self.session.text(), "the platform's text after the edits {:?}", answer.edits); assert_eq!(format!("{}{}{}", answer.settled, answer.tentative, answer.later), self.text); let mut last = usize::MAX; for edit in &answer.edits { assert!(edit.to <= last, "edits come last first and never overlap: {:?}", answer.edits); last = edit.from; } } fn heard(&mut self, pass: Pass, is_final: bool, text: &str, span: Option<(u64, u64)>) -> Answer { let answer = self.session.heard(&Heard { pass, is_final, text, span, upper_case: false }); self.check(&answer); answer } fn partial(&mut self, text: &str) -> Answer { self.heard(Pass::Live, false, text, None) } fn live(&mut self, text: &str) -> Answer { self.heard(Pass::Live, true, text, None) } fn second(&mut self, text: &str) -> Answer { self.heard(Pass::Second, true, text, None) } /// The person replaces the first `word` in the text with `with`. fn person(&mut self, word: &str, with: &str) -> Answer { let at = self.text.find(word).unwrap_or_else(|| panic!("{word:?} in {:?}", self.text)); self.person_at(at, at + word.len(), Some(with)) } fn person_at(&mut self, from: usize, to: usize, with: Option<&str>) -> Answer { let (from16, to16) = (units_at(&self.text, from), units_at(&self.text, to)); if let Some(with) = with { self.text.replace_range(from..to, with); } let answer = self.session.touched_range(from16, to16, with).expect("a range in the text"); assert!(answer.edits.is_empty(), "the person's own change is no edit: {:?}", answer.edits); self.check(&answer); answer } } #[test] fn live_partials_revise_themselves_and_settle() { let mut phone = Phone::new(&["en"], &[]); let a = phone.partial("hello"); assert_eq!((a.settled.as_str(), a.tentative.as_str()), ("", "Hello")); phone.partial("hello word"); let a = phone.partial("hello world how"); assert_eq!(a.tentative, "Hello world how"); assert_eq!(a.edits, vec![Edit { from: 9, to: 10, text: "ld how".into() }]); let a = phone.live("hello world how are you question mark"); assert_eq!((a.settled.as_str(), a.tentative.as_str()), ("Hello world how are you?", "")); assert_eq!(a.awaiting_second, 1); phone.partial("i am fine"); let a = phone.live("i am fine thanks"); assert_eq!(a.settled, "Hello world how are you? I am fine thanks"); } #[test] fn a_second_pass_corrects_a_settled_sentence() { let mut phone = Phone::new(&["en"], &[]); phone.live("i red the book yesterday"); phone.partial("it was"); let a = phone.second("I read the book yesterday."); assert_eq!(phone.text, "I read the book yesterday. It was"); // Word by word, last first: the full stop and the next sentence's capital, then "red" → "read". assert_eq!(a.edits, vec![Edit { from: 24, to: 26, text: ". I".into() }, Edit { from: 4, to: 4, text: "a".into() }]); assert_eq!(a.tentative, " It was"); phone.live("it was good"); let a = phone.second("It was good."); assert_eq!(phone.text, "I read the book yesterday. It was good."); assert_eq!(a.awaiting_second, 0); } #[test] fn a_persons_edit_in_the_middle_is_never_touched_by_the_second_pass() { let mut phone = Phone::new(&["en"], &[]); phone.live("sent it to robbie tomorow"); phone.person("robbie", "Ravi"); phone.second("Send it to Robby tomorrow."); assert_eq!(phone.text, "Send it to Ravi tomorrow."); } #[test] fn a_word_the_person_deleted_is_not_put_back() { let mut phone = Phone::new(&["en"], &[]); phone.live("it was really very good"); let at = phone.text.find(" really").unwrap(); phone.person_at(at, at + " really".len(), Some("")); assert_eq!(phone.text, "It was very good"); phone.second("It was really very good."); assert_eq!(phone.text, "It was very good."); } #[test] fn an_edit_in_the_tentative_words_settles_them_once() { let mut phone = Phone::new(&["en"], &[]); phone.partial("call"); phone.partial("call rubby about"); phone.person("rubby", "Ruby"); phone.partial("call rubby about the"); phone.partial("call rubby about the plan"); phone.live("call rubby about the plan"); assert_eq!(phone.text, "Call Ruby about the plan"); phone.second("Call Robbie about the plan."); assert_eq!(phone.text, "Call Ruby about the plan."); } /// voice-ios's walk: "Quietly. " put at the very start while the first /// sentence's live words were still arriving, and the live engine then re-read /// its first words as fewer ("seed a" → "sita"): the settled sentence lost its /// last word ("…out of the window" → "…out of the"). #[test] fn an_insertion_at_the_start_while_the_first_sentence_is_live_loses_no_word() { let mut phone = Phone::new(&["en"], &[]); phone.partial("ceda"); phone.partial("seed a looks out of the"); phone.person_at(0, 0, Some("Quietly. ")); phone.partial("sita looks out of the"); phone.partial("sita looks out of the window"); phone.live("sita looks out of the window"); assert_eq!(phone.text, "Quietly. Seed a looks out of the window"); let answer = phone.session.end(); phone.check(&answer); assert_eq!(phone.text, "Quietly. Seed a looks out of the window"); phone.second("Sita looks out of the window."); assert_eq!(phone.text, "Quietly. Sita looks out of the window."); } /// The words an edit froze are found in the later hypotheses by what they /// say, not by how many there were: a re-read that splits a word in two /// doubles nothing either. #[test] fn a_rereading_that_splits_a_frozen_word_doubles_nothing() { let mut phone = Phone::new(&["en"], &[]); phone.partial("sita looks out"); phone.person_at(0, 0, Some("Quietly. ")); phone.live("seed a looks out of the window"); assert_eq!(phone.text, "Quietly. Sita looks out of the window"); } #[test] fn mixed_language_sentences() { let mut phone = Phone::new(&["en", "te"], &[]); phone.live("meeting at five కామా సరే full stop"); phone.live("రేపు కలుద్దాం new line bye"); assert_eq!(phone.text, "Meeting at five, సరే. రేపు కలుద్దాం\nBye"); let mut phone = Phone::new(&["hi", "en"], &[]); phone.live("कल meeting है पूर्ण विराम ok"); assert_eq!(phone.text, "कल meeting है। Ok"); } #[test] fn spoken_punctuation_across_utterances() { let mut phone = Phone::new(&["en"], &["Ravi"]); phone.live("dear ravi comma new line"); phone.live("thanks for the book full stop"); phone.live("comma see you soon"); assert_eq!(phone.text, "Dear Ravi,\nThanks for the book., see you soon"); let mut phone = Phone::new(&["ja"], &[]); phone.live("今日は晴れ 句点"); phone.live("明日は雨 改行"); phone.live("以上"); assert_eq!(phone.text, "今日は晴れ。明日は雨\n以上"); } #[test] fn a_story_dialogue_takes_the_characters_names() { // The vocabulary voice.plan hands a Story dialogue: its characters first. let mut phone = Phone::new(&["en"], &["Arjun", "Meera", "Will"]); phone.live("arjun turns to meera comma will you come"); assert_eq!(phone.text, "Arjun turns to Meera, will you come"); } #[test] fn a_second_pass_finds_its_utterance_by_time() { let mut phone = Phone::new(&["en"], &[]); phone.heard(Pass::Live, true, "the first won", Some((0, 1500))); phone.heard(Pass::Live, true, "the second too", Some((2000, 3500))); phone.heard(Pass::Second, true, "The second two.", Some((1900, 3600))); // The second pass's own casing stands: it read the sentence whole. assert_eq!(phone.text, "The first won The second two."); phone.heard(Pass::Second, true, "The first one.", Some((0, 1600))); assert_eq!(phone.text, "The first one. The second two."); } #[test] fn a_second_pass_before_its_live_final_is_not_doubled() { let mut phone = Phone::new(&["en"], &[]); phone.partial("good morning"); phone.second("Good morning everyone."); assert_eq!(phone.text, "Good morning everyone."); phone.partial("good morning every"); phone.live("good morning everyone"); assert_eq!(phone.text, "Good morning everyone."); phone.live("lets begin"); assert_eq!(phone.text, "Good morning everyone. Lets begin"); } #[test] fn a_second_pass_ahead_of_the_live_engine_waits_after_it() { let mut phone = Phone::new(&["en"], &[]); phone.partial("one"); phone.second("One."); phone.second("Two."); let a = phone.partial("ignored"); assert_eq!(phone.text, "One. Two."); assert_eq!(a.tentative, ""); phone.live("one"); let a = phone.partial("two"); assert_eq!(a.tentative, ""); phone.live("two"); let a = phone.partial("three"); assert_eq!(a.tentative, " Three"); assert_eq!(phone.text, "One. Two. Three"); } #[test] fn ending_settles_the_tentative_words() { let mut phone = Phone::new(&["en"], &[]); phone.live("first"); phone.partial("and then"); let answer = phone.session.end(); phone.check(&answer); assert_eq!((answer.settled.as_str(), answer.tentative.as_str()), ("First and then", "")); } #[test] fn offsets_are_utf16() { let mut phone = Phone::new(&["en"], &[]); phone.live("party 🎉 time"); phone.person("time", "now"); assert_eq!(phone.text, "Party 🎉 now"); phone.second("Party 🎉 tim."); assert_eq!(phone.text, "Party 🎉 now."); assert_eq!(byte_at("a🎉b", 1), Some(1)); assert_eq!(byte_at("a🎉b", 2), None); assert_eq!(byte_at("a🎉b", 3), Some(5)); assert_eq!(byte_at("a🎉b", 5), None); } #[test] fn a_range_past_the_text_is_refused() { let mut phone = Phone::new(&["en"], &[]); phone.live("short"); assert_eq!(phone.session.touched_range(2, 99, Some("x")), Err(Refused::Range)); } // ── The property ───────────────────────────────────────────────────────── /// A small seeded generator: the same seed, the same sessions. struct Rng(u64); impl Rng { fn next(&mut self) -> u64 { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 7; self.0 ^= self.0 << 17; self.0 } fn below(&mut self, n: usize) -> usize { (self.next() % n as u64) as usize } fn chance(&mut self, percent: u64) -> bool { self.next() % 100 < percent } } #[derive(Debug, Clone)] enum Event { Partial(usize, usize), Final(usize), Second(usize), Edit, } const WORDS: [&str; 24] = [ "apple", "river", "stone", "cloud", "lamp", "garden", "window", "bread", "music", "paper", "forest", "candle", "mirror", "rocket", "pencil", "orange", "violet", "harbor", "meadow", "copper", "silver", "winter", "button", "tiger", ]; /// Whatever order live, second and the person's edits arrive in: the text /// the person wrote is never changed, and no heard word is doubled, lost or /// moved — every word is the second pass's word in its place, or the /// person's. #[test] fn edits_survive_and_nothing_is_doubled_or_lost_in_any_order() { for seed in 1..=4000u64 { let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); let utterances = 1 + rng.below(4); let mut fresh = 0; let mut word = |rng: &mut Rng| { fresh += 1; format!("{}{}", WORDS[rng.below(WORDS.len())], fresh) }; let live: Vec> = (0..utterances).map(|_| (0..2 + rng.below(5)).map(|_| word(&mut rng)).collect()).collect(); let second: Vec> = live .iter() .map(|words| words.iter().map(|w| if rng.chance(30) { word(&mut rng) } else { w.clone() }).collect()) .collect(); // The live stream in order: growing partials (some with a wrong last word), then the final. let mut live_events = Vec::new(); for (u, words) in live.iter().enumerate() { for n in 1..=words.len() { if rng.chance(60) { live_events.push(Event::Partial(u, n)); } } live_events.push(Event::Final(u)); } let second_events: Vec = (0..utterances).map(Event::Second).collect(); let (mut l, mut s) = (0, 0); let mut events = Vec::new(); while l < live_events.len() || s < second_events.len() { if rng.chance(15) { events.push(Event::Edit); } let take_live = s == second_events.len() || (l < live_events.len() && rng.chance(65)); if take_live { events.push(live_events[l].clone()); l += 1; } else { events.push(second_events[s].clone()); s += 1; } } if rng.chance(50) { events.push(Event::Edit); } let mut phone = Phone::new(&["en"], &[]); let mut markers: Vec = Vec::new(); let mut wrong = 0; for event in &events { match event { Event::Partial(u, n) => { let mut words = live[*u][..*n].to_vec(); if *n < live[*u].len() && rng.chance(25) { wrong += 1; *words.last_mut().unwrap() = format!("wrong{wrong}"); } phone.partial(&words.join(" ")); } Event::Final(u) => { phone.live(&live[*u].join(" ")); } Event::Second(u) => { phone.second(&second[*u].join(" ")); } Event::Edit => { // The person retypes one word that is not already theirs. let candidates: Vec<(usize, usize)> = word_ranges(&phone.text) .into_iter() .filter(|(a, b)| !phone.text[*a..*b].to_lowercase().starts_with("mark")) .collect(); if candidates.is_empty() { continue; } let (a, b) = candidates[rng.below(candidates.len())]; let marker = format!("mark{}", markers.len()); phone.person_at(a, b, Some(&marker)); markers.push(marker); } } } let answer = phone.session.end(); phone.check(&answer); let written: Vec = word_ranges(&phone.text).into_iter().map(|(a, b)| phone.text[a..b].to_lowercase()).collect(); let expected: Vec = second.iter().flatten().map(|w| w.to_lowercase()).collect(); let context = || format!("seed {seed}\nevents {events:?}\nlive {live:?}\nsecond {second:?}\ntext {:?}", phone.text); for marker in &markers { let count = written.iter().filter(|w| *w == marker).count(); let overwritten = !phone.text.contains(marker.as_str()) && count == 0; assert!(count == 1 || overwritten, "the person's {marker} is there once: {}", context()); } let kept: Vec<&String> = markers.iter().filter(|m| written.contains(m)).collect(); assert_eq!(written.len(), expected.len(), "no word doubled or lost: {}", context()); let mut seen_markers = 0; for (got, want) in written.iter().zip(&expected) { if got.starts_with("mark") { seen_markers += 1; } else { assert_eq!(got, want, "every word the second pass's, in its place: {}", context()); } } assert_eq!(seen_markers, kept.len(), "{}", context()); } } /// The byte ranges of the words of `text` (letters and digits). fn word_ranges(text: &str) -> Vec<(usize, usize)> { let mut out = Vec::new(); let mut start = None; for (at, c) in text.char_indices() { match (start, c.is_alphanumeric()) { (None, true) => start = Some(at), (Some(s), false) => { out.push((s, at)); start = None; } _ => {} } } if let Some(s) = start { out.push((s, text.len())); } out }