//! How far all his mail has reached this phone (MAIL ALL ON PHONE, owner via the coordinator, 24 Nov 2026; //! MAIL.md "All mail on the phone", "The progress line's fields"). The facts only: Comms' Senders and Mail draw //! them as a quiet line ("Mail back to March 2019 ยท 41,200 of 111,422"; the wording is decided elsewhere). //! //! Nothing at all once the history is in, and nothing while Comms keeps mail to its window (neither switch is on: //! `all_history` in its manifest, or the account's own `mail_all`): a phone holding 90 days has no history coming. //! //! - `back_to`: the month of the oldest mail on this phone. //! - `held`: the mails on this phone. //! - `total`: `held` and what the pass under way still carries of `email` (the sync answer's `tables` figures). //! - `paused`: why it stands, when it stands: this phone offline; the Mac's walk not moved for half an hour //! (`mac_offline`: asleep or offline, the Mac cannot say which once it is gone); the Mac stopped it (`{mac: "full"}`, //! the person's database near its size). //! //! The Mac's part (24 Nov 2026): Cotton for Mac walks his whole mailbox and reports how far in the //! person's one `mail_history` row (`state` walking/done/held, `reached_at`, `done`, `total` the mailbox's own count, //! `at` its last move). While it walks the line stands, with the switch off too: then the phone holds 90 days and the //! line says the Mac's walk (back to the day it reached, `done` of the mailbox's `total`); with the switch on it says //! this phone, its total the mailbox's count once the Mac knows it. use crate::shell::client::ClientController; use cotton_core::rules::mail_predicate; /// Where all his mail stands on this phone. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] #[serde(rename_all = "camelCase")] pub(crate) struct History { /// The month of the oldest mail here, `YYYY-MM`; `None` while none has come. pub back_to: Option, pub held: u64, pub total: u64, #[serde(skip_serializing_if = "Option::is_none")] pub paused: Option, } /// Why the history stands still. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] #[serde(rename_all = "snake_case")] pub(crate) enum Paused { /// This phone reaches nothing. Offline, /// The Mac has not moved its walk for [`MAC_QUIET_MINUTES`]: asleep or offline. MacOffline, /// The Mac stopped the walk, in its own word (`full`: the person's database is near its size). Mac(String), } /// After this long with no move, the Mac's walk is said to stand. const MAC_QUIET_MINUTES: i64 = 30; /// The Mac's walk through the whole mailbox, as its `mail_history` row says it. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub(crate) struct MacWalk { /// `walking`, `done` or `held`. pub state: String, /// The oldest day walked, `YYYY-MM-DD`. pub reached: Option, pub done: u64, /// The mailbox's own count. pub total: u64, /// No move for [`MAC_QUIET_MINUTES`]. pub quiet: bool, } /// The facts for the line, or `None` when there is no line: the switch is off, or every mail is here. pub(crate) fn mail_history(client: &ClientController) -> Option { let kit = crate::phone::tool_acts::app_kit(client).ok().flatten()?; // The manifest's switch, or the account's own (`mail_all`, kept beside the copy's cursor). let copy = client.layout().replica(&client.attached_database()?); let kit = crate::phone::personal_object::with_account_switches(kit, ©); let mac = mac_walk(client); if !kit.whole_past_window().iter().any(|table| table == "email") { return mac.and_then(|mac| from_mac(&mac)); } let (held, oldest) = client .with_file(|file| { let row = file .driver .get(&format!("SELECT COUNT(*) AS n, MIN(sent_at) AS oldest FROM cotton_emails WHERE {}", mail_predicate::live("")), &[]) .map_err(|error| error.to_string())?; Ok(row.map(|row| (row.int("n").unwrap_or(0).max(0) as u64, row.text("oldest").map(str::to_string))).unwrap_or((0, None))) }) .ok()?; let progress = client.sync_progress().map(|progress| progress.state()); let coming = progress.as_ref().and_then(|state| state.tables.get("email")).map(|pass| (pass.rows - pass.done).max(0) as u64).unwrap_or(0); let offline = client.sync_status()["sync"]["state"].as_str() == Some("offline"); let line = shaped(held, oldest.as_deref(), coming, offline); match mac { Some(mac) => joined(line, held, oldest.as_deref(), offline, &mac), None => line, } } /// The Mac's `mail_history` row on this phone's copy, when the copy has the table and the Mac has written it. fn mac_walk(client: &ClientController) -> Option { let now = crate::phone::cotton_chat::now_ms(client); client .with_file(|file| { let has = file.driver.get("SELECT COUNT(*) AS n FROM sqlite_master WHERE type = 'table' AND name = 'cotton_mail_history'", &[]).map_err(|e| e.to_string())?; if has.and_then(|row| row.int("n")).unwrap_or(0) == 0 { return Ok(None); } let row = file .driver .get("SELECT state, reached_at, done, total, at FROM cotton_mail_history ORDER BY at DESC LIMIT 1", &[]) .map_err(|e| e.to_string())?; Ok(row.map(|row| { let at = row.text("at").and_then(|at| chrono::DateTime::parse_from_rfc3339(at).ok()); MacWalk { state: row.text("state").unwrap_or_default().to_string(), reached: row.text("reached_at").map(|d| d.chars().take(10).collect()), done: row.int("done").unwrap_or(0).max(0) as u64, total: row.int("total").unwrap_or(0).max(0) as u64, quiet: at.is_some_and(|at| now - at.timestamp_millis() > MAC_QUIET_MINUTES * 60_000), } })) }) .ok() .flatten() } /// Why the Mac's walk stands, if it does. fn mac_paused(mac: &MacWalk) -> Option { match mac.state.as_str() { "held" => Some(Paused::Mac("full".into())), "walking" if mac.quiet => Some(Paused::MacOffline), _ => None, } } /// The line from the Mac's walk alone (the phone keeps its window): how far back it reached, `done` of the mailbox. fn from_mac(mac: &MacWalk) -> Option { if mac.state == "done" || mac.state.is_empty() { return None; } let back_to = mac.reached.as_deref().filter(|d| d.len() >= 7).map(|d| d[..7].to_string()); Some(History { back_to, held: mac.done, total: mac.total.max(mac.done), paused: mac_paused(mac) }) } /// The phone's line with the Mac's walk joined: the mailbox's count for the total, the Mac's stops for `paused` /// (the phone's own offline first), and a line while the Mac still walks though the phone's pass is through. fn joined(line: Option, held: u64, oldest: Option<&str>, offline: bool, mac: &MacWalk) -> Option { let walking = mac.state == "walking" || mac.state == "held"; let mut line = match line { Some(line) => line, None if walking => History { back_to: oldest.filter(|at| at.len() >= 7).map(|at| at[..7].to_string()), held, total: held, paused: None }, None => return None, }; if walking { line.total = line.total.max(mac.total); } if line.paused.is_none() { line.paused = if offline { Some(Paused::Offline) } else { mac_paused(mac) }; } Some(line) } /// The rule, apart from where its facts are read. /// No mail still to come is no line, offline or not: a pass that never named `email` carries none of it. fn shaped(held: u64, oldest: Option<&str>, coming: u64, offline: bool) -> Option { if coming == 0 { return None; } let back_to = oldest.filter(|at| at.len() >= 7).map(|at| at[..7].to_string()); Some(History { back_to, held, total: held + coming, paused: offline.then_some(Paused::Offline) }) } #[cfg(test)] mod tests { use super::*; /// RULE (MAIL ALL ON PHONE, 24 Nov 2026): the line stands while mail still comes, says how far back and how /// many of how many, says when the phone is offline, and goes once every mail is here. #[test] fn the_history_line_stands_while_mail_comes_and_goes_once_it_is_all_in() { let coming = shaped(41_200, Some("2019-03-04T10:00:00Z"), 70_222, false).expect("a line"); assert_eq!(coming, History { back_to: Some("2019-03".into()), held: 41_200, total: 111_422, paused: None }); let offline = shaped(41_200, Some("2019-03-04T10:00:00Z"), 70_222, true).expect("a line"); assert_eq!(offline.paused, Some(Paused::Offline)); assert_eq!(serde_json::to_value(&offline).unwrap(), serde_json::json!({"backTo": "2019-03", "held": 41_200, "total": 111_422, "paused": "offline"})); assert_eq!(shaped(111_422, Some("2007-01-02T00:00:00Z"), 0, false), None, "all in: no line"); assert_eq!(shaped(111_422, Some("2007-01-02T00:00:00Z"), 0, true), None, "all in and offline: still no line"); assert_eq!(shaped(0, None, 5_000, false).map(|h| h.back_to), Some(None), "none here yet: no month"); } /// RULE (24 Nov 2026; MAIL.md "All of it"): while the Mac walks his mailbox the line stands, /// with the switch off too (the Mac's walk: back to the day it reached, `done` of the mailbox's count), its total /// is the mailbox's own count, and it says when the Mac stands: quiet half an hour, or stopped at size. #[test] fn the_macs_walk_through_the_mailbox_joins_the_line() { let walking = MacWalk { state: "walking".into(), reached: Some("2015-03-04".into()), done: 41_200, total: 98_000, quiet: false }; assert_eq!(from_mac(&walking), Some(History { back_to: Some("2015-03".into()), held: 41_200, total: 98_000, paused: None })); let quiet = MacWalk { quiet: true, ..walking.clone() }; assert_eq!(from_mac(&quiet).unwrap().paused, Some(Paused::MacOffline)); let full = MacWalk { state: "held".into(), ..walking.clone() }; assert_eq!(serde_json::to_value(from_mac(&full).unwrap()).unwrap()["paused"], serde_json::json!({ "mac": "full" })); assert_eq!(from_mac(&MacWalk { state: "done".into(), ..walking.clone() }), None, "all walked: no line"); // The switch on: the phone's facts, the mailbox's count for the total, a line while the Mac walks. let phone = shaped(41_200, Some("2019-03-04T10:00:00Z"), 10_000, false); assert_eq!(joined(phone, 41_200, Some("2019-03-04T10:00:00Z"), false, &walking).unwrap().total, 98_000); let through = joined(None, 51_200, Some("2016-01-01T00:00:00Z"), false, &quiet).expect("the Mac still walks"); assert_eq!((through.held, through.total, through.paused), (51_200, 98_000, Some(Paused::MacOffline))); assert_eq!(joined(None, 51_200, None, true, &walking).unwrap().paused, Some(Paused::Offline), "the phone's own state first"); assert_eq!(joined(None, 98_000, None, false, &MacWalk { state: "done".into(), ..walking }), None); } }