Skip to main content

ljos_cli/
mail.rs

1//! Mail from one seat to another.
2//!
3//! A message is a pack atom. Seats on one box share the pack and see it at
4//! once. `ljos sync` exports the machine's own atoms, so the same atom
5//! crosses machines in the sealed log. A receipt is its own atom: the pack
6//! and the log are append-only, and an import tells two atoms apart by the
7//! hash of their text, so the text of a message carries its id.
8
9use std::collections::BTreeSet;
10use std::path::PathBuf;
11use std::sync::atomic::{AtomicU64, Ordering};
12
13use anyhow::{bail, Context, Result};
14use serde_json::{json, Value};
15
16/// How many messages a prompt is shown. The rest stay unread.
17const PROMPT_CAP: usize = 8;
18
19/// The first packset that keeps kinds `message`, `receipt` and `group`.
20///
21/// 0.12.1 refuses them. A new kind has been a minor release: `outcome`
22/// arrived in 0.12.0, and `prediction` and `rule` in 0.6.0.
23pub(crate) const MAIL_PACKSET: &str = "0.13.0";
24
25/// What a probe post of an empty `message` means.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27enum Probe {
28    /// The writer refused the kind.
29    Refused,
30    /// The kind passed and a later check refused the empty probe.
31    Kept,
32    /// The writer did not answer.
33    Store,
34}
35
36/// Classify a probe error. Kind is checked before the level, so a pack
37/// that cannot keep mail refuses `message`, and one that can refuses the
38/// unknown level. An empty text is a tool dump on either pack, refused
39/// before the kind, and that 400 does not say which pack answered.
40fn probe_of(text: &str) -> Probe {
41    if text.contains("unknown atom kind") {
42        Probe::Refused
43    } else if text.contains(": 400:") {
44        Probe::Kept
45    } else {
46        Probe::Store
47    }
48}
49
50fn unsupported_mail(version: Option<&str>) -> String {
51    match version {
52        Some(version) => format!(
53            "this pack does not keep mail. packset {version} refused kind message. Mail needs packset {MAIL_PACKSET}."
54        ),
55        None => format!(
56            "this pack does not keep mail. The writer refused kind message. Mail needs packset {MAIL_PACKSET}."
57        ),
58    }
59}
60
61/// One message as it is written.
62#[derive(Debug, Clone)]
63pub struct Outgoing {
64    pub id: String,
65    pub from: String,
66    pub to: Vec<String>,
67    pub body: String,
68    pub interrupt: bool,
69    pub issue: Option<String>,
70    pub group: Option<String>,
71    pub reply: Option<String>,
72    pub scope: Option<String>,
73}
74
75/// What `ljos send` was asked to write.
76pub struct Send<'a> {
77    pub seat: Option<&'a str>,
78    pub group: Option<&'a str>,
79    pub text: &'a str,
80    pub interrupt: bool,
81    pub issue: Option<&'a str>,
82    /// Write to a seat this pack has not heard from yet.
83    pub new_seat: bool,
84}
85
86/// One message as a reader sees it.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Letter {
89    pub id: String,
90    pub from: String,
91    pub to: Vec<String>,
92    pub body: String,
93    pub interrupt: bool,
94    pub issue: Option<String>,
95    pub group: Option<String>,
96    pub reply: Option<String>,
97    pub scope: Option<String>,
98    pub read: bool,
99    ts: String,
100    seq: usize,
101}
102
103/// A read receipt addressed to the seat that sent the message.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct Receipt {
106    pub msg: String,
107    pub by: String,
108    pub at: String,
109    pub key: String,
110}
111
112fn mint_id(kind: &str, parts: &[&str]) -> String {
113    static N: AtomicU64 = AtomicU64::new(1);
114    let n = N.fetch_add(1, Ordering::Relaxed);
115    let nanos = std::time::SystemTime::now()
116        .duration_since(std::time::UNIX_EPOCH)
117        .map(|d| d.as_nanos())
118        .unwrap_or(0);
119    let raw = format!(
120        "{kind}\n{n}\n{nanos}\n{}\n{}",
121        std::process::id(),
122        parts.join("\n")
123    );
124    super::work_id(&raw)
125}
126
127fn check_name(kind: &str, name: &str) -> Result<String> {
128    let name = name.trim();
129    if name.is_empty()
130        || name
131            .chars()
132            .any(|c| c.is_whitespace() || c == ',' || c == ':')
133    {
134        bail!("{kind}: {name:?} is not a name");
135    }
136    Ok(name.to_string())
137}
138
139fn tag(atom: &Value, prefix: &str) -> Option<String> {
140    atom["entities"]
141        .as_array()?
142        .iter()
143        .filter_map(Value::as_str)
144        .find_map(|e| e.strip_prefix(prefix).map(str::to_string))
145}
146
147fn tags(atom: &Value, prefix: &str) -> Vec<String> {
148    atom["entities"]
149        .as_array()
150        .into_iter()
151        .flatten()
152        .filter_map(Value::as_str)
153        .filter_map(|e| e.strip_prefix(prefix).map(str::to_string))
154        .collect()
155}
156
157fn has(atom: &Value, entity: &str) -> bool {
158    atom["entities"]
159        .as_array()
160        .into_iter()
161        .flatten()
162        .any(|e| e.as_str() == Some(entity))
163}
164
165/// The body a person wrote. The lines above the blank line are the id and
166/// the envelope, which keep two messages with the same words distinct.
167#[must_use]
168pub fn body_of(text: &str) -> String {
169    text.split_once("\n\n")
170        .map(|(_, body)| body.trim().to_string())
171        .unwrap_or_else(|| text.trim().to_string())
172}
173
174/// The pack refuses an atom whose text is longer than this, in characters.
175pub const ATOM_TEXT_CAP: usize = 500;
176
177/// The longest body a message carries. Past it, a file and a deed
178/// (`deedar create file`, then the accession in the message) say it better.
179pub const MAIL_BODY_CAP: usize = 16_000;
180
181/// A body past [`MAIL_BODY_CAP`] is refused before anything is written,
182/// with the way to send it as a deed.
183fn check_length(verb: &str, body: &str) -> Result<()> {
184    let n = body.chars().count();
185    if n > MAIL_BODY_CAP {
186        bail!(
187            "{verb}: the message is {n} characters, past {MAIL_BODY_CAP}; write it to a file, \
188             `deedar create file --path FILE --agent SEAT`, and send the accession it prints. Nothing was sent"
189        );
190    }
191    Ok(())
192}
193
194/// The text that travels. The id is in it, so an import that keys on the
195/// text keeps two copies of the same words. A body that would push the
196/// text past [`ATOM_TEXT_CAP`] is cut there with an ellipsis; the whole
197/// body rides in the atom's `body` field, which [`message_atom`] sets.
198#[must_use]
199pub fn message_text(m: &Outgoing) -> String {
200    let mut head = format!("msg {}\nfrom {}\nto {}", m.id, m.from, m.to.join(", "));
201    if m.interrupt {
202        head.push_str("\ninterrupt");
203    }
204    if let Some(issue) = &m.issue {
205        head.push_str(&format!("\nissue {issue}"));
206    }
207    if let Some(group) = &m.group {
208        head.push_str(&format!("\ngroup {group}"));
209    }
210    if let Some(reply) = &m.reply {
211        head.push_str(&format!("\nreply {reply}"));
212    }
213    let body = m.body.trim();
214    let room = ATOM_TEXT_CAP.saturating_sub(head.chars().count() + 2);
215    if body.chars().count() <= room {
216        return format!("{head}\n\n{body}");
217    }
218    let cut: String = body.chars().take(room.saturating_sub(1)).collect();
219    format!("{head}\n\n{cut}\u{2026}")
220}
221
222/// The atom a message posts. The entities are what an inbox filters on.
223#[must_use]
224pub fn message_atom(m: &Outgoing, workspace: &str) -> Value {
225    let mut entities = vec![
226        format!("seat:{}", m.from),
227        format!("from:{}", m.from),
228        format!("msg:{}", m.id),
229    ];
230    for to in &m.to {
231        entities.push(format!("to:{to}"));
232    }
233    if m.interrupt {
234        entities.push("priority:interrupt".to_string());
235    }
236    if let Some(issue) = &m.issue {
237        entities.push(format!("issue:{issue}"));
238    }
239    if let Some(group) = &m.group {
240        entities.push(format!("group:{group}"));
241    }
242    if let Some(reply) = &m.reply {
243        entities.push(format!("reply:{reply}"));
244    }
245    if let Some(scope) = &m.scope {
246        entities.push(format!("scope:{scope}"));
247    }
248    let text = message_text(m);
249    let mut atom = json!({
250        "schema": "inside.atom/v1",
251        "kind": "message",
252        "level": "explicit",
253        "text": text,
254        "workspace": workspace,
255        "entities": entities,
256    });
257    if body_of(&text) != m.body.trim() {
258        atom["body"] = Value::String(m.body.trim().to_string());
259    }
260    atom
261}
262
263fn letter_of(atom: &Value, seq: usize) -> Option<Letter> {
264    if atom["kind"].as_str() != Some("message") {
265        return None;
266    }
267    let id = tag(atom, "msg:")?;
268    let from = tag(atom, "from:").or_else(|| tag(atom, "seat:"))?;
269    let to = tags(atom, "to:");
270    if to.is_empty() {
271        return None;
272    }
273    Some(Letter {
274        id,
275        from,
276        to,
277        // A long body rides whole in `body`; the text holds its start.
278        body: atom["body"]
279            .as_str()
280            .map(|b| b.trim().to_string())
281            .unwrap_or_else(|| body_of(atom["text"].as_str().unwrap_or(""))),
282        interrupt: has(atom, "priority:interrupt"),
283        issue: tag(atom, "issue:"),
284        group: tag(atom, "group:"),
285        reply: tag(atom, "reply:"),
286        scope: tag(atom, "scope:"),
287        read: false,
288        ts: atom["ts"].as_str().unwrap_or("").to_string(),
289        seq,
290    })
291}
292
293fn readers_of(atoms: &[Value]) -> BTreeSet<(String, String)> {
294    let mut out = BTreeSet::new();
295    for atom in atoms {
296        if atom["kind"].as_str() != Some("receipt") {
297            continue;
298        }
299        let Some(msg) = tag(atom, "receipt:") else {
300            continue;
301        };
302        let Some(by) = tag(atom, "from:").or_else(|| tag(atom, "seat:")) else {
303            continue;
304        };
305        out.insert((msg, by));
306    }
307    out
308}
309
310/// Messages addressed to `seat`, interrupts first, then oldest first.
311#[must_use]
312pub fn inbox_letters(atoms: &[Value], seat: &str, all: bool) -> Vec<Letter> {
313    let read = readers_of(atoms);
314    let mut letters: Vec<Letter> = atoms
315        .iter()
316        .enumerate()
317        .filter_map(|(seq, atom)| letter_of(atom, seq))
318        .filter(|letter| letter.to.iter().any(|to| to == seat))
319        .map(|mut letter| {
320            letter.read = read.contains(&(letter.id.clone(), seat.to_string()));
321            letter
322        })
323        .filter(|letter| all || !letter.read)
324        .collect();
325    letters.sort_by(|a, b| {
326        b.interrupt
327            .cmp(&a.interrupt)
328            .then(a.ts.cmp(&b.ts))
329            .then(a.seq.cmp(&b.seq))
330    });
331    letters
332}
333
334/// Receipts on messages this seat sent, newest stamp last.
335#[must_use]
336pub fn receipts_for(atoms: &[Value], seat: &str) -> Vec<Receipt> {
337    let mut out = Vec::new();
338    for atom in atoms {
339        if atom["kind"].as_str() != Some("receipt") {
340            continue;
341        }
342        if tag(atom, "to:").as_deref() != Some(seat) {
343            continue;
344        }
345        let Some(msg) = tag(atom, "receipt:") else {
346            continue;
347        };
348        let Some(by) = tag(atom, "from:") else {
349            continue;
350        };
351        let text = atom["text"].as_str().unwrap_or("");
352        let at = text
353            .lines()
354            .find_map(|l| l.strip_prefix("at "))
355            .unwrap_or("")
356            .to_string();
357        out.push(Receipt {
358            key: super::work_id(text),
359            msg,
360            by,
361            at,
362        });
363    }
364    out.sort_by(|a, b| a.at.cmp(&b.at).then(a.key.cmp(&b.key)));
365    out
366}
367
368/// Seats in a group, in the order they were added. A later drop removes one.
369#[must_use]
370pub fn members(atoms: &[Value], group: &str) -> Vec<String> {
371    let mut events: Vec<(String, usize, String, bool)> = Vec::new();
372    for (seq, atom) in atoms.iter().enumerate() {
373        if atom["kind"].as_str() != Some("group") {
374            continue;
375        }
376        if tag(atom, "group:").as_deref() != Some(group) {
377            continue;
378        }
379        let ts = atom["ts"].as_str().unwrap_or("").to_string();
380        if let Some(seat) = tag(atom, "member:") {
381            events.push((ts, seq, seat, false));
382        } else if let Some(seat) = tag(atom, "drop:") {
383            events.push((ts, seq, seat, true));
384        }
385    }
386    events.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
387    let mut out: Vec<String> = Vec::new();
388    for (_, _, seat, drop) in events {
389        if drop {
390            out.retain(|s| s != &seat);
391        } else if !out.iter().any(|s| s == &seat) {
392            out.push(seat);
393        }
394    }
395    out
396}
397
398/// A body as the prompt shows it: one line of 160 characters, and when it
399/// is cut, where the whole of it is. The prompt marks the letter read, so
400/// a long body would otherwise be seen only by its start.
401fn prompt_body(body: &str) -> String {
402    let n = body.chars().count();
403    let line = one_line(body, Some(160));
404    if n > 160 {
405        format!("{line} (all {n} characters: `ljos inbox --all`)")
406    } else {
407        line
408    }
409}
410
411fn one_line(body: &str, limit: Option<usize>) -> String {
412    let flat = body.split_whitespace().collect::<Vec<_>>().join(" ");
413    match limit {
414        Some(n) if flat.chars().count() > n => {
415            let t: String = flat.chars().take(n.saturating_sub(3)).collect();
416            format!("{t}...")
417        }
418        _ => flat,
419    }
420}
421
422fn flags(letter: &Letter) -> String {
423    let mut parts = Vec::new();
424    if letter.interrupt {
425        parts.push("interrupt".to_string());
426    }
427    if let Some(issue) = &letter.issue {
428        parts.push(format!("issue:{issue}"));
429    }
430    if let Some(group) = &letter.group {
431        parts.push(format!("group:{group}"));
432    }
433    if let Some(reply) = &letter.reply {
434        parts.push(format!("reply:{reply}"));
435    }
436    if letter.read {
437        parts.push("read".to_string());
438    }
439    parts.join(" ")
440}
441
442/// The inbox a seat prints. Receipts already shown are left out.
443#[must_use]
444pub fn render_inbox(
445    atoms: &[Value],
446    seat: &str,
447    all: bool,
448    seen_receipts: &BTreeSet<String>,
449) -> (String, Vec<String>) {
450    let letters = inbox_letters(atoms, seat, all);
451    let receipts: Vec<Receipt> = receipts_for(atoms, seat)
452        .into_iter()
453        .filter(|r| !seen_receipts.contains(&r.key))
454        .collect();
455    if letters.is_empty() && receipts.is_empty() {
456        let line = if all {
457            "inbox: nothing\n"
458        } else {
459            "inbox: nothing unread\n"
460        };
461        return (line.to_string(), Vec::new());
462    }
463    let mut out = String::new();
464    for letter in &letters {
465        out.push_str(&format!(
466            "{}\t{}\t{}\t{}\n",
467            letter.id,
468            letter.from,
469            flags(letter),
470            one_line(&letter.body, None)
471        ));
472    }
473    let mut keys = Vec::new();
474    for receipt in &receipts {
475        out.push_str(&format!(
476            "receipt\t{}\t{}\t{}\n",
477            receipt.msg, receipt.by, receipt.at
478        ));
479        keys.push(receipt.key.clone());
480    }
481    (out, keys)
482}
483
484/// The note a prompt hook prints, and the ids to receipt when it is delivered.
485///
486/// Message ids are prefixed `mail:`. Receipt ids the sender is being told
487/// about are prefixed `rcpt:` and are recorded locally, not written again.
488#[must_use]
489pub fn prompt_lines(letters: &[Letter], receipts: &[Receipt]) -> (String, Vec<String>) {
490    if letters.is_empty() && receipts.is_empty() {
491        return (String::new(), Vec::new());
492    }
493    let mut lines = vec!["mail:".to_string()];
494    let mut ids = Vec::new();
495    for letter in letters.iter().take(PROMPT_CAP) {
496        let mark = if letter.interrupt { "! " } else { "" };
497        let on = letter
498            .issue
499            .as_ref()
500            .map(|issue| format!(" on {issue}"))
501            .unwrap_or_default();
502        lines.push(format!(
503            "{mark}{} from {}{on}: {}",
504            letter.id,
505            letter.from,
506            prompt_body(&letter.body)
507        ));
508        ids.push(format!("mail:{}", letter.id));
509    }
510    let rest = letters.len().saturating_sub(PROMPT_CAP);
511    if rest > 0 {
512        lines.push(format!("{rest} more in ljos inbox"));
513    }
514    for receipt in receipts.iter().take(PROMPT_CAP) {
515        lines.push(format!("read {} by {}", receipt.msg, receipt.by));
516        ids.push(format!("rcpt:{}", receipt.key));
517    }
518    (lines.join("\n"), ids)
519}
520
521fn find_letter(atoms: &[Value], id: &str) -> Result<Letter> {
522    atoms
523        .iter()
524        .enumerate()
525        .filter_map(|(seq, atom)| letter_of(atom, seq))
526        .find(|letter| letter.id == id)
527        .ok_or_else(|| anyhow::anyhow!("no message {id}"))
528}
529
530/// Every seat this pack has heard from: a sender, a reader, a group
531/// member, and the seat any atom was written under.
532#[must_use]
533pub fn known_seats(atoms: &[Value]) -> BTreeSet<String> {
534    let mut out = BTreeSet::new();
535    for atom in atoms {
536        for prefix in ["seat:", "from:", "member:"] {
537            out.extend(tags(atom, prefix));
538        }
539        if let Some(seat) = atom["source"]["harness"].as_str() {
540            out.insert(seat.to_string());
541        }
542    }
543    out.retain(|s| !s.trim().is_empty());
544    out
545}
546
547/// Refuse a seat the pack has never heard from. Mail waits under the name
548/// it was sent to, so a message to `ljos` sat unread while the seat that
549/// meant to read it was `ljos-bot` (ticket-mwy5).
550///
551/// # Errors
552///
553/// `seat` is not in `known` and `new_seat` was not passed.
554pub fn check_known(seat: &str, known: &BTreeSet<String>, new_seat: bool) -> Result<()> {
555    if new_seat || known.contains(seat) {
556        return Ok(());
557    }
558    bail!(
559        "send: no seat named {seat} has written to this pack, so the message would wait unread. \
560         {} Pass --new-seat to write to a seat that has not started yet",
561        seat_hint(seat, known)
562    )
563}
564
565/// The most seat names an error lists after its guess.
566const SEAT_HINT_MAX: usize = 4;
567
568/// Whether `name` reads as a seat name. A conversation id that an older
569/// ljos wrote as a holder does not: a UUID, a long hex run, or `sess-`
570/// and a hex run. Such a name helps nobody pick a seat.
571#[must_use]
572pub fn named_seat(name: &str) -> bool {
573    let name = name.trim();
574    if name.is_empty() {
575        return false;
576    }
577    let rest = name.strip_prefix("sess-").unwrap_or(name);
578    let hex: Vec<char> = rest.chars().filter(|c| *c != '-').collect();
579    let conversation_id = hex.len() >= 16 && hex.iter().all(char::is_ascii_hexdigit);
580    !conversation_id
581}
582
583/// The hint an unknown seat gets: the seat it most likely meant, then a
584/// few other named seats. Conversation ids are left out
585/// ([`named_seat`]), and past [`SEAT_HINT_MAX`] the rest are counted.
586#[must_use]
587pub fn seat_hint(seat: &str, known: &BTreeSet<String>) -> String {
588    let named: BTreeSet<String> = known.iter().filter(|s| named_seat(s)).cloned().collect();
589    let guess = closest_seat(seat, &named).map(str::to_string);
590    let others: Vec<&String> = named
591        .iter()
592        .filter(|s| guess.as_deref() != Some(s.as_str()))
593        .collect();
594    let mut shown = others
595        .iter()
596        .take(SEAT_HINT_MAX)
597        .map(|s| s.as_str())
598        .collect::<Vec<_>>()
599        .join(", ");
600    if others.len() > SEAT_HINT_MAX {
601        shown.push_str(&format!(" and {} more", others.len() - SEAT_HINT_MAX));
602    }
603    match (guess, shown.is_empty()) {
604        (Some(g), true) => format!("Did you mean {g}?"),
605        (Some(g), false) => format!("Did you mean {g}? Other seats: {shown}."),
606        (None, false) => format!("Seats here: {shown}."),
607        (None, true) => "No named seat has started here yet.".to_string(),
608    }
609}
610
611/// The known seat a mistyped name most likely meant: one that starts with
612/// it or holds it (`ljos` for `ljos-bot`), else the nearest by edits, at
613/// most two away. `None` when nothing is that close.
614#[must_use]
615pub fn closest_seat<'a>(seat: &str, known: &'a BTreeSet<String>) -> Option<&'a str> {
616    let lower = seat.to_lowercase();
617    if lower.is_empty() {
618        return None;
619    }
620    let holds = known
621        .iter()
622        .filter(|k| k.to_lowercase().contains(&lower) || lower.contains(&k.to_lowercase()))
623        .min_by_key(|k| (k.len().abs_diff(seat.len()), k.as_str()));
624    if let Some(k) = holds {
625        return Some(k.as_str());
626    }
627    known
628        .iter()
629        .map(|k| (edits(&lower, &k.to_lowercase()), k))
630        .filter(|(d, _)| *d <= 2)
631        .min()
632        .map(|(_, k)| k.as_str())
633}
634
635/// Levenshtein distance, in characters.
636fn edits(a: &str, b: &str) -> usize {
637    let b: Vec<char> = b.chars().collect();
638    let mut row: Vec<usize> = (0..=b.len()).collect();
639    for (i, ca) in a.chars().enumerate() {
640        let mut prev = row[0];
641        row[0] = i + 1;
642        for (j, cb) in b.iter().enumerate() {
643            let cur = row[j + 1];
644            row[j + 1] = if ca == *cb {
645                prev
646            } else {
647                1 + prev.min(cur).min(row[j])
648            };
649            prev = cur;
650        }
651    }
652    row[b.len()]
653}
654
655/// Who a send addresses. A group send leaves the sender off the list.
656pub fn recipients(
657    from: &str,
658    seat: Option<&str>,
659    group: Option<&str>,
660    members: &[String],
661) -> Result<Vec<String>> {
662    if let Some(group) = group {
663        if seat.is_some() {
664            bail!("send: name a seat or a group");
665        }
666        let to: Vec<String> = members
667            .iter()
668            .filter(|m| m.as_str() != from)
669            .cloned()
670            .collect();
671        if to.is_empty() {
672            bail!("send: {group} has no other member");
673        }
674        return Ok(to);
675    }
676    let Some(seat) = seat.map(str::trim).filter(|s| !s.is_empty()) else {
677        bail!("send: name a seat or a group");
678    };
679    let seat = check_name("send", seat)?;
680    if seat == from {
681        bail!("send: {seat} is this seat");
682    }
683    Ok(vec![seat])
684}
685
686fn is_mail_atom(atom: &Value) -> bool {
687    matches!(atom["kind"].as_str(), Some("message" | "receipt" | "group"))
688}
689
690fn writer_version(client: &crate::PacksetClient) -> Option<String> {
691    client
692        .status(Some(&client.workspace()))
693        .ok()
694        .and_then(|status| {
695            status
696                .get("version")
697                .and_then(Value::as_str)
698                .filter(|version| !version.is_empty())
699                .map(str::to_string)
700        })
701}
702
703/// Fail when this writer does not keep mail.
704///
705/// An empty message is a tool dump on every packset, refused before the
706/// kind, so it reads the same from a pack that keeps mail and from one
707/// that does not. The probe names a level the pack does not keep. The
708/// kind is refused, or the level is, and neither answer is stored.
709fn ensure_mail(client: &crate::PacksetClient, verb: &str) -> Result<()> {
710    // The writer's version decides when it gives one. Without a version
711    // the probe below is the check.
712    if let Some(version) = writer_version(client) {
713        match super::cmp_semver(&version, MAIL_PACKSET) {
714            Some(std::cmp::Ordering::Less) => {
715                bail!("{verb}: {}", unsupported_mail(Some(&version)));
716            }
717            Some(_) => return Ok(()),
718            None => {}
719        }
720    }
721    let probe = json!({
722        "schema": "inside.atom/v1",
723        "kind": "message",
724        "level": "nope",
725        "text": "probe",
726        "workspace": workspace_of(Some(&client.workspace())),
727    });
728    let posted = super::with_writer(|| client.post_atom(&probe).map_err(anyhow::Error::from));
729    match posted {
730        Ok(_) => Ok(()),
731        Err(err) => match probe_of(&format!("{err:#}")) {
732            Probe::Kept => Ok(()),
733            Probe::Refused => {
734                let version = writer_version(client);
735                bail!("{verb}: {}", unsupported_mail(version.as_deref()));
736            }
737            Probe::Store => Err(err).context("mail: the pack did not answer"),
738        },
739    }
740}
741
742fn listed() -> Result<Vec<Value>> {
743    let client = super::pack()?;
744    let workspace = client.workspace();
745    super::atoms_lean(&client, &workspace).context("mail: the pack did not answer")
746}
747
748fn load(verb: &str) -> Result<Vec<Value>> {
749    let client = super::pack()?;
750    let atoms = listed()?;
751    if !atoms.iter().any(is_mail_atom) {
752        ensure_mail(&client, verb)?;
753    }
754    Ok(atoms)
755}
756
757fn load_quiet() -> Option<Vec<Value>> {
758    let client = super::pack().ok()?;
759    let workspace = client.workspace();
760    super::atoms_lean_shared(&client, &workspace).ok()
761}
762
763fn post(atom: &Value, verb: &str) -> Result<Value> {
764    let client = super::pack()?;
765    super::with_writer(|| {
766        client
767            .post_atom(atom)
768            .with_context(|| format!("{verb}: POST /v1/atoms failed"))
769    })
770}
771
772fn workspace_of(client_workspace: Option<&str>) -> String {
773    client_workspace.unwrap_or("seat").to_string()
774}
775
776fn stamp_source(atom: &mut Value) {
777    atom["source"] = super::atom_source();
778}
779
780/// Write one message and print its id.
781pub fn send(args: &Send<'_>) -> Result<String> {
782    let text = args.text.trim();
783    if text.is_empty() {
784        bail!("send: empty text");
785    }
786    check_length("send", text)?;
787    let from = super::seat_name();
788    let group = args
789        .group
790        .map(|name| check_name("send", name))
791        .transpose()?;
792    let client = super::pack()?;
793    // A named seat is checked before the pack, so "this seat" stays that
794    // error. A group has no roster until the pack answers.
795    let atoms = if group.is_some() {
796        ensure_mail(&client, "send")?;
797        listed()?
798    } else {
799        Vec::new()
800    };
801    let roster = group
802        .as_deref()
803        .map(|name| members(&atoms, name))
804        .unwrap_or_default();
805    let to = recipients(from.as_str(), args.seat, group.as_deref(), &roster)?;
806    if group.is_none() {
807        ensure_mail(&client, "send")?;
808        if !args.new_seat {
809            let known = known_seats(&listed()?);
810            for seat in &to {
811                check_known(seat, &known, false)?;
812            }
813        }
814    }
815    let issue = args
816        .issue
817        .map(str::trim)
818        .filter(|s| !s.is_empty())
819        .map(|s| check_name("send", s))
820        .transpose()?;
821    let scope = issue.as_deref().and_then(super::sync::scope_for_issue);
822    let outgoing = Outgoing {
823        id: mint_id("msg", &[&from, text]),
824        from,
825        to: to.clone(),
826        body: text.to_string(),
827        interrupt: args.interrupt,
828        issue,
829        group,
830        reply: None,
831        scope,
832    };
833    let mut atom = message_atom(&outgoing, &workspace_of(Some(&client.workspace())));
834    stamp_source(&mut atom);
835    post(&atom, "send")?;
836    let mut said = format!("sent {} to {}\n", outgoing.id, to.join(", "));
837    said.push_str(&wake_after(&outgoing));
838    Ok(said)
839}
840
841/// Start the wake of each recipient that set one, and say which. The
842/// message is already written, so a wake that fails changes nothing here.
843/// In push mode the detached wake pushes the sealed log before it fires.
844fn wake_after(m: &Outgoing) -> String {
845    let events: Vec<super::wake::Event> =
846        m.to.iter()
847            .map(|seat| super::wake::Event {
848                seat: seat.clone(),
849                from: m.from.clone(),
850                msg: m.id.clone(),
851                issue: m.issue.clone(),
852                interrupt: m.interrupt,
853                // The detached wake discovers the log commit after it pushes.
854                commit: None,
855            })
856            .collect();
857    let woken = super::wake::spawn(&events);
858    if woken.is_empty() {
859        String::new()
860    } else {
861        format!("waking {}\n", woken.join(", "))
862    }
863}
864
865/// Unread mail for this seat, then receipts on what it sent that it has not
866/// been shown yet.
867///
868/// Listing does not write a receipt. `ljos hook --prompt` does, for each
869/// message it shows. A pack that does not answer, or that refuses mail, is
870/// an error. `ljos_inbox` calls this. This does not fetch the tracker;
871/// [`inbox_sync`] does.
872pub fn inbox(all: bool) -> Result<String> {
873    inbox_sync(all, None)
874}
875
876/// [`inbox`], after fetching the tracker when `until` is set.
877///
878/// `None` lists the pack as it stands. `Some("")` fetches the remote head,
879/// or the commit in `LJOS_WAKE_COMMIT` when that is set. `Some(commit)`
880/// fetches until the remote has that commit, for up to
881/// `LJOS_INBOX_SYNC_WAIT` seconds, or else takes the remote head. A
882/// checkout with no remote is listed as it is. Fetch notes go to
883/// stderr. The returned text is the inbox.
884///
885/// # Errors
886///
887/// The named commit is not hex, a scope file does not parse, the import
888/// fails, or the pack does not answer. A fetch that fails still lists.
889pub fn inbox_sync(all: bool, until: Option<&str>) -> Result<String> {
890    if let Some(until) = until {
891        let named = commit_named(until);
892        let note = super::sync::fetch_for_inbox(named.as_deref())?;
893        if !note.trim().is_empty() {
894            eprint!("{note}");
895        }
896    }
897    let atoms = load("inbox")?;
898    let seat = super::seat_name();
899    let seen = receipt_seen();
900    let (text, keys) = render_inbox(&atoms, &seat, all, &seen);
901    remember_receipts(&keys);
902    Ok(text)
903}
904
905/// The commit `--sync` asked for. An empty flag means `LJOS_WAKE_COMMIT`
906/// when that is set, and otherwise the remote head.
907fn commit_named(until: &str) -> Option<String> {
908    let named = until.trim();
909    if !named.is_empty() {
910        return Some(named.to_string());
911    }
912    std::env::var("LJOS_WAKE_COMMIT")
913        .ok()
914        .map(|value| value.trim().to_string())
915        .filter(|value| !value.is_empty())
916}
917
918fn already_read(atoms: &[Value], msg: &str, seat: &str) -> bool {
919    readers_of(atoms).contains(&(msg.to_string(), seat.to_string()))
920}
921
922fn receipt_atom(msg: &Letter, reader: &str, at: &str, workspace: &str) -> Value {
923    let id = mint_id("receipt", &[msg.id.as_str(), reader, at]);
924    let text = format!("read {}\nby {reader}\nat {at}\nmsg {id}", msg.id);
925    let mut entities = vec![
926        format!("seat:{reader}"),
927        format!("from:{reader}"),
928        format!("to:{}", msg.from),
929        format!("msg:{id}"),
930        format!("receipt:{}", msg.id),
931    ];
932    if let Some(scope) = &msg.scope {
933        entities.push(format!("scope:{scope}"));
934    }
935    json!({
936        "schema": "inside.atom/v1",
937        "kind": "receipt",
938        "level": "explicit",
939        "text": text,
940        "workspace": workspace,
941        "entities": entities,
942    })
943}
944
945/// Write a receipt for one message. A second read of the same message
946/// writes nothing.
947pub fn read(id: &str) -> Result<String> {
948    let id = id.trim();
949    if id.is_empty() {
950        bail!("read: name a message");
951    }
952    let atoms = load("read")?;
953    let seat = super::seat_name();
954    let letter = find_letter(&atoms, id).context("read")?;
955    if !letter.to.iter().any(|to| to == &seat) {
956        bail!("read: {id} is not for {seat}");
957    }
958    if already_read(&atoms, id, &seat) {
959        return Ok(format!("read {id} already\n"));
960    }
961    let client = super::pack()?;
962    let mut atom = receipt_atom(
963        &letter,
964        &seat,
965        &super::now_utc(),
966        &workspace_of(Some(&client.workspace())),
967    );
968    stamp_source(&mut atom);
969    post(&atom, "read")?;
970    Ok(format!("read {id}\n"))
971}
972
973fn read_ids(ids: &[String]) {
974    let Some(atoms) = load_quiet() else {
975        return;
976    };
977    let seat = super::seat_name();
978    let Ok(client) = super::pack() else {
979        return;
980    };
981    let workspace = client.workspace();
982    let at = super::now_utc();
983    for id in ids {
984        let Ok(letter) = find_letter(&atoms, id) else {
985            continue;
986        };
987        if !letter.to.iter().any(|to| to == &seat) || already_read(&atoms, id, &seat) {
988            continue;
989        }
990        let mut atom = receipt_atom(&letter, &seat, &at, &workspace_of(Some(&workspace)));
991        stamp_source(&mut atom);
992        let _ = post(&atom, "read");
993    }
994}
995
996/// Answer a message. The reply goes to its sender and keeps its issue.
997pub fn reply(id: &str, text: &str, interrupt: bool) -> Result<String> {
998    let id = id.trim();
999    let text = text.trim();
1000    if id.is_empty() {
1001        bail!("reply: name a message");
1002    }
1003    if text.is_empty() {
1004        bail!("reply: empty text");
1005    }
1006    check_length("reply", text)?;
1007    let atoms = load("reply")?;
1008    let parent = find_letter(&atoms, id).context("reply")?;
1009    let from = super::seat_name();
1010    if parent.from == from {
1011        bail!("reply: {id} is from this seat");
1012    }
1013    let issue = parent.issue.clone();
1014    let scope = issue
1015        .as_deref()
1016        .and_then(super::sync::scope_for_issue)
1017        .or(parent.scope);
1018    let outgoing = Outgoing {
1019        id: mint_id("msg", &[&from, id, text]),
1020        from,
1021        to: vec![parent.from.clone()],
1022        body: text.to_string(),
1023        interrupt,
1024        issue,
1025        group: None,
1026        reply: Some(parent.id.clone()),
1027        scope,
1028    };
1029    let client = super::pack()?;
1030    let mut atom = message_atom(&outgoing, &workspace_of(Some(&client.workspace())));
1031    stamp_source(&mut atom);
1032    post(&atom, "reply")?;
1033    let mut line = format!(
1034        "sent {} to {}\nreply {}\n",
1035        outgoing.id, parent.from, parent.id
1036    );
1037    if let Some(issue) = &outgoing.issue {
1038        line.push_str(&format!("issue {issue}\n"));
1039    }
1040    line.push_str(&wake_after(&outgoing));
1041    Ok(line)
1042}
1043
1044fn group_atom(name: &str, seat: &str, drop: bool, by: &str, workspace: &str) -> Value {
1045    let at = super::now_utc();
1046    let id = mint_id("group", &[name, seat, by, &at]);
1047    let verb = if drop { "drop" } else { "member" };
1048    let text = format!("group {id}\nname {name}\n{verb} {seat}\nby {by}\nat {at}");
1049    let mut entities = vec![
1050        format!("seat:{by}"),
1051        format!("group:{name}"),
1052        format!("msg:{id}"),
1053    ];
1054    if drop {
1055        entities.push(format!("drop:{seat}"));
1056    } else {
1057        entities.push(format!("member:{seat}"));
1058    }
1059    json!({
1060        "schema": "inside.atom/v1",
1061        "kind": "group",
1062        "level": "explicit",
1063        "text": text,
1064        "workspace": workspace,
1065        "entities": entities,
1066    })
1067}
1068
1069/// List a group, or add and remove members. A drop is its own atom.
1070pub fn group(name: &str, add: &[String], remove: &[String]) -> Result<String> {
1071    let name = check_name("group", name)?;
1072    if add.is_empty() && remove.is_empty() {
1073        let atoms = load("group")?;
1074        let seats = members(&atoms, &name);
1075        if seats.is_empty() {
1076            return Ok(format!("{name}\t(no members)\n"));
1077        }
1078        let mut out = String::new();
1079        for seat in seats {
1080            out.push_str(&format!("{name}\t{seat}\n"));
1081        }
1082        return Ok(out);
1083    }
1084    let atoms = load("group")?;
1085    let by = super::seat_name();
1086    let client = super::pack()?;
1087    let workspace = client.workspace();
1088    let mut roster = members(&atoms, &name);
1089    let mut out = String::new();
1090    for seat in add {
1091        let seat = check_name("group", seat)?;
1092        if roster.iter().any(|s| s == &seat) {
1093            out.push_str(&format!("{seat} is already in {name}\n"));
1094            continue;
1095        }
1096        let mut atom = group_atom(&name, &seat, false, &by, &workspace_of(Some(&workspace)));
1097        stamp_source(&mut atom);
1098        post(&atom, "group")?;
1099        roster.push(seat.clone());
1100        out.push_str(&format!("added {seat} to {name}\n"));
1101    }
1102    for seat in remove {
1103        let seat = check_name("group", seat)?;
1104        if !roster.iter().any(|s| s == &seat) {
1105            out.push_str(&format!("{seat} is not in {name}\n"));
1106            continue;
1107        }
1108        let mut atom = group_atom(&name, &seat, true, &by, &workspace_of(Some(&workspace)));
1109        stamp_source(&mut atom);
1110        post(&atom, "group")?;
1111        roster.retain(|s| s != &seat);
1112        out.push_str(&format!("removed {seat} from {name}\n"));
1113    }
1114    Ok(out)
1115}
1116
1117fn state_dir() -> PathBuf {
1118    std::env::var_os("XDG_STATE_HOME")
1119        .map(PathBuf::from)
1120        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/state")))
1121        .unwrap_or_else(|| PathBuf::from(".local/state"))
1122        .join("ljos")
1123        .join("mail")
1124}
1125
1126fn receipt_seen_path() -> PathBuf {
1127    state_dir().join("receipts-seen")
1128}
1129
1130fn receipt_seen() -> BTreeSet<String> {
1131    std::fs::read_to_string(receipt_seen_path())
1132        .map(|text| {
1133            text.lines()
1134                .map(str::trim)
1135                .filter(|l| !l.is_empty())
1136                .map(str::to_string)
1137                .collect()
1138        })
1139        .unwrap_or_default()
1140}
1141
1142fn remember_receipts(keys: &[String]) {
1143    if keys.is_empty() {
1144        return;
1145    }
1146    let path = receipt_seen_path();
1147    if let Some(dir) = path.parent() {
1148        let _ = std::fs::create_dir_all(dir);
1149    }
1150    let mut text = std::fs::read_to_string(&path).unwrap_or_default();
1151    for key in keys {
1152        if text.lines().any(|l| l == key) {
1153            continue;
1154        }
1155        text.push_str(key);
1156        text.push('\n');
1157    }
1158    let _ = std::fs::write(path, text);
1159}
1160
1161/// What the prompt hook prints when the pack does not answer.
1162///
1163/// One line. The hook still exits 0, so the prompt is not blocked.
1164pub const MAIL_UNCHECKED: &str = "mail could not be checked";
1165
1166/// Unread mail and unseen receipts for the prompt hook. A pack that does
1167/// not answer leaves one line, so unread mail is not silent.
1168#[must_use]
1169pub fn prompt_note() -> (String, Vec<String>) {
1170    let Some(atoms) = load_quiet() else {
1171        return (MAIL_UNCHECKED.to_string(), Vec::new());
1172    };
1173    let seat = super::seat_name();
1174    let letters = inbox_letters(&atoms, &seat, false);
1175    let seen = receipt_seen();
1176    let receipts: Vec<Receipt> = receipts_for(&atoms, &seat)
1177        .into_iter()
1178        .filter(|r| !seen.contains(&r.key))
1179        .collect();
1180    prompt_lines(&letters, &receipts)
1181}
1182
1183/// The line a held stop opens with, before the mail it carries.
1184pub const STOP_MAIL_HEAD: &str =
1185    "Mail marked interrupt reached this seat while you worked. Read it before you stop:";
1186
1187/// Unread interrupt mail for a stop hook, and the ids to receipt once the
1188/// runner has it. A running session takes it as one more round before it
1189/// goes idle, so a sender's interrupt does not wait for a prompt that may
1190/// never come. Plain mail waits for the next prompt or the seat's wake. A
1191/// pack that does not answer says nothing here: holding a stop on an
1192/// error would keep every turn open.
1193#[must_use]
1194pub fn stop_note() -> (String, Vec<String>) {
1195    let Some(atoms) = load_quiet() else {
1196        return (String::new(), Vec::new());
1197    };
1198    stop_lines(&atoms, &super::seat_name())
1199}
1200
1201/// [`stop_note`] over atoms already read.
1202#[must_use]
1203pub fn stop_lines(atoms: &[Value], seat: &str) -> (String, Vec<String>) {
1204    let hot: Vec<Letter> = inbox_letters(atoms, seat, false)
1205        .into_iter()
1206        .filter(|l| l.interrupt)
1207        .collect();
1208    let (lines, ids) = prompt_lines(&hot, &[]);
1209    if lines.is_empty() {
1210        return (String::new(), Vec::new());
1211    }
1212    let reply = "Answer with `ljos reply ID TEXT`.";
1213    (format!("{STOP_MAIL_HEAD}\n{lines}\n{reply}"), ids)
1214}
1215
1216/// Receipts for messages a runner was just shown, and a local mark for
1217/// receipts this seat was told about. A pack that does not answer leaves
1218/// the message unread, so the next prompt shows it again.
1219pub fn ack_delivered(ids: &[String]) {
1220    let mut reads = Vec::new();
1221    let mut seen = Vec::new();
1222    for id in ids {
1223        if let Some(msg) = id.strip_prefix("mail:") {
1224            reads.push(msg.to_string());
1225        } else if let Some(key) = id.strip_prefix("rcpt:") {
1226            seen.push(key.to_string());
1227        }
1228    }
1229    if !reads.is_empty() {
1230        read_ids(&reads);
1231    }
1232    remember_receipts(&seen);
1233}
1234
1235#[cfg(test)]
1236mod tests {
1237    use super::*;
1238
1239    fn outgoing(id: &str, from: &str, to: &[&str], body: &str) -> Outgoing {
1240        Outgoing {
1241            id: id.to_string(),
1242            from: from.to_string(),
1243            to: to.iter().map(|s| (*s).to_string()).collect(),
1244            body: body.to_string(),
1245            interrupt: false,
1246            issue: None,
1247            group: None,
1248            reply: None,
1249            scope: None,
1250        }
1251    }
1252
1253    #[test]
1254    fn a_long_body_fits_the_pack_and_reads_back_whole() {
1255        let long = "the aarch64 log says the Highway test times out. ".repeat(40);
1256        let m = outgoing("msg-1", "saddle", &["inky"], &long);
1257        let atom = message_atom(&m, "seat");
1258        let text = atom["text"].as_str().unwrap();
1259        assert!(
1260            text.chars().count() <= ATOM_TEXT_CAP,
1261            "{}",
1262            text.chars().count()
1263        );
1264        assert!(text.ends_with('\u{2026}'), "{text}");
1265        assert!(
1266            text.starts_with("msg msg-1\nfrom saddle\nto inky\n\n"),
1267            "{text}"
1268        );
1269        assert_eq!(atom["body"].as_str(), Some(long.trim()));
1270        let letter = letter_of(&atom, 0).expect("a letter");
1271        assert_eq!(letter.body, long.trim());
1272        // A short body has no `body` field and reads back from the text.
1273        let short = message_atom(&outgoing("msg-2", "saddle", &["inky"], "ok"), "seat");
1274        assert!(short.get("body").is_none());
1275        assert_eq!(letter_of(&short, 0).unwrap().body, "ok");
1276        // Past the mail cap, a refusal that names the deed route.
1277        let err = check_length("send", &"x".repeat(MAIL_BODY_CAP + 1))
1278            .unwrap_err()
1279            .to_string();
1280        assert!(err.contains("deedar create file"), "{err}");
1281        assert!(check_length("send", &"x".repeat(MAIL_BODY_CAP)).is_ok());
1282        let shown = prompt_body(&long);
1283        assert!(shown.contains("`ljos inbox --all`"), "{shown}");
1284        assert_eq!(prompt_body("ok"), "ok");
1285    }
1286
1287    fn atom(m: &Outgoing, ts: &str) -> Value {
1288        let mut v = message_atom(m, "seat");
1289        v["ts"] = json!(ts);
1290        v
1291    }
1292
1293    #[test]
1294    fn the_same_words_stay_two_messages() {
1295        let a = outgoing("a", "alice", &["bob"], "ok");
1296        let b = outgoing("b", "carol", &["bob"], "ok");
1297        let left = message_text(&a);
1298        let right = message_text(&b);
1299        assert_ne!(left, right);
1300        assert_ne!(super::super::work_id(&left), super::super::work_id(&right));
1301        assert_eq!(body_of(&left), "ok");
1302        let atoms = [
1303            atom(&a, "2026-10-09T00:00:00Z"),
1304            atom(&b, "2026-10-09T00:00:01Z"),
1305        ];
1306        let plain = super::super::sync::log_plaintext(&atoms, "seat", "seat");
1307        assert_eq!(plain.lines().count(), 2, "{plain}");
1308        let got = super::super::sync::incoming(&plain, "other", &BTreeSet::new(), &BTreeSet::new());
1309        assert_eq!(got.post.len(), 2);
1310    }
1311
1312    #[test]
1313    fn inbox_is_the_seat_named_and_an_interrupt_leads() {
1314        let mut late = outgoing("late", "alice", &["bob"], "when you can");
1315        late.issue = Some("acme-4".into());
1316        let mut hot = outgoing("hot", "carol", &["bob"], "the build is red");
1317        hot.interrupt = true;
1318        hot.issue = Some("acme-4".into());
1319        let other = outgoing("other", "alice", &["dave"], "not for bob");
1320        let atoms = [
1321            atom(&late, "2026-10-09T00:00:00Z"),
1322            atom(&hot, "2026-10-09T00:00:02Z"),
1323            atom(&other, "2026-10-09T00:00:01Z"),
1324        ];
1325        let letters = inbox_letters(&atoms, "bob", false);
1326        assert_eq!(
1327            letters.iter().map(|l| l.id.as_str()).collect::<Vec<_>>(),
1328            ["hot", "late"]
1329        );
1330        assert!(letters[0].interrupt);
1331        assert_eq!(letters[1].issue.as_deref(), Some("acme-4"));
1332        let (text, ids) = prompt_lines(&letters, &[]);
1333        assert!(
1334            text.starts_with("mail:\n! hot from carol on acme-4:"),
1335            "{text}"
1336        );
1337        assert!(ids.contains(&"mail:hot".to_string()), "{ids:?}");
1338        assert!(text.contains("late from alice on acme-4:"));
1339    }
1340
1341    #[test]
1342    fn a_receipt_takes_the_message_out_of_the_unread_list() {
1343        let msg = outgoing("m1", "alice", &["bob"], "look at the log");
1344        let message = atom(&msg, "2026-10-09T00:00:00Z");
1345        let receipt = json!({
1346            "kind": "receipt",
1347            "text": "read m1\nby bob\nat 2026-10-09T00:01:00Z\nmsg r1",
1348            "ts": "2026-10-09T00:01:00Z",
1349            "entities": ["seat:bob", "from:bob", "to:alice", "receipt:m1", "msg:r1"],
1350        });
1351        let held = [message, receipt];
1352        let unread = inbox_letters(&held, "bob", false);
1353        assert!(unread.is_empty());
1354        let all = inbox_letters(&held, "bob", true);
1355        assert!(all[0].read);
1356        let (text, keys) = render_inbox(&held, "alice", false, &BTreeSet::new());
1357        assert!(
1358            text.contains("receipt\tm1\tbob\t2026-10-09T00:01:00Z"),
1359            "{text}"
1360        );
1361        assert_eq!(keys.len(), 1);
1362        let (again, _) = render_inbox(&held, "alice", false, &keys.into_iter().collect());
1363        assert_eq!(again, "inbox: nothing unread\n");
1364    }
1365
1366    #[test]
1367    fn a_reply_keeps_the_issue_and_names_the_sender() {
1368        let mut parent = outgoing("p", "alice", &["bob"], "the build is red");
1369        parent.issue = Some("acme-4".into());
1370        parent.scope = Some("tools".into());
1371        let letter = letter_of(&atom(&parent, "2026-10-09T00:00:00Z"), 0).unwrap();
1372        let reply = Outgoing {
1373            id: "r".into(),
1374            from: "bob".into(),
1375            to: vec![letter.from.clone()],
1376            body: "looking".into(),
1377            interrupt: false,
1378            issue: letter.issue.clone(),
1379            group: None,
1380            reply: Some(letter.id.clone()),
1381            scope: letter.scope.clone(),
1382        };
1383        let atom = message_atom(&reply, "seat");
1384        let back = letter_of(&atom, 1).unwrap();
1385        assert_eq!(back.to, ["alice"]);
1386        assert_eq!(back.reply.as_deref(), Some("p"));
1387        assert_eq!(back.issue.as_deref(), Some("acme-4"));
1388        assert_eq!(back.scope.as_deref(), Some("tools"));
1389        assert!(super::super::sync::is_own(&atom));
1390    }
1391
1392    #[test]
1393    fn a_group_send_reaches_the_other_members() {
1394        let atoms = [
1395            json!({
1396                "kind": "group",
1397                "ts": "2026-10-09T00:00:00Z",
1398                "entities": ["group:ops", "member:alice"],
1399            }),
1400            json!({
1401                "kind": "group",
1402                "ts": "2026-10-09T00:00:01Z",
1403                "entities": ["group:ops", "member:bob"],
1404            }),
1405            json!({
1406                "kind": "group",
1407                "ts": "2026-10-09T00:00:02Z",
1408                "entities": ["group:ops", "member:carol"],
1409            }),
1410            json!({
1411                "kind": "group",
1412                "ts": "2026-10-09T00:00:03Z",
1413                "entities": ["group:ops", "drop:carol"],
1414            }),
1415        ];
1416        assert_eq!(members(&atoms, "ops"), ["alice", "bob"]);
1417        let to = recipients("alice", None, Some("ops"), &members(&atoms, "ops")).unwrap();
1418        assert_eq!(to, ["bob"]);
1419        let err = recipients("alice", None, Some("ops"), &["alice".into()]).unwrap_err();
1420        assert!(err.to_string().contains("no other member"), "{err}");
1421        let err = recipients("alice", Some("alice"), None, &[]).unwrap_err();
1422        assert!(err.to_string().contains("this seat"), "{err}");
1423    }
1424
1425    #[test]
1426    fn a_prompt_caps_the_note_and_keeps_the_rest_unread() {
1427        let letters: Vec<Letter> = (0..10)
1428            .map(|n| Letter {
1429                id: format!("m{n}"),
1430                from: "alice".into(),
1431                to: vec!["bob".into()],
1432                body: format!("line {n}"),
1433                interrupt: n == 9,
1434                issue: None,
1435                group: None,
1436                reply: None,
1437                scope: None,
1438                read: false,
1439                ts: format!("2026-10-09T00:00:{n:02}Z"),
1440                seq: n,
1441            })
1442            .collect();
1443        let mut ordered = letters.clone();
1444        ordered.sort_by(|a, b| b.interrupt.cmp(&a.interrupt).then(a.ts.cmp(&b.ts)));
1445        let (text, ids) = prompt_lines(&ordered, &[]);
1446        assert!(text.lines().next().unwrap() == "mail:");
1447        assert!(text.contains("! m9 from alice:"));
1448        assert!(text.contains("2 more in ljos inbox"), "{text}");
1449        assert_eq!(ids.iter().filter(|id| id.starts_with("mail:")).count(), 8);
1450        assert!(!ids.iter().any(|id| id == "mail:m7" || id == "mail:m8"));
1451    }
1452
1453    #[test]
1454    fn a_seat_hint_names_a_few_seats_and_no_ids() {
1455        let known: BTreeSet<String> = [
1456            "alpha",
1457            "bravo",
1458            "charlie",
1459            "delta",
1460            "echo",
1461            "foxtrot",
1462            "saddle",
1463            "01a0dab3-895e-7533-93ca-c9807d5cb680",
1464            "sess-4f2a9c0d1e2b3a4f",
1465        ]
1466        .iter()
1467        .map(|s| (*s).to_string())
1468        .collect();
1469        assert!(named_seat("codex-vax0"));
1470        assert!(named_seat("disk-saver"));
1471        assert!(!named_seat("01a0dab3-895e-7533-93ca-c9807d5cb680"));
1472        assert!(!named_seat("sess-4f2a9c0d1e2b3a4f"));
1473        let hint = seat_hint("sadle", &known);
1474        assert_eq!(
1475            hint,
1476            "Did you mean saddle? Other seats: alpha, bravo, charlie, delta and 2 more."
1477        );
1478        let hint = seat_hint("zzz", &known);
1479        assert_eq!(hint, "Seats here: alpha, bravo, charlie, delta and 3 more.");
1480        let ids: BTreeSet<String> = ["01a0dab3-895e-7533-93ca-c9807d5cb680".to_string()].into();
1481        assert_eq!(
1482            seat_hint("codex", &ids),
1483            "No named seat has started here yet."
1484        );
1485        let err = check_known("sadle", &known, false).unwrap_err().to_string();
1486        assert!(!err.contains("01a0dab3"), "{err}");
1487        assert!(err.contains("Did you mean saddle?"), "{err}");
1488    }
1489
1490    #[test]
1491    fn a_misspelt_seat_is_answered_with_the_seat_it_meant() {
1492        let known: BTreeSet<String> = ["ljos-bot", "saddle", "inky"]
1493            .iter()
1494            .map(|s| (*s).to_string())
1495            .collect();
1496        assert_eq!(closest_seat("ljos", &known), Some("ljos-bot"));
1497        assert_eq!(closest_seat("sadle", &known), Some("saddle"));
1498        assert_eq!(closest_seat("eessi", &known), None);
1499        let err = check_known("ljos", &known, false).unwrap_err().to_string();
1500        assert!(err.contains("Did you mean ljos-bot?"), "{err}");
1501        let err = check_known("eessi", &known, false).unwrap_err().to_string();
1502        assert!(!err.contains("Did you mean"), "{err}");
1503        assert!(check_known("eessi", &known, true).is_ok());
1504    }
1505
1506    #[test]
1507    fn a_stop_carries_unread_interrupt_mail_only() {
1508        let plain = outgoing("plain", "grok", &["claude"], "when you can");
1509        let mut hot = outgoing("hot", "grok", &["claude"], "take ticket-d9n6 now");
1510        hot.interrupt = true;
1511        hot.issue = Some("ticket-d9n6".into());
1512        let atoms = [
1513            atom(&plain, "2026-10-11T00:00:00Z"),
1514            atom(&hot, "2026-10-11T00:00:01Z"),
1515        ];
1516        let (text, ids) = stop_lines(&atoms, "claude");
1517        assert!(text.starts_with(STOP_MAIL_HEAD), "{text}");
1518        assert!(
1519            text.contains("! hot from grok on ticket-d9n6: take ticket-d9n6 now"),
1520            "{text}"
1521        );
1522        assert!(!text.contains("when you can"), "{text}");
1523        assert_eq!(ids, ["mail:hot"]);
1524        let read = json!({
1525            "kind": "receipt",
1526            "text": "read hot\nby claude\nat 2026-10-11T00:00:02Z\nmsg r1",
1527            "entities": ["seat:claude", "from:claude", "to:grok", "receipt:hot", "msg:r1"],
1528        });
1529        let after = [atoms[0].clone(), atoms[1].clone(), read];
1530        assert_eq!(stop_lines(&after, "claude"), (String::new(), Vec::new()));
1531        assert_eq!(stop_lines(&atoms, "grok"), (String::new(), Vec::new()));
1532    }
1533
1534    #[test]
1535    fn an_unknown_kind_is_a_pack_without_mail() {
1536        let refused =
1537            "bad response: http://127.0.0.1:8761/v1/atoms: 400: unknown atom kind: message";
1538        assert_eq!(probe_of(refused), Probe::Refused);
1539        let kept = "bad response: http://127.0.0.1:8761/v1/atoms: 400: atom text is required";
1540        assert_eq!(probe_of(kept), Probe::Kept);
1541        let level = "bad response: http://127.0.0.1:8761/v1/atoms: 400: unknown atom level: nope";
1542        assert_eq!(probe_of(level), Probe::Kept);
1543        // An empty body is this 400 on a pack that keeps mail and on one
1544        // that does not. It must not be read as a kind refusal, and it
1545        // must not be the probe.
1546        let dump =
1547            "bad response: http://127.0.0.1:8761/v1/atoms: 400: tool dump is attach, not an atom";
1548        assert_eq!(probe_of(dump), Probe::Kept);
1549        let down = "http://127.0.0.1:8761/v1/atoms: http: connection refused";
1550        assert_eq!(probe_of(down), Probe::Store);
1551        let named = unsupported_mail(Some("0.12.1"));
1552        assert!(named.contains("packset 0.12.1"), "{named}");
1553        assert!(named.contains(MAIL_PACKSET), "{named}");
1554        assert!(named.contains("kind message"), "{named}");
1555        let quiet = unsupported_mail(None);
1556        assert!(quiet.contains(MAIL_PACKSET), "{quiet}");
1557        assert!(quiet.contains("refused kind message"), "{quiet}");
1558    }
1559}