//! `read.keyboardSnapshot` — the bytes of `cotton.keyboard.snapshot.v1`. //! //! The keyboard is the Android input method //! (`apps/cotton-android/…/keyboard/KeyboardSnapshotBridge.kt`): it asks this //! read for one JSON blob and keeps it beside the takes it is still offering. //! //! ## The pending carry-forward, and why it is an ARGUMENT //! //! A take is `pending` while the keyboard may still auto-insert it. That flag //! is not a column and never will be: it is App Group state, minted when a take //! finishes and cleared the moment the keyboard inserts it. A rebuild has to //! CARRY it — but only for takes still inside the ten-minute window, because //! inserting a forgotten take into tomorrow's first text field would be the bug //! the window exists to prevent. //! //! The previous snapshot lives in `UserDefaults`, which Rust does not read. So //! the caller passes the pending ids and their finished times it currently holds and this decides //! which of them survive: the WINDOW ARITHMETIC is a clock decision and belongs //! below the boundary with every other one. The alternative — Swift merging — //! would put the one rule that makes this correct in the one place there is no //! test for it. use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use crate::shell::file::ReadFile; /// Most takes the snapshot carries, newest first. pub const MAX_SNAPSHOT_TAKES: usize = 5; /// How long a finished take stays auto-insertable, in milliseconds. pub const TAKE_PENDING_WINDOW_MS: i64 = 10 * 60 * 1000; #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct KeyboardTake { pub id: String, pub text: String, pub words: i64, /// When the take FINISHED — the row's `spoken_at`, not its `created_at`. /// An imported 2024 transcript sorts into 2024 and a take from this morning /// sorts into this morning, which is the order a person remembers their own /// day in. pub created_at: String, pub pending: bool, } /// The whole of `cotton.keyboard.snapshot.v1`. Nothing here is optional: every /// field is filled, and the SWIFT side reads each one as an Optional because a /// snapshot outlives the binary that wrote it. No settings: the keyboard is /// voice only (Spec 10.6), so nothing typed is kept and there is no switch. #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct KeyboardSnapshot { pub as_of: String, pub takes: Vec, } /// One take as it comes off the corpus, before the pending decision. #[derive(Debug, Clone, PartialEq, Eq)] pub struct TakeRow { pub id: String, pub text: String, pub words: i64, pub created_at: String, } /// The word count the whole feature uses — whitespace runs, nothing cleverer. /// /// The same arithmetic `dictation.create` falls back to, so a take counted by /// the app and a burst counted below cannot disagree about one sentence. pub use cotton_core::js_text::count_words; /// Pending state from the standing snapshot, including its own finished time. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PendingTake { pub id: String, pub created_at: String, } /// Build the snapshot. The port of `buildKeyboardSnapshot`. /// /// `pending` are the ids and finished times the caller's standing snapshot currently holds as /// pending. A flag is CARRIED, never invented: a fresh take the previous /// snapshot did not know is not pending, because only a finished take mints /// that. And it is carried only while the take is inside the window, measured /// STRICTLY — a take exactly ten minutes old is no longer auto-insertable, and /// the TypeScript has a test pinning that boundary. pub fn build_keyboard_snapshot( takes: &[TakeRow], pending: &[PendingTake], now_ms: i64, ) -> KeyboardSnapshot { let carried: std::collections::BTreeSet<&str> = pending .iter() .filter(|take| { cotton_store::protocol::js::parse_date_ms(&take.created_at) .is_some_and(|created| now_ms - created < TAKE_PENDING_WINDOW_MS) }) .map(|take| take.id.as_str()) .collect(); KeyboardSnapshot { as_of: cotton_store::protocol::js::to_iso_string(now_ms) .expect("parsed snapshot instant fits ISO"), takes: takes .iter() .take(MAX_SNAPSHOT_TAKES) .map(|take| KeyboardTake { pending: carried.contains(take.id.as_str()), id: take.id.clone(), text: take.text.clone(), words: take.words, created_at: take.created_at.clone(), }) .collect(), } } /// `read.keyboardSnapshot`. pub fn keyboard_snapshot(replica: &ReadFile<'_>, args: &Map) -> Result { let now_iso = args .get("now") .and_then(Value::as_str) .ok_or_else(|| "`now` is the instant this snapshot speaks for".to_string())?; let now_ms = cotton_store::protocol::js::parse_date_ms(now_iso) .ok_or_else(|| format!("`now` is not an instant: {now_iso:?}"))?; let pending: Vec = match args.get("pending") { None | Some(Value::Null) => Vec::new(), Some(value) => serde_json::from_value(value.clone()).map_err(|error| { format!("`pending` carries id and createdAt from the standing snapshot: {error}") })?, }; // Only takes reach the tray; a `typed` row an older keyboard wrote stays out. let rows = replica .driver .all( "SELECT id, text, words, spoken_at FROM cotton_dictations WHERE workspace_id = ? AND source = 'take' ORDER BY spoken_at DESC LIMIT ?", &[ rusqlite::types::Value::Text(replica.workspace_id.to_string()), rusqlite::types::Value::Integer(MAX_SNAPSHOT_TAKES as i64), ], ) .map_err(|error| error.to_string())?; let takes: Vec = rows .iter() .map(|row| { let text = row.text("text").unwrap_or_default().to_string(); TakeRow { id: row.text("id").unwrap_or_default().to_string(), words: row.int("words").unwrap_or_else(|| count_words(&text)), text, created_at: row.text("spoken_at").unwrap_or_default().to_string(), } }) .collect(); let snapshot = build_keyboard_snapshot(&takes, &pending, now_ms); serde_json::to_value(&snapshot).map_err(|error| error.to_string()) } #[cfg(test)] #[path = "keyboard_tests.rs"] mod tests;