1use std::path::{Path, PathBuf};
47use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
48use std::time::Duration;
49
50use anyhow::{Context, Result, bail};
51use jiff::Timestamp;
52use serde::{Deserialize, Serialize};
53
54use crate::agent::{self, Invocation, SeatState};
55use crate::config::Config;
56use crate::queue::{Queue, Source, Task};
57
58pub const SCHEMA: u32 = 1;
60
61fn turn_timeout(cfg: &Config) -> Duration {
72 Duration::from_secs(cfg.graph.timeout_talk)
73}
74
75const SEAT: &str = "talk";
78
79const MAGI_NOTE: &str = "magi: ";
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(rename_all = "lowercase")]
85pub enum Who {
86 Operator,
88 Agent,
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(deny_unknown_fields)]
102pub struct Attachment {
103 pub id: String,
105 pub name: String,
107 pub mime: String,
110 pub bytes: u64,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(deny_unknown_fields)]
117pub struct Turn {
118 pub who: Who,
120 pub body: String,
122 pub at: Timestamp,
124 #[serde(default)]
127 pub attachments: Vec<Attachment>,
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(rename_all = "lowercase")]
135pub enum TalkStatus {
136 Open,
139 Closed,
141}
142
143impl TalkStatus {
144 pub fn open(self) -> bool {
146 matches!(self, Self::Open)
147 }
148
149 pub fn as_str(self) -> &'static str {
151 match self {
152 Self::Open => "open",
153 Self::Closed => "closed",
154 }
155 }
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize)]
160#[serde(deny_unknown_fields)]
161pub struct Talk {
162 pub schema: u32,
164 pub id: String,
166 pub repo: PathBuf,
168 pub agent: String,
170 pub status: TalkStatus,
172 pub turns: Vec<Turn>,
174 #[serde(default)]
177 pub pending: String,
178 #[serde(default)]
180 pub pending_attachments: Vec<Attachment>,
181 pub created_at: Timestamp,
183 pub updated_at: Timestamp,
185 seat: SeatState,
190}
191
192impl Talk {
193 pub fn short(&self) -> &str {
195 short(&self.id)
196 }
197}
198
199#[derive(Debug, Clone)]
201pub struct Talks {
202 root: PathBuf,
203 lock: Arc<Mutex<()>>,
212}
213
214impl Talks {
215 pub fn open() -> Self {
217 Self::at(crate::run::home().join("talks"))
218 }
219
220 pub fn at(root: PathBuf) -> Self {
223 Self {
224 root,
225 lock: Arc::new(Mutex::new(())),
226 }
227 }
228
229 fn guard(&self) -> MutexGuard<'_, ()> {
238 self.lock.lock().unwrap_or_else(PoisonError::into_inner)
239 }
240
241 pub fn root(&self) -> &Path {
243 &self.root
244 }
245
246 pub fn path_of(&self, id: &str) -> PathBuf {
248 self.root.join(format!("{id}.json"))
249 }
250
251 pub fn artifacts_of(&self, id: &str) -> PathBuf {
254 self.root.join(format!("{id}.artifacts"))
255 }
256
257 pub fn attachments_dir(&self, id: &str) -> PathBuf {
261 self.artifacts_of(id).join("attachments")
262 }
263
264 pub fn put_attachment(
273 &self,
274 id: &str,
275 mime: &str,
276 name: &str,
277 data: &[u8],
278 ) -> Result<Attachment> {
279 let dir = self.attachments_dir(id);
280 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
281 let ext = attachment_ext(mime).with_context(|| format!("unsupported mime `{mime}`"))?;
282 let att = Attachment {
283 id: new_attachment_id(),
284 name: name.to_owned(),
285 mime: mime.to_owned(),
286 bytes: data.len() as u64,
287 };
288 std::fs::write(dir.join(format!("{}.{ext}", att.id)), data)
289 .with_context(|| format!("write attachment {}", att.id))?;
290 std::fs::write(
291 dir.join(format!("{}.json", att.id)),
292 serde_json::to_string(&att).context("serialize attachment")?,
293 )
294 .with_context(|| format!("write attachment metadata {}", att.id))?;
295 Ok(att)
296 }
297
298 pub fn attachment_meta(&self, id: &str, att_id: &str) -> Result<Option<Attachment>> {
307 if !valid_attachment_id(att_id) {
308 return Ok(None);
309 }
310 let meta_path = self.attachments_dir(id).join(format!("{att_id}.json"));
311 if !meta_path.is_file() {
312 return Ok(None);
313 }
314 let att = serde_json::from_str(
315 &std::fs::read_to_string(&meta_path)
316 .with_context(|| format!("read {}", meta_path.display()))?,
317 )
318 .with_context(|| format!("parse {}", meta_path.display()))?;
319 Ok(Some(att))
320 }
321
322 pub fn read_attachment(&self, id: &str, att_id: &str) -> Result<Option<(Attachment, Vec<u8>)>> {
326 let Some(att) = self.attachment_meta(id, att_id)? else {
327 return Ok(None);
328 };
329 let ext = attachment_ext(&att.mime).with_context(|| {
330 format!("attachment {att_id} has an unsupported mime `{}`", att.mime)
331 })?;
332 let data_path = self.attachments_dir(id).join(format!("{att_id}.{ext}"));
333 let data =
334 std::fs::read(&data_path).with_context(|| format!("read {}", data_path.display()))?;
335 Ok(Some((att, data)))
336 }
337
338 fn attachment_path(&self, id: &str, att: &Attachment) -> Option<PathBuf> {
355 let ext = attachment_ext(&att.mime)?;
356 let path = self.attachments_dir(id).join(format!("{}.{ext}", att.id));
357 std::path::absolute(&path).ok()
358 }
359
360 pub fn put(&self, t: &mut Talk) -> Result<()> {
369 std::fs::create_dir_all(&self.root)
370 .with_context(|| format!("create {}", self.root.display()))?;
371 t.updated_at = Timestamp::now();
372 let body = serde_json::to_string_pretty(t).context("serialize talk")?;
373 let path = self.path_of(&t.id);
374 let tmp = path.with_extension("json.tmp");
375 write_atomic(&tmp, &path, &body)
376 }
377
378 pub fn get(&self, id: &str) -> Result<Talk> {
380 let resolved = self.resolve_id(id)?;
381 read_path(&self.path_of(&resolved))
382 }
383
384 pub fn list(&self) -> Vec<Talk> {
387 let mut all: Vec<Talk> = std::fs::read_dir(&self.root)
388 .into_iter()
389 .flatten()
390 .flatten()
391 .map(|e| e.path())
392 .filter(|p| p.extension().is_some_and(|x| x == "json"))
393 .filter_map(|p| read_path(&p).ok())
394 .collect();
395 all.sort_unstable_by(|a, b| {
396 let rank = |t: &Talk| u8::from(!t.status.open());
397 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
398 });
399 all
400 }
401
402 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
404 if self.path_of(prefix).is_file() {
405 return Ok(prefix.to_owned());
406 }
407 let hits: Vec<String> = self
408 .list()
409 .into_iter()
410 .map(|t| t.id)
411 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
412 .collect();
413 match hits.len() {
414 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
415 0 => bail!("no talk matches `{prefix}`"),
416 _ => bail!(
417 "`{prefix}` matches {} talks: {}",
418 hits.len(),
419 hits.join(", ")
420 ),
421 }
422 }
423
424 pub fn revision(&self) -> u64 {
427 std::fs::read_dir(&self.root)
428 .into_iter()
429 .flatten()
430 .flatten()
431 .filter_map(|e| e.metadata().ok())
432 .filter_map(|m| m.modified().ok())
433 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
434 .map(|d| d.as_millis() as u64)
435 .max()
436 .unwrap_or(0)
437 }
438
439 pub fn count_open(&self) -> usize {
441 self.list().iter().filter(|t| t.status.open()).count()
442 }
443
444 pub fn remove(&self, id: &str) -> Result<()> {
457 let _guard = self.guard();
458 let resolved = self.resolve_id(id)?;
459 let path = self.path_of(&resolved);
460 std::fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
461 let artifacts = self.artifacts_of(&resolved);
462 if artifacts.is_dir() {
463 std::fs::remove_dir_all(&artifacts)
464 .with_context(|| format!("remove {}", artifacts.display()))?;
465 }
466 Ok(())
467 }
468}
469
470pub fn begin(store: &Talks, cfg: &Config, repo: PathBuf, agent: Option<&str>) -> Result<Talk> {
480 let repo = repo.canonicalize().unwrap_or(repo);
483 let want = agent.or(cfg.roles.chatter.as_deref());
484 let spec = agent::pick(&cfg.agents, want, &agent::installed)?;
485
486 let now = Timestamp::now();
487 let mut talk = Talk {
488 schema: SCHEMA,
489 id: new_id(),
490 repo,
491 agent: spec.id.clone(),
492 status: TalkStatus::Open,
493 turns: Vec::new(),
494 pending: String::new(),
495 pending_attachments: Vec::new(),
496 created_at: now,
497 updated_at: now,
498 seat: SeatState::new(SEAT, &spec.id, crate::rng::entropy()),
499 };
500 store.put(&mut talk)?;
501 Ok(talk)
502}
503
504pub fn record(
511 talk: &mut Talk,
512 store: &Talks,
513 text: &str,
514 attachments: Vec<Attachment>,
515) -> Result<String> {
516 let _guard = store.guard();
524 let Ok(fresh) = store.get(&talk.id) else {
529 bail!("talk {} was deleted", talk.short());
530 };
531 talk.status = fresh.status;
532 talk.pending = fresh.pending;
535 talk.pending_attachments = fresh.pending_attachments;
536 if !talk.status.open() {
537 bail!(
538 "talk {} is {} and takes no more turns",
539 talk.short(),
540 talk.status.as_str()
541 );
542 }
543 let text = text.trim();
544 if text.is_empty() && attachments.is_empty() {
545 bail!("nothing to say");
546 }
547 talk.turns.push(Turn {
548 who: Who::Operator,
549 body: text.to_owned(),
550 at: Timestamp::now(),
551 attachments,
552 });
553 store.put(talk)?;
554 Ok(text.to_owned())
555}
556
557pub fn queue(
559 talk: &mut Talk,
560 store: &Talks,
561 text: &str,
562 attachments: Vec<Attachment>,
563) -> Result<()> {
564 let text = text.trim();
565 if text.is_empty() && attachments.is_empty() {
566 bail!("nothing to say");
567 }
568 let _guard = store.guard();
569 let mut fresh = store
570 .get(&talk.id)
571 .with_context(|| format!("talk {} was deleted", talk.short()))?;
572 if !fresh.status.open() {
573 bail!(
574 "talk {} is {} and takes no more turns",
575 fresh.short(),
576 fresh.status.as_str()
577 );
578 }
579 if !text.is_empty() {
580 if fresh.pending.is_empty() {
581 fresh.pending = text.to_owned();
582 } else {
583 fresh.pending.push_str("\n\n");
584 fresh.pending.push_str(text);
585 }
586 }
587 fresh.pending_attachments.extend(attachments);
588 store.put(&mut fresh)?;
589 *talk = fresh;
590 Ok(())
591}
592
593pub fn drain(talk: &mut Talk, store: &Talks) -> Result<Option<String>> {
595 let _guard = store.guard();
596 let mut fresh = store
597 .get(&talk.id)
598 .with_context(|| format!("talk {} was deleted", talk.short()))?;
599 if !fresh.status.open() || (fresh.pending.is_empty() && fresh.pending_attachments.is_empty()) {
600 *talk = fresh;
601 return Ok(None);
602 }
603 let text = std::mem::take(&mut fresh.pending);
604 let attachments = std::mem::take(&mut fresh.pending_attachments);
605 fresh.turns.push(Turn {
606 who: Who::Operator,
607 body: text.clone(),
608 at: Timestamp::now(),
609 attachments,
610 });
611 store.put(&mut fresh)?;
612 *talk = fresh;
613 Ok(Some(text))
614}
615
616pub async fn say(
619 talk: &mut Talk,
620 store: &Talks,
621 cfg: &Config,
622 text: &str,
623 attachments: Vec<Attachment>,
624) -> Result<()> {
625 let text = record(talk, store, text, attachments)?;
626 turn(talk, store, cfg, &text).await
627}
628
629pub async fn respond(talk: &mut Talk, store: &Talks, cfg: &Config, text: &str) -> Result<()> {
631 turn(talk, store, cfg, text).await
632}
633
634pub fn close(talk: &mut Talk, store: &Talks) -> Result<()> {
652 let _guard = store.guard();
653 let mut fresh = store
654 .get(&talk.id)
655 .with_context(|| format!("talk {} was deleted", talk.short()))?;
656 fresh.status = TalkStatus::Closed;
657 fresh.pending.clear();
659 fresh.pending_attachments.clear();
660 store.put(&mut fresh)?;
661 *talk = fresh;
662 Ok(())
663}
664
665pub fn reopen(talk: &mut Talk, store: &Talks) -> Result<()> {
676 let _guard = store.guard();
677 let mut fresh = store
678 .get(&talk.id)
679 .with_context(|| format!("talk {} was deleted", talk.short()))?;
680 fresh.status = TalkStatus::Open;
681 store.put(&mut fresh)?;
682 *talk = fresh;
683 Ok(())
684}
685
686pub fn clear_pending(talk: &mut Talk, store: &Talks) -> Result<()> {
688 let _guard = store.guard();
689 let mut fresh = store
690 .get(&talk.id)
691 .with_context(|| format!("talk {} was deleted", talk.short()))?;
692 fresh.pending.clear();
693 fresh.pending_attachments.clear();
694 store.put(&mut fresh)?;
695 *talk = fresh;
696 Ok(())
697}
698
699pub fn clear_pending_if_matches(
701 talk: &mut Talk,
702 store: &Talks,
703 expected_text: &str,
704 expected_attachments: &[String],
705) -> Result<bool> {
706 let _guard = store.guard();
707 let mut fresh = store
708 .get(&talk.id)
709 .with_context(|| format!("talk {} was deleted", talk.short()))?;
710 if !pending_matches(&fresh, expected_text, expected_attachments) {
711 *talk = fresh;
712 return Ok(false);
713 }
714 fresh.pending.clear();
715 fresh.pending_attachments.clear();
716 store.put(&mut fresh)?;
717 *talk = fresh;
718 Ok(true)
719}
720
721pub fn edit_pending_text(
725 talk: &mut Talk,
726 store: &Talks,
727 text: &str,
728 expected_text: &str,
729 expected_attachments: &[String],
730) -> Result<bool> {
731 let _guard = store.guard();
732 let mut fresh = store
733 .get(&talk.id)
734 .with_context(|| format!("talk {} was deleted", talk.short()))?;
735 if !pending_matches(&fresh, expected_text, expected_attachments) {
736 *talk = fresh;
737 return Ok(false);
738 }
739 fresh.pending = text.trim().to_owned();
740 store.put(&mut fresh)?;
741 *talk = fresh;
742 Ok(true)
743}
744
745fn pending_matches(talk: &Talk, expected_text: &str, expected_attachments: &[String]) -> bool {
746 talk.pending == expected_text
747 && talk
748 .pending_attachments
749 .iter()
750 .map(|attachment| &attachment.id)
751 .eq(expected_attachments.iter())
752}
753
754async fn turn(talk: &mut Talk, store: &Talks, cfg: &Config, text: &str) -> Result<()> {
761 let spec = cfg
762 .agents
763 .iter()
764 .find(|a| a.id == talk.agent)
765 .with_context(|| {
766 format!(
767 "talk {} was opened with agent `{}`, which is no longer in \
768 the roster; restore it in magi.toml or start a new \
769 conversation",
770 talk.short(),
771 talk.agent
772 )
773 })?;
774
775 let resuming = agent::has_session(spec.kind, &talk.seat, cfg.graph.sessions);
776 let last_note = attachment_note(
780 store,
781 &talk.id,
782 talk.turns
783 .last()
784 .map_or(&[][..], |t| t.attachments.as_slice()),
785 );
786 let body = if talk.seat.turns == 0 {
787 format!(
788 "{}\n\n# Operator\n\n{text}{last_note}",
789 briefing(&talk.repo, &cfg.graph.language, cfg.talk.allow_write)
790 )
791 } else if resuming {
792 format!("{text}{last_note}")
793 } else {
794 format!("{}\n\n{text}{last_note}", transcript(talk, store))
795 };
796
797 let attachment_paths: Vec<PathBuf> = talk
803 .turns
804 .iter()
805 .flat_map(|t| t.attachments.iter())
806 .filter_map(|a| store.attachment_path(&talk.id, a))
807 .collect();
808
809 let artifacts = store.artifacts_of(&talk.id);
810 let stem = format!("turn-{}", talk.seat.turns + 1);
811 let cache_dir = cfg.cache_dir();
814 let inv = Invocation {
815 cwd: &talk.repo,
816 prompt: &body,
817 timeout: turn_timeout(cfg),
818 allow_write: cfg.talk.allow_write,
823 sessions: cfg.graph.sessions,
824 artifacts: &artifacts,
825 stem: &stem,
826 run: &talk.id,
829 node: "chat",
830 cache_dir: cache_dir.as_deref(),
831 attachments: &attachment_paths,
832 };
833
834 let outcome = agent::invoke(spec, &mut talk.seat, &inv).await;
835 let note = |why: String| Turn {
836 who: Who::Agent,
837 body: format!("{MAGI_NOTE}{why}"),
838 at: Timestamp::now(),
839 attachments: Vec::new(),
840 };
841 let (reply, failure) = match outcome {
842 Err(e) => (
843 note(format!("could not run agent `{}`: {e}", talk.agent)),
844 Some(format!("could not run agent `{}`: {e}", talk.agent)),
845 ),
846 Ok(out) if out.quota_exhausted() => {
847 let reset = out
848 .quota
849 .as_ref()
850 .and_then(|q| q.reset.clone())
851 .map_or_else(String::new, |r| format!(" (resets {r})"));
852 let why = format!(
853 "agent `{}` is out of quota{reset}; your message is saved, so \
854 say it again when the window reopens",
855 talk.agent
856 );
857 (note(why.clone()), Some(why))
858 }
859 Ok(out) if out.timed_out => {
860 let why = format!(
861 "agent `{}` did not answer within {}s; your message is saved",
862 talk.agent,
863 turn_timeout(cfg).as_secs()
864 );
865 (note(why.clone()), Some(why))
866 }
867 Ok(out) if !out.usable() => {
868 let why = format!(
869 "agent `{}` produced no answer (exit {}); your message is saved",
870 talk.agent,
871 out.exit_code
872 .map_or_else(|| "unknown".to_owned(), |c| c.to_string())
873 );
874 (note(why.clone()), Some(why))
875 }
876 Ok(out) => (
877 Turn {
878 who: Who::Agent,
879 body: out.text.trim().to_owned(),
880 at: Timestamp::now(),
881 attachments: Vec::new(),
882 },
883 None,
884 ),
885 };
886
887 let _guard = store.guard();
899 let Ok(fresh) = store.get(&talk.id) else {
905 return Ok(());
906 };
907 talk.status = fresh.status;
908 talk.pending = fresh.pending;
912 talk.pending_attachments = fresh.pending_attachments;
913 talk.turns.push(reply);
914 if let Err(put_err) = store.put(talk) {
915 let lost = talk.turns.pop().expect("just pushed above");
924 let stash = stash_lost_turn(store, &talk.id, &stem, &lost);
925 let why = match &stash {
926 Ok(path) => format!(
927 "agent `{}` answered, but the reply could not be saved to \
928 this conversation ({put_err:#}); the raw text was kept at \
929 {} - your message is saved, ask again",
930 talk.agent,
931 path.display()
932 ),
933 Err(stash_err) => format!(
934 "agent `{}` answered, but the reply could not be saved to \
935 this conversation ({put_err:#}), and it could not be kept \
936 anywhere else either ({stash_err:#}); your message is \
937 saved, ask again",
938 talk.agent
939 ),
940 };
941 talk.turns.push(note(why.clone()));
942 return match store.put(talk) {
949 Ok(()) => bail!("{why}"),
950 Err(note_err) => {
951 talk.turns.pop();
971 Err(note_err).context(why)
972 }
973 };
974 }
975
976 match failure {
977 Some(why) => bail!("{why}"),
978 None => Ok(()),
979 }
980}
981
982fn transcript(talk: &Talk, store: &Talks) -> String {
985 let mut out = String::from(
986 "This conversation cannot resume on the CLI's side, so here is \
987 everything said so far; answer only the last message.\n",
988 );
989 for t in &talk.turns {
990 let who = match t.who {
991 Who::Operator => "operator",
992 Who::Agent => "you",
993 };
994 out.push_str(&format!("\n## {who}\n\n{}\n", t.body.trim()));
995 out.push_str(&attachment_note(store, &talk.id, &t.attachments));
996 }
997 out
998}
999
1000fn attachment_note(store: &Talks, talk_id: &str, attachments: &[Attachment]) -> String {
1005 if attachments.is_empty() {
1006 return String::new();
1007 }
1008 let mut out = String::from(
1009 "\n\nThe operator attached the image(s) below to this message. Open \
1010 and look at each one before you answer.\n",
1011 );
1012 for att in attachments {
1013 if let Some(path) = store.attachment_path(talk_id, att) {
1014 out.push_str(&format!("\n- {} ({})", path.display(), att.mime));
1015 }
1016 }
1017 out.push('\n');
1018 out
1019}
1020
1021pub fn briefing(repo: &Path, language: &str, allow_write: bool) -> String {
1043 let write_policy = if allow_write {
1044 "Write access is enabled for this conversation (`allow_write = \
1045 true`), so you may write files - but only a small, \
1046 already-decided edit the operator names outright in this \
1047 conversation, not an implementation. This is a permission on the \
1048 conversation as a whole, not a property of whichever repository \
1049 it happened to start in: if the operator names a different \
1050 repository for that small edit, the policy allows it there too. \
1051 Your own tool may still confine writes to the repository this \
1052 conversation started in regardless - if a write elsewhere is \
1053 refused, say so plainly rather than working around it. Once you \
1054 have made an edit, say plainly what you edited. Anything bigger, \
1055 or anything still open-ended, still goes through the queue below \
1056 rather than being done here."
1057 } else {
1058 "Do not write files. Implementing a change is not this \
1059 conversation's job; a separate, blind competition of agents does \
1060 that, and a repository this conversation has already edited would \
1061 make their diffs unjudgeable."
1062 };
1063 let mut out = format!(
1064 "You are magi's standing conversation partner for its operator, who \
1065 usually has this open on a phone. Keep replies short: no preamble, \
1066 no restating what they just said.\n\n\
1067 # Repository\n\n{repo}\n\n\
1068 You may look around: read files, run shell commands, search history, \
1069 run tests - whatever answers the question. {write_policy}\n\n\
1070 A short, command-shaped message (\"list\", \"info <id>\", \"show \
1071 3cbf\") is almost always the operator asking you to look something \
1072 up, not an instruction to file - answer it yourself with `magi \
1073 list`, `magi show <id>`, `magi task list`, or the like, the same way \
1074 you would answer any other question in this conversation.\n\n\
1075 # When the operator wants something done\n\n\
1076 Run:\n\n\
1077 magi task add --solo --repo {repo} <instruction>\n\n\
1078 and tell the operator the task id it prints, so they can follow it \
1079 from the Queue. Write <instruction> so that an implementer who has \
1080 never seen this conversation can act on it alone - it is everything \
1081 they get. Use --solo: it runs the task through one implementer \
1082 straight into review instead of the usual multi-agent competition, \
1083 which is the right shape for a change this conversation has already \
1084 settled, rather than one still worth several independent takes.\n\n\
1085 If the operator asks for something in a different repository, \
1086 --repo does not have to be a full path: --repo owner/repo (or just \
1087 repo, when that is unambiguous) is resolved against local checkouts \
1088 the same way `magi repos` lists them. If the command fails because \
1089 nothing matches or more than one checkout shares that name, ask the \
1090 operator which repository they mean (or run `magi repos` yourself \
1091 to see the candidates) rather than guessing.\n\n\
1092 If the operator attached an image (a screenshot, say) that the task \
1093 is about, pass it with `--attach <path>`, using the absolute path \
1094 the turn's attachment note gives; repeat the flag for several. \
1095 `magi task add --solo --attach <path> <instruction>` copies the \
1096 file into the task, so the implementer receives it. Do not paste the \
1097 path into <instruction> instead: deleting this conversation deletes \
1098 its attachments, and then that path reaches no one.\n",
1099 repo = repo.display(),
1100 );
1101 out.push_str(&language_note(language));
1102 out
1103}
1104
1105fn language_note(language: &str) -> String {
1108 if language.trim().is_empty() || language.eq_ignore_ascii_case("en") {
1109 String::new()
1110 } else {
1111 format!("\nHold this conversation in {language}.\n")
1112 }
1113}
1114
1115pub fn tasks_of(queue: &Queue, talk_id: &str) -> Vec<Task> {
1122 let mut tasks: Vec<Task> = queue
1123 .list()
1124 .into_iter()
1125 .filter(|t| matches!(&t.source, Source::Agent { run, .. } if run == talk_id))
1126 .collect();
1127 tasks.sort_unstable_by(|a, b| a.id.cmp(&b.id));
1128 tasks
1129}
1130
1131fn read_path(path: &Path) -> Result<Talk> {
1132 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1133 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))
1134}
1135
1136const PUT_RETRIES: u32 = 5;
1139
1140fn write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
1152 let mut last_err = None;
1153 for attempt in 0..PUT_RETRIES {
1154 if attempt > 0 {
1155 std::thread::sleep(Duration::from_millis(20 * u64::from(attempt)));
1156 }
1157 match try_write_atomic(tmp, path, body) {
1158 Ok(()) => return Ok(()),
1159 Err(e) => last_err = Some(e),
1160 }
1161 }
1162 Err(last_err.expect("the loop above always runs at least once"))
1163}
1164
1165fn try_write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
1166 #[cfg(test)]
1167 if failpoint::take_forced_put_failure() {
1168 bail!("simulated write failure (test)");
1169 }
1170 std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
1171 std::fs::rename(tmp, path).with_context(|| format!("replace {}", path.display()))?;
1172 Ok(())
1173}
1174
1175fn stash_lost_turn(store: &Talks, id: &str, stem: &str, reply: &Turn) -> Result<PathBuf> {
1180 let dir = store.artifacts_of(id);
1181 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
1182 let path = dir.join(format!("{stem}-lost.txt"));
1183 std::fs::write(&path, &reply.body).with_context(|| format!("write {}", path.display()))?;
1184 Ok(path)
1185}
1186
1187#[cfg(test)]
1194mod failpoint {
1195 use std::cell::Cell;
1196
1197 thread_local! {
1198 static FORCE_PUT_FAILURES: Cell<u32> = const { Cell::new(0) };
1199 }
1200
1201 pub(super) fn force_put_failures(count: u32) {
1204 FORCE_PUT_FAILURES.with(|c| c.set(count));
1205 }
1206
1207 pub(super) fn take_forced_put_failure() -> bool {
1210 FORCE_PUT_FAILURES.with(|c| {
1211 let n = c.get();
1212 if n == 0 {
1213 false
1214 } else {
1215 c.set(n - 1);
1216 true
1217 }
1218 })
1219 }
1220}
1221
1222fn short(id: &str) -> &str {
1223 id.split('-').next_back().unwrap_or(id)
1224}
1225
1226fn new_id() -> String {
1227 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
1228 let seed = crate::rng::entropy();
1229 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
1230}
1231
1232fn attachment_ext(mime: &str) -> Option<&'static str> {
1237 match mime {
1238 "image/png" => Some("png"),
1239 "image/jpeg" => Some("jpg"),
1240 "image/gif" => Some("gif"),
1241 "image/webp" => Some("webp"),
1242 _ => None,
1243 }
1244}
1245
1246pub fn valid_attachment_id(id: &str) -> bool {
1251 id.len() == 32
1252 && id
1253 .bytes()
1254 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
1255}
1256
1257fn new_attachment_id() -> String {
1261 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy());
1262 format!("{:016x}{:016x}", r.next_u64(), r.next_u64())
1263}
1264
1265#[cfg(test)]
1266mod tests {
1267 use std::collections::BTreeMap;
1268
1269 use crate::config::{AgentKind, AgentSpec, Graph};
1270 use crate::queue::{Queue, Source, Task};
1271
1272 use super::*;
1273
1274 fn store() -> (tempfile::TempDir, Talks) {
1276 let tmp = tempfile::tempdir().expect("tempdir");
1277 let talks = Talks::at(tmp.path().join("talks"));
1278 (tmp, talks)
1279 }
1280
1281 fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
1285 let path = dir.join("mock-talk-agent.sh");
1286 std::fs::write(&path, script).expect("write mock");
1287 AgentSpec {
1288 id: "mock".to_owned(),
1289 kind: AgentKind::Command,
1290 model: None,
1291 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
1292 extra_args: Vec::new(),
1293 env,
1294 prompt_delivery: None,
1295 }
1296 }
1297
1298 fn config(spec: AgentSpec) -> Config {
1299 Config {
1300 agents: vec![spec],
1301 graph: Graph {
1302 language: "en".to_owned(),
1303 ..Graph::default()
1304 },
1305 ..Config::default()
1306 }
1307 }
1308
1309 const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
1311
1312 const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
1314
1315 const ECHO: &str = "#!/bin/sh\ncat\n";
1318
1319 fn env(reply: &str) -> BTreeMap<String, String> {
1320 BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
1321 }
1322
1323 #[test]
1324 fn the_frozen_json_field_names_round_trip_through_disk() {
1325 let (tmp, talks) = store();
1326 let mut talk = Talk {
1327 schema: SCHEMA,
1328 id: "20260904-014455-ab12".to_owned(),
1329 repo: tmp.path().to_owned(),
1330 agent: "sonnet".to_owned(),
1331 status: TalkStatus::Open,
1332 turns: Vec::new(),
1333 pending: String::new(),
1334 pending_attachments: Vec::new(),
1335 created_at: Timestamp::now(),
1336 updated_at: Timestamp::now(),
1337 seat: SeatState::new(SEAT, "sonnet", 7),
1338 };
1339 talks.put(&mut talk).expect("put");
1340
1341 let raw = std::fs::read_to_string(talks.path_of(&talk.id)).expect("read back");
1342 let v: serde_json::Value = serde_json::from_str(&raw).expect("parse");
1343 for field in [
1344 "schema",
1345 "id",
1346 "repo",
1347 "agent",
1348 "status",
1349 "turns",
1350 "created_at",
1351 "updated_at",
1352 ] {
1353 assert!(v.get(field).is_some(), "missing field `{field}`");
1354 }
1355 assert_eq!(v["schema"], 1);
1356 assert_eq!(v["status"], "open");
1357
1358 let back = talks.get(&talk.id).expect("get");
1359 assert_eq!(back.id, talk.id);
1360 assert_eq!(back.status, TalkStatus::Open);
1361 }
1362
1363 #[test]
1364 fn opening_a_talk_takes_no_agent_turn() {
1365 let (tmp, talks) = store();
1366 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
1370 let cfg = config(spec);
1371
1372 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1373 assert_eq!(talk.status, TalkStatus::Open);
1374 assert!(talk.turns.is_empty(), "nothing has been said yet");
1375
1376 let on_disk = talks.get(&talk.id).expect("get");
1377 assert_eq!(on_disk.turns.len(), 0);
1378 }
1379
1380 #[test]
1388 fn chatter_wins_when_set_and_falls_back_to_pick_s_default_order_otherwise() {
1389 let (tmp, talks) = store();
1390 let first_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
1391 let mut chatter_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
1392 chatter_spec.id = "chatter-mock".to_owned();
1393
1394 let mut cfg = Config {
1395 agents: vec![first_spec.clone(), chatter_spec.clone()],
1396 graph: Graph {
1397 language: "en".to_owned(),
1398 ..Graph::default()
1399 },
1400 ..Config::default()
1401 };
1402 cfg.roles.chatter = Some(chatter_spec.id.clone());
1403
1404 let talk =
1405 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter set");
1406 assert_eq!(talk.agent, chatter_spec.id, "an explicit chatter must win");
1407
1408 cfg.roles.chatter = None;
1409 let fallback =
1410 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter unset");
1411 assert_eq!(
1412 fallback.agent, first_spec.id,
1413 "unset chatter must fall back to agent::pick's own default order"
1414 );
1415 }
1416
1417 #[test]
1420 fn a_talk_recorded_without_attachments_still_reads() {
1421 let (tmp, talks) = store();
1422 let path = talks.path_of("20260904-014455-ab12");
1423 std::fs::create_dir_all(talks.root()).expect("talks dir");
1424 std::fs::write(
1425 &path,
1426 serde_json::json!({
1427 "schema": 1,
1428 "id": "20260904-014455-ab12",
1429 "repo": tmp.path(),
1430 "agent": "sonnet",
1431 "status": "open",
1432 "turns": [
1433 { "who": "operator", "body": "still there?",
1434 "at": Timestamp::now().to_string() },
1435 ],
1436 "created_at": Timestamp::now().to_string(),
1437 "updated_at": Timestamp::now().to_string(),
1438 "seat": SeatState::new(SEAT, "sonnet", 7),
1439 })
1440 .to_string(),
1441 )
1442 .expect("write pre-attachments talk");
1443
1444 let talk = talks.get("20260904-014455-ab12").expect("must still read");
1445 assert!(talk.turns[0].attachments.is_empty());
1446 }
1447
1448 #[test]
1449 fn queued_text_is_durable_combined_and_drained_as_one_operator_turn() {
1450 let (tmp, talks) = store();
1451 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
1452 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1453
1454 queue(&mut talk, &talks, "first", Vec::new()).expect("queue first");
1455 queue(&mut talk, &talks, "second", Vec::new()).expect("queue second");
1456 let saved = talks.get(&talk.id).expect("reload queued talk");
1457 assert_eq!(saved.pending, "first\n\nsecond");
1458 assert!(saved.turns.is_empty(), "a draft is not a transcript turn");
1459
1460 let drained = drain(&mut talk, &talks).expect("drain");
1461 assert_eq!(drained.as_deref(), Some("first\n\nsecond"));
1462 let saved = talks.get(&talk.id).expect("reload drained talk");
1463 assert!(saved.pending.is_empty());
1464 assert_eq!(saved.turns.len(), 1);
1465 assert_eq!(saved.turns[0].body, "first\n\nsecond");
1466 }
1467
1468 #[test]
1469 fn editing_a_queued_draft_preserves_its_attachments_and_rejects_a_stale_snapshot() {
1470 let (tmp, talks) = store();
1471 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
1472 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1473 let attachment = Attachment {
1474 id: "a".repeat(32),
1475 name: "shot.png".to_owned(),
1476 mime: "image/png".to_owned(),
1477 bytes: 3,
1478 };
1479
1480 queue(&mut talk, &talks, "first", vec![attachment.clone()]).expect("queue");
1481 assert!(
1482 edit_pending_text(
1483 &mut talk,
1484 &talks,
1485 "corrected",
1486 "first",
1487 std::slice::from_ref(&attachment.id),
1488 )
1489 .expect("edit")
1490 );
1491 let saved = talks.get(&talk.id).expect("reload edited draft");
1492 assert_eq!(saved.pending, "corrected");
1493 assert_eq!(saved.pending_attachments, vec![attachment]);
1494
1495 queue(&mut talk, &talks, "later", Vec::new()).expect("queue concurrent draft");
1496 assert!(
1497 !edit_pending_text(
1498 &mut talk,
1499 &talks,
1500 "stale edit",
1501 "corrected",
1502 &["a".repeat(32)],
1503 )
1504 .expect("stale edit is a conflict")
1505 );
1506 assert_eq!(
1507 talks.get(&talk.id).expect("reload after conflict").pending,
1508 "corrected\n\nlater"
1509 );
1510 assert!(
1511 !clear_pending_if_matches(&mut talk, &talks, "corrected", &["a".repeat(32)])
1512 .expect("stale clear is a conflict")
1513 );
1514 assert_eq!(
1515 talks
1516 .get(&talk.id)
1517 .expect("reload after stale clear")
1518 .pending,
1519 "corrected\n\nlater"
1520 );
1521 }
1522
1523 #[tokio::test]
1524 async fn a_reply_save_preserves_pending_accepted_while_the_cli_runs() {
1525 let (tmp, talks) = store();
1526 let slow = "#!/bin/sh\ncat >/dev/null\nsleep 0.1\nprintf reply\n";
1527 let cfg = config(mock_agent(tmp.path(), slow, BTreeMap::new()));
1528 let mut running = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1529 let id = running.id.clone();
1530 let first = record(&mut running, &talks, "first", Vec::new()).expect("record");
1531
1532 let response_talks = talks.clone();
1533 let response_cfg = cfg.clone();
1534 let reply = tokio::spawn(async move {
1535 respond(&mut running, &response_talks, &response_cfg, &first).await
1536 });
1537 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1538
1539 let mut queued = talks.get(&id).expect("queued handle");
1540 queue(&mut queued, &talks, "next", Vec::new()).expect("queue");
1541 reply.await.expect("join").expect("reply");
1542
1543 let saved = talks.get(&id).expect("reload");
1544 assert_eq!(saved.pending, "next");
1545 assert_eq!(saved.turns.len(), 2, "operator message and reply remain");
1546 }
1547
1548 #[tokio::test]
1549 async fn the_first_turn_carries_the_briefing_and_later_turns_do_not() {
1550 let (tmp, talks) = store();
1551 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
1552 let cfg = config(spec);
1553 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1554
1555 say(
1556 &mut talk,
1557 &talks,
1558 &cfg,
1559 "what does the queue module do?",
1560 Vec::new(),
1561 )
1562 .await
1563 .expect("first turn");
1564 let first_prompt = &talk.turns[1].body;
1565 assert!(first_prompt.contains("magi task add --solo"));
1566 assert!(first_prompt.contains("what does the queue module do?"));
1567
1568 say(&mut talk, &talks, &cfg, "and how is it locked?", Vec::new())
1569 .await
1570 .expect("second turn");
1571 let second_prompt = &talk.turns[3].body;
1572 assert!(
1573 !second_prompt.contains("magi task add --solo"),
1574 "the briefing is sent once, not on every turn: {second_prompt}"
1575 );
1576 assert!(second_prompt.contains("and how is it locked?"));
1577 }
1578
1579 #[tokio::test]
1580 async fn say_appends_the_operator_turn_then_the_agent_turn() {
1581 let (tmp, talks) = store();
1582 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
1583 let cfg = config(spec);
1584 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1585
1586 say(
1587 &mut talk,
1588 &talks,
1589 &cfg,
1590 "can I rename this function?",
1591 Vec::new(),
1592 )
1593 .await
1594 .expect("say");
1595
1596 assert_eq!(talk.turns.len(), 2);
1597 assert_eq!(talk.turns[0].who, Who::Operator);
1598 assert_eq!(talk.turns[0].body, "can I rename this function?");
1599 assert_eq!(talk.turns[1].who, Who::Agent);
1600 assert_eq!(talk.turns[1].body, "go ahead");
1601 assert_eq!(talks.get(&talk.id).expect("get").turns, talk.turns);
1602 }
1603
1604 #[tokio::test]
1605 async fn a_failed_turn_keeps_the_operator_message_and_says_what_happened() {
1606 let (tmp, talks) = store();
1607 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
1608 let cfg = config(spec);
1609 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1610
1611 let err = say(&mut talk, &talks, &cfg, "check the tests", Vec::new())
1612 .await
1613 .expect_err("a turn with no answer is an error");
1614 assert!(err.to_string().contains("no answer"), "{err}");
1615
1616 let on_disk = talks.get(&talk.id).expect("get");
1617 assert_eq!(on_disk.turns.len(), 2);
1618 assert_eq!(on_disk.turns[0].body, "check the tests");
1619 let note = &on_disk.turns[1];
1620 assert_eq!(note.who, Who::Agent);
1621 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
1622 assert!(note.body.contains("your message is saved"));
1623 }
1624
1625 #[tokio::test]
1631 async fn a_passing_write_failure_while_saving_the_reply_does_not_lose_it() {
1632 let (tmp, talks) = store();
1633 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
1634 let cfg = config(spec);
1635 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1636
1637 let text =
1638 record(&mut talk, &talks, "can I rename this function?", Vec::new()).expect("record");
1639 failpoint::force_put_failures(PUT_RETRIES - 1);
1642 respond(&mut talk, &talks, &cfg, &text)
1643 .await
1644 .expect("respond must survive a write failure its own retries can outlast");
1645
1646 assert_eq!(talk.turns.len(), 2);
1647 assert_eq!(talk.turns[1].who, Who::Agent);
1648 assert_eq!(talk.turns[1].body, "go ahead");
1649 let on_disk = talks.get(&talk.id).expect("get");
1650 assert_eq!(
1651 on_disk.turns, talk.turns,
1652 "the reply must reach disk despite the early write failures"
1653 );
1654 }
1655
1656 #[tokio::test]
1662 async fn a_persistent_write_failure_while_saving_the_reply_is_never_silent() {
1663 let (tmp, talks) = store();
1664 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
1665 let cfg = config(spec);
1666 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1667
1668 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
1669 failpoint::force_put_failures(PUT_RETRIES);
1674 let err = respond(&mut talk, &talks, &cfg, &text)
1675 .await
1676 .expect_err("a reply that cannot be saved must be reported, not swallowed");
1677 assert!(err.to_string().contains("could not be saved"), "{err}");
1678
1679 let on_disk = talks.get(&talk.id).expect("get");
1680 assert_eq!(
1681 on_disk.turns.len(),
1682 2,
1683 "the operator turn plus a visible note"
1684 );
1685 assert_eq!(on_disk.turns[0].body, "check the tests");
1686 let note = &on_disk.turns[1];
1687 assert_eq!(note.who, Who::Agent);
1688 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
1689 assert!(
1690 note.body.contains("could not be saved"),
1691 "the operator must be told the reply is missing, not left staring \
1692 at a gap with no explanation: {}",
1693 note.body
1694 );
1695 assert_eq!(
1696 talk.turns, on_disk.turns,
1697 "the in-memory talk must match what actually landed on disk"
1698 );
1699
1700 let artifacts = talks.artifacts_of(&talk.id);
1703 let stash = std::fs::read_dir(&artifacts)
1704 .expect("artifacts dir")
1705 .filter_map(|e| e.ok())
1706 .find(|e| e.file_name().to_string_lossy().ends_with("-lost.txt"))
1707 .expect("a stash file for the lost reply");
1708 let stashed = std::fs::read_to_string(stash.path()).expect("read stash");
1709 assert_eq!(stashed, "go ahead");
1710
1711 assert_eq!(
1719 on_disk.seat.turns, 1,
1720 "the note's write must carry the turn the CLI actually took"
1721 );
1722 assert_eq!(
1723 on_disk.seat.claude_session, talk.seat.claude_session,
1724 "the session id handed to the CLI must survive the failed reply"
1725 );
1726 assert_eq!(on_disk.seat.captured_session, talk.seat.captured_session);
1727 assert!(
1728 agent::has_session(AgentKind::Command, &on_disk.seat, cfg.graph.sessions),
1729 "the next turn must resume, not open the same session id twice"
1730 );
1731 }
1732
1733 #[tokio::test]
1738 async fn a_write_failure_that_also_loses_the_note_still_reports_it() {
1739 let (tmp, talks) = store();
1740 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
1741 let cfg = config(spec);
1742 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1743
1744 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
1745 failpoint::force_put_failures(PUT_RETRIES * 2);
1748 let err = respond(&mut talk, &talks, &cfg, &text)
1749 .await
1750 .expect_err("neither the reply nor the note could be saved");
1751 assert!(err.to_string().contains("could not be saved"), "{err}");
1752
1753 assert_eq!(talk.turns.len(), 1, "only the operator's own turn");
1754 let on_disk = talks.get(&talk.id).expect("get");
1755 assert_eq!(on_disk.turns.len(), 1);
1756
1757 assert_eq!(
1767 on_disk.seat.turns, 0,
1768 "an unwritable file cannot record the turn the CLI took"
1769 );
1770 assert_eq!(
1771 talk.seat.turns, 1,
1772 "the in-memory seat still reports the turn the CLI actually took"
1773 );
1774 assert_eq!(
1775 on_disk.seat.claude_session, talk.seat.claude_session,
1776 "the session id was minted at `begin` and never changes here"
1777 );
1778 }
1779
1780 #[tokio::test]
1784 async fn attachments_reach_the_prompt_and_an_empty_body_is_still_a_turn() {
1785 let (tmp, talks) = store();
1786 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
1787 let cfg = config(spec);
1788 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1789
1790 let att = talks
1791 .put_attachment(
1792 &talk.id,
1793 "image/png",
1794 "screenshot.png",
1795 b"pretend-png-bytes",
1796 )
1797 .expect("put attachment");
1798
1799 say(&mut talk, &talks, &cfg, "", vec![att.clone()])
1800 .await
1801 .expect("an empty body with an attachment is still a turn");
1802
1803 let operator_turn = &talk.turns[0];
1804 assert_eq!(operator_turn.who, Who::Operator);
1805 assert_eq!(operator_turn.body, "");
1806 assert_eq!(operator_turn.attachments, vec![att.clone()]);
1807
1808 let prompt = &talk.turns[1].body;
1809 let expected_path = talks
1810 .attachments_dir(&talk.id)
1811 .join(format!("{}.png", att.id));
1812 assert!(
1813 prompt.contains(&expected_path.display().to_string()),
1814 "the agent must be told the attachment's absolute path: {prompt}"
1815 );
1816 assert!(prompt.contains("image/png"), "and its mime: {prompt}");
1817 }
1818
1819 #[test]
1828 fn attachment_path_is_absolute_even_when_the_store_root_is_relative() {
1829 let talks = Talks::at(PathBuf::from("relative-talks-root-for-this-test"));
1830 let att = Attachment {
1831 id: "0".repeat(32),
1832 name: "shot.png".to_owned(),
1833 mime: "image/png".to_owned(),
1834 bytes: 3,
1835 };
1836 let path = talks
1837 .attachment_path("some-talk-id", &att)
1838 .expect("a supported mime always yields a path");
1839 assert!(
1840 path.is_absolute(),
1841 "must be absolute even off a relative store root: {}",
1842 path.display()
1843 );
1844 }
1845
1846 #[tokio::test]
1847 async fn a_turn_past_the_configured_talk_timeout_is_reported_with_that_timeout() {
1848 let (tmp, talks) = store();
1853 let slow = mock_agent(
1854 tmp.path(),
1855 "#!/bin/sh\ncat >/dev/null\nsleep 2\n",
1856 BTreeMap::new(),
1857 );
1858 let mut cfg = config(slow);
1859 cfg.graph.timeout_talk = 1;
1860 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1861
1862 let err = say(&mut talk, &talks, &cfg, "check the tests", Vec::new())
1863 .await
1864 .expect_err("a turn that never answers is an error");
1865 assert!(
1866 err.to_string().contains("did not answer within 1s"),
1867 "{err}"
1868 );
1869
1870 let on_disk = talks.get(&talk.id).expect("get");
1871 let note = on_disk.turns.last().expect("a note turn was recorded");
1872 assert!(
1873 note.body.contains("did not answer within 1s"),
1874 "the transcript must show the configured timeout: {}",
1875 note.body
1876 );
1877 }
1878
1879 #[test]
1880 fn closing_is_idempotent_and_a_closed_talk_takes_no_more_turns() {
1881 let (tmp, talks) = store();
1882 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
1883 let cfg = config(spec);
1884 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1885
1886 close(&mut talk, &talks).expect("close");
1887 assert_eq!(talk.status, TalkStatus::Closed);
1888 close(&mut talk, &talks).expect("closing twice is not an error");
1889
1890 let err =
1891 record(&mut talk, &talks, "still there?", Vec::new()).expect_err("closed talks refuse");
1892 assert!(err.to_string().contains("closed"));
1893 let _ = &cfg; }
1895
1896 #[tokio::test]
1897 async fn a_close_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
1898 let (tmp, talks) = store();
1899 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
1900 let cfg = config(spec);
1901 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1904
1905 let mut closed_elsewhere = talks.get(&in_flight.id).expect("reread");
1909 close(&mut closed_elsewhere, &talks).expect("close");
1910 assert_eq!(
1911 talks.get(&in_flight.id).expect("reread").status,
1912 TalkStatus::Closed,
1913 "the close landed on disk before the turn finished"
1914 );
1915
1916 assert_eq!(in_flight.status, TalkStatus::Open);
1920 respond(&mut in_flight, &talks, &cfg, "one more question")
1921 .await
1922 .expect("the turn itself still completes");
1923
1924 let on_disk = talks.get(&in_flight.id).expect("reread");
1925 assert_eq!(
1926 on_disk.status,
1927 TalkStatus::Closed,
1928 "a close must stick even when a turn that started before it finishes after it"
1929 );
1930 assert!(
1933 on_disk.turns.iter().any(|t| t.body == "here you go"),
1934 "the in-flight turn's own reply is still recorded: {:?}",
1935 on_disk.turns
1936 );
1937 }
1938
1939 #[test]
1940 fn a_close_that_lands_before_record_is_called_is_not_undone_by_it() {
1941 let (tmp, talks) = store();
1942 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
1943 let cfg = config(spec);
1944 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1947
1948 let mut closed_elsewhere = talks.get(&stale.id).expect("reread");
1951 close(&mut closed_elsewhere, &talks).expect("close");
1952 assert_eq!(
1953 talks.get(&stale.id).expect("reread").status,
1954 TalkStatus::Closed,
1955 "the close landed on disk before record was called"
1956 );
1957
1958 assert_eq!(stale.status, TalkStatus::Open);
1962 let err = record(&mut stale, &talks, "still there?", Vec::new())
1963 .expect_err("a close that landed first must be honored, not overwritten");
1964 assert!(err.to_string().contains("closed"));
1965
1966 let on_disk = talks.get(&stale.id).expect("reread");
1967 assert_eq!(
1968 on_disk.status,
1969 TalkStatus::Closed,
1970 "record must not resurrect a conversation closed while its snapshot was stale"
1971 );
1972 assert!(
1973 on_disk.turns.is_empty(),
1974 "the rejected turn must not have been appended: {:?}",
1975 on_disk.turns
1976 );
1977 let _ = &cfg; }
1979
1980 #[test]
1981 fn close_blocks_on_records_guard_rather_than_interleaving_with_it() {
1982 let (tmp, talks) = store();
1983 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
1984 let cfg = config(spec);
1985 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1986
1987 let held = talks.guard();
1991
1992 let talks2 = talks.clone();
1993 let id = talk.id.clone();
1994 let closing = std::thread::spawn(move || {
1995 let mut talk = talks2.get(&id).expect("get");
1996 close(&mut talk, &talks2).expect("close");
1997 });
1998
1999 std::thread::sleep(Duration::from_millis(50));
2000 assert!(
2001 !closing.is_finished(),
2002 "close must wait for the guard, not read and write while it is held - \
2003 a re-read alone narrows this window without closing it"
2004 );
2005
2006 drop(held);
2007 closing.join().expect("close thread panicked");
2008
2009 assert_eq!(
2010 talks.get(&talk.id).expect("reread").status,
2011 TalkStatus::Closed,
2012 "once the guard is free, close still lands"
2013 );
2014 let _ = &cfg; }
2016
2017 #[test]
2018 fn reopening_a_closed_talk_lets_it_take_turns_again_and_reopening_twice_is_not_an_error() {
2019 let (tmp, talks) = store();
2020 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2021 let cfg = config(spec);
2022 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2023
2024 close(&mut talk, &talks).expect("close");
2025 assert_eq!(talk.status, TalkStatus::Closed);
2026
2027 reopen(&mut talk, &talks).expect("reopen");
2028 assert_eq!(talk.status, TalkStatus::Open);
2029 assert_eq!(
2030 talks.get(&talk.id).expect("reread").status,
2031 TalkStatus::Open
2032 );
2033
2034 reopen(&mut talk, &talks).expect("reopening an open talk is not an error");
2036 assert_eq!(talk.status, TalkStatus::Open);
2037
2038 record(&mut talk, &talks, "one more thing", Vec::new())
2039 .expect("a reopened talk takes turns again");
2040 let _ = &cfg; }
2042
2043 #[test]
2044 fn removing_a_talk_deletes_its_record_and_artifacts_and_refuses_an_unknown_id() {
2045 let (tmp, talks) = store();
2046 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2047 let cfg = config(spec);
2048 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2049
2050 let artifacts = talks.artifacts_of(&talk.id);
2051 std::fs::create_dir_all(&artifacts).expect("create artifacts dir");
2052 std::fs::write(artifacts.join("turn-1.txt"), "hello").expect("write artifact");
2053
2054 talks.remove(&talk.id).expect("remove");
2055 assert!(!talks.path_of(&talk.id).is_file(), "the record is gone");
2056 assert!(!artifacts.is_dir(), "the artifacts directory is gone");
2057 assert!(
2058 talks.get(&talk.id).is_err(),
2059 "a removed talk cannot be read back"
2060 );
2061
2062 let err = talks
2063 .remove("nonexistent-id")
2064 .expect_err("unknown id refused");
2065 assert!(err.to_string().contains("no talk matches"), "{err}");
2066 let _ = &cfg; }
2068
2069 #[tokio::test]
2070 async fn a_delete_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
2071 let (tmp, talks) = store();
2072 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
2073 let cfg = config(spec);
2074 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2077
2078 talks.remove(&in_flight.id).expect("remove");
2079 assert!(
2080 talks.get(&in_flight.id).is_err(),
2081 "the delete landed on disk before the turn finished"
2082 );
2083
2084 respond(&mut in_flight, &talks, &cfg, "one more question")
2087 .await
2088 .expect("the turn itself still completes rather than erroring");
2089
2090 assert!(
2091 talks.get(&in_flight.id).is_err(),
2092 "a delete must stick even when a turn that started before it finishes after it"
2093 );
2094 }
2095
2096 #[test]
2097 fn a_delete_that_lands_before_record_is_called_is_not_undone_by_it() {
2098 let (tmp, talks) = store();
2099 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2100 let cfg = config(spec);
2101 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2104
2105 talks.remove(&stale.id).expect("remove");
2106
2107 let err = record(&mut stale, &talks, "still there?", Vec::new())
2111 .expect_err("a delete that landed first must be honored, not overwritten");
2112 assert!(err.to_string().contains("deleted"), "{err}");
2113
2114 assert!(
2115 talks.get(&stale.id).is_err(),
2116 "record must not resurrect a conversation deleted while its snapshot was stale"
2117 );
2118 let _ = &cfg; }
2120
2121 #[test]
2122 fn a_delete_that_lands_before_close_is_called_is_not_undone_by_it() {
2123 let (tmp, talks) = store();
2124 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2125 let cfg = config(spec);
2126 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2129
2130 talks.remove(&stale.id).expect("remove");
2131
2132 let err = close(&mut stale, &talks)
2136 .expect_err("a delete that landed first must be honored, not overwritten");
2137 assert!(err.to_string().contains("deleted"), "{err}");
2138
2139 assert!(
2140 talks.get(&stale.id).is_err(),
2141 "close must not resurrect a conversation deleted while its snapshot was stale"
2142 );
2143 let _ = &cfg; }
2145
2146 #[test]
2147 fn a_delete_that_lands_before_reopen_is_called_is_not_undone_by_it() {
2148 let (tmp, talks) = store();
2149 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2150 let cfg = config(spec);
2151 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2154 close(&mut stale, &talks).expect("close");
2155
2156 talks.remove(&stale.id).expect("remove");
2157
2158 let err = reopen(&mut stale, &talks)
2162 .expect_err("a delete that landed first must be honored, not overwritten");
2163 assert!(err.to_string().contains("deleted"), "{err}");
2164
2165 assert!(
2166 talks.get(&stale.id).is_err(),
2167 "reopen must not resurrect a conversation deleted while its snapshot was stale"
2168 );
2169 let _ = &cfg; }
2171
2172 #[test]
2173 fn list_puts_open_talks_before_closed_ones() {
2174 let (tmp, talks) = store();
2175 let make = |id: &str, status: TalkStatus| {
2176 let mut t = Talk {
2177 schema: SCHEMA,
2178 id: id.to_owned(),
2179 repo: tmp.path().to_owned(),
2180 agent: "mock".to_owned(),
2181 status,
2182 turns: Vec::new(),
2183 pending: String::new(),
2184 pending_attachments: Vec::new(),
2185 created_at: Timestamp::now(),
2186 updated_at: Timestamp::now(),
2187 seat: SeatState::new(SEAT, "mock", 7),
2188 };
2189 talks.put(&mut t).expect("put");
2190 };
2191 make("20260901-000000-0001", TalkStatus::Open);
2192 make("20260902-000000-0002", TalkStatus::Open);
2193 make("20260903-000000-0003", TalkStatus::Closed);
2194
2195 let ids: Vec<String> = talks.list().into_iter().map(|t| t.id).collect();
2196 assert_eq!(
2197 ids,
2198 [
2199 "20260902-000000-0002",
2200 "20260901-000000-0001",
2201 "20260903-000000-0003"
2202 ]
2203 );
2204 assert_eq!(talks.count_open(), 2);
2205 }
2206
2207 #[test]
2208 fn tasks_of_finds_only_this_talks_own_tasks() {
2209 let dir = tempfile::tempdir().expect("tempdir");
2210 let queue = Queue::at(dir.path().join("queue"));
2211
2212 let mut mine = Task::new(
2213 "rework the loader".to_owned(),
2214 "rework the loader".to_owned(),
2215 PathBuf::from("/repo"),
2216 Source::Agent {
2217 run: "20260904-014455-ab12".to_owned(),
2218 node: "chat".to_owned(),
2219 },
2220 );
2221 queue.put(&mut mine).expect("put mine");
2222
2223 let mut theirs = Task::new(
2224 "unrelated".to_owned(),
2225 "unrelated".to_owned(),
2226 PathBuf::from("/repo"),
2227 Source::Agent {
2228 run: "20260904-090000-zz99".to_owned(),
2229 node: "implement".to_owned(),
2230 },
2231 );
2232 queue.put(&mut theirs).expect("put theirs");
2233
2234 let mut human = Task::new(
2235 "typed by hand".to_owned(),
2236 "typed by hand".to_owned(),
2237 PathBuf::from("/repo"),
2238 Source::Human,
2239 );
2240 queue.put(&mut human).expect("put human");
2241
2242 let found = tasks_of(&queue, "20260904-014455-ab12");
2243 assert_eq!(found.len(), 1);
2244 assert_eq!(found[0].id, mine.id);
2245 }
2246
2247 #[test]
2248 fn the_briefing_names_solo_task_add() {
2249 let brief = briefing(Path::new("/repo"), "en", false);
2250 assert!(brief.contains("magi task add --solo"));
2251 assert!(brief.contains("/repo"));
2252 assert!(!brief.contains("Hold this conversation in"));
2253 }
2254
2255 #[test]
2261 fn the_briefing_explains_targeting_a_different_repository_by_name() {
2262 let brief = briefing(Path::new("/repo"), "en", false);
2263 assert!(brief.contains("--repo does not have to be a full path"));
2264 assert!(brief.contains("owner/repo"));
2265 assert!(brief.contains("magi repos"));
2266 assert!(brief.contains("ask the operator"));
2267 }
2268
2269 #[test]
2270 fn the_briefing_tells_the_assistant_to_pass_images_with_attach() {
2271 let brief = briefing(Path::new("/repo"), "en", false);
2272 assert!(brief.contains("--attach <path>"), "{brief}");
2273 assert!(brief.contains("deleting this conversation"), "{brief}");
2274 }
2275
2276 #[test]
2277 fn the_briefing_names_the_language_when_it_is_not_english() {
2278 let brief = briefing(Path::new("/repo"), "Japanese", false);
2279 assert!(brief.contains("Hold this conversation in Japanese"));
2280 }
2281
2282 #[test]
2283 fn the_briefing_forbids_writes_unless_the_repository_opted_in() {
2284 let read_only = briefing(Path::new("/repo"), "en", false);
2285 assert!(read_only.contains("Do not write files"));
2286 assert!(!read_only.contains("allow_write"));
2287
2288 let writable = briefing(Path::new("/repo"), "en", true);
2289 assert!(!writable.contains("Do not write files"));
2290 assert!(writable.contains("allow_write = true"));
2291 assert!(writable.contains("magi task add --solo"));
2294 assert!(writable.contains("say plainly what you"));
2295 }
2296}