1use 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
16const PROMPT_CAP: usize = 8;
18
19pub(crate) const MAIL_PACKSET: &str = "0.13.0";
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27enum Probe {
28 Refused,
30 Kept,
32 Store,
34}
35
36fn 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#[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
75pub 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 pub new_seat: bool,
84}
85
86#[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#[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#[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
174pub const ATOM_TEXT_CAP: usize = 500;
176
177pub const MAIL_BODY_CAP: usize = 16_000;
180
181fn 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#[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#[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 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#[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#[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#[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
398fn 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#[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#[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#[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
547pub 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
565const SEAT_HINT_MAX: usize = 4;
567
568#[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#[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#[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
635fn 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
655pub 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
703fn ensure_mail(client: &crate::PacksetClient, verb: &str) -> Result<()> {
710 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 _clock = super::arm_cmd_pack();
744 let client = super::pack()?;
745 let workspace = client.workspace();
746 match super::atoms_mail(&client, &workspace) {
747 Err(err) if super::is_pack_busy(&err) => Err(super::pack_busy_err()),
748 Err(err) => Err(err).context("mail: the pack did not answer"),
749 Ok(atoms) => Ok(atoms),
750 }
751}
752
753fn load(verb: &str) -> Result<Vec<Value>> {
754 let _clock = super::arm_cmd_pack();
755 let client = super::pack()?;
756 let atoms = listed()?;
757 if !atoms.iter().any(is_mail_atom) {
758 ensure_mail(&client, verb)?;
759 }
760 Ok(atoms)
761}
762
763fn load_quiet() -> Option<Vec<Value>> {
764 listed().ok()
765}
766
767fn post(atom: &Value, verb: &str) -> Result<Value> {
768 let _clock = super::arm_cmd_pack();
769 let client = super::pack()?;
770 super::with_writer(|| {
771 client
772 .post_atom(atom)
773 .with_context(|| format!("{verb}: POST /v1/atoms failed"))
774 })
775 .map_err(|err| {
776 if super::is_pack_busy(&err) {
777 super::pack_busy_err()
778 } else {
779 err
780 }
781 })
782}
783
784fn workspace_of(client_workspace: Option<&str>) -> String {
785 client_workspace.unwrap_or("seat").to_string()
786}
787
788fn stamp_source(atom: &mut Value) {
789 atom["source"] = super::atom_source();
790}
791
792pub fn send(args: &Send<'_>) -> Result<String> {
794 let _clock = super::arm_cmd_pack();
795 let text = args.text.trim();
796 if text.is_empty() {
797 bail!("send: empty text");
798 }
799 check_length("send", text)?;
800 let from = super::seat_name();
801 let group = args
802 .group
803 .map(|name| check_name("send", name))
804 .transpose()?;
805 let client = super::pack()?;
806 let atoms = if group.is_some() {
809 ensure_mail(&client, "send")?;
810 listed()?
811 } else {
812 Vec::new()
813 };
814 let roster = group
815 .as_deref()
816 .map(|name| members(&atoms, name))
817 .unwrap_or_default();
818 let to = recipients(from.as_str(), args.seat, group.as_deref(), &roster)?;
819 if group.is_none() {
820 ensure_mail(&client, "send")?;
821 if !args.new_seat {
822 let known = known_seats(&seats_heard()?);
823 for seat in &to {
824 check_known(seat, &known, false)?;
825 }
826 }
827 }
828 let issue = args
829 .issue
830 .map(str::trim)
831 .filter(|s| !s.is_empty())
832 .map(|s| check_name("send", s))
833 .transpose()?;
834 let scope = issue.as_deref().and_then(super::sync::scope_for_issue);
835 let outgoing = Outgoing {
836 id: mint_id("msg", &[&from, text]),
837 from,
838 to: to.clone(),
839 body: text.to_string(),
840 interrupt: args.interrupt,
841 issue,
842 group,
843 reply: None,
844 scope,
845 };
846 let mut atom = message_atom(&outgoing, &workspace_of(Some(&client.workspace())));
847 stamp_source(&mut atom);
848 post(&atom, "send")?;
849 let mut said = format!("sent {} to {}\n", outgoing.id, to.join(", "));
850 said.push_str(&wake_after(&outgoing));
851 Ok(said)
852}
853
854fn wake_after(m: &Outgoing) -> String {
858 let events: Vec<super::wake::Event> =
859 m.to.iter()
860 .map(|seat| super::wake::Event {
861 seat: seat.clone(),
862 from: m.from.clone(),
863 msg: m.id.clone(),
864 issue: m.issue.clone(),
865 interrupt: m.interrupt,
866 commit: None,
868 })
869 .collect();
870 let woken = super::wake::spawn(&events);
871 if woken.is_empty() {
872 String::new()
873 } else {
874 format!("waking {}\n", woken.join(", "))
875 }
876}
877
878pub fn inbox(all: bool) -> Result<String> {
888 inbox_sync(all, None)
889}
890
891pub fn inbox_sync(all: bool, until: Option<&str>) -> Result<String> {
905 if let Some(until) = until {
906 let named = commit_named(until);
907 let note = super::sync::fetch_for_inbox(named.as_deref())?;
908 if !note.trim().is_empty() {
909 eprint!("{note}");
910 }
911 }
912 let atoms = {
917 let _clock = super::arm_cmd_pack();
918 load("inbox")?
919 };
920 let seat = super::seat_name();
921 let seen = receipt_seen();
922 let (text, keys) = render_inbox(&atoms, &seat, all, &seen);
923 remember_receipts(&keys);
924 if let Err(err) = mark_shown(&atoms, &seat) {
927 if !super::is_pack_busy(&err) {
928 return Err(err);
929 }
930 }
931 Ok(text)
932}
933
934fn mark_shown(atoms: &[Value], seat: &str) -> Result<()> {
937 let letters = inbox_letters(atoms, seat, false);
938 if letters.is_empty() {
939 return Ok(());
940 }
941 let _clock = super::arm_cmd_pack();
944 let client = super::pack()?;
945 let workspace = workspace_of(Some(&client.workspace()));
946 let at = super::now_utc();
947 for letter in &letters {
948 let mut atom = receipt_atom(letter, seat, &at, &workspace);
949 stamp_source(&mut atom);
950 post(&atom, "inbox")?;
951 }
952 Ok(())
953}
954
955fn seats_heard() -> Result<Vec<Value>> {
961 let client = super::pack()?;
962 let workspace = client.workspace();
963 match super::atoms_lean(&client, &workspace) {
964 Err(err) if super::is_pack_busy(&err) => Err(super::pack_busy_err()),
965 other => other.context("mail: the pack did not answer"),
966 }
967}
968
969fn commit_named(until: &str) -> Option<String> {
972 let named = until.trim();
973 if !named.is_empty() {
974 return Some(named.to_string());
975 }
976 std::env::var("LJOS_WAKE_COMMIT")
977 .ok()
978 .map(|value| value.trim().to_string())
979 .filter(|value| !value.is_empty())
980}
981
982fn already_read(atoms: &[Value], msg: &str, seat: &str) -> bool {
983 readers_of(atoms).contains(&(msg.to_string(), seat.to_string()))
984}
985
986fn receipt_atom(msg: &Letter, reader: &str, at: &str, workspace: &str) -> Value {
987 let id = mint_id("receipt", &[msg.id.as_str(), reader, at]);
988 let text = format!("read {}\nby {reader}\nat {at}\nmsg {id}", msg.id);
989 let mut entities = vec![
990 format!("seat:{reader}"),
991 format!("from:{reader}"),
992 format!("to:{}", msg.from),
993 format!("msg:{id}"),
994 format!("receipt:{}", msg.id),
995 ];
996 if let Some(scope) = &msg.scope {
997 entities.push(format!("scope:{scope}"));
998 }
999 json!({
1000 "schema": "inside.atom/v1",
1001 "kind": "receipt",
1002 "level": "explicit",
1003 "text": text,
1004 "workspace": workspace,
1005 "entities": entities,
1006 })
1007}
1008
1009pub fn read(id: &str) -> Result<String> {
1012 let _clock = super::arm_cmd_pack();
1013 let id = id.trim();
1014 if id.is_empty() {
1015 bail!("read: name a message");
1016 }
1017 let atoms = load("read")?;
1018 let seat = super::seat_name();
1019 let letter = find_letter(&atoms, id).context("read")?;
1020 if !letter.to.iter().any(|to| to == &seat) {
1021 bail!("read: {id} is not for {seat}");
1022 }
1023 if already_read(&atoms, id, &seat) {
1024 return Ok(format!("read {id} already\n"));
1025 }
1026 let client = super::pack()?;
1027 let mut atom = receipt_atom(
1028 &letter,
1029 &seat,
1030 &super::now_utc(),
1031 &workspace_of(Some(&client.workspace())),
1032 );
1033 stamp_source(&mut atom);
1034 post(&atom, "read")?;
1035 Ok(format!("read {id}\n"))
1036}
1037
1038fn read_ids(ids: &[String]) {
1039 let Some(atoms) = load_quiet() else {
1040 return;
1041 };
1042 let seat = super::seat_name();
1043 let Ok(client) = super::pack() else {
1044 return;
1045 };
1046 let workspace = client.workspace();
1047 let at = super::now_utc();
1048 for id in ids {
1049 let Ok(letter) = find_letter(&atoms, id) else {
1050 continue;
1051 };
1052 if !letter.to.iter().any(|to| to == &seat) || already_read(&atoms, id, &seat) {
1053 continue;
1054 }
1055 let mut atom = receipt_atom(&letter, &seat, &at, &workspace_of(Some(&workspace)));
1056 stamp_source(&mut atom);
1057 let _ = post(&atom, "read");
1058 }
1059}
1060
1061pub fn reply(id: &str, text: &str, interrupt: bool) -> Result<String> {
1063 let _clock = super::arm_cmd_pack();
1064 let id = id.trim();
1065 let text = text.trim();
1066 if id.is_empty() {
1067 bail!("reply: name a message");
1068 }
1069 if text.is_empty() {
1070 bail!("reply: empty text");
1071 }
1072 check_length("reply", text)?;
1073 let atoms = load("reply")?;
1074 let parent = find_letter(&atoms, id).context("reply")?;
1075 let from = super::seat_name();
1076 if parent.from == from {
1077 bail!("reply: {id} is from this seat");
1078 }
1079 let issue = parent.issue.clone();
1080 let scope = issue
1081 .as_deref()
1082 .and_then(super::sync::scope_for_issue)
1083 .or(parent.scope);
1084 let outgoing = Outgoing {
1085 id: mint_id("msg", &[&from, id, text]),
1086 from,
1087 to: vec![parent.from.clone()],
1088 body: text.to_string(),
1089 interrupt,
1090 issue,
1091 group: None,
1092 reply: Some(parent.id.clone()),
1093 scope,
1094 };
1095 let client = super::pack()?;
1096 let mut atom = message_atom(&outgoing, &workspace_of(Some(&client.workspace())));
1097 stamp_source(&mut atom);
1098 post(&atom, "reply")?;
1099 let mut line = format!(
1100 "sent {} to {}\nreply {}\n",
1101 outgoing.id, parent.from, parent.id
1102 );
1103 if let Some(issue) = &outgoing.issue {
1104 line.push_str(&format!("issue {issue}\n"));
1105 }
1106 line.push_str(&wake_after(&outgoing));
1107 Ok(line)
1108}
1109
1110fn group_atom(name: &str, seat: &str, drop: bool, by: &str, workspace: &str) -> Value {
1111 let at = super::now_utc();
1112 let id = mint_id("group", &[name, seat, by, &at]);
1113 let verb = if drop { "drop" } else { "member" };
1114 let text = format!("group {id}\nname {name}\n{verb} {seat}\nby {by}\nat {at}");
1115 let mut entities = vec![
1116 format!("seat:{by}"),
1117 format!("group:{name}"),
1118 format!("msg:{id}"),
1119 ];
1120 if drop {
1121 entities.push(format!("drop:{seat}"));
1122 } else {
1123 entities.push(format!("member:{seat}"));
1124 }
1125 json!({
1126 "schema": "inside.atom/v1",
1127 "kind": "group",
1128 "level": "explicit",
1129 "text": text,
1130 "workspace": workspace,
1131 "entities": entities,
1132 })
1133}
1134
1135pub fn group(name: &str, add: &[String], remove: &[String]) -> Result<String> {
1137 let _clock = super::arm_cmd_pack();
1138 let name = check_name("group", name)?;
1139 if add.is_empty() && remove.is_empty() {
1140 let atoms = load("group")?;
1141 let seats = members(&atoms, &name);
1142 if seats.is_empty() {
1143 return Ok(format!("{name}\t(no members)\n"));
1144 }
1145 let mut out = String::new();
1146 for seat in seats {
1147 out.push_str(&format!("{name}\t{seat}\n"));
1148 }
1149 return Ok(out);
1150 }
1151 let atoms = load("group")?;
1152 let by = super::seat_name();
1153 let client = super::pack()?;
1154 let workspace = client.workspace();
1155 let mut roster = members(&atoms, &name);
1156 let mut out = String::new();
1157 for seat in add {
1158 let seat = check_name("group", seat)?;
1159 if roster.iter().any(|s| s == &seat) {
1160 out.push_str(&format!("{seat} is already in {name}\n"));
1161 continue;
1162 }
1163 let mut atom = group_atom(&name, &seat, false, &by, &workspace_of(Some(&workspace)));
1164 stamp_source(&mut atom);
1165 post(&atom, "group")?;
1166 roster.push(seat.clone());
1167 out.push_str(&format!("added {seat} to {name}\n"));
1168 }
1169 for seat in remove {
1170 let seat = check_name("group", seat)?;
1171 if !roster.iter().any(|s| s == &seat) {
1172 out.push_str(&format!("{seat} is not in {name}\n"));
1173 continue;
1174 }
1175 let mut atom = group_atom(&name, &seat, true, &by, &workspace_of(Some(&workspace)));
1176 stamp_source(&mut atom);
1177 post(&atom, "group")?;
1178 roster.retain(|s| s != &seat);
1179 out.push_str(&format!("removed {seat} from {name}\n"));
1180 }
1181 Ok(out)
1182}
1183
1184fn state_dir() -> PathBuf {
1185 std::env::var_os("XDG_STATE_HOME")
1186 .map(PathBuf::from)
1187 .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/state")))
1188 .unwrap_or_else(|| PathBuf::from(".local/state"))
1189 .join("ljos")
1190 .join("mail")
1191}
1192
1193fn receipt_seen_path() -> PathBuf {
1194 state_dir().join("receipts-seen")
1195}
1196
1197fn receipt_seen() -> BTreeSet<String> {
1198 std::fs::read_to_string(receipt_seen_path())
1199 .map(|text| {
1200 text.lines()
1201 .map(str::trim)
1202 .filter(|l| !l.is_empty())
1203 .map(str::to_string)
1204 .collect()
1205 })
1206 .unwrap_or_default()
1207}
1208
1209fn remember_receipts(keys: &[String]) {
1210 if keys.is_empty() {
1211 return;
1212 }
1213 let path = receipt_seen_path();
1214 if let Some(dir) = path.parent() {
1215 let _ = std::fs::create_dir_all(dir);
1216 }
1217 let mut text = std::fs::read_to_string(&path).unwrap_or_default();
1218 for key in keys {
1219 if text.lines().any(|l| l == key) {
1220 continue;
1221 }
1222 text.push_str(key);
1223 text.push('\n');
1224 }
1225 let _ = std::fs::write(path, text);
1226}
1227
1228pub const MAIL_UNCHECKED: &str = "mail could not be checked";
1232
1233#[must_use]
1237pub fn prompt_note() -> (String, Vec<String>) {
1238 let atoms = match listed() {
1241 Ok(atoms) => atoms,
1242 Err(err) if super::is_pack_busy(&err) => return (String::new(), Vec::new()),
1243 Err(_) => return (MAIL_UNCHECKED.to_string(), Vec::new()),
1244 };
1245 let seat = super::seat_name();
1246 let letters = inbox_letters(&atoms, &seat, false);
1247 let seen = receipt_seen();
1248 let receipts: Vec<Receipt> = receipts_for(&atoms, &seat)
1249 .into_iter()
1250 .filter(|r| !seen.contains(&r.key))
1251 .collect();
1252 prompt_lines(&letters, &receipts)
1253}
1254
1255pub const STOP_MAIL_HEAD: &str =
1257 "Mail marked interrupt reached this seat while you worked. Read it before you stop:";
1258
1259#[must_use]
1266pub fn stop_note() -> (String, Vec<String>) {
1267 let Ok(atoms) = listed() else {
1268 return (String::new(), Vec::new());
1269 };
1270 stop_lines(&atoms, &super::seat_name())
1271}
1272
1273#[must_use]
1275pub fn stop_lines(atoms: &[Value], seat: &str) -> (String, Vec<String>) {
1276 let hot: Vec<Letter> = inbox_letters(atoms, seat, false)
1277 .into_iter()
1278 .filter(|l| l.interrupt)
1279 .collect();
1280 let (lines, ids) = prompt_lines(&hot, &[]);
1281 if lines.is_empty() {
1282 return (String::new(), Vec::new());
1283 }
1284 let reply = "Answer with `ljos reply ID TEXT`.";
1285 (format!("{STOP_MAIL_HEAD}\n{lines}\n{reply}"), ids)
1286}
1287
1288pub fn ack_delivered(ids: &[String]) {
1292 let mut reads = Vec::new();
1293 let mut seen = Vec::new();
1294 for id in ids {
1295 if let Some(msg) = id.strip_prefix("mail:") {
1296 reads.push(msg.to_string());
1297 } else if let Some(key) = id.strip_prefix("rcpt:") {
1298 seen.push(key.to_string());
1299 }
1300 }
1301 if !reads.is_empty() {
1302 read_ids(&reads);
1303 }
1304 remember_receipts(&seen);
1305}
1306
1307#[cfg(test)]
1308mod tests {
1309 use super::*;
1310
1311 fn outgoing(id: &str, from: &str, to: &[&str], body: &str) -> Outgoing {
1312 Outgoing {
1313 id: id.to_string(),
1314 from: from.to_string(),
1315 to: to.iter().map(|s| (*s).to_string()).collect(),
1316 body: body.to_string(),
1317 interrupt: false,
1318 issue: None,
1319 group: None,
1320 reply: None,
1321 scope: None,
1322 }
1323 }
1324
1325 #[test]
1326 fn a_long_body_fits_the_pack_and_reads_back_whole() {
1327 let long = "the aarch64 log says the Highway test times out. ".repeat(40);
1328 let m = outgoing("msg-1", "saddle", &["inky"], &long);
1329 let atom = message_atom(&m, "seat");
1330 let text = atom["text"].as_str().unwrap();
1331 assert!(
1332 text.chars().count() <= ATOM_TEXT_CAP,
1333 "{}",
1334 text.chars().count()
1335 );
1336 assert!(text.ends_with('\u{2026}'), "{text}");
1337 assert!(
1338 text.starts_with("msg msg-1\nfrom saddle\nto inky\n\n"),
1339 "{text}"
1340 );
1341 assert_eq!(atom["body"].as_str(), Some(long.trim()));
1342 let letter = letter_of(&atom, 0).expect("a letter");
1343 assert_eq!(letter.body, long.trim());
1344 let short = message_atom(&outgoing("msg-2", "saddle", &["inky"], "ok"), "seat");
1346 assert!(short.get("body").is_none());
1347 assert_eq!(letter_of(&short, 0).unwrap().body, "ok");
1348 let err = check_length("send", &"x".repeat(MAIL_BODY_CAP + 1))
1350 .unwrap_err()
1351 .to_string();
1352 assert!(err.contains("deedar create file"), "{err}");
1353 assert!(check_length("send", &"x".repeat(MAIL_BODY_CAP)).is_ok());
1354 let shown = prompt_body(&long);
1355 assert!(shown.contains("`ljos inbox --all`"), "{shown}");
1356 assert_eq!(prompt_body("ok"), "ok");
1357 }
1358
1359 fn atom(m: &Outgoing, ts: &str) -> Value {
1360 let mut v = message_atom(m, "seat");
1361 v["ts"] = json!(ts);
1362 v
1363 }
1364
1365 #[test]
1366 fn the_same_words_stay_two_messages() {
1367 let a = outgoing("a", "alice", &["bob"], "ok");
1368 let b = outgoing("b", "carol", &["bob"], "ok");
1369 let left = message_text(&a);
1370 let right = message_text(&b);
1371 assert_ne!(left, right);
1372 assert_ne!(super::super::work_id(&left), super::super::work_id(&right));
1373 assert_eq!(body_of(&left), "ok");
1374 let atoms = [
1375 atom(&a, "2026-10-09T00:00:00Z"),
1376 atom(&b, "2026-10-09T00:00:01Z"),
1377 ];
1378 let plain = super::super::sync::log_plaintext(&atoms, "seat", "seat");
1379 assert_eq!(plain.lines().count(), 2, "{plain}");
1380 let got = super::super::sync::incoming(&plain, "other", &BTreeSet::new(), &BTreeSet::new());
1381 assert_eq!(got.post.len(), 2);
1382 }
1383
1384 #[test]
1385 fn inbox_is_the_seat_named_and_an_interrupt_leads() {
1386 let mut late = outgoing("late", "alice", &["bob"], "when you can");
1387 late.issue = Some("acme-4".into());
1388 let mut hot = outgoing("hot", "carol", &["bob"], "the build is red");
1389 hot.interrupt = true;
1390 hot.issue = Some("acme-4".into());
1391 let other = outgoing("other", "alice", &["dave"], "not for bob");
1392 let atoms = [
1393 atom(&late, "2026-10-09T00:00:00Z"),
1394 atom(&hot, "2026-10-09T00:00:02Z"),
1395 atom(&other, "2026-10-09T00:00:01Z"),
1396 ];
1397 let letters = inbox_letters(&atoms, "bob", false);
1398 assert_eq!(
1399 letters.iter().map(|l| l.id.as_str()).collect::<Vec<_>>(),
1400 ["hot", "late"]
1401 );
1402 assert!(letters[0].interrupt);
1403 assert_eq!(letters[1].issue.as_deref(), Some("acme-4"));
1404 let (text, ids) = prompt_lines(&letters, &[]);
1405 assert!(
1406 text.starts_with("mail:\n! hot from carol on acme-4:"),
1407 "{text}"
1408 );
1409 assert!(ids.contains(&"mail:hot".to_string()), "{ids:?}");
1410 assert!(text.contains("late from alice on acme-4:"));
1411 }
1412
1413 #[test]
1414 fn a_receipt_takes_the_message_out_of_the_unread_list() {
1415 let msg = outgoing("m1", "alice", &["bob"], "look at the log");
1416 let message = atom(&msg, "2026-10-09T00:00:00Z");
1417 let receipt = json!({
1418 "kind": "receipt",
1419 "text": "read m1\nby bob\nat 2026-10-09T00:01:00Z\nmsg r1",
1420 "ts": "2026-10-09T00:01:00Z",
1421 "entities": ["seat:bob", "from:bob", "to:alice", "receipt:m1", "msg:r1"],
1422 });
1423 let held = [message, receipt];
1424 let unread = inbox_letters(&held, "bob", false);
1425 assert!(unread.is_empty());
1426 let all = inbox_letters(&held, "bob", true);
1427 assert!(all[0].read);
1428 let (text, keys) = render_inbox(&held, "alice", false, &BTreeSet::new());
1429 assert!(
1430 text.contains("receipt\tm1\tbob\t2026-10-09T00:01:00Z"),
1431 "{text}"
1432 );
1433 assert_eq!(keys.len(), 1);
1434 let (again, _) = render_inbox(&held, "alice", false, &keys.into_iter().collect());
1435 assert_eq!(again, "inbox: nothing unread\n");
1436 }
1437
1438 #[test]
1439 fn a_reply_keeps_the_issue_and_names_the_sender() {
1440 let mut parent = outgoing("p", "alice", &["bob"], "the build is red");
1441 parent.issue = Some("acme-4".into());
1442 parent.scope = Some("tools".into());
1443 let letter = letter_of(&atom(&parent, "2026-10-09T00:00:00Z"), 0).unwrap();
1444 let reply = Outgoing {
1445 id: "r".into(),
1446 from: "bob".into(),
1447 to: vec![letter.from.clone()],
1448 body: "looking".into(),
1449 interrupt: false,
1450 issue: letter.issue.clone(),
1451 group: None,
1452 reply: Some(letter.id.clone()),
1453 scope: letter.scope.clone(),
1454 };
1455 let atom = message_atom(&reply, "seat");
1456 let back = letter_of(&atom, 1).unwrap();
1457 assert_eq!(back.to, ["alice"]);
1458 assert_eq!(back.reply.as_deref(), Some("p"));
1459 assert_eq!(back.issue.as_deref(), Some("acme-4"));
1460 assert_eq!(back.scope.as_deref(), Some("tools"));
1461 assert!(super::super::sync::is_own(&atom));
1462 }
1463
1464 #[test]
1465 fn a_group_send_reaches_the_other_members() {
1466 let atoms = [
1467 json!({
1468 "kind": "group",
1469 "ts": "2026-10-09T00:00:00Z",
1470 "entities": ["group:ops", "member:alice"],
1471 }),
1472 json!({
1473 "kind": "group",
1474 "ts": "2026-10-09T00:00:01Z",
1475 "entities": ["group:ops", "member:bob"],
1476 }),
1477 json!({
1478 "kind": "group",
1479 "ts": "2026-10-09T00:00:02Z",
1480 "entities": ["group:ops", "member:carol"],
1481 }),
1482 json!({
1483 "kind": "group",
1484 "ts": "2026-10-09T00:00:03Z",
1485 "entities": ["group:ops", "drop:carol"],
1486 }),
1487 ];
1488 assert_eq!(members(&atoms, "ops"), ["alice", "bob"]);
1489 let to = recipients("alice", None, Some("ops"), &members(&atoms, "ops")).unwrap();
1490 assert_eq!(to, ["bob"]);
1491 let err = recipients("alice", None, Some("ops"), &["alice".into()]).unwrap_err();
1492 assert!(err.to_string().contains("no other member"), "{err}");
1493 let err = recipients("alice", Some("alice"), None, &[]).unwrap_err();
1494 assert!(err.to_string().contains("this seat"), "{err}");
1495 }
1496
1497 #[test]
1498 fn a_prompt_caps_the_note_and_keeps_the_rest_unread() {
1499 let letters: Vec<Letter> = (0..10)
1500 .map(|n| Letter {
1501 id: format!("m{n}"),
1502 from: "alice".into(),
1503 to: vec!["bob".into()],
1504 body: format!("line {n}"),
1505 interrupt: n == 9,
1506 issue: None,
1507 group: None,
1508 reply: None,
1509 scope: None,
1510 read: false,
1511 ts: format!("2026-10-09T00:00:{n:02}Z"),
1512 seq: n,
1513 })
1514 .collect();
1515 let mut ordered = letters.clone();
1516 ordered.sort_by(|a, b| b.interrupt.cmp(&a.interrupt).then(a.ts.cmp(&b.ts)));
1517 let (text, ids) = prompt_lines(&ordered, &[]);
1518 assert!(text.lines().next().unwrap() == "mail:");
1519 assert!(text.contains("! m9 from alice:"));
1520 assert!(text.contains("2 more in ljos inbox"), "{text}");
1521 assert_eq!(ids.iter().filter(|id| id.starts_with("mail:")).count(), 8);
1522 assert!(!ids.iter().any(|id| id == "mail:m7" || id == "mail:m8"));
1523 }
1524
1525 #[test]
1526 fn a_seat_hint_names_a_few_seats_and_no_ids() {
1527 let known: BTreeSet<String> = [
1528 "alpha",
1529 "bravo",
1530 "charlie",
1531 "delta",
1532 "echo",
1533 "foxtrot",
1534 "saddle",
1535 "01a0dab3-895e-7533-93ca-c9807d5cb680",
1536 "sess-4f2a9c0d1e2b3a4f",
1537 ]
1538 .iter()
1539 .map(|s| (*s).to_string())
1540 .collect();
1541 assert!(named_seat("codex-vax0"));
1542 assert!(named_seat("disk-saver"));
1543 assert!(!named_seat("01a0dab3-895e-7533-93ca-c9807d5cb680"));
1544 assert!(!named_seat("sess-4f2a9c0d1e2b3a4f"));
1545 let hint = seat_hint("sadle", &known);
1546 assert_eq!(
1547 hint,
1548 "Did you mean saddle? Other seats: alpha, bravo, charlie, delta and 2 more."
1549 );
1550 let hint = seat_hint("zzz", &known);
1551 assert_eq!(hint, "Seats here: alpha, bravo, charlie, delta and 3 more.");
1552 let ids: BTreeSet<String> = ["01a0dab3-895e-7533-93ca-c9807d5cb680".to_string()].into();
1553 assert_eq!(
1554 seat_hint("codex", &ids),
1555 "No named seat has started here yet."
1556 );
1557 let err = check_known("sadle", &known, false).unwrap_err().to_string();
1558 assert!(!err.contains("01a0dab3"), "{err}");
1559 assert!(err.contains("Did you mean saddle?"), "{err}");
1560 }
1561
1562 #[test]
1563 fn a_misspelt_seat_is_answered_with_the_seat_it_meant() {
1564 let known: BTreeSet<String> = ["ljos-bot", "saddle", "inky"]
1565 .iter()
1566 .map(|s| (*s).to_string())
1567 .collect();
1568 assert_eq!(closest_seat("ljos", &known), Some("ljos-bot"));
1569 assert_eq!(closest_seat("sadle", &known), Some("saddle"));
1570 assert_eq!(closest_seat("eessi", &known), None);
1571 let err = check_known("ljos", &known, false).unwrap_err().to_string();
1572 assert!(err.contains("Did you mean ljos-bot?"), "{err}");
1573 let err = check_known("eessi", &known, false).unwrap_err().to_string();
1574 assert!(!err.contains("Did you mean"), "{err}");
1575 assert!(check_known("eessi", &known, true).is_ok());
1576 }
1577
1578 #[test]
1579 fn a_stop_carries_unread_interrupt_mail_only() {
1580 let plain = outgoing("plain", "grok", &["claude"], "when you can");
1581 let mut hot = outgoing("hot", "grok", &["claude"], "take ticket-d9n6 now");
1582 hot.interrupt = true;
1583 hot.issue = Some("ticket-d9n6".into());
1584 let atoms = [
1585 atom(&plain, "2026-10-11T00:00:00Z"),
1586 atom(&hot, "2026-10-11T00:00:01Z"),
1587 ];
1588 let (text, ids) = stop_lines(&atoms, "claude");
1589 assert!(text.starts_with(STOP_MAIL_HEAD), "{text}");
1590 assert!(
1591 text.contains("! hot from grok on ticket-d9n6: take ticket-d9n6 now"),
1592 "{text}"
1593 );
1594 assert!(!text.contains("when you can"), "{text}");
1595 assert_eq!(ids, ["mail:hot"]);
1596 let read = json!({
1597 "kind": "receipt",
1598 "text": "read hot\nby claude\nat 2026-10-11T00:00:02Z\nmsg r1",
1599 "entities": ["seat:claude", "from:claude", "to:grok", "receipt:hot", "msg:r1"],
1600 });
1601 let after = [atoms[0].clone(), atoms[1].clone(), read];
1602 assert_eq!(stop_lines(&after, "claude"), (String::new(), Vec::new()));
1603 assert_eq!(stop_lines(&atoms, "grok"), (String::new(), Vec::new()));
1604 }
1605
1606 #[test]
1607 fn an_unknown_kind_is_a_pack_without_mail() {
1608 let refused =
1609 "bad response: http://127.0.0.1:8761/v1/atoms: 400: unknown atom kind: message";
1610 assert_eq!(probe_of(refused), Probe::Refused);
1611 let kept = "bad response: http://127.0.0.1:8761/v1/atoms: 400: atom text is required";
1612 assert_eq!(probe_of(kept), Probe::Kept);
1613 let level = "bad response: http://127.0.0.1:8761/v1/atoms: 400: unknown atom level: nope";
1614 assert_eq!(probe_of(level), Probe::Kept);
1615 let dump =
1619 "bad response: http://127.0.0.1:8761/v1/atoms: 400: tool dump is attach, not an atom";
1620 assert_eq!(probe_of(dump), Probe::Kept);
1621 let down = "http://127.0.0.1:8761/v1/atoms: http: connection refused";
1622 assert_eq!(probe_of(down), Probe::Store);
1623 let named = unsupported_mail(Some("0.12.1"));
1624 assert!(named.contains("packset 0.12.1"), "{named}");
1625 assert!(named.contains(MAIL_PACKSET), "{named}");
1626 assert!(named.contains("kind message"), "{named}");
1627 let quiet = unsupported_mail(None);
1628 assert!(quiet.contains(MAIL_PACKSET), "{quiet}");
1629 assert!(quiet.contains("refused kind message"), "{quiet}");
1630 }
1631}