//! THE WORDS A SESSION IS READ IN — the sentences the app's //! `SessionTableSource` worked out in Swift (`SessionRows.record`, with the //! rules of `SessionFacts` and `CodeFacts`), said ONCE here so the generic //! read (`records.list` / `records.get` of the `session` table) and the //! phone's own reads (`read.sessions`, `read.session`, `read.project`) answer //! the same section, line and facts for the same row. //! //! PURE: every rule reads a session spelled the way `list_sessions` and //! `read.session` spell one to the app (camelCase — `startedAt`, //! `hostOwned`, `projectName` …), and `now` comes in from the caller, floored //! to the minute as the app floored it (`SessionFacts.minuteFloor`). Each //! function is the Swift one ported line for line, its `file:line` cited above //! it (`SF` SessionFacts.swift, `SC` SessionCuts.swift, `STS` //! SessionTableSource.swift, `SMTS` SessionMessageTableSource.swift, all under //! `apps/cotton/Sources/CottonUI/Sources/`). //! //! It lives beside [`crate::session_birth`] because Resume is //! [`crate::session_birth::can_carry_on`] and nothing else, and because //! `cotton-ffi` depends on this crate: the phone's reads call these rules //! rather than keep a second copy (`drawn_as_running`, the pending decision). use cotton_store::protocol::js::parse_date_ms; use serde_json::{Map, Value}; use crate::session_birth::can_carry_on; /// How far back the session list looks — SEVEN DAYS, by a session's last /// activity — and the window the list's sections are cut by /// (`CodeFacts.quietWindow`, SC:140). `read.sessions` sends it as /// `quietWindowMs`; this is the one copy. pub const SESSIONS_WINDOW_MS: i64 = 7 * 24 * 60 * 60 * 1000; /// How long an idle session Cotton holds still counts as RUNNING: an hour /// (`CodeFacts.idleIsRunningWindow`, SC:147). pub const IDLE_IS_RUNNING_MS: i64 = 60 * 60 * 1000; /// `now` floored to the minute — SF:21 (`minuteFloor`). pub fn minute_floor(now_ms: i64) -> i64 { now_ms - now_ms.rem_euclid(60_000) } /// A string member, trimmed, and nothing for the blank — the app's /// `JSONValue.text` (JSONValue+Fields.swift:21-25). fn said(session: &Map, key: &str) -> Option { session .get(key) .and_then(Value::as_str) .map(str::trim) .filter(|words| !words.is_empty()) .map(str::to_string) } /// A flag where absent is false — `JSONValue.flag` (JSONValue+Fields.swift:45). /// A stored `1` counts too: the store keeps a flag as an integer. fn flag(session: &Map, key: &str) -> bool { match session.get(key) { Some(Value::Bool(set)) => *set, Some(other) => other.as_i64().is_some_and(|set| set != 0), None => false, } } fn number(session: &Map, key: &str) -> Option { session.get(key).and_then(Value::as_i64) } fn when(session: &Map, key: &str) -> Option { said(session, key).and_then(|at| parse_date_ms(&at)) } /// The facts joined ` · `; an absent or empty fact adds nothing — /// `metaLine` (JSONValue+Fields.swift:78-81). fn meta_line(parts: &[Option]) -> Option { let kept: Vec<&str> = parts.iter().flatten().map(String::as_str).filter(|part| !part.is_empty()).collect(); (!kept.is_empty()).then(|| kept.join(" · ")) } // ── what a session is called ───────────────────────────────────────────── /// SF:33-43 (`title`): the tool's own title, else the repo and branch, else /// the honest fallback. pub fn title(session: &Map) -> String { if let Some(title) = said(session, "title") { return title; } if let Some(repo) = repo_name(said(session, "repoUrl").as_deref()) { if let Some(branch) = said(session, "branch") { return format!("{repo} · {branch}"); } return repo; } "Untitled session".to_string() } /// `git.example.com/team/project.git` → `project` — SF:47-54 (`repoName`). pub fn repo_name(repo_url: Option<&str>) -> Option { let repo_url = repo_url?; let last = repo_url.split('/').filter(|part| !part.is_empty()).last().unwrap_or_default(); let name = last.strip_suffix(".git").unwrap_or(last).trim(); (!name.is_empty()).then(|| name.to_string()) } /// `owner@example.com` → `owner@…` — SF:58-63 (`shortAccount`). pub fn short_account(account: &str) -> String { match account.find('@') { Some(at) if at > 0 => format!("{}@…", &account[..at]), _ => account.to_string(), } } /// Whether Cotton holds this session's terminal — SF:241 (`isOurs`). pub fn is_ours(session: &Map) -> bool { flag(session, "hostOwned") } /// SF:257-262 (`header`): a project's conversation is named after its /// project; everything else is called what it was called. pub fn heading(session: &Map) -> String { if said(session, "kind").as_deref() != Some("conversation") { return title(session); } match said(session, "projectName").or_else(|| said(session, "project")) { Some(project) => format!("{project} · conversation"), None => "Conversation".to_string(), } } /// Which agent ran it in a person's words — SF:318-321 (`agentName`), with /// SessionVocabulary.swift:17-21 (`SessionAgent.title`). pub fn agent_name(session: &Map) -> Option { let tool = said(session, "tool")?; Some(match tool.as_str() { "claude-code" => "Claude Code".to_string(), "codex" => "Codex".to_string(), _ => tool, }) } // ── the sections ───────────────────────────────────────────────────────── /// Which section a session's card sits in — SC:36-53 (`Section`). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Section { NeedsYou, Running, Quiet, FromTerminal, Done, } impl Section { /// The `section` choice it is written as — SC:45-53 (`choice`). pub fn choice(self) -> &'static str { match self { Section::NeedsYou => "needs_you", Section::Running => "running", Section::Quiet => "quiet", Section::FromTerminal => "from_terminal", Section::Done => "ended", } } } /// What a card says: its section and its line under the title. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Card { pub section: Section, pub state: String, } /// How a list is cut: by the queue's quiet window, or — a project's sessions /// of all time, a search's hits — with none (`historyCard`). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Cut { Window(i64), History, } /// When a row last DID something: the turn it logged, else the state it /// took, else the moment it started — SC:357-360 (`activeAt`). pub fn active_at(session: &Map) -> Option { said(session, "lastActiveAt") .or_else(|| said(session, "stateAt")) .or_else(|| said(session, "startedAt")) .and_then(|at| parse_date_ms(&at)) } /// The state words of [`word`]. struct StateFacts { state: Option, waiting: Option, exit: Option, hold: Option, error: Option, machine: Option, } impl StateFacts { fn of(session: &Map) -> Self { StateFacts { state: said(session, "state"), waiting: said(session, "waitingKind"), exit: number(session, "exitCode"), hold: said(session, "holdReason"), error: said(session, "error"), machine: said(session, "machine"), } } } /// A session's card, or nothing when the queue does not draw it — SC:170-284 /// (`card`). `quiet` is the window in milliseconds; `None` is unbounded. pub fn card(session: &Map, quiet: Option, now: i64) -> Option { said(session, "id")?; let facts = StateFacts::of(session); let state = facts.state.as_deref(); let ended = when(session, "endedAt"); let active = active_at(session); let ours = is_ours(session); let too_quiet = |at: i64| quiet.is_some_and(|quiet| now - at > quiet); let mut finished = None; let section = if state == Some("withdrawn") && !ours { return None; } else if !ours { if active.is_some_and(too_quiet) { return None; } Section::FromTerminal } else if state == Some("waiting") { Section::NeedsYou } else if matches!(state, Some("ended" | "failed" | "withdrawn")) || ended.is_some() { let end = ended.or(active)?; if too_quiet(end) { return None; } finished = Some(end); Section::Done } else if matches!(state, Some("queued" | "starting" | "running")) { Section::Running } else if state == Some("idle") && active.is_some_and(|active| now - active <= IDLE_IS_RUNNING_MS) { Section::Running } else { if active.is_some_and(too_quiet) { return None; } Section::Quiet }; // An idle session under Quiet and a terminal's say how long (SC:271-275). let since = (section == Section::FromTerminal || (section == Section::Quiet && state == Some("idle"))) .then_some(active) .flatten(); let words = word(&facts, since, now); Some(Card { section, state: done_line(words, finished, now) }) } /// A session's card in a project's history, every row drawn — SC:314-341 /// (`historyCard`): the queue's card with no window, else finished. pub fn history_card(session: &Map, now: i64) -> Option { if let Some(card) = card(session, None, now) { return Some(card); } said(session, "id")?; // The history card's word names no hold reason (SC:330-337). let facts = StateFacts { hold: None, ..StateFacts::of(session) }; Some(Card { section: Section::Done, state: word(&facts, None, now) }) } /// The words a session's state is drawn in — SC:376-417 (`word`). `since` is /// how long it has been that way, passed only where the age is the reason. fn word(facts: &StateFacts, since: Option, now: i64) -> String { if let Some(since) = since { return format!("Quiet for {}", span((now - since).max(0) / 1000)); } let machine = facts.machine.as_deref(); match facts.state.as_deref() { Some("queued") => { if let Some(hold) = &facts.hold { return hold.clone(); } match machine { Some(machine) => format!("Waiting for {machine} to pick it up"), None => "Waiting for a Mac".to_string(), } } Some("starting") => match machine { Some(machine) => format!("Starting on {machine}"), None => "Starting".to_string(), }, Some("running") => "Running".to_string(), Some("idle") => "Idle".to_string(), Some("waiting") => match facts.waiting.as_deref() { Some("permission") => "Waiting for a permission", Some("question") => "It asked you a question", Some("input") => "Waiting for you to type", _ => "Waiting on you", } .to_string(), Some("failed") => facts.error.clone().unwrap_or_else(|| "Did not start".to_string()), Some("withdrawn") => "You took it back".to_string(), Some("ended") => match facts.exit { None => "Ended".to_string(), Some(0) => "Finished".to_string(), Some(exit) => format!("Ended with code {exit}"), }, None => "No state reported".to_string(), Some(other) => other.to_string(), } } /// The state in words with no age on it — the page's `state_line` /// (STS:475-481, `CodeFacts.word` with no `since`). pub fn state_line(session: &Map) -> String { word(&StateFacts::of(session), None, 0) } /// A finished card's line with how long ago it finished on the end — /// SC:426-430 (`doneLine`). fn done_line(sentence: String, finished: Option, now: i64) -> String { match finished { Some(finished) => format!("{sentence} \u{00B7} {} ago", span((now - finished).max(0) / 1000)), None => sentence, } } /// The line a read-only card carries in place of its verbs — SC:434-439 /// (`terminalNotice`). pub fn terminal_notice(machine: Option<&str>) -> String { match machine.filter(|machine| !machine.is_empty()) { Some(machine) => format!( "Started from a terminal on {machine} — Cotton can read it and pass a reply when it next polls." ), None => "Started from a terminal — Cotton can read it and pass a reply when it next polls.".to_string(), } } /// How long it has been going — SC:446-452 (`elapsed`): from the start, else /// from when it was claimed or asked for; nothing where none is datable. pub fn elapsed(session: &Map, now: i64) -> Option { let at = said(session, "startedAt") .or_else(|| said(session, "claimedAt")) .or_else(|| said(session, "createdAt")) .and_then(|at| parse_date_ms(&at))?; let end = when(session, "endedAt").unwrap_or(now); Some(span((end - at).max(0) / 1000)) } /// `45s`, `12m`, `2h 14m`, `3d` — SC:456-466 (`span`). pub fn span(seconds: i64) -> String { if seconds < 60 { return format!("{seconds}s"); } let minutes = seconds / 60; if minutes < 60 { return format!("{minutes}m"); } let hours = minutes / 60; if hours < 24 { let rest = minutes % 60; return if rest == 0 { format!("{hours}h") } else { format!("{hours}h {rest}m") }; } format!("{}d", hours / 24) } /// Whether a session row is one a project's page draws as RUNNING under its /// conversation: a session Cotton holds, last active inside the queue's /// window, whose card is *Needs you* or *Running* ([`card`]). Without a /// `lastActiveAt` it is not. pub fn drawn_as_running(session: &Map, now: i64) -> bool { let Some(active) = when(session, "lastActiveAt") else { return false; }; is_ours(session) && now - active <= SESSIONS_WINDOW_MS && card(session, Some(SESSIONS_WINDOW_MS), now) .is_some_and(|card| matches!(card.section, Section::NeedsYou | Section::Running)) } // ── the page's own words ───────────────────────────────────────────────── /// One line of a session's own task list. #[derive(Debug, Clone, PartialEq, Eq)] pub struct TaskLine { pub seq: i64, pub text: String, pub state: String, } /// The list in the agent's own order — SF:298-309 (`tasks`): a line with no /// words is not a task, and a state that is none of the three reads `open`. pub fn task_lines(tasks: &[Value]) -> Vec { let mut lines: Vec = tasks .iter() .enumerate() .filter_map(|(index, row)| { let row = row.as_object()?; let text = said(row, "text")?; let state = said(row, "state").unwrap_or_else(|| "open".to_string()); Some(TaskLine { seq: number(row, "seq").unwrap_or(index as i64), text, state: if matches!(state.as_str(), "open" | "active" | "done") { state } else { "open".to_string() }, }) }) .collect(); lines.sort_by_key(|line| line.seq); lines } /// The mark a task line wears — STS:580-586 (`mark`). fn mark(state: &str) -> &'static str { match state { "done" => "\u{2713}", "active" => "\u{25CF}", _ => "\u{25CB}", } } /// What one record's page read besides the row: its task list. A list row /// has none. #[derive(Debug, Clone, Default)] pub struct PageFacts { pub tasks: Vec, } /// Every word a session's record carries — STS:466-550 /// (`SessionRows.record`): `heading`, `section`, `project_slug`, `line`, /// `facts`, `state_line`, `notice`, `can_resume`, `tasks`, `tasks_count`, /// `active_at`. `now` is floored to the minute here. An absent word is /// left out. pub fn session_words(session: &Map, page: Option<&PageFacts>, cut: Cut, now: i64) -> Map { let now = minute_floor(now); let mut words = Map::new(); let mut put = |key: &str, value: Option| { if let Some(value) = value { words.insert(key.to_string(), Value::from(value)); } }; let card = match cut { Cut::Window(quiet) => card(session, Some(quiet), now), Cut::History => history_card(session, now), }; let machine = said(session, "machine"); let state = state_line(session); put("heading", Some(heading(session))); put("section", card.as_ref().map(|card| card.section.choice().to_string())); put("project_slug", said(session, "project").or_else(|| said(session, "projectSlug"))); put( "line", Some(cotton_core::transforms::note_title::plain_preview(&said(session, "lastLine").or_else(|| card.as_ref().map(|card| card.state.clone())).unwrap_or_else(|| state.clone()))), ); put( "facts", meta_line(&[ agent_name(session), said(session, "account").map(|account| short_account(&account)), elapsed(session, now), machine.clone(), ]), ); put("state_line", Some(state)); put("notice", (!is_ours(session)).then(|| terminal_notice(machine.as_deref()))); // STS:482-490: the page's own list, else the counts the list row carries. let lines = page.map(|page| task_lines(&page.tasks)).unwrap_or_default(); if !lines.is_empty() { let list: Vec = lines.iter().map(|line| format!("{} {}", mark(&line.state), line.text)).collect(); put("tasks", Some(list.join("\n"))); let done = lines.iter().filter(|line| line.state == "done").count(); put("tasks_count", Some(format!("{done}/{}", lines.len()))); } else if let Some(total) = number(session, "tasksTotal").filter(|total| *total > 0) { put("tasks_count", Some(format!("{}/{total}", number(session, "tasksDone").unwrap_or(0)))); } // STS:546-548: when it ended, else when it last did anything. put( "active_at", said(session, "endedAt") .or_else(|| said(session, "lastActiveAt")) .or_else(|| said(session, "stateAt")) .or_else(|| said(session, "startedAt")), ); // STS:541 — Resume is `session.resume`'s own rule, answered on the row. words.insert( "can_resume".to_string(), Value::Bool(can_carry_on( said(session, "state").as_deref().unwrap_or_default(), is_ours(session), said(session, "externalId").as_deref(), said(session, "deviceId").as_deref(), )), ); words } /// The URLs a run says it shipped, one a line — SF:352 (`shipped`) joined as /// STS:544 joins them; nothing where it shipped none. pub fn shipped_lines(shipped: &Value) -> Option { let list = match shipped { Value::String(raw) => serde_json::from_str::(raw).unwrap_or(Value::Null), other => other.clone(), }; let lines: Vec<&str> = list.as_array()?.iter().filter_map(Value::as_str).collect(); (!lines.is_empty()).then(|| lines.join("\n")) } #[cfg(test)] #[path = "session_words_tests.rs"] mod tests;