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 _clock = super::arm_cmd_pack();
915 let atoms = load("inbox")?;
916 let seat = super::seat_name();
917 let seen = receipt_seen();
918 let (text, keys) = render_inbox(&atoms, &seat, all, &seen);
919 remember_receipts(&keys);
920 mark_shown(&atoms, &seat)?;
921 Ok(text)
922}
923
924fn mark_shown(atoms: &[Value], seat: &str) -> Result<()> {
927 let letters = inbox_letters(atoms, seat, false);
928 if letters.is_empty() {
929 return Ok(());
930 }
931 let client = super::pack()?;
932 let workspace = workspace_of(Some(&client.workspace()));
933 let at = super::now_utc();
934 for letter in &letters {
935 let mut atom = receipt_atom(letter, seat, &at, &workspace);
936 stamp_source(&mut atom);
937 post(&atom, "inbox")?;
938 }
939 Ok(())
940}
941
942fn seats_heard() -> Result<Vec<Value>> {
948 let client = super::pack()?;
949 let workspace = client.workspace();
950 match super::atoms_lean(&client, &workspace) {
951 Err(err) if super::is_pack_busy(&err) => Err(super::pack_busy_err()),
952 other => other.context("mail: the pack did not answer"),
953 }
954}
955
956fn commit_named(until: &str) -> Option<String> {
959 let named = until.trim();
960 if !named.is_empty() {
961 return Some(named.to_string());
962 }
963 std::env::var("LJOS_WAKE_COMMIT")
964 .ok()
965 .map(|value| value.trim().to_string())
966 .filter(|value| !value.is_empty())
967}
968
969fn already_read(atoms: &[Value], msg: &str, seat: &str) -> bool {
970 readers_of(atoms).contains(&(msg.to_string(), seat.to_string()))
971}
972
973fn receipt_atom(msg: &Letter, reader: &str, at: &str, workspace: &str) -> Value {
974 let id = mint_id("receipt", &[msg.id.as_str(), reader, at]);
975 let text = format!("read {}\nby {reader}\nat {at}\nmsg {id}", msg.id);
976 let mut entities = vec![
977 format!("seat:{reader}"),
978 format!("from:{reader}"),
979 format!("to:{}", msg.from),
980 format!("msg:{id}"),
981 format!("receipt:{}", msg.id),
982 ];
983 if let Some(scope) = &msg.scope {
984 entities.push(format!("scope:{scope}"));
985 }
986 json!({
987 "schema": "inside.atom/v1",
988 "kind": "receipt",
989 "level": "explicit",
990 "text": text,
991 "workspace": workspace,
992 "entities": entities,
993 })
994}
995
996pub fn read(id: &str) -> Result<String> {
999 let _clock = super::arm_cmd_pack();
1000 let id = id.trim();
1001 if id.is_empty() {
1002 bail!("read: name a message");
1003 }
1004 let atoms = load("read")?;
1005 let seat = super::seat_name();
1006 let letter = find_letter(&atoms, id).context("read")?;
1007 if !letter.to.iter().any(|to| to == &seat) {
1008 bail!("read: {id} is not for {seat}");
1009 }
1010 if already_read(&atoms, id, &seat) {
1011 return Ok(format!("read {id} already\n"));
1012 }
1013 let client = super::pack()?;
1014 let mut atom = receipt_atom(
1015 &letter,
1016 &seat,
1017 &super::now_utc(),
1018 &workspace_of(Some(&client.workspace())),
1019 );
1020 stamp_source(&mut atom);
1021 post(&atom, "read")?;
1022 Ok(format!("read {id}\n"))
1023}
1024
1025fn read_ids(ids: &[String]) {
1026 let Some(atoms) = load_quiet() else {
1027 return;
1028 };
1029 let seat = super::seat_name();
1030 let Ok(client) = super::pack() else {
1031 return;
1032 };
1033 let workspace = client.workspace();
1034 let at = super::now_utc();
1035 for id in ids {
1036 let Ok(letter) = find_letter(&atoms, id) else {
1037 continue;
1038 };
1039 if !letter.to.iter().any(|to| to == &seat) || already_read(&atoms, id, &seat) {
1040 continue;
1041 }
1042 let mut atom = receipt_atom(&letter, &seat, &at, &workspace_of(Some(&workspace)));
1043 stamp_source(&mut atom);
1044 let _ = post(&atom, "read");
1045 }
1046}
1047
1048pub fn reply(id: &str, text: &str, interrupt: bool) -> Result<String> {
1050 let _clock = super::arm_cmd_pack();
1051 let id = id.trim();
1052 let text = text.trim();
1053 if id.is_empty() {
1054 bail!("reply: name a message");
1055 }
1056 if text.is_empty() {
1057 bail!("reply: empty text");
1058 }
1059 check_length("reply", text)?;
1060 let atoms = load("reply")?;
1061 let parent = find_letter(&atoms, id).context("reply")?;
1062 let from = super::seat_name();
1063 if parent.from == from {
1064 bail!("reply: {id} is from this seat");
1065 }
1066 let issue = parent.issue.clone();
1067 let scope = issue
1068 .as_deref()
1069 .and_then(super::sync::scope_for_issue)
1070 .or(parent.scope);
1071 let outgoing = Outgoing {
1072 id: mint_id("msg", &[&from, id, text]),
1073 from,
1074 to: vec![parent.from.clone()],
1075 body: text.to_string(),
1076 interrupt,
1077 issue,
1078 group: None,
1079 reply: Some(parent.id.clone()),
1080 scope,
1081 };
1082 let client = super::pack()?;
1083 let mut atom = message_atom(&outgoing, &workspace_of(Some(&client.workspace())));
1084 stamp_source(&mut atom);
1085 post(&atom, "reply")?;
1086 let mut line = format!(
1087 "sent {} to {}\nreply {}\n",
1088 outgoing.id, parent.from, parent.id
1089 );
1090 if let Some(issue) = &outgoing.issue {
1091 line.push_str(&format!("issue {issue}\n"));
1092 }
1093 line.push_str(&wake_after(&outgoing));
1094 Ok(line)
1095}
1096
1097fn group_atom(name: &str, seat: &str, drop: bool, by: &str, workspace: &str) -> Value {
1098 let at = super::now_utc();
1099 let id = mint_id("group", &[name, seat, by, &at]);
1100 let verb = if drop { "drop" } else { "member" };
1101 let text = format!("group {id}\nname {name}\n{verb} {seat}\nby {by}\nat {at}");
1102 let mut entities = vec![
1103 format!("seat:{by}"),
1104 format!("group:{name}"),
1105 format!("msg:{id}"),
1106 ];
1107 if drop {
1108 entities.push(format!("drop:{seat}"));
1109 } else {
1110 entities.push(format!("member:{seat}"));
1111 }
1112 json!({
1113 "schema": "inside.atom/v1",
1114 "kind": "group",
1115 "level": "explicit",
1116 "text": text,
1117 "workspace": workspace,
1118 "entities": entities,
1119 })
1120}
1121
1122pub fn group(name: &str, add: &[String], remove: &[String]) -> Result<String> {
1124 let _clock = super::arm_cmd_pack();
1125 let name = check_name("group", name)?;
1126 if add.is_empty() && remove.is_empty() {
1127 let atoms = load("group")?;
1128 let seats = members(&atoms, &name);
1129 if seats.is_empty() {
1130 return Ok(format!("{name}\t(no members)\n"));
1131 }
1132 let mut out = String::new();
1133 for seat in seats {
1134 out.push_str(&format!("{name}\t{seat}\n"));
1135 }
1136 return Ok(out);
1137 }
1138 let atoms = load("group")?;
1139 let by = super::seat_name();
1140 let client = super::pack()?;
1141 let workspace = client.workspace();
1142 let mut roster = members(&atoms, &name);
1143 let mut out = String::new();
1144 for seat in add {
1145 let seat = check_name("group", seat)?;
1146 if roster.iter().any(|s| s == &seat) {
1147 out.push_str(&format!("{seat} is already in {name}\n"));
1148 continue;
1149 }
1150 let mut atom = group_atom(&name, &seat, false, &by, &workspace_of(Some(&workspace)));
1151 stamp_source(&mut atom);
1152 post(&atom, "group")?;
1153 roster.push(seat.clone());
1154 out.push_str(&format!("added {seat} to {name}\n"));
1155 }
1156 for seat in remove {
1157 let seat = check_name("group", seat)?;
1158 if !roster.iter().any(|s| s == &seat) {
1159 out.push_str(&format!("{seat} is not in {name}\n"));
1160 continue;
1161 }
1162 let mut atom = group_atom(&name, &seat, true, &by, &workspace_of(Some(&workspace)));
1163 stamp_source(&mut atom);
1164 post(&atom, "group")?;
1165 roster.retain(|s| s != &seat);
1166 out.push_str(&format!("removed {seat} from {name}\n"));
1167 }
1168 Ok(out)
1169}
1170
1171fn state_dir() -> PathBuf {
1172 std::env::var_os("XDG_STATE_HOME")
1173 .map(PathBuf::from)
1174 .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/state")))
1175 .unwrap_or_else(|| PathBuf::from(".local/state"))
1176 .join("ljos")
1177 .join("mail")
1178}
1179
1180fn receipt_seen_path() -> PathBuf {
1181 state_dir().join("receipts-seen")
1182}
1183
1184fn receipt_seen() -> BTreeSet<String> {
1185 std::fs::read_to_string(receipt_seen_path())
1186 .map(|text| {
1187 text.lines()
1188 .map(str::trim)
1189 .filter(|l| !l.is_empty())
1190 .map(str::to_string)
1191 .collect()
1192 })
1193 .unwrap_or_default()
1194}
1195
1196fn remember_receipts(keys: &[String]) {
1197 if keys.is_empty() {
1198 return;
1199 }
1200 let path = receipt_seen_path();
1201 if let Some(dir) = path.parent() {
1202 let _ = std::fs::create_dir_all(dir);
1203 }
1204 let mut text = std::fs::read_to_string(&path).unwrap_or_default();
1205 for key in keys {
1206 if text.lines().any(|l| l == key) {
1207 continue;
1208 }
1209 text.push_str(key);
1210 text.push('\n');
1211 }
1212 let _ = std::fs::write(path, text);
1213}
1214
1215pub const MAIL_UNCHECKED: &str = "mail could not be checked";
1219
1220#[must_use]
1224pub fn prompt_note() -> (String, Vec<String>) {
1225 let atoms = match listed() {
1228 Ok(atoms) => atoms,
1229 Err(err) if super::is_pack_busy(&err) => return (String::new(), Vec::new()),
1230 Err(_) => return (MAIL_UNCHECKED.to_string(), Vec::new()),
1231 };
1232 let seat = super::seat_name();
1233 let letters = inbox_letters(&atoms, &seat, false);
1234 let seen = receipt_seen();
1235 let receipts: Vec<Receipt> = receipts_for(&atoms, &seat)
1236 .into_iter()
1237 .filter(|r| !seen.contains(&r.key))
1238 .collect();
1239 prompt_lines(&letters, &receipts)
1240}
1241
1242pub const STOP_MAIL_HEAD: &str =
1244 "Mail marked interrupt reached this seat while you worked. Read it before you stop:";
1245
1246#[must_use]
1253pub fn stop_note() -> (String, Vec<String>) {
1254 let Ok(atoms) = listed() else {
1255 return (String::new(), Vec::new());
1256 };
1257 stop_lines(&atoms, &super::seat_name())
1258}
1259
1260#[must_use]
1262pub fn stop_lines(atoms: &[Value], seat: &str) -> (String, Vec<String>) {
1263 let hot: Vec<Letter> = inbox_letters(atoms, seat, false)
1264 .into_iter()
1265 .filter(|l| l.interrupt)
1266 .collect();
1267 let (lines, ids) = prompt_lines(&hot, &[]);
1268 if lines.is_empty() {
1269 return (String::new(), Vec::new());
1270 }
1271 let reply = "Answer with `ljos reply ID TEXT`.";
1272 (format!("{STOP_MAIL_HEAD}\n{lines}\n{reply}"), ids)
1273}
1274
1275pub fn ack_delivered(ids: &[String]) {
1279 let mut reads = Vec::new();
1280 let mut seen = Vec::new();
1281 for id in ids {
1282 if let Some(msg) = id.strip_prefix("mail:") {
1283 reads.push(msg.to_string());
1284 } else if let Some(key) = id.strip_prefix("rcpt:") {
1285 seen.push(key.to_string());
1286 }
1287 }
1288 if !reads.is_empty() {
1289 read_ids(&reads);
1290 }
1291 remember_receipts(&seen);
1292}
1293
1294#[cfg(test)]
1295mod tests {
1296 use super::*;
1297
1298 fn outgoing(id: &str, from: &str, to: &[&str], body: &str) -> Outgoing {
1299 Outgoing {
1300 id: id.to_string(),
1301 from: from.to_string(),
1302 to: to.iter().map(|s| (*s).to_string()).collect(),
1303 body: body.to_string(),
1304 interrupt: false,
1305 issue: None,
1306 group: None,
1307 reply: None,
1308 scope: None,
1309 }
1310 }
1311
1312 #[test]
1313 fn a_long_body_fits_the_pack_and_reads_back_whole() {
1314 let long = "the aarch64 log says the Highway test times out. ".repeat(40);
1315 let m = outgoing("msg-1", "saddle", &["inky"], &long);
1316 let atom = message_atom(&m, "seat");
1317 let text = atom["text"].as_str().unwrap();
1318 assert!(
1319 text.chars().count() <= ATOM_TEXT_CAP,
1320 "{}",
1321 text.chars().count()
1322 );
1323 assert!(text.ends_with('\u{2026}'), "{text}");
1324 assert!(
1325 text.starts_with("msg msg-1\nfrom saddle\nto inky\n\n"),
1326 "{text}"
1327 );
1328 assert_eq!(atom["body"].as_str(), Some(long.trim()));
1329 let letter = letter_of(&atom, 0).expect("a letter");
1330 assert_eq!(letter.body, long.trim());
1331 let short = message_atom(&outgoing("msg-2", "saddle", &["inky"], "ok"), "seat");
1333 assert!(short.get("body").is_none());
1334 assert_eq!(letter_of(&short, 0).unwrap().body, "ok");
1335 let err = check_length("send", &"x".repeat(MAIL_BODY_CAP + 1))
1337 .unwrap_err()
1338 .to_string();
1339 assert!(err.contains("deedar create file"), "{err}");
1340 assert!(check_length("send", &"x".repeat(MAIL_BODY_CAP)).is_ok());
1341 let shown = prompt_body(&long);
1342 assert!(shown.contains("`ljos inbox --all`"), "{shown}");
1343 assert_eq!(prompt_body("ok"), "ok");
1344 }
1345
1346 fn atom(m: &Outgoing, ts: &str) -> Value {
1347 let mut v = message_atom(m, "seat");
1348 v["ts"] = json!(ts);
1349 v
1350 }
1351
1352 #[test]
1353 fn the_same_words_stay_two_messages() {
1354 let a = outgoing("a", "alice", &["bob"], "ok");
1355 let b = outgoing("b", "carol", &["bob"], "ok");
1356 let left = message_text(&a);
1357 let right = message_text(&b);
1358 assert_ne!(left, right);
1359 assert_ne!(super::super::work_id(&left), super::super::work_id(&right));
1360 assert_eq!(body_of(&left), "ok");
1361 let atoms = [
1362 atom(&a, "2026-10-09T00:00:00Z"),
1363 atom(&b, "2026-10-09T00:00:01Z"),
1364 ];
1365 let plain = super::super::sync::log_plaintext(&atoms, "seat", "seat");
1366 assert_eq!(plain.lines().count(), 2, "{plain}");
1367 let got = super::super::sync::incoming(&plain, "other", &BTreeSet::new(), &BTreeSet::new());
1368 assert_eq!(got.post.len(), 2);
1369 }
1370
1371 #[test]
1372 fn inbox_is_the_seat_named_and_an_interrupt_leads() {
1373 let mut late = outgoing("late", "alice", &["bob"], "when you can");
1374 late.issue = Some("acme-4".into());
1375 let mut hot = outgoing("hot", "carol", &["bob"], "the build is red");
1376 hot.interrupt = true;
1377 hot.issue = Some("acme-4".into());
1378 let other = outgoing("other", "alice", &["dave"], "not for bob");
1379 let atoms = [
1380 atom(&late, "2026-10-09T00:00:00Z"),
1381 atom(&hot, "2026-10-09T00:00:02Z"),
1382 atom(&other, "2026-10-09T00:00:01Z"),
1383 ];
1384 let letters = inbox_letters(&atoms, "bob", false);
1385 assert_eq!(
1386 letters.iter().map(|l| l.id.as_str()).collect::<Vec<_>>(),
1387 ["hot", "late"]
1388 );
1389 assert!(letters[0].interrupt);
1390 assert_eq!(letters[1].issue.as_deref(), Some("acme-4"));
1391 let (text, ids) = prompt_lines(&letters, &[]);
1392 assert!(
1393 text.starts_with("mail:\n! hot from carol on acme-4:"),
1394 "{text}"
1395 );
1396 assert!(ids.contains(&"mail:hot".to_string()), "{ids:?}");
1397 assert!(text.contains("late from alice on acme-4:"));
1398 }
1399
1400 #[test]
1401 fn a_receipt_takes_the_message_out_of_the_unread_list() {
1402 let msg = outgoing("m1", "alice", &["bob"], "look at the log");
1403 let message = atom(&msg, "2026-10-09T00:00:00Z");
1404 let receipt = json!({
1405 "kind": "receipt",
1406 "text": "read m1\nby bob\nat 2026-10-09T00:01:00Z\nmsg r1",
1407 "ts": "2026-10-09T00:01:00Z",
1408 "entities": ["seat:bob", "from:bob", "to:alice", "receipt:m1", "msg:r1"],
1409 });
1410 let held = [message, receipt];
1411 let unread = inbox_letters(&held, "bob", false);
1412 assert!(unread.is_empty());
1413 let all = inbox_letters(&held, "bob", true);
1414 assert!(all[0].read);
1415 let (text, keys) = render_inbox(&held, "alice", false, &BTreeSet::new());
1416 assert!(
1417 text.contains("receipt\tm1\tbob\t2026-10-09T00:01:00Z"),
1418 "{text}"
1419 );
1420 assert_eq!(keys.len(), 1);
1421 let (again, _) = render_inbox(&held, "alice", false, &keys.into_iter().collect());
1422 assert_eq!(again, "inbox: nothing unread\n");
1423 }
1424
1425 #[test]
1426 fn a_reply_keeps_the_issue_and_names_the_sender() {
1427 let mut parent = outgoing("p", "alice", &["bob"], "the build is red");
1428 parent.issue = Some("acme-4".into());
1429 parent.scope = Some("tools".into());
1430 let letter = letter_of(&atom(&parent, "2026-10-09T00:00:00Z"), 0).unwrap();
1431 let reply = Outgoing {
1432 id: "r".into(),
1433 from: "bob".into(),
1434 to: vec![letter.from.clone()],
1435 body: "looking".into(),
1436 interrupt: false,
1437 issue: letter.issue.clone(),
1438 group: None,
1439 reply: Some(letter.id.clone()),
1440 scope: letter.scope.clone(),
1441 };
1442 let atom = message_atom(&reply, "seat");
1443 let back = letter_of(&atom, 1).unwrap();
1444 assert_eq!(back.to, ["alice"]);
1445 assert_eq!(back.reply.as_deref(), Some("p"));
1446 assert_eq!(back.issue.as_deref(), Some("acme-4"));
1447 assert_eq!(back.scope.as_deref(), Some("tools"));
1448 assert!(super::super::sync::is_own(&atom));
1449 }
1450
1451 #[test]
1452 fn a_group_send_reaches_the_other_members() {
1453 let atoms = [
1454 json!({
1455 "kind": "group",
1456 "ts": "2026-10-09T00:00:00Z",
1457 "entities": ["group:ops", "member:alice"],
1458 }),
1459 json!({
1460 "kind": "group",
1461 "ts": "2026-10-09T00:00:01Z",
1462 "entities": ["group:ops", "member:bob"],
1463 }),
1464 json!({
1465 "kind": "group",
1466 "ts": "2026-10-09T00:00:02Z",
1467 "entities": ["group:ops", "member:carol"],
1468 }),
1469 json!({
1470 "kind": "group",
1471 "ts": "2026-10-09T00:00:03Z",
1472 "entities": ["group:ops", "drop:carol"],
1473 }),
1474 ];
1475 assert_eq!(members(&atoms, "ops"), ["alice", "bob"]);
1476 let to = recipients("alice", None, Some("ops"), &members(&atoms, "ops")).unwrap();
1477 assert_eq!(to, ["bob"]);
1478 let err = recipients("alice", None, Some("ops"), &["alice".into()]).unwrap_err();
1479 assert!(err.to_string().contains("no other member"), "{err}");
1480 let err = recipients("alice", Some("alice"), None, &[]).unwrap_err();
1481 assert!(err.to_string().contains("this seat"), "{err}");
1482 }
1483
1484 #[test]
1485 fn a_prompt_caps_the_note_and_keeps_the_rest_unread() {
1486 let letters: Vec<Letter> = (0..10)
1487 .map(|n| Letter {
1488 id: format!("m{n}"),
1489 from: "alice".into(),
1490 to: vec!["bob".into()],
1491 body: format!("line {n}"),
1492 interrupt: n == 9,
1493 issue: None,
1494 group: None,
1495 reply: None,
1496 scope: None,
1497 read: false,
1498 ts: format!("2026-10-09T00:00:{n:02}Z"),
1499 seq: n,
1500 })
1501 .collect();
1502 let mut ordered = letters.clone();
1503 ordered.sort_by(|a, b| b.interrupt.cmp(&a.interrupt).then(a.ts.cmp(&b.ts)));
1504 let (text, ids) = prompt_lines(&ordered, &[]);
1505 assert!(text.lines().next().unwrap() == "mail:");
1506 assert!(text.contains("! m9 from alice:"));
1507 assert!(text.contains("2 more in ljos inbox"), "{text}");
1508 assert_eq!(ids.iter().filter(|id| id.starts_with("mail:")).count(), 8);
1509 assert!(!ids.iter().any(|id| id == "mail:m7" || id == "mail:m8"));
1510 }
1511
1512 #[test]
1513 fn a_seat_hint_names_a_few_seats_and_no_ids() {
1514 let known: BTreeSet<String> = [
1515 "alpha",
1516 "bravo",
1517 "charlie",
1518 "delta",
1519 "echo",
1520 "foxtrot",
1521 "saddle",
1522 "01a0dab3-895e-7533-93ca-c9807d5cb680",
1523 "sess-4f2a9c0d1e2b3a4f",
1524 ]
1525 .iter()
1526 .map(|s| (*s).to_string())
1527 .collect();
1528 assert!(named_seat("codex-vax0"));
1529 assert!(named_seat("disk-saver"));
1530 assert!(!named_seat("01a0dab3-895e-7533-93ca-c9807d5cb680"));
1531 assert!(!named_seat("sess-4f2a9c0d1e2b3a4f"));
1532 let hint = seat_hint("sadle", &known);
1533 assert_eq!(
1534 hint,
1535 "Did you mean saddle? Other seats: alpha, bravo, charlie, delta and 2 more."
1536 );
1537 let hint = seat_hint("zzz", &known);
1538 assert_eq!(hint, "Seats here: alpha, bravo, charlie, delta and 3 more.");
1539 let ids: BTreeSet<String> = ["01a0dab3-895e-7533-93ca-c9807d5cb680".to_string()].into();
1540 assert_eq!(
1541 seat_hint("codex", &ids),
1542 "No named seat has started here yet."
1543 );
1544 let err = check_known("sadle", &known, false).unwrap_err().to_string();
1545 assert!(!err.contains("01a0dab3"), "{err}");
1546 assert!(err.contains("Did you mean saddle?"), "{err}");
1547 }
1548
1549 #[test]
1550 fn a_misspelt_seat_is_answered_with_the_seat_it_meant() {
1551 let known: BTreeSet<String> = ["ljos-bot", "saddle", "inky"]
1552 .iter()
1553 .map(|s| (*s).to_string())
1554 .collect();
1555 assert_eq!(closest_seat("ljos", &known), Some("ljos-bot"));
1556 assert_eq!(closest_seat("sadle", &known), Some("saddle"));
1557 assert_eq!(closest_seat("eessi", &known), None);
1558 let err = check_known("ljos", &known, false).unwrap_err().to_string();
1559 assert!(err.contains("Did you mean ljos-bot?"), "{err}");
1560 let err = check_known("eessi", &known, false).unwrap_err().to_string();
1561 assert!(!err.contains("Did you mean"), "{err}");
1562 assert!(check_known("eessi", &known, true).is_ok());
1563 }
1564
1565 #[test]
1566 fn a_stop_carries_unread_interrupt_mail_only() {
1567 let plain = outgoing("plain", "grok", &["claude"], "when you can");
1568 let mut hot = outgoing("hot", "grok", &["claude"], "take ticket-d9n6 now");
1569 hot.interrupt = true;
1570 hot.issue = Some("ticket-d9n6".into());
1571 let atoms = [
1572 atom(&plain, "2026-10-11T00:00:00Z"),
1573 atom(&hot, "2026-10-11T00:00:01Z"),
1574 ];
1575 let (text, ids) = stop_lines(&atoms, "claude");
1576 assert!(text.starts_with(STOP_MAIL_HEAD), "{text}");
1577 assert!(
1578 text.contains("! hot from grok on ticket-d9n6: take ticket-d9n6 now"),
1579 "{text}"
1580 );
1581 assert!(!text.contains("when you can"), "{text}");
1582 assert_eq!(ids, ["mail:hot"]);
1583 let read = json!({
1584 "kind": "receipt",
1585 "text": "read hot\nby claude\nat 2026-10-11T00:00:02Z\nmsg r1",
1586 "entities": ["seat:claude", "from:claude", "to:grok", "receipt:hot", "msg:r1"],
1587 });
1588 let after = [atoms[0].clone(), atoms[1].clone(), read];
1589 assert_eq!(stop_lines(&after, "claude"), (String::new(), Vec::new()));
1590 assert_eq!(stop_lines(&atoms, "grok"), (String::new(), Vec::new()));
1591 }
1592
1593 #[test]
1594 fn an_unknown_kind_is_a_pack_without_mail() {
1595 let refused =
1596 "bad response: http://127.0.0.1:8761/v1/atoms: 400: unknown atom kind: message";
1597 assert_eq!(probe_of(refused), Probe::Refused);
1598 let kept = "bad response: http://127.0.0.1:8761/v1/atoms: 400: atom text is required";
1599 assert_eq!(probe_of(kept), Probe::Kept);
1600 let level = "bad response: http://127.0.0.1:8761/v1/atoms: 400: unknown atom level: nope";
1601 assert_eq!(probe_of(level), Probe::Kept);
1602 let dump =
1606 "bad response: http://127.0.0.1:8761/v1/atoms: 400: tool dump is attach, not an atom";
1607 assert_eq!(probe_of(dump), Probe::Kept);
1608 let down = "http://127.0.0.1:8761/v1/atoms: http: connection refused";
1609 assert_eq!(probe_of(down), Probe::Store);
1610 let named = unsupported_mail(Some("0.12.1"));
1611 assert!(named.contains("packset 0.12.1"), "{named}");
1612 assert!(named.contains(MAIL_PACKSET), "{named}");
1613 assert!(named.contains("kind message"), "{named}");
1614 let quiet = unsupported_mail(None);
1615 assert!(quiet.contains(MAIL_PACKSET), "{quiet}");
1616 assert!(quiet.contains("refused kind message"), "{quiet}");
1617 }
1618}