Cotton code
205 lines · 8.5 KB · RustRaw
//! Asked of you — the ONE list of things only the owner can answer. Home draws//! it above "Done for you"; the two replace the old "To decide" band.//!//! The rule it follows is the design's (Cotton note d0e27772, "what Cotton asks//! the owner, and what it does without asking"): Cotton asks only when ONLY the//! owner knows the answer AND a wrong guess cannot be put right cheaply//! afterwards. These sources pass that test: a person asking to join a//! database the owner admits people to (only an owner or admin may let them//! in, and an admission hands over a full copy that cannot be taken back), a//! calendar invite still ahead with no answer//! — another person is waiting —, a document locked by a password only the//! owner has, and the AI-access state. Nothing else.//!//! The history is why the list is this short. On 27 Sep 2026 the owner was told//! 1,108 things were waiting on him — 1,042 photo-duplicate pairs, 50//! memory entries, 11 thoughts routing was unsure of and 12//! documents that failed to read — against 20 questions an assistant had//! actually asked. His word: something is off if that many are waiting. What//! Cotton does by itself is shown in `done_for_you` with an undo, never here.//! "Normally under five, never above nine": a count past that means the policy//! that fills the list is wrong, and it is fixed at its source.//!//! One selector, so Home and a test read the same//! answer. Pure: every count is a function of lists the caller already holds,//! and `now` comes through the seam — never a clock here, or the memo it feeds//! is new every frame and the tests are a time bomb.//!//! A row with a zero count does not render, and an empty result means the whole//! list is hidden. "AI access needed to file" is a STATE, not a count — it//! answers 1 or 0.use super::shell_lines::{number, resolve, LineRow};use cotton_store::protocol::js::parse_date_ms;/// The rows, in the order Home draws them.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum AskedKey {    JoinRequests,    Invites,    Passwords,    AiAccess,}impl AskedKey {    pub const fn as_str(self) -> &'static str {        match self {            AskedKey::JoinRequests => "joinRequests",            AskedKey::Invites => "invites",            AskedKey::Passwords => "passwords",            AskedKey::AiAccess => "aiAccess",        }    }}/// `ASKED_KEYS`, in the list's fixed order. A person asking to join is first:/// they are standing at their own Join screen waiting for the answer now.pub const ASKED_KEYS: [AskedKey; 4] = [    AskedKey::JoinRequests,    AskedKey::Invites,    AskedKey::Passwords,    AskedKey::AiAccess,];/// One occurrence the owner may still have to answer.#[derive(Debug, Clone, PartialEq, Eq)]pub struct DecidableEvent {    pub starts_at: String,    pub my_response: Option<String>,    /// The owner organizes it — an event they made themselves, or one with no    /// organizer at all, which both sync paths read as the owner's own.    pub organizer_is_self: bool,}/// An invite: someone else organizes it and the owner has not answered —/// the sync says `needs_action`. The owner's own events never ask anything,/// and an event with no reply on it at all (a subscribed calendar, one the/// owner made) is not a question either.pub fn is_invite(event: &DecidableEvent) -> bool {    !event.organizer_is_self && event.my_response.as_deref() == Some(INVITE_RESPONSE)}/// The reply an unanswered invite carries (Google's `needsAction`, iCal's/// `NEEDS-ACTION`, as both sync paths write it).pub const INVITE_RESPONSE: &str = "needs_action";/// [`is_invite`] as SQL over `cotton_events`, for the reads that list the/// invites themselves, so the figure and the list it opens are one set.pub const INVITE_SQL: &str = "my_response = 'needs_action' AND organizer_is_self = 0";#[derive(Debug, Clone, Default)]pub struct AskedInput<'a> {    /// Occurrences ahead of and behind `now`; the filter is below.    pub events: &'a [DecidableEvent],    /// The AI gate refused routing THIS session (client state). Not a row in    /// anybody's file, and deliberately not persisted.    /// Documents that stopped at a password the owner has not given    /// (`status = 'locked'`). The one document state that is a question: only    /// he knows the password. A document that failed to READ is not — it is a    /// state on its own page, and a row in Done for you.    pub locked_documents: usize,    pub ai_access_needed: bool,    /// People asking to join a database this person admits people to, with an    /// invite they were sent. The waiting requests live in each serving Mac's    /// registry, never in a database file, so `read.home` passes 0 and the app    /// counts them from the Macs (`pairing.pending`), as it raises `aiAccess`.    pub join_requests: usize,    pub now: &'a str,}#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct AskedRow {    pub key: AskedKey,    pub count: usize,}/// Parsed, never lexical — an offset-bearing instant sorts wrong as a string./// An unparseable one is negative infinity, which is behind every `now`.fn instant(value: &str) -> Option<i64> {    parse_date_ms(value)}/// What waits, in list order, zero-count rows omitted.pub fn asked_rows(input: &AskedInput<'_>) -> Vec<AskedRow> {    let at = instant(input.now);    let count_of = |key: AskedKey| -> usize {        match key {            // Only what is still AHEAD: an invitation to a meeting that has            // happened is not a decision anyone can make.            AskedKey::Invites => input                .events                .iter()                .filter(|event| {                    is_invite(event)                        && match (instant(&event.starts_at), at) {                            (Some(starts), Some(now)) => starts >= now,                            // `NEGATIVE_INFINITY >= anything-real` is false, and                            // `anything >= NEGATIVE_INFINITY` is true — the                            // TypeScript's arithmetic, spelled out.                            (None, Some(_)) => false,                            (_, None) => true,                        }                })                .count(),            AskedKey::Passwords => input.locked_documents,            AskedKey::AiAccess => usize::from(input.ai_access_needed),            AskedKey::JoinRequests => input.join_requests,        }    };    ASKED_KEYS        .into_iter()        .map(|key| AskedRow {            key,            count: count_of(key),        })        .filter(|row| row.count > 0)        .collect()}/// The list's own figure — what shows beside "Asked of you".pub fn asked_total(rows: &[AskedRow]) -> usize {    rows.iter().map(|row| row.count).sum()}// ── The words and the surface, said once ──────────────────────────────────//// Its header explains that Home needs the counting rules, finished sentence// and path. These functions give every consumer one implementation of the// latter two.///// Where each row's decision is made.////// An invite is answered on the calendar, AI access is/// granted in Settings. A locked document is unlocked on the documents list,/// filtered to the locked ones — the only path here that carries a query./// A join request is answered on its member page, which each of its cards/// opens in its own database; the row's own path is the Members list.pub const fn asked_path(key: AskedKey) -> &'static str {    match key {        AskedKey::JoinRequests => "/members",        // The calendar narrowed to the invites, each opening its page with        // its reply to give — never the plain calendar.        AskedKey::Invites => "/calendar?show=invites",        AskedKey::Passwords => "/documents?status=locked",        AskedKey::AiAccess => "/passwords",    }}/// The row's sentence, in the database's words (set `home`, `asked.<key>`):/// a figure that says what it counts, never a bare number, its form picked/// by the count (`rules::shell_lines`, CLDR) and grouped by `icu_decimal`.////// `AiAccess` takes no figure at all: it is a STATE, not a count, and "1 AI/// access needed to file" would read as a queue of one — its line has no/// `{n}` and no plural forms.pub fn asked_label(asked: AskedKey, count: usize, rows: &[LineRow]) -> String {    let n = number(count as i64);    resolve("home", &format!("asked.{}", asked.as_str()), rows, &[("n", &n)]).unwrap_or_default()}#[cfg(test)]#[path = "asked_of_you_tests.rs"]mod tests;