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::{AgentSpec, 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 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub usage: Option<TurnUsage>,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
144pub struct TurnUsage {
145 pub context_tokens: u64,
147 pub agent: String,
149 #[serde(default)]
151 pub model: Option<String>,
152}
153
154#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
159pub struct ContextUsage {
160 pub tokens: Option<u64>,
162 pub window: Option<u64>,
164 pub percent: Option<u64>,
166 pub warn: bool,
168 pub since_switch: bool,
172 pub model: Option<String>,
174 #[serde(default)]
177 pub estimated: bool,
178}
179
180const CONTEXT_WARN_PERCENT: u64 = 80;
182
183const STANDING_PROMPT_FALLBACK_CHARS: u64 = 7000;
186
187pub fn estimate_context_tokens(talk: &Talk, standing_chars: u64) -> Option<u64> {
200 let mut counted = false;
201 let mut chars = standing_chars;
202 for t in talk.turns.iter().filter(|t| !t.body.starts_with(MAGI_NOTE)) {
203 counted = true;
204 chars += t.body.chars().count() as u64;
205 }
206 counted.then(|| (chars * 2).div_ceil(7))
208}
209
210pub fn context_usage(talk: &Talk, cfg: Option<&Config>) -> ContextUsage {
223 let current = cfg.and_then(|c| c.agents.iter().find(|a| a.id == talk.agent));
224 let model = current.and_then(|a| a.model.clone());
225 let window = cfg
226 .zip(model.as_deref())
227 .and_then(|(c, m)| c.context_window(m))
228 .filter(|w| *w > 0);
229 let usage = talk
230 .turns
231 .iter()
232 .rev()
233 .find(|t| t.who == Who::Agent && !t.body.starts_with(MAGI_NOTE))
234 .and_then(|t| t.usage.as_ref());
235 let measured = usage.map(|u| u.context_tokens);
236 let tokens = measured.or_else(|| {
237 let standing = cfg.map_or(STANDING_PROMPT_FALLBACK_CHARS, |c| {
238 briefing(&talk.repo, &c.graph.language, c.talk.allow_write)
239 .chars()
240 .count() as u64
241 });
242 estimate_context_tokens(talk, standing)
243 });
244 let estimated = measured.is_none() && tokens.is_some();
245 let since_switch =
246 usage.is_some_and(|u| u.agent != talk.agent || (current.is_some() && u.model != model));
247 let (percent, warn) = match (tokens, window) {
248 (Some(t), Some(w)) => (
249 Some(t.saturating_mul(100) / w),
250 t.saturating_mul(100) >= w.saturating_mul(CONTEXT_WARN_PERCENT),
251 ),
252 _ => (None, false),
253 };
254 ContextUsage {
255 tokens,
256 window,
257 percent,
258 warn,
259 since_switch,
260 model,
261 estimated,
262 }
263}
264
265#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(rename_all = "lowercase")]
270pub enum TalkStatus {
271 Open,
274 Closed,
276}
277
278impl TalkStatus {
279 pub fn open(self) -> bool {
281 matches!(self, Self::Open)
282 }
283
284 pub fn as_str(self) -> &'static str {
286 match self {
287 Self::Open => "open",
288 Self::Closed => "closed",
289 }
290 }
291}
292
293#[derive(Debug, Clone, Serialize, Deserialize)]
295#[serde(deny_unknown_fields)]
296pub struct Talk {
297 pub schema: u32,
299 pub id: String,
301 pub repo: PathBuf,
303 pub agent: String,
305 pub status: TalkStatus,
307 pub turns: Vec<Turn>,
309 #[serde(default)]
312 pub pending: String,
313 #[serde(default)]
315 pub pending_attachments: Vec<Attachment>,
316 #[serde(default)]
321 pub fallback: bool,
322 pub created_at: Timestamp,
324 pub updated_at: Timestamp,
326 seat: SeatState,
331}
332
333impl Talk {
334 pub fn short(&self) -> &str {
336 short(&self.id)
337 }
338}
339
340#[derive(Debug, Clone)]
342pub struct Talks {
343 root: PathBuf,
344 lock: Arc<Mutex<()>>,
353}
354
355impl Talks {
356 pub fn open() -> Self {
358 Self::at(crate::run::home().join("talks"))
359 }
360
361 pub fn at(root: PathBuf) -> Self {
364 Self {
365 root,
366 lock: Arc::new(Mutex::new(())),
367 }
368 }
369
370 fn guard(&self) -> MutexGuard<'_, ()> {
379 self.lock.lock().unwrap_or_else(PoisonError::into_inner)
380 }
381
382 pub fn root(&self) -> &Path {
384 &self.root
385 }
386
387 pub fn path_of(&self, id: &str) -> PathBuf {
389 self.root.join(format!("{id}.json"))
390 }
391
392 pub fn artifacts_of(&self, id: &str) -> PathBuf {
395 self.root.join(format!("{id}.artifacts"))
396 }
397
398 pub fn attachments_dir(&self, id: &str) -> PathBuf {
402 self.artifacts_of(id).join("attachments")
403 }
404
405 pub fn put_attachment(
414 &self,
415 id: &str,
416 mime: &str,
417 name: &str,
418 data: &[u8],
419 ) -> Result<Attachment> {
420 let dir = self.attachments_dir(id);
421 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
422 let ext = attachment_ext(mime).with_context(|| format!("unsupported mime `{mime}`"))?;
423 let att = Attachment {
424 id: new_attachment_id(),
425 name: name.to_owned(),
426 mime: mime.to_owned(),
427 bytes: data.len() as u64,
428 };
429 std::fs::write(dir.join(format!("{}.{ext}", att.id)), data)
430 .with_context(|| format!("write attachment {}", att.id))?;
431 std::fs::write(
432 dir.join(format!("{}.json", att.id)),
433 serde_json::to_string(&att).context("serialize attachment")?,
434 )
435 .with_context(|| format!("write attachment metadata {}", att.id))?;
436 Ok(att)
437 }
438
439 pub fn attachment_meta(&self, id: &str, att_id: &str) -> Result<Option<Attachment>> {
448 if !valid_attachment_id(att_id) {
449 return Ok(None);
450 }
451 let meta_path = self.attachments_dir(id).join(format!("{att_id}.json"));
452 if !meta_path.is_file() {
453 return Ok(None);
454 }
455 let att = serde_json::from_str(
456 &std::fs::read_to_string(&meta_path)
457 .with_context(|| format!("read {}", meta_path.display()))?,
458 )
459 .with_context(|| format!("parse {}", meta_path.display()))?;
460 Ok(Some(att))
461 }
462
463 pub fn read_attachment(&self, id: &str, att_id: &str) -> Result<Option<(Attachment, Vec<u8>)>> {
467 let Some(att) = self.attachment_meta(id, att_id)? else {
468 return Ok(None);
469 };
470 let ext = attachment_ext(&att.mime).with_context(|| {
471 format!("attachment {att_id} has an unsupported mime `{}`", att.mime)
472 })?;
473 let data_path = self.attachments_dir(id).join(format!("{att_id}.{ext}"));
474 let data =
475 std::fs::read(&data_path).with_context(|| format!("read {}", data_path.display()))?;
476 Ok(Some((att, data)))
477 }
478
479 fn attachment_path(&self, id: &str, att: &Attachment) -> Option<PathBuf> {
496 let ext = attachment_ext(&att.mime)?;
497 let path = self.attachments_dir(id).join(format!("{}.{ext}", att.id));
498 std::path::absolute(&path).ok()
499 }
500
501 pub fn put(&self, t: &mut Talk) -> Result<()> {
510 std::fs::create_dir_all(&self.root)
511 .with_context(|| format!("create {}", self.root.display()))?;
512 t.updated_at = Timestamp::now();
513 let body = serde_json::to_string_pretty(t).context("serialize talk")?;
514 let path = self.path_of(&t.id);
515 let tmp = path.with_extension("json.tmp");
516 write_atomic(&tmp, &path, &body)
517 }
518
519 pub fn get(&self, id: &str) -> Result<Talk> {
521 let resolved = self.resolve_id(id)?;
522 read_path(&self.path_of(&resolved))
523 }
524
525 pub fn list(&self) -> Vec<Talk> {
528 self.list_counting_unreadable().0
529 }
530
531 pub fn list_counting_unreadable(&self) -> (Vec<Talk>, usize) {
534 let mut unreadable = 0;
535 let mut all: Vec<Talk> = std::fs::read_dir(&self.root)
536 .into_iter()
537 .flatten()
538 .flatten()
539 .map(|e| e.path())
540 .filter(|p| p.extension().is_some_and(|x| x == "json"))
541 .filter_map(|p| {
542 let talk = read_path(&p).ok();
543 if talk.is_none() {
544 unreadable += 1;
545 }
546 talk
547 })
548 .collect();
549 all.sort_unstable_by(|a, b| {
550 let rank = |t: &Talk| u8::from(!t.status.open());
551 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
552 });
553 (all, unreadable)
554 }
555
556 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
558 if self.path_of(prefix).is_file() {
559 return Ok(prefix.to_owned());
560 }
561 let hits: Vec<String> = self
562 .list()
563 .into_iter()
564 .map(|t| t.id)
565 .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
566 .collect();
567 match hits.len() {
568 1 => Ok(hits.into_iter().next().expect("exactly one hit")),
569 0 => bail!("no talk matches `{prefix}`"),
570 _ => bail!(
571 "`{prefix}` matches {} talks: {}",
572 hits.len(),
573 hits.join(", ")
574 ),
575 }
576 }
577
578 pub fn revision(&self) -> u64 {
581 std::fs::read_dir(&self.root)
582 .into_iter()
583 .flatten()
584 .flatten()
585 .filter_map(|e| e.metadata().ok())
586 .filter_map(|m| m.modified().ok())
587 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
588 .map(|d| d.as_millis() as u64)
589 .max()
590 .unwrap_or(0)
591 }
592
593 pub fn count_open(&self) -> usize {
595 self.list().iter().filter(|t| t.status.open()).count()
596 }
597
598 pub fn remove(&self, id: &str) -> Result<()> {
611 let _guard = self.guard();
612 let resolved = self.resolve_id(id)?;
613 let path = self.path_of(&resolved);
614 std::fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
615 let artifacts = self.artifacts_of(&resolved);
616 if artifacts.is_dir() {
617 std::fs::remove_dir_all(&artifacts)
618 .with_context(|| format!("remove {}", artifacts.display()))?;
619 }
620 Ok(())
621 }
622}
623
624pub fn begin(store: &Talks, cfg: &Config, repo: PathBuf, agent: Option<&str>) -> Result<Talk> {
634 let repo = repo.canonicalize().unwrap_or(repo);
637 let spec = match agent {
640 Some(id) => agent::pick(&cfg.agents, Some(id), &agent::installed)?,
641 None => agent::pick_chain(
642 &cfg.agents,
643 cfg.roles.chatter.as_ref(),
644 &agent::installed,
645 "chatter",
646 )?
647 .remove(0),
648 };
649
650 let now = Timestamp::now();
651 let mut talk = Talk {
652 schema: SCHEMA,
653 id: new_id(),
654 repo,
655 agent: spec.id.clone(),
656 status: TalkStatus::Open,
657 turns: Vec::new(),
658 pending: String::new(),
659 pending_attachments: Vec::new(),
660 fallback: agent.is_none(),
661 created_at: now,
662 updated_at: now,
663 seat: SeatState::new(SEAT, &spec.id, crate::rng::entropy()),
664 };
665 store.put(&mut talk)?;
666 Ok(talk)
667}
668
669pub fn record(
676 talk: &mut Talk,
677 store: &Talks,
678 text: &str,
679 attachments: Vec<Attachment>,
680) -> Result<String> {
681 let _guard = store.guard();
689 let Ok(fresh) = store.get(&talk.id) else {
694 bail!("talk {} was deleted", talk.short());
695 };
696 talk.status = fresh.status;
697 talk.pending = fresh.pending;
700 talk.pending_attachments = fresh.pending_attachments;
701 if !talk.status.open() {
702 bail!(
703 "talk {} is {} and takes no more turns",
704 talk.short(),
705 talk.status.as_str()
706 );
707 }
708 let text = text.trim();
709 if text.is_empty() && attachments.is_empty() {
710 bail!("nothing to say");
711 }
712 talk.turns.push(Turn {
713 who: Who::Operator,
714 body: text.to_owned(),
715 at: Timestamp::now(),
716 attachments,
717 usage: None,
718 });
719 store.put(talk)?;
720 Ok(text.to_owned())
721}
722
723pub fn queue(
725 talk: &mut Talk,
726 store: &Talks,
727 text: &str,
728 attachments: Vec<Attachment>,
729) -> Result<()> {
730 let text = text.trim();
731 if text.is_empty() && attachments.is_empty() {
732 bail!("nothing to say");
733 }
734 let _guard = store.guard();
735 let mut fresh = store
736 .get(&talk.id)
737 .with_context(|| format!("talk {} was deleted", talk.short()))?;
738 if !fresh.status.open() {
739 bail!(
740 "talk {} is {} and takes no more turns",
741 fresh.short(),
742 fresh.status.as_str()
743 );
744 }
745 if !text.is_empty() {
746 if fresh.pending.is_empty() {
747 fresh.pending = text.to_owned();
748 } else {
749 fresh.pending.push_str("\n\n");
750 fresh.pending.push_str(text);
751 }
752 }
753 fresh.pending_attachments.extend(attachments);
754 store.put(&mut fresh)?;
755 *talk = fresh;
756 Ok(())
757}
758
759pub fn drain(talk: &mut Talk, store: &Talks) -> Result<Option<String>> {
761 let _guard = store.guard();
762 let mut fresh = store
763 .get(&talk.id)
764 .with_context(|| format!("talk {} was deleted", talk.short()))?;
765 if !fresh.status.open() || (fresh.pending.is_empty() && fresh.pending_attachments.is_empty()) {
766 *talk = fresh;
767 return Ok(None);
768 }
769 let text = std::mem::take(&mut fresh.pending);
770 let attachments = std::mem::take(&mut fresh.pending_attachments);
771 fresh.turns.push(Turn {
772 who: Who::Operator,
773 body: text.clone(),
774 at: Timestamp::now(),
775 attachments,
776 usage: None,
777 });
778 store.put(&mut fresh)?;
779 *talk = fresh;
780 Ok(Some(text))
781}
782
783pub async fn say(
786 talk: &mut Talk,
787 store: &Talks,
788 cfg: &Config,
789 text: &str,
790 attachments: Vec<Attachment>,
791) -> Result<()> {
792 let text = record(talk, store, text, attachments)?;
793 turn(talk, store, cfg, &text).await
794}
795
796pub async fn respond(talk: &mut Talk, store: &Talks, cfg: &Config, text: &str) -> Result<()> {
798 turn(talk, store, cfg, text).await
799}
800
801pub fn close(talk: &mut Talk, store: &Talks) -> Result<()> {
819 let _guard = store.guard();
820 let mut fresh = store
821 .get(&talk.id)
822 .with_context(|| format!("talk {} was deleted", talk.short()))?;
823 fresh.status = TalkStatus::Closed;
824 fresh.pending.clear();
826 fresh.pending_attachments.clear();
827 store.put(&mut fresh)?;
828 *talk = fresh;
829 Ok(())
830}
831
832pub fn reopen(talk: &mut Talk, store: &Talks) -> Result<()> {
843 let _guard = store.guard();
844 let mut fresh = store
845 .get(&talk.id)
846 .with_context(|| format!("talk {} was deleted", talk.short()))?;
847 fresh.status = TalkStatus::Open;
848 store.put(&mut fresh)?;
849 *talk = fresh;
850 Ok(())
851}
852
853pub fn switch_agent(talk: &mut Talk, store: &Talks, spec: &AgentSpec) -> Result<bool> {
866 let _guard = store.guard();
867 let mut fresh = store
868 .get(&talk.id)
869 .with_context(|| format!("talk {} was deleted", talk.short()))?;
870 if fresh.agent == spec.id {
871 *talk = fresh;
872 return Ok(false);
873 }
874 let from = std::mem::replace(&mut fresh.agent, spec.id.clone());
875 fresh.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
876 fresh.fallback = false;
878 fresh.turns.push(Turn {
879 who: Who::Agent,
880 body: format!("{MAGI_NOTE}agent changed from {from} to {}", spec.id),
881 at: Timestamp::now(),
882 attachments: Vec::new(),
883 usage: None,
884 });
885 store.put(&mut fresh)?;
886 *talk = fresh;
887 Ok(true)
888}
889
890pub fn clear_pending(talk: &mut Talk, store: &Talks) -> Result<()> {
892 let _guard = store.guard();
893 let mut fresh = store
894 .get(&talk.id)
895 .with_context(|| format!("talk {} was deleted", talk.short()))?;
896 fresh.pending.clear();
897 fresh.pending_attachments.clear();
898 store.put(&mut fresh)?;
899 *talk = fresh;
900 Ok(())
901}
902
903pub fn clear_pending_if_matches(
905 talk: &mut Talk,
906 store: &Talks,
907 expected_text: &str,
908 expected_attachments: &[String],
909) -> Result<bool> {
910 let _guard = store.guard();
911 let mut fresh = store
912 .get(&talk.id)
913 .with_context(|| format!("talk {} was deleted", talk.short()))?;
914 if !pending_matches(&fresh, expected_text, expected_attachments) {
915 *talk = fresh;
916 return Ok(false);
917 }
918 fresh.pending.clear();
919 fresh.pending_attachments.clear();
920 store.put(&mut fresh)?;
921 *talk = fresh;
922 Ok(true)
923}
924
925pub fn edit_pending_text(
929 talk: &mut Talk,
930 store: &Talks,
931 text: &str,
932 expected_text: &str,
933 expected_attachments: &[String],
934) -> Result<bool> {
935 let _guard = store.guard();
936 let mut fresh = store
937 .get(&talk.id)
938 .with_context(|| format!("talk {} was deleted", talk.short()))?;
939 if !pending_matches(&fresh, expected_text, expected_attachments) {
940 *talk = fresh;
941 return Ok(false);
942 }
943 fresh.pending = text.trim().to_owned();
944 store.put(&mut fresh)?;
945 *talk = fresh;
946 Ok(true)
947}
948
949fn pending_matches(talk: &Talk, expected_text: &str, expected_attachments: &[String]) -> bool {
950 talk.pending == expected_text
951 && talk
952 .pending_attachments
953 .iter()
954 .map(|attachment| &attachment.id)
955 .eq(expected_attachments.iter())
956}
957
958async fn turn(talk: &mut Talk, store: &Talks, cfg: &Config, text: &str) -> Result<()> {
965 let spec = cfg
966 .agents
967 .iter()
968 .find(|a| a.id == talk.agent)
969 .with_context(|| {
970 format!(
971 "talk {} was opened with agent `{}`, which is no longer in \
972 the roster; restore it in magi.toml or start a new \
973 conversation",
974 talk.short(),
975 talk.agent
976 )
977 })?;
978
979 let last_note = attachment_note(
983 store,
984 &talk.id,
985 talk.turns
986 .last()
987 .map_or(&[][..], |t| t.attachments.as_slice()),
988 );
989
990 let attachment_paths: Vec<PathBuf> = talk
996 .turns
997 .iter()
998 .flat_map(|t| t.attachments.iter())
999 .filter_map(|a| store.attachment_path(&talk.id, a))
1000 .collect();
1001
1002 let artifacts = store.artifacts_of(&talk.id);
1003 let operator_turns = talk.turns.iter().filter(|t| t.who == Who::Operator).count();
1006 let stem = format!("turn-{}", operator_turns.max(1));
1007 let cache_dir = cfg.cache_dir();
1010
1011 let mut chain = vec![spec.clone()];
1014 if let Some(choice) = cfg.roles.chatter.as_ref()
1015 && talk.fallback
1016 {
1017 for id in choice.ids() {
1018 if id == talk.agent || chain.iter().any(|s| s.id == id) {
1019 continue;
1020 }
1021 match agent::pick(&cfg.agents, Some(id), &agent::installed) {
1022 Ok(s) => chain.push(s),
1023 Err(e) => tracing::warn!("[roles] chatter: skipping `{id}`: {e:#}"),
1024 }
1025 }
1026 }
1027
1028 let mut outcome = None;
1029 let mut fell_back_from: Option<String> = None;
1030 let mut first_try: Option<(String, SeatState)> = None;
1033 for (n, spec) in chain.iter().enumerate() {
1034 if n > 0 {
1035 if first_try.is_none() {
1036 first_try = Some((talk.agent.clone(), talk.seat.clone()));
1037 }
1038 tracing::warn!("chat: falling back from `{}` to `{}`", talk.agent, spec.id);
1039 fell_back_from.get_or_insert_with(|| talk.agent.clone());
1042 talk.agent = spec.id.clone();
1043 talk.seat = SeatState::new(SEAT, &spec.id, crate::rng::entropy());
1044 }
1045 let resuming = agent::has_session(spec.kind, &talk.seat, cfg.graph.sessions);
1046 let first_ever = talk.turns.len() <= 1;
1047 let body = if talk.seat.turns == 0 && first_ever {
1048 format!(
1049 "{}\n\n# Operator\n\n{text}{last_note}",
1050 briefing(&talk.repo, &cfg.graph.language, cfg.talk.allow_write)
1051 )
1052 } else if talk.seat.turns == 0 {
1053 format!(
1056 "{}\n\n{}\n\n# Operator\n\n{text}{last_note}",
1057 briefing(&talk.repo, &cfg.graph.language, cfg.talk.allow_write),
1058 transcript(talk, store)
1059 )
1060 } else if resuming {
1061 format!("{text}{last_note}")
1062 } else {
1063 format!("{}\n\n{text}{last_note}", transcript(talk, store))
1064 };
1065 let attempt_stem = if n == 0 {
1066 stem.clone()
1067 } else {
1068 format!("{stem}-{}", spec.id)
1069 };
1070 let inv = Invocation {
1071 cwd: &talk.repo,
1072 prompt: &body,
1073 timeout: turn_timeout(cfg),
1074 allow_write: cfg.talk.allow_write,
1079 sessions: cfg.graph.sessions,
1080 artifacts: &artifacts,
1081 stem: &attempt_stem,
1082 run: &talk.id,
1085 node: crate::queue::CHAT_NODE,
1086 cache_dir: cache_dir.as_deref(),
1087 attachments: &attachment_paths,
1088 writable: &[],
1089 };
1090 let result = agent::invoke(spec, &mut talk.seat, &inv).await;
1091 let advance = agent::chain_advances(&result);
1092 if n == 0 || !advance {
1093 outcome = Some(result);
1094 } else {
1095 tracing::warn!("chat: fallback agent `{}` also failed", spec.id);
1097 }
1098 if !advance {
1099 break;
1100 }
1101 }
1102 if outcome.as_ref().is_some_and(agent::chain_advances) {
1103 if let Some((id, seat)) = first_try {
1106 talk.agent = id;
1107 talk.seat = seat;
1108 fell_back_from = None;
1109 }
1110 }
1111 let outcome = outcome.expect("a chain holds at least one agent");
1112 let note = |why: String| Turn {
1113 who: Who::Agent,
1114 body: format!("{MAGI_NOTE}{why}"),
1115 at: Timestamp::now(),
1116 attachments: Vec::new(),
1117 usage: None,
1118 };
1119 let (reply, failure) = match outcome {
1120 Err(e) => (
1121 note(format!("could not run agent `{}`: {e}", talk.agent)),
1122 Some(format!("could not run agent `{}`: {e}", talk.agent)),
1123 ),
1124 Ok(out) if out.quota_exhausted() => {
1125 let reset = out
1126 .quota
1127 .as_ref()
1128 .and_then(|q| q.reset.clone())
1129 .map_or_else(String::new, |r| format!(" (resets {r})"));
1130 let why = format!(
1131 "agent `{}` is out of quota{reset}; your message is saved, so \
1132 say it again when the window reopens",
1133 talk.agent
1134 );
1135 (note(why.clone()), Some(why))
1136 }
1137 Ok(out) if out.timed_out => {
1138 let why = format!(
1139 "agent `{}` did not answer within {}s; your message is saved",
1140 talk.agent,
1141 turn_timeout(cfg).as_secs()
1142 );
1143 (note(why.clone()), Some(why))
1144 }
1145 Ok(out) if !out.usable() => {
1146 let why = format!(
1147 "agent `{}` produced no answer (exit {}); your message is saved",
1148 talk.agent,
1149 out.exit_code
1150 .map_or_else(|| "unknown".to_owned(), |c| c.to_string())
1151 );
1152 (note(why.clone()), Some(why))
1153 }
1154 Ok(out) => (
1155 Turn {
1156 who: Who::Agent,
1157 body: out.text.trim().to_owned(),
1158 at: Timestamp::now(),
1159 attachments: Vec::new(),
1160 usage: out.context_tokens.map(|context_tokens| TurnUsage {
1163 context_tokens,
1164 agent: talk.agent.clone(),
1165 model: cfg
1166 .agents
1167 .iter()
1168 .find(|a| a.id == talk.agent)
1169 .and_then(|a| a.model.clone()),
1170 }),
1171 },
1172 None,
1173 ),
1174 };
1175
1176 let _guard = store.guard();
1188 let Ok(fresh) = store.get(&talk.id) else {
1194 return Ok(());
1195 };
1196 talk.status = fresh.status;
1197 talk.pending = fresh.pending;
1201 talk.pending_attachments = fresh.pending_attachments;
1202 if let Some(from) = fell_back_from.filter(|_| failure.is_none()) {
1203 talk.turns.push(note(format!(
1206 "agent changed from {from} to {} (fallback)",
1207 talk.agent
1208 )));
1209 }
1210 talk.turns.push(reply);
1211 if let Err(put_err) = store.put(talk) {
1212 let lost = talk.turns.pop().expect("just pushed above");
1221 let stash = stash_lost_turn(store, &talk.id, &stem, &lost);
1222 let why = match &stash {
1223 Ok(path) => format!(
1224 "agent `{}` answered, but the reply could not be saved to \
1225 this conversation ({put_err:#}); the raw text was kept at \
1226 {} - your message is saved, ask again",
1227 talk.agent,
1228 path.display()
1229 ),
1230 Err(stash_err) => format!(
1231 "agent `{}` answered, but the reply could not be saved to \
1232 this conversation ({put_err:#}), and it could not be kept \
1233 anywhere else either ({stash_err:#}); your message is \
1234 saved, ask again",
1235 talk.agent
1236 ),
1237 };
1238 talk.turns.push(note(why.clone()));
1239 return match store.put(talk) {
1246 Ok(()) => bail!("{why}"),
1247 Err(note_err) => {
1248 talk.turns.pop();
1268 Err(note_err).context(why)
1269 }
1270 };
1271 }
1272
1273 match failure {
1274 Some(why) => bail!("{why}"),
1275 None => Ok(()),
1276 }
1277}
1278
1279fn transcript(talk: &Talk, store: &Talks) -> String {
1282 let mut out = String::from(
1283 "This conversation cannot resume on the CLI's side, so here is \
1284 everything said so far; answer only the last message.\n",
1285 );
1286 for t in &talk.turns {
1287 let who = match t.who {
1288 Who::Operator => "operator",
1289 Who::Agent if t.body.starts_with(MAGI_NOTE) => "magi",
1290 Who::Agent => "you",
1291 };
1292 out.push_str(&format!("\n## {who}\n\n{}\n", t.body.trim()));
1293 out.push_str(&attachment_note(store, &talk.id, &t.attachments));
1294 }
1295 out
1296}
1297
1298fn attachment_note(store: &Talks, talk_id: &str, attachments: &[Attachment]) -> String {
1303 if attachments.is_empty() {
1304 return String::new();
1305 }
1306 let mut out = String::from(
1307 "\n\nThe operator attached the image(s) below to this message. Open \
1308 and look at each one before you answer.\n",
1309 );
1310 for att in attachments {
1311 if let Some(path) = store.attachment_path(talk_id, att) {
1312 out.push_str(&format!("\n- {} ({})", path.display(), att.mime));
1313 }
1314 }
1315 out.push('\n');
1316 out
1317}
1318
1319pub fn briefing(repo: &Path, language: &str, allow_write: bool) -> String {
1341 let write_policy = if allow_write {
1342 "Write access is enabled for this conversation (`allow_write = \
1343 true`), so you may write files - but only a small, \
1344 already-decided edit the operator names outright in this \
1345 conversation, not an implementation. This is a permission on the \
1346 conversation as a whole, not a property of whichever repository \
1347 it happened to start in: if the operator names a different \
1348 repository for that small edit, the policy allows it there too. \
1349 Your own tool may still confine writes to the repository this \
1350 conversation started in regardless - if a write elsewhere is \
1351 refused, say so plainly rather than working around it. Once you \
1352 have made an edit, say plainly what you edited. Anything bigger, \
1353 or anything still open-ended, still goes through the queue below \
1354 rather than being done here."
1355 } else {
1356 "Do not write files. Implementing a change is not this \
1357 conversation's job; a separate, blind competition of agents does \
1358 that, and a repository this conversation has already edited would \
1359 make their diffs unjudgeable."
1360 };
1361 let mut out = format!(
1362 "You are magi's standing conversation partner for its operator, who \
1363 usually has this open on a phone. Keep replies short: no preamble, \
1364 no restating what they just said.\n\n\
1365 # Repository\n\n{repo}\n\n\
1366 You may look around: read files, run shell commands, search history, \
1367 run tests - whatever answers the question. {write_policy}\n\n\
1368 A short, command-shaped message (\"list\", \"info <id>\", \"show \
1369 3cbf\") is almost always the operator asking you to look something \
1370 up, not an instruction to file - answer it yourself with `magi \
1371 list`, `magi show <id>`, `magi task list`, or the like, the same way \
1372 you would answer any other question in this conversation.\n\n\
1373 # When the operator wants something done\n\n\
1374 Run:\n\n\
1375 magi task add --solo --repo {repo} <instruction>\n\n\
1376 and tell the operator the task id it prints, so they can follow it \
1377 from the Queue. If it refuses with a duplicate warning (the \
1378 instruction names a branch, commit or pull request that an \
1379 unfinished task, run or PR already owns), do not repeat it with \
1380 --force yourself: tell the operator what it matched and let them \
1381 decide. Write <instruction> so that an implementer who has \
1382 never seen this conversation can act on it alone - it is everything \
1383 they get. Use --solo: it runs the task through one implementer \
1384 straight into review instead of the usual multi-agent competition, \
1385 which is the right shape for a change this conversation has already \
1386 settled, rather than one still worth several independent takes.\n\n\
1387 If the operator asks for something in a different repository, \
1388 --repo does not have to be a full path: --repo owner/repo (or just \
1389 repo, when that is unambiguous) is resolved against local checkouts \
1390 the same way `magi repos` lists them. If the command fails because \
1391 nothing matches or more than one checkout shares that name, ask the \
1392 operator which repository they mean (or run `magi repos` yourself \
1393 to see the candidates) rather than guessing.\n\n\
1394 The current state of the code is whatever origin/main holds, not \
1395 whatever a working tree shows: a primary checkout often lags \
1396 upstream, sits on a detached HEAD and carries uncommitted changes. \
1397 Before answering about code, run `git fetch origin` in that \
1398 repository if it is cheap, then read through \
1399 `git show origin/main:<path>` or `git grep <pattern> origin/main`. \
1400 If the working tree differs, say so; if the fetch fails, say that \
1401 too, so the operator knows the answer may be stale.\n\n\
1402 If the operator attached an image (a screenshot, say) that the task \
1403 is about, pass it with `--attach <path>`, using the absolute path \
1404 the turn's attachment note gives; repeat the flag for several. \
1405 `magi task add --solo --attach <path> <instruction>` copies the \
1406 file into the task, so the implementer receives it. Do not paste the \
1407 path into <instruction> instead: deleting this conversation deletes \
1408 its attachments, and then that path reaches no one.\n",
1409 repo = repo.display(),
1410 );
1411 out.push_str(&language_note(language));
1412 out
1413}
1414
1415fn language_note(language: &str) -> String {
1418 if language.trim().is_empty() || language.eq_ignore_ascii_case("en") {
1419 String::new()
1420 } else {
1421 format!("\nHold this conversation in {language}.\n")
1422 }
1423}
1424
1425pub fn tasks_of(queue: &Queue, talk_id: &str) -> Vec<Task> {
1432 let mut tasks: Vec<Task> = queue
1433 .list()
1434 .into_iter()
1435 .filter(|t| matches!(&t.source, Source::Agent { run, .. } if run == talk_id))
1436 .collect();
1437 tasks.sort_unstable_by(|a, b| a.id.cmp(&b.id));
1438 tasks
1439}
1440
1441fn read_path(path: &Path) -> Result<Talk> {
1442 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1443 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))
1444}
1445
1446const PUT_RETRIES: u32 = 5;
1449
1450fn write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
1462 let mut last_err = None;
1463 for attempt in 0..PUT_RETRIES {
1464 if attempt > 0 {
1465 std::thread::sleep(Duration::from_millis(20 * u64::from(attempt)));
1466 }
1467 match try_write_atomic(tmp, path, body) {
1468 Ok(()) => return Ok(()),
1469 Err(e) => last_err = Some(e),
1470 }
1471 }
1472 Err(last_err.expect("the loop above always runs at least once"))
1473}
1474
1475fn try_write_atomic(tmp: &Path, path: &Path, body: &str) -> Result<()> {
1476 #[cfg(test)]
1477 if failpoint::take_forced_put_failure() {
1478 bail!("simulated write failure (test)");
1479 }
1480 std::fs::write(tmp, body).with_context(|| format!("write {}", tmp.display()))?;
1481 std::fs::rename(tmp, path).with_context(|| format!("replace {}", path.display()))?;
1482 Ok(())
1483}
1484
1485fn stash_lost_turn(store: &Talks, id: &str, stem: &str, reply: &Turn) -> Result<PathBuf> {
1490 let dir = store.artifacts_of(id);
1491 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
1492 let path = dir.join(format!("{stem}-lost.txt"));
1493 std::fs::write(&path, &reply.body).with_context(|| format!("write {}", path.display()))?;
1494 Ok(path)
1495}
1496
1497#[cfg(test)]
1504mod failpoint {
1505 use std::cell::Cell;
1506
1507 thread_local! {
1508 static FORCE_PUT_FAILURES: Cell<u32> = const { Cell::new(0) };
1509 }
1510
1511 pub(super) fn force_put_failures(count: u32) {
1514 FORCE_PUT_FAILURES.with(|c| c.set(count));
1515 }
1516
1517 pub(super) fn take_forced_put_failure() -> bool {
1520 FORCE_PUT_FAILURES.with(|c| {
1521 let n = c.get();
1522 if n == 0 {
1523 false
1524 } else {
1525 c.set(n - 1);
1526 true
1527 }
1528 })
1529 }
1530}
1531
1532fn short(id: &str) -> &str {
1533 id.split('-').next_back().unwrap_or(id)
1534}
1535
1536fn new_id() -> String {
1537 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
1538 let seed = crate::rng::entropy();
1539 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
1540}
1541
1542fn attachment_ext(mime: &str) -> Option<&'static str> {
1547 match mime {
1548 "image/png" => Some("png"),
1549 "image/jpeg" => Some("jpg"),
1550 "image/gif" => Some("gif"),
1551 "image/webp" => Some("webp"),
1552 _ => None,
1553 }
1554}
1555
1556pub fn valid_attachment_id(id: &str) -> bool {
1561 id.len() == 32
1562 && id
1563 .bytes()
1564 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
1565}
1566
1567fn new_attachment_id() -> String {
1571 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy());
1572 format!("{:016x}{:016x}", r.next_u64(), r.next_u64())
1573}
1574
1575#[cfg(test)]
1576mod tests {
1577 #[test]
1578 fn the_briefing_points_at_origin_main_not_the_working_tree() {
1579 let b = briefing(Path::new("/r"), "en", false);
1580 assert!(b.contains("origin/main"));
1581 assert!(b.contains("git show origin/main:"));
1582 }
1583 use std::collections::BTreeMap;
1584
1585 use crate::config::{AgentChoice, AgentKind, AgentSpec, Graph};
1586 use crate::queue::{Queue, Source, Task};
1587
1588 use super::*;
1589
1590 fn ctx_agent(id: &str, model: Option<&str>) -> AgentSpec {
1591 AgentSpec {
1592 id: id.to_owned(),
1593 kind: AgentKind::Command,
1594 model: model.map(str::to_owned),
1595 command: Vec::new(),
1596 extra_args: Vec::new(),
1597 env: BTreeMap::new(),
1598 prompt_delivery: None,
1599 }
1600 }
1601
1602 fn ctx_talk(agent: &str, turns: Vec<Turn>) -> Talk {
1603 Talk {
1604 schema: SCHEMA,
1605 id: "20260904-014455-ab12".to_owned(),
1606 repo: PathBuf::from("."),
1607 agent: agent.to_owned(),
1608 status: TalkStatus::Open,
1609 turns,
1610 pending: String::new(),
1611 pending_attachments: Vec::new(),
1612 fallback: false,
1613 created_at: Timestamp::now(),
1614 updated_at: Timestamp::now(),
1615 seat: SeatState::new(SEAT, agent, 1),
1616 }
1617 }
1618
1619 fn reply(body: &str, usage: Option<(u64, &str, Option<&str>)>) -> Turn {
1620 Turn {
1621 who: Who::Agent,
1622 body: body.to_owned(),
1623 at: Timestamp::now(),
1624 attachments: Vec::new(),
1625 usage: usage.map(|(t, a, m)| TurnUsage {
1626 context_tokens: t,
1627 agent: a.to_owned(),
1628 model: m.map(str::to_owned),
1629 }),
1630 }
1631 }
1632
1633 fn ctx_config(windows: &[(&str, u64)]) -> Config {
1634 Config {
1635 agents: vec![
1636 ctx_agent("small", Some("small-model")),
1637 ctx_agent("big", Some("big-model")),
1638 ctx_agent("plain", None),
1639 ],
1640 context_windows: windows.iter().map(|(k, v)| ((*k).to_owned(), *v)).collect(),
1641 ..Config::default()
1642 }
1643 }
1644
1645 #[test]
1646 fn context_usage_computes_percent_and_warns_at_eighty() {
1647 let cfg = ctx_config(&[("small-model", 1000)]);
1648 let at = |tokens| {
1649 let t = ctx_talk(
1650 "small",
1651 vec![reply("hi", Some((tokens, "small", Some("small-model"))))],
1652 );
1653 context_usage(&t, Some(&cfg))
1654 };
1655 let u = at(799);
1656 assert_eq!((u.percent, u.warn, u.window), (Some(79), false, Some(1000)));
1657 let u = at(800);
1658 assert_eq!((u.percent, u.warn), (Some(80), true));
1659 let u = at(1500);
1660 assert_eq!((u.percent, u.warn), (Some(150), true));
1661 assert!(!u.since_switch);
1662 }
1663
1664 #[test]
1665 fn context_usage_is_unknown_without_usage_and_never_looks_back() {
1666 let cfg = ctx_config(&[("small-model", 1000)]);
1667 let t = ctx_talk(
1668 "small",
1669 vec![
1670 reply("old", Some((900, "small", Some("small-model")))),
1671 reply("new", None),
1672 ],
1673 );
1674 let u = context_usage(&t, Some(&cfg));
1675 assert!(u.estimated);
1677 assert_ne!(u.tokens, Some(900));
1678 assert!(u.tokens.is_some());
1679 let t = ctx_talk(
1681 "small",
1682 vec![
1683 reply("old", Some((900, "small", Some("small-model")))),
1684 reply("magi: could not run agent", None),
1685 ],
1686 );
1687 assert_eq!(context_usage(&t, Some(&cfg)).tokens, Some(900));
1688 assert_eq!(
1689 context_usage(&ctx_talk("small", Vec::new()), Some(&cfg)).tokens,
1690 None
1691 );
1692 }
1693
1694 #[test]
1695 fn estimate_counts_chars_both_sides_and_standing_prompt() {
1696 let mut t = ctx_talk("small", vec![reply("abcdefg", None)]);
1697 assert_eq!(estimate_context_tokens(&t, 0), Some(2)); let op = Turn {
1699 who: Who::Operator,
1700 ..reply("abcdefg", None)
1701 };
1702 t.turns.push(op);
1703 assert_eq!(estimate_context_tokens(&t, 0), Some(4));
1704 assert!(
1705 estimate_context_tokens(&t, 700).unwrap() > estimate_context_tokens(&t, 0).unwrap()
1706 );
1707 let ja = ctx_talk("small", vec![reply("日本語日本語日", None)]);
1709 assert_eq!(estimate_context_tokens(&ja, 0), Some(2));
1710 let note = ctx_talk("small", vec![reply("magi: could not run agent", None)]);
1712 assert_eq!(estimate_context_tokens(¬e, 1000), None);
1713 assert_eq!(
1714 estimate_context_tokens(&ctx_talk("small", Vec::new()), 1000),
1715 None
1716 );
1717 }
1718
1719 #[test]
1720 fn context_usage_measured_wins_and_estimate_gets_percent_and_warn() {
1721 let cfg = ctx_config(&[("small-model", 1000)]);
1722 let t = ctx_talk(
1723 "small",
1724 vec![reply(
1725 &"x".repeat(5000),
1726 Some((10, "small", Some("small-model"))),
1727 )],
1728 );
1729 let u = context_usage(&t, Some(&cfg));
1730 assert_eq!((u.tokens, u.estimated), (Some(10), false));
1731 let t = ctx_talk("small", vec![reply(&"x".repeat(5000), None)]);
1732 let u = context_usage(&t, Some(&cfg));
1733 assert!(u.estimated && !u.since_switch);
1734 assert_eq!(u.window, Some(1000));
1735 assert!(u.warn && u.percent.unwrap() >= 80);
1736 let t = ctx_talk("small", vec![reply("hi", None)]);
1737 let u = context_usage(&t, Some(&cfg));
1738 assert!(u.estimated && u.percent.is_some());
1739 }
1740
1741 #[test]
1742 fn context_usage_without_a_window_shows_tokens_only() {
1743 let cfg = ctx_config(&[]);
1744 let t = ctx_talk("plain", vec![reply("hi", Some((5000, "plain", None)))]);
1746 let u = context_usage(&t, Some(&cfg));
1747 assert_eq!(
1748 (u.tokens, u.window, u.percent, u.warn),
1749 (Some(5000), None, None, false)
1750 );
1751 let t = ctx_talk(
1752 "small",
1753 vec![reply("hi", Some((5000, "small", Some("small-model"))))],
1754 );
1755 assert_eq!(context_usage(&t, Some(&cfg)).percent, None);
1756 assert_eq!(context_usage(&t, None).window, None);
1758 }
1759
1760 #[test]
1761 fn context_usage_switching_model_changes_the_denominator() {
1762 let cfg = ctx_config(&[("small-model", 1000), ("big-model", 10_000)]);
1763 let used = reply("hi", Some((900, "small", Some("small-model"))));
1764 let before = context_usage(&ctx_talk("small", vec![used.clone()]), Some(&cfg));
1765 assert_eq!(
1766 (before.percent, before.warn, before.since_switch),
1767 (Some(90), true, false)
1768 );
1769 let after = context_usage(&ctx_talk("big", vec![used]), Some(&cfg));
1772 assert_eq!(after.window, Some(10_000));
1773 assert_eq!(
1774 (after.percent, after.warn, after.since_switch),
1775 (Some(9), false, true)
1776 );
1777 assert_eq!(after.model.as_deref(), Some("big-model"));
1778 }
1779
1780 #[test]
1781 fn a_turn_recorded_before_usage_existed_still_reads() {
1782 let old = r#"{"who":"agent","body":"hi","at":"2026-09-04T01:44:55Z"}"#;
1783 let turn: Turn = serde_json::from_str(old).expect("old turn reads");
1784 assert!(turn.usage.is_none());
1785 let json = serde_json::to_string(&turn).expect("serialize");
1786 assert!(
1787 !json.contains("usage"),
1788 "absent usage is not written: {json}"
1789 );
1790 }
1791
1792 fn store() -> (tempfile::TempDir, Talks) {
1794 let tmp = tempfile::tempdir().expect("tempdir");
1795 let talks = Talks::at(tmp.path().join("talks"));
1796 (tmp, talks)
1797 }
1798
1799 fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
1803 let path = dir.join("mock-talk-agent.sh");
1804 std::fs::write(&path, script).expect("write mock");
1805 AgentSpec {
1806 id: "mock".to_owned(),
1807 kind: AgentKind::Command,
1808 model: None,
1809 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
1810 extra_args: Vec::new(),
1811 env,
1812 prompt_delivery: None,
1813 }
1814 }
1815
1816 fn config(spec: AgentSpec) -> Config {
1817 Config {
1818 agents: vec![spec],
1819 graph: Graph {
1820 language: "en".to_owned(),
1821 ..Graph::default()
1822 },
1823 ..Config::default()
1824 }
1825 }
1826
1827 const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
1829
1830 const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
1832
1833 const ECHO: &str = "#!/bin/sh\ncat\n";
1836
1837 fn env(reply: &str) -> BTreeMap<String, String> {
1838 BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
1839 }
1840
1841 #[test]
1842 fn the_frozen_json_field_names_round_trip_through_disk() {
1843 let (tmp, talks) = store();
1844 let mut talk = Talk {
1845 schema: SCHEMA,
1846 id: "20260904-014455-ab12".to_owned(),
1847 repo: tmp.path().to_owned(),
1848 agent: "sonnet".to_owned(),
1849 status: TalkStatus::Open,
1850 turns: Vec::new(),
1851 pending: String::new(),
1852 pending_attachments: Vec::new(),
1853 fallback: false,
1854 created_at: Timestamp::now(),
1855 updated_at: Timestamp::now(),
1856 seat: SeatState::new(SEAT, "sonnet", 7),
1857 };
1858 talks.put(&mut talk).expect("put");
1859
1860 let raw = std::fs::read_to_string(talks.path_of(&talk.id)).expect("read back");
1861 let v: serde_json::Value = serde_json::from_str(&raw).expect("parse");
1862 for field in [
1863 "schema",
1864 "id",
1865 "repo",
1866 "agent",
1867 "status",
1868 "turns",
1869 "created_at",
1870 "updated_at",
1871 ] {
1872 assert!(v.get(field).is_some(), "missing field `{field}`");
1873 }
1874 assert_eq!(v["schema"], 1);
1875 assert_eq!(v["status"], "open");
1876
1877 let back = talks.get(&talk.id).expect("get");
1878 assert_eq!(back.id, talk.id);
1879 assert_eq!(back.status, TalkStatus::Open);
1880 }
1881
1882 #[test]
1883 fn opening_a_talk_takes_no_agent_turn() {
1884 let (tmp, talks) = store();
1885 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
1889 let cfg = config(spec);
1890
1891 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1892 assert_eq!(talk.status, TalkStatus::Open);
1893 assert!(talk.turns.is_empty(), "nothing has been said yet");
1894
1895 let on_disk = talks.get(&talk.id).expect("get");
1896 assert_eq!(on_disk.turns.len(), 0);
1897 }
1898
1899 #[test]
1907 fn chatter_wins_when_set_and_falls_back_to_pick_s_default_order_otherwise() {
1908 let (tmp, talks) = store();
1909 let first_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
1910 let mut chatter_spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
1911 chatter_spec.id = "chatter-mock".to_owned();
1912
1913 let mut cfg = Config {
1914 agents: vec![first_spec.clone(), chatter_spec.clone()],
1915 graph: Graph {
1916 language: "en".to_owned(),
1917 ..Graph::default()
1918 },
1919 ..Config::default()
1920 };
1921 cfg.roles.chatter = Some(chatter_spec.id.as_str().into());
1922
1923 let talk =
1924 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter set");
1925 assert_eq!(talk.agent, chatter_spec.id, "an explicit chatter must win");
1926
1927 cfg.roles.chatter = None;
1928 let fallback =
1929 begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin with chatter unset");
1930 assert_eq!(
1931 fallback.agent, first_spec.id,
1932 "unset chatter must fall back to agent::pick's own default order"
1933 );
1934 }
1935
1936 #[test]
1939 fn a_talk_recorded_without_attachments_still_reads() {
1940 let (tmp, talks) = store();
1941 let path = talks.path_of("20260904-014455-ab12");
1942 std::fs::create_dir_all(talks.root()).expect("talks dir");
1943 std::fs::write(
1944 &path,
1945 serde_json::json!({
1946 "schema": 1,
1947 "id": "20260904-014455-ab12",
1948 "repo": tmp.path(),
1949 "agent": "sonnet",
1950 "status": "open",
1951 "turns": [
1952 { "who": "operator", "body": "still there?",
1953 "at": Timestamp::now().to_string() },
1954 ],
1955 "created_at": Timestamp::now().to_string(),
1956 "updated_at": Timestamp::now().to_string(),
1957 "seat": SeatState::new(SEAT, "sonnet", 7),
1958 })
1959 .to_string(),
1960 )
1961 .expect("write pre-attachments talk");
1962
1963 let talk = talks.get("20260904-014455-ab12").expect("must still read");
1964 assert!(talk.turns[0].attachments.is_empty());
1965 }
1966
1967 #[test]
1968 fn queued_text_is_durable_combined_and_drained_as_one_operator_turn() {
1969 let (tmp, talks) = store();
1970 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
1971 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1972
1973 queue(&mut talk, &talks, "first", Vec::new()).expect("queue first");
1974 queue(&mut talk, &talks, "second", Vec::new()).expect("queue second");
1975 let saved = talks.get(&talk.id).expect("reload queued talk");
1976 assert_eq!(saved.pending, "first\n\nsecond");
1977 assert!(saved.turns.is_empty(), "a draft is not a transcript turn");
1978
1979 let drained = drain(&mut talk, &talks).expect("drain");
1980 assert_eq!(drained.as_deref(), Some("first\n\nsecond"));
1981 let saved = talks.get(&talk.id).expect("reload drained talk");
1982 assert!(saved.pending.is_empty());
1983 assert_eq!(saved.turns.len(), 1);
1984 assert_eq!(saved.turns[0].body, "first\n\nsecond");
1985 }
1986
1987 #[test]
1988 fn editing_a_queued_draft_preserves_its_attachments_and_rejects_a_stale_snapshot() {
1989 let (tmp, talks) = store();
1990 let cfg = config(mock_agent(tmp.path(), REPLY, env("reply")));
1991 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
1992 let attachment = Attachment {
1993 id: "a".repeat(32),
1994 name: "shot.png".to_owned(),
1995 mime: "image/png".to_owned(),
1996 bytes: 3,
1997 };
1998
1999 queue(&mut talk, &talks, "first", vec![attachment.clone()]).expect("queue");
2000 assert!(
2001 edit_pending_text(
2002 &mut talk,
2003 &talks,
2004 "corrected",
2005 "first",
2006 std::slice::from_ref(&attachment.id),
2007 )
2008 .expect("edit")
2009 );
2010 let saved = talks.get(&talk.id).expect("reload edited draft");
2011 assert_eq!(saved.pending, "corrected");
2012 assert_eq!(saved.pending_attachments, vec![attachment]);
2013
2014 queue(&mut talk, &talks, "later", Vec::new()).expect("queue concurrent draft");
2015 assert!(
2016 !edit_pending_text(
2017 &mut talk,
2018 &talks,
2019 "stale edit",
2020 "corrected",
2021 &["a".repeat(32)],
2022 )
2023 .expect("stale edit is a conflict")
2024 );
2025 assert_eq!(
2026 talks.get(&talk.id).expect("reload after conflict").pending,
2027 "corrected\n\nlater"
2028 );
2029 assert!(
2030 !clear_pending_if_matches(&mut talk, &talks, "corrected", &["a".repeat(32)])
2031 .expect("stale clear is a conflict")
2032 );
2033 assert_eq!(
2034 talks
2035 .get(&talk.id)
2036 .expect("reload after stale clear")
2037 .pending,
2038 "corrected\n\nlater"
2039 );
2040 }
2041
2042 #[tokio::test]
2043 async fn a_reply_save_preserves_pending_accepted_while_the_cli_runs() {
2044 let (tmp, talks) = store();
2045 let slow = "#!/bin/sh\ncat >/dev/null\nsleep 0.1\nprintf reply\n";
2046 let cfg = config(mock_agent(tmp.path(), slow, BTreeMap::new()));
2047 let mut running = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2048 let id = running.id.clone();
2049 let first = record(&mut running, &talks, "first", Vec::new()).expect("record");
2050
2051 let response_talks = talks.clone();
2052 let response_cfg = cfg.clone();
2053 let reply = tokio::spawn(async move {
2054 respond(&mut running, &response_talks, &response_cfg, &first).await
2055 });
2056 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
2057
2058 let mut queued = talks.get(&id).expect("queued handle");
2059 queue(&mut queued, &talks, "next", Vec::new()).expect("queue");
2060 reply.await.expect("join").expect("reply");
2061
2062 let saved = talks.get(&id).expect("reload");
2063 assert_eq!(saved.pending, "next");
2064 assert_eq!(saved.turns.len(), 2, "operator message and reply remain");
2065 }
2066
2067 fn counting_agent(dir: &Path, id: &str, body: &str) -> AgentSpec {
2070 let calls = dir.join(format!("{id}.calls"));
2071 let script = format!(
2072 "#!/bin/sh\necho x >> '{}'\n{body}\n",
2073 calls.to_string_lossy()
2074 );
2075 let path = dir.join(format!("mock-{id}.sh"));
2076 std::fs::write(&path, script).expect("write mock");
2077 AgentSpec {
2078 id: id.to_owned(),
2079 kind: AgentKind::Command,
2080 model: None,
2081 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
2082 extra_args: Vec::new(),
2083 env: BTreeMap::new(),
2084 prompt_delivery: None,
2085 }
2086 }
2087
2088 fn calls(dir: &Path, id: &str) -> usize {
2089 std::fs::read_to_string(dir.join(format!("{id}.calls"))).map_or(0, |s| s.lines().count())
2090 }
2091
2092 fn chain_config(specs: Vec<AgentSpec>, ids: &[&str]) -> Config {
2093 let mut cfg = config(specs[0].clone());
2094 cfg.agents = specs;
2095 cfg.roles.chatter = Some(AgentChoice::Chain(
2096 ids.iter().map(|s| (*s).to_owned()).collect(),
2097 ));
2098 cfg
2099 }
2100
2101 #[tokio::test]
2102 async fn a_chatter_chain_falls_back_resends_the_transcript_and_sticks() {
2103 let (tmp, talks) = store();
2104 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
2105 let b = counting_agent(tmp.path(), "b", "cat");
2106 let cfg = chain_config(vec![a, b], &["a", "b"]);
2107 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2108 assert_eq!(talk.agent, "a");
2109
2110 say(&mut talk, &talks, &cfg, "hello there", Vec::new())
2111 .await
2112 .expect("turn");
2113 assert_eq!(calls(tmp.path(), "a"), 1, "each id is tried once");
2114 assert_eq!(calls(tmp.path(), "b"), 1);
2115 assert_eq!(talk.agent, "b", "the switch persists");
2116 assert!(talks.get(&talk.id).unwrap().agent == "b");
2117 let reply = talk.turns.last().unwrap();
2118 assert!(reply.body.contains("hello there"));
2119 assert!(
2120 reply.body.contains("magi task add --solo"),
2121 "a fresh seat gets the full briefing"
2122 );
2123 assert!(
2124 talk.turns
2125 .iter()
2126 .any(|t| t.body.contains("agent changed from a to b")),
2127 "the switch is noted"
2128 );
2129 }
2130
2131 #[tokio::test]
2132 async fn an_exhausted_chatter_chain_fails_like_a_single_seat_and_stays_put() {
2133 let (tmp, talks) = store();
2134 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
2135 let b = counting_agent(tmp.path(), "b", "cat >/dev/null\nexit 4");
2136 let cfg = chain_config(vec![a, b], &["a", "b", "a"]);
2137 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2138
2139 let err = say(&mut talk, &talks, &cfg, "hi", Vec::new())
2140 .await
2141 .expect_err("every agent failed");
2142 assert!(err.to_string().contains("`a`"), "{err:#}");
2143 assert_eq!(calls(tmp.path(), "a"), 1);
2144 assert_eq!(calls(tmp.path(), "b"), 1);
2145 assert_eq!(talk.agent, "a", "an exhausted chain leaves the agent alone");
2146 }
2147
2148 #[test]
2149 fn a_chatter_chain_skips_an_unknown_id_at_begin() {
2150 let (tmp, talks) = store();
2151 let b = counting_agent(tmp.path(), "b", "cat");
2152 let cfg = chain_config(vec![b], &["ghost", "b"]);
2153 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2154 assert_eq!(talk.agent, "b");
2155 }
2156
2157 #[tokio::test]
2158 async fn an_explicit_agent_inside_the_chatter_chain_stays_pinned() {
2159 let (tmp, talks) = store();
2160 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
2161 let b = counting_agent(tmp.path(), "b", "cat");
2162 let cfg = chain_config(vec![a, b], &["a", "b"]);
2163 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("a")).expect("begin");
2164 say(&mut talk, &talks, &cfg, "hi", Vec::new())
2165 .await
2166 .expect_err("a alone, and it fails");
2167 assert_eq!(calls(tmp.path(), "b"), 0);
2168 assert_eq!(talk.agent, "a");
2169 }
2170
2171 #[tokio::test]
2172 async fn an_explicit_agent_does_not_borrow_the_chatter_chain() {
2173 let (tmp, talks) = store();
2174 let a = counting_agent(tmp.path(), "a", "cat >/dev/null\nexit 3");
2175 let b = counting_agent(tmp.path(), "b", "cat");
2176 let c = counting_agent(tmp.path(), "c", "cat >/dev/null\nexit 3");
2177 let cfg = chain_config(vec![a, b, c], &["a", "b"]);
2178 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some("c")).expect("begin");
2179 say(&mut talk, &talks, &cfg, "hi", Vec::new())
2180 .await
2181 .expect_err("c alone, and it fails");
2182 assert_eq!(calls(tmp.path(), "b"), 0);
2183 }
2184
2185 #[tokio::test]
2186 async fn the_first_turn_carries_the_briefing_and_later_turns_do_not() {
2187 let (tmp, talks) = store();
2188 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
2189 let cfg = config(spec);
2190 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2191
2192 say(
2193 &mut talk,
2194 &talks,
2195 &cfg,
2196 "what does the queue module do?",
2197 Vec::new(),
2198 )
2199 .await
2200 .expect("first turn");
2201 let first_prompt = &talk.turns[1].body;
2202 assert!(first_prompt.contains("magi task add --solo"));
2203 assert!(first_prompt.contains("what does the queue module do?"));
2204
2205 say(&mut talk, &talks, &cfg, "and how is it locked?", Vec::new())
2206 .await
2207 .expect("second turn");
2208 let second_prompt = &talk.turns[3].body;
2209 assert!(
2210 !second_prompt.contains("magi task add --solo"),
2211 "the briefing is sent once, not on every turn: {second_prompt}"
2212 );
2213 assert!(second_prompt.contains("and how is it locked?"));
2214 }
2215
2216 #[tokio::test]
2217 async fn switching_agent_resets_the_seat_notes_it_and_resends_the_transcript() {
2218 let (tmp, talks) = store();
2219 let a = mock_agent(tmp.path(), ECHO, BTreeMap::new());
2220 let mut b = a.clone();
2221 b.id = "other".to_owned();
2222 let mut cfg = config(a.clone());
2223 cfg.agents.push(b.clone());
2224 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), Some(&a.id)).expect("begin");
2225 say(&mut talk, &talks, &cfg, "remember the walrus", Vec::new())
2226 .await
2227 .expect("first turn");
2228 let old_session = talk.seat.claude_session.clone();
2229 assert_eq!(talk.seat.turns, 1);
2230
2231 assert!(switch_agent(&mut talk, &talks, &b).expect("switch"));
2232 assert_eq!(talk.agent, "other");
2233 assert_eq!(talk.seat.turns, 0);
2234 assert_eq!(talk.seat.agent, "other");
2235 assert_ne!(talk.seat.claude_session, old_session);
2236 let note = talk.turns.last().expect("note");
2237 assert_eq!(note.who, Who::Agent);
2238 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
2239 assert!(note.body.contains("changed from"), "{}", note.body);
2240 assert_eq!(talks.get(&talk.id).expect("reload").agent, "other");
2241
2242 let before = talk.turns.len();
2243 assert!(!switch_agent(&mut talk, &talks, &b).expect("same agent"));
2244 assert_eq!(talk.turns.len(), before, "a no-op writes no note");
2245
2246 say(&mut talk, &talks, &cfg, "what did I say?", Vec::new())
2247 .await
2248 .expect("turn after switch");
2249 let prompt = &talk.turns.last().expect("reply").body;
2250 assert!(prompt.contains("remember the walrus"), "{prompt}");
2251 assert!(prompt.contains("## magi"), "{prompt}");
2252 assert!(prompt.contains("what did I say?"), "{prompt}");
2253 }
2254
2255 #[tokio::test]
2256 async fn say_appends_the_operator_turn_then_the_agent_turn() {
2257 let (tmp, talks) = store();
2258 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
2259 let cfg = config(spec);
2260 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2261
2262 say(
2263 &mut talk,
2264 &talks,
2265 &cfg,
2266 "can I rename this function?",
2267 Vec::new(),
2268 )
2269 .await
2270 .expect("say");
2271
2272 assert_eq!(talk.turns.len(), 2);
2273 assert_eq!(talk.turns[0].who, Who::Operator);
2274 assert_eq!(talk.turns[0].body, "can I rename this function?");
2275 assert_eq!(talk.turns[1].who, Who::Agent);
2276 assert_eq!(talk.turns[1].body, "go ahead");
2277 assert_eq!(talks.get(&talk.id).expect("get").turns, talk.turns);
2278 }
2279
2280 #[tokio::test]
2281 async fn a_failed_turn_keeps_the_operator_message_and_says_what_happened() {
2282 let (tmp, talks) = store();
2283 let spec = mock_agent(tmp.path(), BROKEN, BTreeMap::new());
2284 let cfg = config(spec);
2285 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2286
2287 let err = say(&mut talk, &talks, &cfg, "check the tests", Vec::new())
2288 .await
2289 .expect_err("a turn with no answer is an error");
2290 assert!(err.to_string().contains("no answer"), "{err}");
2291
2292 let on_disk = talks.get(&talk.id).expect("get");
2293 assert_eq!(on_disk.turns.len(), 2);
2294 assert_eq!(on_disk.turns[0].body, "check the tests");
2295 let note = &on_disk.turns[1];
2296 assert_eq!(note.who, Who::Agent);
2297 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
2298 assert!(note.body.contains("your message is saved"));
2299 }
2300
2301 #[tokio::test]
2307 async fn a_passing_write_failure_while_saving_the_reply_does_not_lose_it() {
2308 let (tmp, talks) = store();
2309 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
2310 let cfg = config(spec);
2311 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2312
2313 let text =
2314 record(&mut talk, &talks, "can I rename this function?", Vec::new()).expect("record");
2315 failpoint::force_put_failures(PUT_RETRIES - 1);
2318 respond(&mut talk, &talks, &cfg, &text)
2319 .await
2320 .expect("respond must survive a write failure its own retries can outlast");
2321
2322 assert_eq!(talk.turns.len(), 2);
2323 assert_eq!(talk.turns[1].who, Who::Agent);
2324 assert_eq!(talk.turns[1].body, "go ahead");
2325 let on_disk = talks.get(&talk.id).expect("get");
2326 assert_eq!(
2327 on_disk.turns, talk.turns,
2328 "the reply must reach disk despite the early write failures"
2329 );
2330 }
2331
2332 #[tokio::test]
2338 async fn a_persistent_write_failure_while_saving_the_reply_is_never_silent() {
2339 let (tmp, talks) = store();
2340 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
2341 let cfg = config(spec);
2342 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2343
2344 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
2345 failpoint::force_put_failures(PUT_RETRIES);
2350 let err = respond(&mut talk, &talks, &cfg, &text)
2351 .await
2352 .expect_err("a reply that cannot be saved must be reported, not swallowed");
2353 assert!(err.to_string().contains("could not be saved"), "{err}");
2354
2355 let on_disk = talks.get(&talk.id).expect("get");
2356 assert_eq!(
2357 on_disk.turns.len(),
2358 2,
2359 "the operator turn plus a visible note"
2360 );
2361 assert_eq!(on_disk.turns[0].body, "check the tests");
2362 let note = &on_disk.turns[1];
2363 assert_eq!(note.who, Who::Agent);
2364 assert!(note.body.starts_with(MAGI_NOTE), "{}", note.body);
2365 assert!(
2366 note.body.contains("could not be saved"),
2367 "the operator must be told the reply is missing, not left staring \
2368 at a gap with no explanation: {}",
2369 note.body
2370 );
2371 assert_eq!(
2372 talk.turns, on_disk.turns,
2373 "the in-memory talk must match what actually landed on disk"
2374 );
2375
2376 let artifacts = talks.artifacts_of(&talk.id);
2379 let stash = std::fs::read_dir(&artifacts)
2380 .expect("artifacts dir")
2381 .filter_map(|e| e.ok())
2382 .find(|e| e.file_name().to_string_lossy().ends_with("-lost.txt"))
2383 .expect("a stash file for the lost reply");
2384 let stashed = std::fs::read_to_string(stash.path()).expect("read stash");
2385 assert_eq!(stashed, "go ahead");
2386
2387 assert_eq!(
2395 on_disk.seat.turns, 1,
2396 "the note's write must carry the turn the CLI actually took"
2397 );
2398 assert_eq!(
2399 on_disk.seat.claude_session, talk.seat.claude_session,
2400 "the session id handed to the CLI must survive the failed reply"
2401 );
2402 assert_eq!(on_disk.seat.captured_session, talk.seat.captured_session);
2403 assert!(
2404 agent::has_session(AgentKind::Command, &on_disk.seat, cfg.graph.sessions),
2405 "the next turn must resume, not open the same session id twice"
2406 );
2407 }
2408
2409 #[tokio::test]
2414 async fn a_write_failure_that_also_loses_the_note_still_reports_it() {
2415 let (tmp, talks) = store();
2416 let spec = mock_agent(tmp.path(), REPLY, env("go ahead"));
2417 let cfg = config(spec);
2418 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2419
2420 let text = record(&mut talk, &talks, "check the tests", Vec::new()).expect("record");
2421 failpoint::force_put_failures(PUT_RETRIES * 2);
2424 let err = respond(&mut talk, &talks, &cfg, &text)
2425 .await
2426 .expect_err("neither the reply nor the note could be saved");
2427 assert!(err.to_string().contains("could not be saved"), "{err}");
2428
2429 assert_eq!(talk.turns.len(), 1, "only the operator's own turn");
2430 let on_disk = talks.get(&talk.id).expect("get");
2431 assert_eq!(on_disk.turns.len(), 1);
2432
2433 assert_eq!(
2443 on_disk.seat.turns, 0,
2444 "an unwritable file cannot record the turn the CLI took"
2445 );
2446 assert_eq!(
2447 talk.seat.turns, 1,
2448 "the in-memory seat still reports the turn the CLI actually took"
2449 );
2450 assert_eq!(
2451 on_disk.seat.claude_session, talk.seat.claude_session,
2452 "the session id was minted at `begin` and never changes here"
2453 );
2454 }
2455
2456 #[tokio::test]
2460 async fn attachments_reach_the_prompt_and_an_empty_body_is_still_a_turn() {
2461 let (tmp, talks) = store();
2462 let spec = mock_agent(tmp.path(), ECHO, BTreeMap::new());
2463 let cfg = config(spec);
2464 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2465
2466 let att = talks
2467 .put_attachment(
2468 &talk.id,
2469 "image/png",
2470 "screenshot.png",
2471 b"pretend-png-bytes",
2472 )
2473 .expect("put attachment");
2474
2475 say(&mut talk, &talks, &cfg, "", vec![att.clone()])
2476 .await
2477 .expect("an empty body with an attachment is still a turn");
2478
2479 let operator_turn = &talk.turns[0];
2480 assert_eq!(operator_turn.who, Who::Operator);
2481 assert_eq!(operator_turn.body, "");
2482 assert_eq!(operator_turn.attachments, vec![att.clone()]);
2483
2484 let prompt = &talk.turns[1].body;
2485 let expected_path = talks
2486 .attachments_dir(&talk.id)
2487 .join(format!("{}.png", att.id));
2488 assert!(
2489 prompt.contains(&expected_path.display().to_string()),
2490 "the agent must be told the attachment's absolute path: {prompt}"
2491 );
2492 assert!(prompt.contains("image/png"), "and its mime: {prompt}");
2493 }
2494
2495 #[test]
2504 fn attachment_path_is_absolute_even_when_the_store_root_is_relative() {
2505 let talks = Talks::at(PathBuf::from("relative-talks-root-for-this-test"));
2506 let att = Attachment {
2507 id: "0".repeat(32),
2508 name: "shot.png".to_owned(),
2509 mime: "image/png".to_owned(),
2510 bytes: 3,
2511 };
2512 let path = talks
2513 .attachment_path("some-talk-id", &att)
2514 .expect("a supported mime always yields a path");
2515 assert!(
2516 path.is_absolute(),
2517 "must be absolute even off a relative store root: {}",
2518 path.display()
2519 );
2520 }
2521
2522 #[tokio::test]
2523 async fn a_turn_past_the_configured_talk_timeout_is_reported_with_that_timeout() {
2524 let (tmp, talks) = store();
2529 let slow = mock_agent(
2530 tmp.path(),
2531 "#!/bin/sh\ncat >/dev/null\nsleep 2\n",
2532 BTreeMap::new(),
2533 );
2534 let mut cfg = config(slow);
2535 cfg.graph.timeout_talk = 1;
2536 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2537
2538 let err = say(&mut talk, &talks, &cfg, "check the tests", Vec::new())
2539 .await
2540 .expect_err("a turn that never answers is an error");
2541 assert!(
2542 err.to_string().contains("did not answer within 1s"),
2543 "{err}"
2544 );
2545
2546 let on_disk = talks.get(&talk.id).expect("get");
2547 let note = on_disk.turns.last().expect("a note turn was recorded");
2548 assert!(
2549 note.body.contains("did not answer within 1s"),
2550 "the transcript must show the configured timeout: {}",
2551 note.body
2552 );
2553 }
2554
2555 #[test]
2556 fn closing_is_idempotent_and_a_closed_talk_takes_no_more_turns() {
2557 let (tmp, talks) = store();
2558 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2559 let cfg = config(spec);
2560 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2561
2562 close(&mut talk, &talks).expect("close");
2563 assert_eq!(talk.status, TalkStatus::Closed);
2564 close(&mut talk, &talks).expect("closing twice is not an error");
2565
2566 let err =
2567 record(&mut talk, &talks, "still there?", Vec::new()).expect_err("closed talks refuse");
2568 assert!(err.to_string().contains("closed"));
2569 let _ = &cfg; }
2571
2572 #[tokio::test]
2573 async fn a_close_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
2574 let (tmp, talks) = store();
2575 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
2576 let cfg = config(spec);
2577 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2580
2581 let mut closed_elsewhere = talks.get(&in_flight.id).expect("reread");
2585 close(&mut closed_elsewhere, &talks).expect("close");
2586 assert_eq!(
2587 talks.get(&in_flight.id).expect("reread").status,
2588 TalkStatus::Closed,
2589 "the close landed on disk before the turn finished"
2590 );
2591
2592 assert_eq!(in_flight.status, TalkStatus::Open);
2596 respond(&mut in_flight, &talks, &cfg, "one more question")
2597 .await
2598 .expect("the turn itself still completes");
2599
2600 let on_disk = talks.get(&in_flight.id).expect("reread");
2601 assert_eq!(
2602 on_disk.status,
2603 TalkStatus::Closed,
2604 "a close must stick even when a turn that started before it finishes after it"
2605 );
2606 assert!(
2609 on_disk.turns.iter().any(|t| t.body == "here you go"),
2610 "the in-flight turn's own reply is still recorded: {:?}",
2611 on_disk.turns
2612 );
2613 }
2614
2615 #[test]
2616 fn a_close_that_lands_before_record_is_called_is_not_undone_by_it() {
2617 let (tmp, talks) = store();
2618 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2619 let cfg = config(spec);
2620 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2623
2624 let mut closed_elsewhere = talks.get(&stale.id).expect("reread");
2627 close(&mut closed_elsewhere, &talks).expect("close");
2628 assert_eq!(
2629 talks.get(&stale.id).expect("reread").status,
2630 TalkStatus::Closed,
2631 "the close landed on disk before record was called"
2632 );
2633
2634 assert_eq!(stale.status, TalkStatus::Open);
2638 let err = record(&mut stale, &talks, "still there?", Vec::new())
2639 .expect_err("a close that landed first must be honored, not overwritten");
2640 assert!(err.to_string().contains("closed"));
2641
2642 let on_disk = talks.get(&stale.id).expect("reread");
2643 assert_eq!(
2644 on_disk.status,
2645 TalkStatus::Closed,
2646 "record must not resurrect a conversation closed while its snapshot was stale"
2647 );
2648 assert!(
2649 on_disk.turns.is_empty(),
2650 "the rejected turn must not have been appended: {:?}",
2651 on_disk.turns
2652 );
2653 let _ = &cfg; }
2655
2656 #[test]
2657 fn close_blocks_on_records_guard_rather_than_interleaving_with_it() {
2658 let (tmp, talks) = store();
2659 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2660 let cfg = config(spec);
2661 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2662
2663 let held = talks.guard();
2667
2668 let talks2 = talks.clone();
2669 let id = talk.id.clone();
2670 let closing = std::thread::spawn(move || {
2671 let mut talk = talks2.get(&id).expect("get");
2672 close(&mut talk, &talks2).expect("close");
2673 });
2674
2675 std::thread::sleep(Duration::from_millis(50));
2676 assert!(
2677 !closing.is_finished(),
2678 "close must wait for the guard, not read and write while it is held - \
2679 a re-read alone narrows this window without closing it"
2680 );
2681
2682 drop(held);
2683 closing.join().expect("close thread panicked");
2684
2685 assert_eq!(
2686 talks.get(&talk.id).expect("reread").status,
2687 TalkStatus::Closed,
2688 "once the guard is free, close still lands"
2689 );
2690 let _ = &cfg; }
2692
2693 #[test]
2694 fn reopening_a_closed_talk_lets_it_take_turns_again_and_reopening_twice_is_not_an_error() {
2695 let (tmp, talks) = store();
2696 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2697 let cfg = config(spec);
2698 let mut talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2699
2700 close(&mut talk, &talks).expect("close");
2701 assert_eq!(talk.status, TalkStatus::Closed);
2702
2703 reopen(&mut talk, &talks).expect("reopen");
2704 assert_eq!(talk.status, TalkStatus::Open);
2705 assert_eq!(
2706 talks.get(&talk.id).expect("reread").status,
2707 TalkStatus::Open
2708 );
2709
2710 reopen(&mut talk, &talks).expect("reopening an open talk is not an error");
2712 assert_eq!(talk.status, TalkStatus::Open);
2713
2714 record(&mut talk, &talks, "one more thing", Vec::new())
2715 .expect("a reopened talk takes turns again");
2716 let _ = &cfg; }
2718
2719 #[test]
2720 fn removing_a_talk_deletes_its_record_and_artifacts_and_refuses_an_unknown_id() {
2721 let (tmp, talks) = store();
2722 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2723 let cfg = config(spec);
2724 let talk = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2725
2726 let artifacts = talks.artifacts_of(&talk.id);
2727 std::fs::create_dir_all(&artifacts).expect("create artifacts dir");
2728 std::fs::write(artifacts.join("turn-1.txt"), "hello").expect("write artifact");
2729
2730 talks.remove(&talk.id).expect("remove");
2731 assert!(!talks.path_of(&talk.id).is_file(), "the record is gone");
2732 assert!(!artifacts.is_dir(), "the artifacts directory is gone");
2733 assert!(
2734 talks.get(&talk.id).is_err(),
2735 "a removed talk cannot be read back"
2736 );
2737
2738 let err = talks
2739 .remove("nonexistent-id")
2740 .expect_err("unknown id refused");
2741 assert!(err.to_string().contains("no talk matches"), "{err}");
2742 let _ = &cfg; }
2744
2745 #[tokio::test]
2746 async fn a_delete_that_lands_while_a_turn_is_in_flight_is_not_undone_by_the_reply() {
2747 let (tmp, talks) = store();
2748 let spec = mock_agent(tmp.path(), REPLY, env("here you go"));
2749 let cfg = config(spec);
2750 let mut in_flight = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2753
2754 talks.remove(&in_flight.id).expect("remove");
2755 assert!(
2756 talks.get(&in_flight.id).is_err(),
2757 "the delete landed on disk before the turn finished"
2758 );
2759
2760 respond(&mut in_flight, &talks, &cfg, "one more question")
2763 .await
2764 .expect("the turn itself still completes rather than erroring");
2765
2766 assert!(
2767 talks.get(&in_flight.id).is_err(),
2768 "a delete must stick even when a turn that started before it finishes after it"
2769 );
2770 }
2771
2772 #[test]
2773 fn a_delete_that_lands_before_record_is_called_is_not_undone_by_it() {
2774 let (tmp, talks) = store();
2775 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2776 let cfg = config(spec);
2777 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2780
2781 talks.remove(&stale.id).expect("remove");
2782
2783 let err = record(&mut stale, &talks, "still there?", Vec::new())
2787 .expect_err("a delete that landed first must be honored, not overwritten");
2788 assert!(err.to_string().contains("deleted"), "{err}");
2789
2790 assert!(
2791 talks.get(&stale.id).is_err(),
2792 "record must not resurrect a conversation deleted while its snapshot was stale"
2793 );
2794 let _ = &cfg; }
2796
2797 #[test]
2798 fn a_delete_that_lands_before_close_is_called_is_not_undone_by_it() {
2799 let (tmp, talks) = store();
2800 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2801 let cfg = config(spec);
2802 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2805
2806 talks.remove(&stale.id).expect("remove");
2807
2808 let err = close(&mut stale, &talks)
2812 .expect_err("a delete that landed first must be honored, not overwritten");
2813 assert!(err.to_string().contains("deleted"), "{err}");
2814
2815 assert!(
2816 talks.get(&stale.id).is_err(),
2817 "close must not resurrect a conversation deleted while its snapshot was stale"
2818 );
2819 let _ = &cfg; }
2821
2822 #[test]
2823 fn a_delete_that_lands_before_reopen_is_called_is_not_undone_by_it() {
2824 let (tmp, talks) = store();
2825 let spec = mock_agent(tmp.path(), REPLY, env("hi"));
2826 let cfg = config(spec);
2827 let mut stale = begin(&talks, &cfg, tmp.path().to_owned(), None).expect("begin");
2830 close(&mut stale, &talks).expect("close");
2831
2832 talks.remove(&stale.id).expect("remove");
2833
2834 let err = reopen(&mut stale, &talks)
2838 .expect_err("a delete that landed first must be honored, not overwritten");
2839 assert!(err.to_string().contains("deleted"), "{err}");
2840
2841 assert!(
2842 talks.get(&stale.id).is_err(),
2843 "reopen must not resurrect a conversation deleted while its snapshot was stale"
2844 );
2845 let _ = &cfg; }
2847
2848 #[test]
2849 fn list_puts_open_talks_before_closed_ones() {
2850 let (tmp, talks) = store();
2851 let make = |id: &str, status: TalkStatus| {
2852 let mut t = Talk {
2853 schema: SCHEMA,
2854 id: id.to_owned(),
2855 repo: tmp.path().to_owned(),
2856 agent: "mock".to_owned(),
2857 status,
2858 turns: Vec::new(),
2859 pending: String::new(),
2860 pending_attachments: Vec::new(),
2861 fallback: false,
2862 created_at: Timestamp::now(),
2863 updated_at: Timestamp::now(),
2864 seat: SeatState::new(SEAT, "mock", 7),
2865 };
2866 talks.put(&mut t).expect("put");
2867 };
2868 make("20260901-000000-0001", TalkStatus::Open);
2869 make("20260902-000000-0002", TalkStatus::Open);
2870 make("20260903-000000-0003", TalkStatus::Closed);
2871
2872 let ids: Vec<String> = talks.list().into_iter().map(|t| t.id).collect();
2873 assert_eq!(
2874 ids,
2875 [
2876 "20260902-000000-0002",
2877 "20260901-000000-0001",
2878 "20260903-000000-0003"
2879 ]
2880 );
2881 assert_eq!(talks.count_open(), 2);
2882 }
2883
2884 #[test]
2885 fn tasks_of_finds_only_this_talks_own_tasks() {
2886 let dir = tempfile::tempdir().expect("tempdir");
2887 let queue = Queue::at(dir.path().join("queue"));
2888
2889 let mut mine = Task::new(
2890 "rework the loader".to_owned(),
2891 "rework the loader".to_owned(),
2892 PathBuf::from("/repo"),
2893 Source::Agent {
2894 run: "20260904-014455-ab12".to_owned(),
2895 node: "chat".to_owned(),
2896 },
2897 );
2898 queue.put(&mut mine).expect("put mine");
2899
2900 let mut theirs = Task::new(
2901 "unrelated".to_owned(),
2902 "unrelated".to_owned(),
2903 PathBuf::from("/repo"),
2904 Source::Agent {
2905 run: "20260904-090000-zz99".to_owned(),
2906 node: "implement".to_owned(),
2907 },
2908 );
2909 queue.put(&mut theirs).expect("put theirs");
2910
2911 let mut human = Task::new(
2912 "typed by hand".to_owned(),
2913 "typed by hand".to_owned(),
2914 PathBuf::from("/repo"),
2915 Source::Human,
2916 );
2917 queue.put(&mut human).expect("put human");
2918
2919 let found = tasks_of(&queue, "20260904-014455-ab12");
2920 assert_eq!(found.len(), 1);
2921 assert_eq!(found[0].id, mine.id);
2922 }
2923
2924 #[test]
2925 fn the_briefing_names_solo_task_add() {
2926 let brief = briefing(Path::new("/repo"), "en", false);
2927 assert!(brief.contains("magi task add --solo"));
2928 assert!(brief.contains("/repo"));
2929 assert!(!brief.contains("Hold this conversation in"));
2930 }
2931
2932 #[test]
2938 fn the_briefing_explains_targeting_a_different_repository_by_name() {
2939 let brief = briefing(Path::new("/repo"), "en", false);
2940 assert!(brief.contains("--repo does not have to be a full path"));
2941 assert!(brief.contains("owner/repo"));
2942 assert!(brief.contains("magi repos"));
2943 assert!(brief.contains("ask the operator"));
2944 }
2945
2946 #[test]
2947 fn the_briefing_tells_the_assistant_to_pass_images_with_attach() {
2948 let brief = briefing(Path::new("/repo"), "en", false);
2949 assert!(brief.contains("--attach <path>"), "{brief}");
2950 assert!(brief.contains("deleting this conversation"), "{brief}");
2951 }
2952
2953 #[test]
2954 fn the_briefing_names_the_language_when_it_is_not_english() {
2955 let brief = briefing(Path::new("/repo"), "Japanese", false);
2956 assert!(brief.contains("Hold this conversation in Japanese"));
2957 }
2958
2959 #[test]
2960 fn the_briefing_forbids_writes_unless_the_repository_opted_in() {
2961 let read_only = briefing(Path::new("/repo"), "en", false);
2962 assert!(read_only.contains("Do not write files"));
2963 assert!(!read_only.contains("allow_write"));
2964
2965 let writable = briefing(Path::new("/repo"), "en", true);
2966 assert!(!writable.contains("Do not write files"));
2967 assert!(writable.contains("allow_write = true"));
2968 assert!(writable.contains("magi task add --solo"));
2971 assert!(writable.contains("say plainly what you"));
2972 }
2973}