//! A message the phone sent to a coding session, and the same words coming//! back as the session's own user turn.//!//! A reply typed on the phone is a `cotton_session_messages` row, and the Mac//! that holds the session pastes it into the terminal. The agent then has it//! in its transcript as a user turn, and whoever logs that transcript — the//! Stop hook through `log_session`, or the Mac's own mirror for a session no//! hook logs — would write it again as a `cotton_prompts` row. The session page//! then drew the owner's words twice, the second copy looking typed on the Mac.//!//! The owner's decision (30 Sep): the phone's own row is the only one. So both//! writers skip a user turn that is a delivered message, and both ask the ONE//! question below, because two spellings of "is this the same words" would//! disagree the first time a body carried a line break./// The kinds that are TYPED INTO THE TERMINAL rather than answered — the only/// messages that can come back as a turn.pubconst TYPED_KINDS: [&str; 2] = ["instruction", "answer"];/// The longest turn text a writer sends; a longer message comes back clipped,/// so a turn this long is compared as a prefix.pubconst TURN_TEXT_CAP: usize = 8000;/// The messages a user turn of this session may be the echo of: typed kinds/// addressed to it, and not withdrawn (a withdrawn message never reached the/// terminal). An `open` or `claimed` one counts too: the turn can reach a/// server before the Mac's `done` does, and a message still `open` there has/// been typed if its words are already in the transcript. Oldest first — the/// order they were typed.pubconst DELIVERED_MESSAGES_SQL: &str ="SELECT id, body, created_at FROM cotton_session_messages \ WHERE to_kind = 'session' AND to_session_id = ? \ AND kind IN ('instruction', 'answer') AND status <> 'withdrawn' \ ORDER BY created_at, id";/// One message a user turn may be the echo of, as [`DELIVERED_MESSAGES_SQL`]/// reads it.#[derive(Debug, Clone, PartialEq, Eq)]pubstructDeliveredMessage {pub id: String,pub body: String,pub created_at: String,}/// What a message body becomes in the terminal: line breaks kept (`\r\n` and/// `\r` become `\n`), every other control character but a tab dropped, the end/// trimmed. The Mac types exactly this, so it is also what comes back.pubfn typed_text(body: &str) -> String {letmut text = String::with_capacity(body.len());for character in body.replace("\r\n", "\n").chars() {match character { '\r' => text.push('\n'), '\n' | '\t' => text.push(character), other if other.is_control() => {} other => text.push(other), } } text.trim_end().to_string()}/// Whitespace runs as one space, the ends trimmed: an agent may store a paste/// with its line endings or indentation changed, and those are not different/// words.fn comparable(text: &str) -> String { text.split_whitespace().collect::<Vec<_>>().join(" ")}/// Whether a user turn says the words of this message body.fn same_words(turn: &str, body: &str) -> bool {let said = comparable(turn);if said.is_empty() {returnfalse; }let clipped = turn.chars().count() >= TURN_TEXT_CAP;let sent = comparable(&typed_text(body)); sent == said || (clipped && sent.starts_with(&said))}/// An instant as milliseconds, for comparing a phone's `created_at` with a/// transcript's `ts` — two writers, two spellings (with and without/// milliseconds), so never compared as text.fn instant_ms(at: &str) -> Option<i64> { chrono::DateTime::parse_from_rfc3339(at) .ok() .map(|at| at.timestamp_millis())}/// Which delivered message a user turn is the echo of, if any.////// **A message absorbs at most one turn, with no record kept of which** — the/// bound comes from the turns the session DID keep:////// * `after` is the `ts` of the session's last kept turn before this one, of/// either role. A message sent before it has had its turn already: the/// agent answered past it. Only messages sent after it are candidates, so/// one delivered "yes" cannot absorb a "yes" typed at the Mac an exchange/// later./// * `past` is the message the previous turn of the SAME window absorbed (no/// kept turn between the two), when the writer knows it. Only messages after/// it are candidates, so two identical messages absorb two turns, not one/// message twice.////// The oldest candidate with the same words takes the turn. A turn nothing/// matches is the owner's own, typed at the Mac, and is kept. The rule is a/// function of what is on disk, so the same turn told again (a hook resend,/// the mirror re-reading the last turn) gets the same answer.////// It errs towards KEEPING: a message typed while the agent was still/// answering can land after that answer's turn, and its echo is then kept —/// the page shows the words twice, as before this module, and never loses a/// turn the owner typed.pubfn absorbing<'a>( turn: &str, after: Option<&str>, past: Option<&DeliveredMessage>, messages: &'a [DeliveredMessage],) -> Option<&'a DeliveredMessage> {let after_ms = match after {Some(at) => Some(instant_ms(at)?),None => None, };let key = |message: &DeliveredMessage| { instant_ms(&message.created_at).map(|at| (at, message.id.clone())) };let past_key = match past {Some(message) => Some(key(message)?),None => None, }; messages .iter() .filter_map(|message| key(message).map(|at| (at, message))) .filter(|(at, _)| after_ms.is_none_or(|after| at.0 > after)) .filter(|(at, _)| past_key.as_ref().is_none_or(|past| at > past)) .filter(|(_, message)| same_words(turn, &message.body)) .min_by(|(left, _), (right, _)| left.cmp(right)) .map(|(_, message)| message)}/// The messages a user turn on this session row may be the echo of, read from/// a file the writer holds itself — the Mac's mirror; `log_session` reads them/// through its own query.pubfn delivered_messages( db: &cotton_store::driver::Driver, session_row_id: &str,) -> Result<Vec<DeliveredMessage>, String> {let rows = db .all( DELIVERED_MESSAGES_SQL, &[rusqlite::types::Value::Text(session_row_id.to_string())], ) .map_err(|error| error.to_string())?;Ok(rows .iter() .filter_map(|row| {Some(DeliveredMessage { id: row.text("id")?.to_string(), body: row.text("body")?.to_string(), created_at: row.text("created_at")?.to_string(), }) }) .collect())}#[cfg(test)]#[path = "session_echo_tests.rs"]mod tests;