//! `shell.stream` over a synthetic Messages phone: one stream across every //! source, unread first then newest, the quiet count, each chat's mark, what //! the top button holds and which chats take a reply. EVERY ROW IS SYNTHETIC. use super::*; use crate::handle::CottonHandle; use rusqlite::types::Value as SqlValue; /// A fresh Cotton Messages phone, local first, as its flavour ships it. fn phone() -> (tempfile::TempDir, CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); let manifest: Value = serde_json::from_slice(&std::fs::read(cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours/messages/flavour.json")).expect("Messages' manifest, apps/cotton/App/Flavours/messages/flavour.json")).expect("a manifest"); let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(manifest), }) .expect("an open core"); crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started"); (dir, handle) } fn seed(handle: &CottonHandle, sql: &str, params: &[SqlValue]) { handle.client().with_writer(|file| { file.driver.run(sql, params).map_err(|error| error.to_string())?; crate::fixture::receipted(file.driver, sql); Ok(()) }).unwrap(); } fn workspace(handle: &CottonHandle) -> String { handle.client().with_writer(|file| Ok(file.workspace_id.to_string())).unwrap() } /// A chat whose last message, of `channel`, came in at `at`; `live` and past /// the read cursor when `unread`, an imported archive's row otherwise. fn chat(handle: &CottonHandle, id: &str, title: &str, channel: &str, at: &str, unread: bool) { let ws = workspace(handle); let key = if channel == "cotton" { SqlValue::Text(format!("cotton:+9100000{}", id.len())) } else { SqlValue::Null }; seed(handle, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, external_key, last_message_at, created_at, updated_at) VALUES (?, ?, 'group', ?, ?, ?, ?, ?)", &[SqlValue::Text(id.into()), SqlValue::Text(ws.clone()), SqlValue::Text(title.into()), key, SqlValue::Text(at.into()), SqlValue::Text(at.into()), SqlValue::Text(at.into())]); seed(handle, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, seq) VALUES (?, ?, ?, 'in', ?, ?, 'An invented line', ?, ?, ?)", &[SqlValue::Text(format!("m-{id}")), SqlValue::Text(id.into()), SqlValue::Text(ws), SqlValue::Text(channel.into()), SqlValue::Text(if unread { "live" } else { "imported" }.into()), SqlValue::Text(at.into()), SqlValue::Text(at.into()), if unread { SqlValue::Integer(5) } else { SqlValue::Null }]); } fn stream(handle: &CottonHandle, request: Value) -> Value { let mut request = request; request["table"] = json!("thread"); crate::methods::dispatch(handle, METHOD, &request).expect("the stream reads") } fn ids(answer: &Value) -> Vec { answer["chats"].as_array().unwrap().iter().map(|chat| chat["id"].as_str().unwrap().to_string()).collect() } fn seeded() -> (tempfile::TempDir, CottonHandle) { let (dir, handle) = phone(); chat(&handle, "wa-old", "Invented WhatsApp group", "whatsapp", "2026-11-01T09:00:00.000Z", false); chat(&handle, "cotton-unread", "Invented Cotton chat", "cotton", "2026-10-01T09:00:00.000Z", true); chat(&handle, "sms-new", "Invented SMS", "sms", "2026-11-14T09:00:00.000Z", false); chat(&handle, "ig-unread", "Invented Instagram", "instagram", "2026-11-13T09:00:00.000Z", true); (dir, handle) } // RULE (owner, 14 Nov 2026): one stream across every source, unread first, then newest; it opens on the newest unread. #[test] fn the_stream_is_unread_first_then_newest_and_opens_on_the_newest_unread() { let (_dir, handle) = seeded(); let answer = stream(&handle, json!({})); assert_eq!(ids(&answer), ["ig-unread", "cotton-unread", "sms-new", "wa-old"], "{answer}"); assert_eq!(answer["opens"], "ig-unread"); assert_eq!(answer["chats"][0]["name"], "Invented Instagram"); assert!(crate::methods::read_only(METHOD)); } // RULE: a quiet count says how many are unread, and nothing when none is. #[test] fn the_count_says_how_many_are_unread_and_nothing_when_none() { let (_dir, handle) = seeded(); let answer = stream(&handle, json!({})); assert_eq!(answer["unread"], 2); assert_eq!(answer["unread_line"], "2 unread"); let (_dir, quiet) = phone(); chat(&quiet, "wa", "Invented group", "whatsapp", "2026-11-01T09:00:00.000Z", false); let answer = stream(&quiet, json!({})); assert_eq!(answer["unread"], 0); assert_eq!(answer["unread_line"], Value::Null); } // RULE: each chat carries a mark for where it is from. #[test] fn each_chat_carries_the_mark_of_its_source() { let (_dir, handle) = seeded(); let answer = stream(&handle, json!({})); let marks: Vec<(String, String)> = answer["chats"].as_array().unwrap().iter() .map(|chat| (chat["mark"]["id"].as_str().unwrap_or_default().to_string(), chat["mark"]["label"].as_str().unwrap_or_default().to_string())).collect(); assert_eq!(marks, [("instagram".into(), "Instagram".into()), ("cotton".into(), "Cotton".into()), ("textmessage".into(), "Text message".into()), ("whatsapp".into(), "WhatsApp".into())], "{answer}"); } // RULE: an archive takes no reply; the core says which chats do. #[test] fn an_imported_archive_takes_no_reply() { let (_dir, handle) = seeded(); let answer = stream(&handle, json!({})); for chat in answer["chats"].as_array().unwrap() { if chat["id"] != "cotton-unread" { assert_eq!(chat["replies"], false, "an archive: {chat}"); } } } // RULE: a chat read while a person stands in the stream keeps its place; a new one goes in front. #[test] fn a_standing_stream_keeps_its_order_and_search_stands_on_none() { let (_dir, handle) = seeded(); let standing = json!(["wa-old", "ig-unread", "cotton-unread"]); let answer = stream(&handle, json!({"standing": standing})); assert_eq!(ids(&answer), ["sms-new", "wa-old", "ig-unread", "cotton-unread"], "{answer}"); // Letters written narrow the same stream, in its own order. let inked = stream(&handle, json!({"ink": "inst", "standing": standing})); assert_eq!(ids(&inked), ["ig-unread"], "{inked}"); // And typed words do. let typed = stream(&handle, json!({"query": "WhatsApp"})); assert_eq!(ids(&typed), ["wa-old"], "{typed}"); // The leading letters of a word of its name, as a person types them. let begun = stream(&handle, json!({"query": "what"})); assert_eq!(ids(&begun), ["wa-old"], "{begun}"); let none = stream(&handle, json!({"ink": "zzz"})); assert!(ids(&none).is_empty()); assert_eq!(none["empty"], "No chat by that name."); } // RULE: one top button holds what the fan held: New chat here (a phone that backs up deals Account before it). #[test] fn the_top_button_holds_new_chat() { let (_dir, handle) = seeded(); let answer = stream(&handle, json!({})); let top = answer["top"].as_array().unwrap(); let new = top.iter().find(|item| item["id"] == "new").unwrap_or_else(|| panic!("no New chat: {answer}")); assert_eq!(new["label"], "New chat"); assert_eq!(new["route"], "/messages/new"); } // RULE: the flavour says the app is one stream; the fan answers its table and every other app says nothing. #[test] fn the_fan_says_the_stream_for_messages_alone() { let (_dir, handle) = seeded(); let fan = crate::methods::dispatch(&handle, "shell.fan", &json!({"timezone": "Asia/Kolkata"})).expect("the fan"); assert_eq!(fan["stream"], json!({"tool": "messages", "table": "thread"}), "{fan}"); }