//! `shell.stream`: an app whose face is ONE STREAM of its conversations//! (Cotton Messages on iPhone, 14 Nov 2026), answered whole. The flavour//! says so (`fan.stream`, `shell.fan`'s `stream`); the shell draws no fan//! and pages the chats this names, loading only the one in front and its//! neighbours.//!//! Takes `{table, query?, ink?, standing?, timezone?}`://! - `table`: the conversation table (`thread`).//! - `query`: typed search words: the chats whose name has a word starting//! with them first, then those the table's own search finds.//! - `ink`: letters written on the screen; the deck's match narrows it.//! - `standing`: the ids the shell holds, in the order it holds them. A chat//! read a moment ago keeps its place while a person stands in the stream//! (`stream::standing_order`); absent at a launch and under a search.//!//! Answers `{table, chats, opens, unread, unread_line, top, search, empty}`://! - `chats`: every chat in the stream's order, each `{id, name, unread,//! mark: {id, label}?, replies}`. `mark` is where it is from; `replies`//! whether a message may be written into it from here (an archive's is false).//! - `opens`: the chat it opens on (its first: the newest unread, else the newest).//! - `unread` and `unread_line`: how many are unread, in words; the line is//! null when none is.//! - `top`: what the one top button holds, each `{id, label, route?}`://! `account` (where the app deals the Account card) and `new`, each with the `object` its line wears.//! - `search`: the search button's word. `empty`: the line when no chat stands.usecrate::methods::MethodError;usecrate::shell::client::ClientController;use cotton_core::messages::stream::{self, StreamChat};use cotton_core::rules::ink_match;use cotton_core::rules::shell_lines::resolve;use serde_json::{json, Map, Value};const METHOD: &str = "shell.stream";const SET: &str = "chat";typeNative<'a> = &'a dynFn(&Value) -> Result<Value, MethodError>;fn say(line: &str, fills: &[(&str, &str)]) -> String { resolve(SET, &format!("stream.{line}"), &[], fills).unwrap_or_default()}fn bad(message: &str) -> MethodError {MethodError::new("bad_request", message)}pubfn call(handle: &crate::handle::CottonHandle, request: &Value) -> Result<Value, MethodError> {let table = request["table"].as_str().filter(|table| !table.is_empty()).ok_or_else(|| bad("shell.stream takes a table"))?;let plus = crate::methods::shell_deck::plus(handle, &json!({"table": table}))?; read_with(&handle.client(), request, &plus, &|args| {crate::methods::dispatch(handle, "records.list", &crate::phone::records::in_named_database(args.clone())) })}/// Every row `args` reads, page after page.fn every_row(args: &Map<String, Value>, native: Native) -> Result<Vec<Value>, MethodError> {letmut asked = Value::Object(args.clone()); asked["limit"] = json!(cotton_tools::mcp::handlers::tables::MAX_PAGE_SIZE);letmut page = 0u64;letmut rows = Vec::new();loop { asked["page"] = json!(page);let answer = native(&asked)?; rows.extend(answer["records"].as_array().cloned().unwrap_or_default());match answer["next_page"].as_u64() {Some(next) if next > page => page = next,Some(_) => returnErr(MethodError::new("unreadable", format!("{METHOD}: a page did not advance"))),None => returnOk(rows), } }}/// A source's id as a mark names it: its word, lowercased, letters and digits alone.fn mark_id(word: &str) -> String { word.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect()}pub(super) fn read_with(client: &ClientController, request: &Value, plus: &Value, native: Native) -> Result<Value, MethodError> {let table = request["table"].as_str().filter(|table| !table.is_empty()).ok_or_else(|| bad("shell.stream takes a table"))?;let query = request["query"].as_str().map(str::trim).filter(|query| !query.is_empty());let ink = request["ink"].as_str().map(str::trim).filter(|ink| !ink.is_empty());let standing: Vec<String> = match request.get("standing") {None | Some(Value::Null) => Vec::new(),Some(Value::Array(ids)) if ids.iter().all(Value::is_string) => ids.iter().filter_map(Value::as_str).map(str::to_string).collect(),Some(_) => returnErr(bad("standing is the chat ids the shell holds, in its order")), };// The stored and computed columns alone (`light`): no slip, no card, no// history read for a chat that is not in front.letmut args = Map::new(); args.insert("table".into(), json!(table)); args.insert("light".into(), json!(true));ifletSome(zone) = request.get("timezone").filter(|zone| !zone.is_null()) { args.insert("timezone".into(), zone.clone()); }letmut rows = every_row(&args, native)?;let stops = ink_match::stop_words();// Typed words: the chats whose name has a word starting with them, as// letters written narrow, then the chats the table's own search finds// (a member, a line said in it).letmut named: std::collections::HashSet<String> = std::collections::HashSet::new();ifletSome(query) = query {letmut found: std::collections::HashSet<String> = std::collections::HashSet::new();letmut searched = args.clone(); searched.insert("query".into(), json!(query));for row in every_row(&searched, native)? {ifletSome(id) = row["id"].as_str() { found.insert(id.to_string()); } }for row in &rows {letSome(id) = row["id"].as_str() else { continue };if ink_match::holds(row["data"]["name"].as_str(), query, &stops) { named.insert(id.to_string()); } } rows.retain(|row| row["id"].as_str().is_some_and(|id| named.contains(id) || found.contains(id))); }ifletSome(ink) = ink { rows.retain(|row| ink_match::holds(row["data"]["name"].as_str(), ink, &stops)); }letmut said: std::collections::HashMap<String, Value> = std::collections::HashMap::new();letmut read: Vec<StreamChat> = Vec::new();for row in &rows {letSome(id) = row["id"].as_str() else { continue };let data = &row["data"];// Where it is from: the sources its messages name, a Cotton chat's// own address where it holds no message yet.letmut sources: Vec<String> = data["channels"].as_str().unwrap_or_default() .split(" \u{00B7} ").map(str::trim).filter(|word| !word.is_empty()).map(str::to_string).collect();if sources.is_empty() && data["external_key"].as_str().is_some_and(|key| key.starts_with("cotton:")) { sources.push("Cotton".to_string()); }let chat = StreamChat { id: id.to_string(), unread: data["unread"] == "unread", at: data["last_message_at"].as_str().filter(|at| !at.is_empty()).map(str::to_string), channels: sources, };let mark = stream::mark(&chat).map(|word| json!({"id": mark_id(word), "label": word})); said.insert(id.to_string(), json!({"id": id,"name": data["name"],"unread": chat.unread,"mark": mark,// May a message be written into it from here: the chat's own gate// (an archive's is shut, a filed copy's, a blocked request's)."replies": data["sendable"] == true, })); read.push(chat); }let fresh = stream::ordered(read);let unread = stream::unread_count(&fresh);// A search stands on nothing: its answer is the stream's own order.let ordered = if query.is_some() || ink.is_some() {// The chats named by the typed words before those only found inside.let (by_name, inside): (Vec<StreamChat>, Vec<StreamChat>) = fresh.into_iter().partition(|chat| query.is_none() || named.contains(&chat.id)); by_name.into_iter().chain(inside).collect() } else { stream::standing_order(fresh, &standing) };let opens = stream::opens(&ordered).map(str::to_string);let chats: Vec<Value> = ordered.iter().filter_map(|chat| said.remove(&chat.id)).collect();letmut top: Vec<Value> = Vec::new();ifsuper::shell_account::home(client).is_some() { top.push(json!({"id": cotton_core::kit::ACCOUNT_CARD, "label": super::shell_account::name(), "object": "person"})); }ifletSome(route) = plus["route"].as_str() { top.push(json!({"id": "new", "label": say("new", &[]), "object": "message", "route": route})); }Ok(json!({"table": table,"chats": chats,"opens": opens,"unread": unread,"unread_line": (unread > 0).then(|| say("unread", &[("n", &unread.to_string())])),"top": top,"search": say("search", &[]),"empty": if query.is_some() || ink.is_some() { say("none_found", &[]) } else { say("empty", &[]) }, }))}#[cfg(test)]#[path = "shell_stream_tests.rs"]mod tests;