1use std::collections::HashSet;
31use std::path::{Path, PathBuf};
32use std::sync::{Arc, Mutex, OnceLock};
33use std::time::Duration;
34
35use serde::{Deserialize, Serialize};
36
37pub const RECORD_FILE: &str = "agentmux-last-version.json";
39pub const PENDING_FOR: Duration = Duration::from_secs(60 * 60);
41const NOTE_KEY: &str = "upgrade";
43const SETTLE: Duration = Duration::from_secs(1);
45pub(crate) const RETRY_GAP: Duration = Duration::from_secs(2);
48pub(crate) const RETRIES: u32 = 15;
49pub const INTERRUPTED_FILE: &str = "agentmux-interrupted-turns.json";
52
53#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
54struct Record {
55 version: String,
56 at: i64,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
59 upgraded_from: Option<String>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
61 upgraded_at: Option<i64>,
62 #[serde(default, skip_serializing_if = "Vec::is_empty")]
64 notified: Vec<String>,
65}
66
67#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
71struct Interrupted {
72 at: i64,
73 agents: Vec<String>,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Upgraded {
80 pub from: String,
81 pub to: String,
82 pub at_ms: i64,
83 pub notified: Vec<String>,
84}
85
86fn read(dir: &Path) -> Option<Record> {
87 std::fs::read(dir.join(RECORD_FILE)).ok().and_then(|b| serde_json::from_slice(&b).ok())
88}
89
90fn write(dir: &Path, record: &Record) {
93 let path = dir.join(RECORD_FILE);
94 let tmp = path.with_extension("json.tmp");
95 let written = serde_json::to_vec_pretty(record)
96 .map_err(|e| e.to_string())
97 .and_then(|bytes| std::fs::write(&tmp, bytes).map_err(|e| e.to_string()))
98 .and_then(|()| std::fs::rename(&tmp, &path).map_err(|e| e.to_string()));
99 if let Err(e) = written {
100 tracing::warn!(path = %path.display(), error = %e, "upgrade notice: could not save the record");
101 }
102}
103
104pub fn observe_start(dir: &Path, version: &str, now_ms: i64) -> Option<Upgraded> {
109 use crate::backend::update::check::version_core;
110 let _guard = RECORD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
111 let previous = read(dir);
112 let mut record = Record { version: version.to_string(), at: now_ms, ..Default::default() };
113 match &previous {
114 Some(p) if version_core(&p.version).is_some() && version_core(version) > version_core(&p.version) => {
115 record.upgraded_from = Some(p.version.clone());
116 record.upgraded_at = Some(now_ms);
117 }
118 Some(p) if p.version == version && p.upgraded_from.is_some() => {
119 let still = p.upgraded_at.is_some_and(|t| now_ms - t < PENDING_FOR.as_millis() as i64);
120 if still {
121 record.upgraded_from = p.upgraded_from.clone();
122 record.upgraded_at = p.upgraded_at;
123 record.notified = p.notified.clone();
124 }
125 }
126 _ => {}
127 }
128 write(dir, &record);
129 Some(Upgraded {
130 from: record.upgraded_from?,
131 to: version.to_string(),
132 at_ms: record.upgraded_at?,
133 notified: record.notified,
134 })
135}
136
137pub fn record_interrupted(dir: &Path, agents: &[String], now_ms: i64) {
144 if agents.is_empty() {
145 return;
146 }
147 let _guard = RECORD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
148 let mut record = read_interrupted(dir, now_ms);
149 for agent in agents {
150 if !record.agents.contains(agent) {
151 record.agents.push(agent.clone());
152 }
153 }
154 record.at = now_ms;
155 write_interrupted(dir, &record);
156}
157
158fn write_interrupted(dir: &Path, record: &Interrupted) {
159 let path = dir.join(INTERRUPTED_FILE);
160 let tmp = path.with_extension("json.tmp");
161 let written = serde_json::to_vec_pretty(record)
162 .map_err(|e| e.to_string())
163 .and_then(|bytes| std::fs::write(&tmp, bytes).map_err(|e| e.to_string()))
164 .and_then(|()| std::fs::rename(&tmp, &path).map_err(|e| e.to_string()));
165 if let Err(e) = written {
166 tracing::warn!(path = %path.display(), error = %e, "upgrade notice: could not save the interrupted turns");
167 }
168}
169
170fn read_interrupted(dir: &Path, now_ms: i64) -> Interrupted {
173 read_interrupted_any_age(dir).filter(|r| now_ms - r.at < PENDING_FOR.as_millis() as i64).unwrap_or_default()
174}
175
176fn read_interrupted_any_age(dir: &Path) -> Option<Interrupted> {
177 std::fs::read(dir.join(INTERRUPTED_FILE)).ok().and_then(|b| serde_json::from_slice(&b).ok())
178}
179
180fn record_continued(dir: &Path, agent: &str) {
182 let _guard = RECORD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
183 let mut record = read_interrupted_any_age(dir).unwrap_or_default();
184 record.agents.retain(|a| a != agent);
185 if record.agents.is_empty() {
186 let _ = std::fs::remove_file(dir.join(INTERRUPTED_FILE));
187 } else {
188 write_interrupted(dir, &record);
189 }
190}
191
192static RECORD_LOCK: Mutex<()> = Mutex::new(());
194
195fn record_notified(dir: &Path, block_id: &str) {
197 let _guard = RECORD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
198 if let Some(mut record) = read(dir) {
199 if !record.notified.iter().any(|b| b == block_id) {
200 record.notified.push(block_id.to_string());
201 write(dir, &record);
202 }
203 }
204}
205
206fn at_text(ms: i64) -> String {
208 chrono::DateTime::from_timestamp_millis(ms)
209 .map(|t| t.with_timezone(&chrono::Local).format(" at %H:%M").to_string())
210 .unwrap_or_default()
211}
212
213const TOOLS_MAY_HAVE_CHANGED: &str = "Its tools may have changed: a tool you loaded before the upgrade keeps its old description in this session (loading it again returns the old one), so a parameter added in this version can be missing from it but still works when you pass it; a tool you have not loaded yet shows the new description.";
222
223pub fn note_text(u: &Upgraded) -> String {
225 format!(
226 "[AgentMux] AgentMux was upgraded from {} to {}{}. Your session resumed; nothing is needed from you. {TOOLS_MAY_HAVE_CHANGED}",
227 u.from,
228 u.to,
229 at_text(u.at_ms)
230 )
231}
232
233pub fn continue_text(upgrade: Option<&Upgraded>, quit_ms: i64) -> String {
237 match upgrade {
238 Some(u) => format!(
239 "[AgentMux] AgentMux was upgraded from {} to {}{} while you were working; your last turn was cut off mid-tool. {TOOLS_MAY_HAVE_CHANGED} Check the state of what you were doing and carry on.",
240 u.from,
241 u.to,
242 at_text(u.at_ms)
243 ),
244 None => format!(
245 "[AgentMux] AgentMux restarted{} while you were working; your last turn was cut off mid-tool. Check the state of what you were doing and carry on.",
246 at_text(quit_ms)
247 ),
248 }
249}
250
251struct State {
252 upgraded: Option<Upgraded>,
254 interrupted: Mutex<HashSet<String>>,
257 quit_ms: i64,
258 dir: PathBuf,
259 store: Arc<crate::backend::storage::store::Store>,
261 noted: Mutex<HashSet<String>>,
262 told: Mutex<HashSet<String>>,
265 continuing: Mutex<HashSet<String>>,
269}
270
271static STATE: OnceLock<Option<State>> = OnceLock::new();
272
273#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct Started {
277 pub version: String,
278 pub upgraded_from: Option<String>,
279 pub at_ms: i64,
280}
281
282static STARTED: OnceLock<Started> = OnceLock::new();
283
284pub fn this_start() -> Option<Started> {
286 STARTED.get().cloned()
287}
288
289pub fn init(store: Arc<crate::backend::storage::store::Store>) {
293 let state = agentmux_common::DataPaths::from_env().and_then(|paths| {
294 let dir = paths.instance_dir.clone();
295 let now = agentmux_common::time::now_ms();
296 let upgraded = observe_start(&dir, env!("CARGO_PKG_VERSION"), now);
297 let _ = STARTED.set(Started {
298 version: env!("CARGO_PKG_VERSION").to_string(),
299 upgraded_from: upgraded.as_ref().filter(|u| u.at_ms == now).map(|u| u.from.clone()),
300 at_ms: now,
301 });
302 let cut_off = read_interrupted(&dir, now);
303 if upgraded.is_none() && cut_off.agents.is_empty() {
304 return None;
305 }
306 if let Some(upgraded) = &upgraded {
307 if upgraded.at_ms == now {
310 tracing::info!(from = %upgraded.from, to = %upgraded.to, "upgrade notice: resumed agents will be told of the upgrade");
311 } else {
312 tracing::debug!(from = %upgraded.from, to = %upgraded.to, told = upgraded.notified.len(), "upgrade notice: still announcing an earlier start's upgrade");
313 }
314 if upgraded.at_ms == now {
317 let db_dir = paths.data_dir.join("db");
318 if let Some(problem) = crate::migrations::carry_forward::continuity_problem(&db_dir, &upgraded.from) {
319 tracing::error!(from = %upgraded.from, to = %upgraded.to, "upgrade continuity: {problem}");
320 }
321 }
322 }
323 if !cut_off.agents.is_empty() {
324 tracing::info!(count = cut_off.agents.len(), "upgrade notice: agents whose turn the last quit cut off will be told to carry on");
325 }
326 let noted = Mutex::new(upgraded.iter().flat_map(|u| u.notified.iter().cloned()).collect());
327 let told = Mutex::new(upgraded.iter().flat_map(|u| u.notified.iter().cloned()).collect());
328 Some(State {
329 upgraded,
330 interrupted: Mutex::new(cut_off.agents.into_iter().collect()),
331 quit_ms: cut_off.at,
332 dir,
333 store,
334 noted,
335 told,
336 continuing: Mutex::new(HashSet::new()),
337 })
338 });
339 let _ = STATE.set(state);
340}
341
342fn agent_id_of(store: &crate::backend::storage::store::Store, block_id: &str) -> String {
345 store
346 .get::<crate::backend::obj::Block>(block_id)
347 .ok()
348 .flatten()
349 .map(|b| crate::backend::obj::meta_get_string(&b.meta, "agentId", "").trim().to_string())
350 .unwrap_or_default()
351}
352
353fn has_session(store: &crate::backend::storage::store::Store, block_id: &str) -> bool {
360 store
361 .get::<crate::backend::obj::Block>(block_id)
362 .ok()
363 .flatten()
364 .is_some_and(|b| !crate::backend::obj::meta_get_string(&b.meta, "agent:sessionid", "").trim().is_empty())
365}
366
367fn told_key(agent: &str, block_id: &str) -> String {
370 if agent.is_empty() { block_id.to_string() } else { agent.to_string() }
371}
372
373fn claim_told(told: &Mutex<HashSet<String>>, key: &str) -> bool {
375 told.lock().unwrap_or_else(|e| e.into_inner()).insert(key.to_string())
376}
377
378pub enum Undelivered {
380 Gone(String),
381 Retry(String),
382}
383
384pub async fn deliver_with_retry(
387 mut deliver: impl FnMut() -> Result<(), Undelivered>,
388 attempts: u32,
389 gap: Duration,
390) -> Result<(), String> {
391 let mut last = String::from("no attempt made");
392 for attempt in 0..attempts {
393 if attempt > 0 {
394 tokio::time::sleep(gap).await;
395 }
396 match deliver() {
397 Ok(()) => return Ok(()),
398 Err(Undelivered::Gone(e)) => return Err(e),
399 Err(Undelivered::Retry(e)) => last = e,
400 }
401 }
402 Err(last)
403}
404
405pub fn on_registered(block_id: &str) {
411 let Some(Some(state)) = STATE.get() else { return };
412 let now = agentmux_common::time::now_ms();
413 let open = |at_ms: i64| now - at_ms < PENDING_FOR.as_millis() as i64;
414 let upgrade_open = state.upgraded.as_ref().is_some_and(|u| open(u.at_ms));
415 let cut_off_open = open(state.quit_ms) && !state.interrupted.lock().unwrap_or_else(|e| e.into_inner()).is_empty();
416 if !upgrade_open && !cut_off_open {
417 return;
418 }
419 let want_note = upgrade_open && state.noted.lock().unwrap_or_else(|e| e.into_inner()).insert(block_id.to_string());
420 let want_continue = cut_off_open && state.continuing.lock().unwrap_or_else(|e| e.into_inner()).insert(block_id.to_string());
421 if !want_note && !want_continue {
422 return;
423 }
424 let block_id = block_id.to_string();
425 tokio::spawn(async move {
426 let Some(Some(state)) = STATE.get() else { return };
427 let forget = |note: bool, cont: bool| {
430 if note {
431 state.noted.lock().unwrap_or_else(|e| e.into_inner()).remove(&block_id);
432 }
433 if cont {
434 state.continuing.lock().unwrap_or_else(|e| e.into_inner()).remove(&block_id);
435 }
436 };
437 if !has_session(&state.store, &block_id) {
438 forget(want_note, want_continue);
439 return;
440 }
441 let agent = agent_id_of(&state.store, &block_id);
442 let cut_off = want_continue && !agent.is_empty() && state.interrupted.lock().unwrap_or_else(|e| e.into_inner()).contains(&agent);
443 let upgrade = state.upgraded.as_ref().filter(|_| upgrade_open);
444 let key = told_key(&agent, &block_id);
446 let mut claimed_here = false;
447 let text = if cut_off {
448 claimed_here = upgrade.is_some() && claim_told(&state.told, &key);
450 continue_text(upgrade, state.quit_ms)
451 } else if let (true, Some(u)) = (want_note, upgrade) {
452 if !claim_told(&state.told, &key) {
453 tracing::debug!(block_id = %block_id, "upgrade notice: this agent was told already");
454 return;
455 }
456 claimed_here = true;
457 note_text(u)
458 } else {
459 forget(want_note, want_continue);
460 return;
461 };
462 tokio::time::sleep(SETTLE).await;
463 let handler = crate::backend::reactive::get_global_handler();
464 let delivered = deliver_with_retry(
465 || {
466 let target = handler
467 .list_agents()
468 .into_iter()
469 .find(|r| r.block_id == block_id)
470 .map(|r| r.uid.unwrap_or(r.agent_id))
471 .ok_or_else(|| Undelivered::Gone("not registered any more".to_string()))?;
472 let sent = if cut_off { handler.deliver_system_note(&target, &text) } else { handler.hold_system_note(&target, NOTE_KEY, &text) };
475 sent.map_err(Undelivered::Retry)
476 },
477 RETRIES,
478 RETRY_GAP,
479 )
480 .await;
481 match delivered {
482 Ok(()) => {
483 let what = if cut_off { "upgrade notice: the agent was told to carry on" } else { "upgrade notice: held for the agent's next message" };
485 tracing::info!(block_id = %block_id, cut_off, "{}", what);
486 if state.upgraded.is_some() {
487 record_notified(&state.dir, &key);
488 }
489 if cut_off {
490 state.interrupted.lock().unwrap_or_else(|e| e.into_inner()).remove(&agent);
491 record_continued(&state.dir, &agent);
492 }
493 }
494 Err(e) => {
495 tracing::info!(block_id = %block_id, error = %e, "upgrade notice: not delivered; the next registration tries again");
496 forget(want_note, want_continue);
498 if claimed_here {
499 state.told.lock().unwrap_or_else(|e| e.into_inner()).remove(&key);
500 }
501 }
502 }
503 });
504}
505
506#[cfg(test)]
507mod tests {
508 use super::*;
509
510 fn up(from: &str, to: &str, at: i64, notified: &[&str]) -> Option<Upgraded> {
511 Some(Upgraded { from: from.into(), to: to.into(), at_ms: at, notified: notified.iter().map(|s| s.to_string()).collect() })
512 }
513
514 #[test]
515 fn only_a_start_on_a_newer_release_is_an_upgrade() {
516 let dir = tempfile::tempdir().unwrap();
517 assert_eq!(observe_start(dir.path(), "0.59.26", 1), None);
519 assert_eq!(observe_start(dir.path(), "0.59.26", 2), None);
521 assert_eq!(observe_start(dir.path(), "0.59.27", 3), up("0.59.26", "0.59.27", 3, &[]));
523 assert_eq!(observe_start(dir.path(), "0.59.26", 4), None);
526 assert_eq!(observe_start(dir.path(), "0.59.100", 5).map(|u| u.from), Some("0.59.26".into()));
527 }
528
529 #[test]
530 fn an_upgrade_is_announced_across_restarts_for_an_hour_and_to_each_pane_once() {
531 let dir = tempfile::tempdir().unwrap();
532 observe_start(dir.path(), "0.59.26", 0);
533 let hour = PENDING_FOR.as_millis() as i64;
534 assert_eq!(observe_start(dir.path(), "0.59.27", 1_000), up("0.59.26", "0.59.27", 1_000, &[]));
535 record_notified(dir.path(), "block-a");
536 record_notified(dir.path(), "block-a");
537 assert_eq!(observe_start(dir.path(), "0.59.27", 2_000), up("0.59.26", "0.59.27", 1_000, &["block-a"]));
539 assert_eq!(observe_start(dir.path(), "0.59.27", 1_000 + hour), None);
541 assert_eq!(observe_start(dir.path(), "0.59.27", 2_000 + hour), None);
542 }
543
544 #[test]
545 fn an_agent_told_once_is_not_told_again_in_the_pane_a_restart_restores_it_into() {
546 let dir = tempfile::tempdir().unwrap();
547 observe_start(dir.path(), "0.59.26", 0);
548 observe_start(dir.path(), "0.59.27", 1_000);
549 let told = Mutex::new(HashSet::new());
550 assert!(claim_told(&told, &told_key("def-a", "before")));
552 record_notified(dir.path(), &told_key("def-a", "before"));
553 let again = observe_start(dir.path(), "0.59.27", 2_000).unwrap();
555 assert_eq!(again.at_ms, 1_000, "this start made no upgrade: it only goes on announcing the earlier one");
556 let told = Mutex::new(again.notified.iter().cloned().collect::<HashSet<_>>());
557 assert!(!claim_told(&told, &told_key("def-a", "after")), "told already, under its new pane id");
558 let third = observe_start(dir.path(), "0.59.27", 3_000).unwrap();
560 assert_eq!(third.notified, vec!["def-a".to_string()]);
561 }
562
563 #[test]
564 fn an_agent_not_running_at_the_first_start_is_told_once_when_it_next_resumes() {
565 let dir = tempfile::tempdir().unwrap();
566 observe_start(dir.path(), "0.59.26", 0);
567 observe_start(dir.path(), "0.59.27", 1_000);
568 record_notified(dir.path(), &told_key("def-a", "pane-1"));
570 let later = observe_start(dir.path(), "0.59.27", 2_000).unwrap();
571 let told = Mutex::new(later.notified.iter().cloned().collect::<HashSet<_>>());
572 assert!(!claim_told(&told, &told_key("def-a", "pane-9")));
573 assert!(claim_told(&told, &told_key("def-b", "pane-2")), "b is told when it first resumes");
574 assert!(!claim_told(&told, &told_key("def-b", "pane-3")), "and only once, though it registers again");
575 assert_eq!(told_key("", "pane-4"), "pane-4");
577 let hour = PENDING_FOR.as_millis() as i64;
579 assert_eq!(observe_start(dir.path(), "0.59.27", 1_000 + hour), None);
580 }
581
582 #[test]
583 fn an_unreadable_record_is_a_first_start() {
584 let dir = tempfile::tempdir().unwrap();
585 std::fs::write(dir.path().join(RECORD_FILE), b"not json").unwrap();
586 assert_eq!(observe_start(dir.path(), "0.59.27", 1), None);
587 assert_eq!(observe_start(dir.path(), "0.59.28", 2).map(|u| u.from), Some("0.59.27".into()));
588 }
589
590 #[tokio::test]
591 async fn a_pane_restored_after_the_start_is_a_resumed_one_when_its_block_has_a_session() {
592 use crate::backend::obj::Block;
593 let state = crate::test_support::core_parts();
594 let block = |oid: &str, session: Option<&str>| {
595 let mut b = Block { oid: oid.into(), ..Default::default() };
596 if let Some(id) = session {
597 b.meta.insert("agent:sessionid".into(), serde_json::json!(id));
598 }
599 state.mstore.insert(&mut b).unwrap();
600 };
601 block("restored", Some("28ec4fdb-58a0-4571-9c14-c1b8b877ab60"));
603 block("new-pane", None);
604 block("blank-session", Some(" "));
605 assert!(has_session(&state.mstore, "restored"));
606 assert!(!has_session(&state.mstore, "new-pane"), "a new pane gets its session with its first turn");
607 assert!(!has_session(&state.mstore, "blank-session"));
608 assert!(!has_session(&state.mstore, "no-such-block"));
609 }
610
611 #[tokio::test(start_paused = true)]
612 async fn a_note_finding_no_controller_yet_is_tried_again_until_it_goes_through() {
613 let mut calls = 0;
614 let r = deliver_with_retry(
615 || {
616 calls += 1;
617 if calls < 3 { Err(Undelivered::Retry("no controller for block b".into())) } else { Ok(()) }
618 },
619 15,
620 Duration::from_secs(2),
621 )
622 .await;
623 assert_eq!((r, calls), (Ok(()), 3));
624 let mut calls = 0;
626 let r = deliver_with_retry(
627 || {
628 calls += 1;
629 Err(Undelivered::Retry(format!("no controller (try {calls})")))
630 },
631 4,
632 Duration::from_secs(2),
633 )
634 .await;
635 assert_eq!((r, calls), (Err("no controller (try 4)".to_string()), 4));
636 let mut calls = 0;
638 let r = deliver_with_retry(
639 || {
640 calls += 1;
641 Err(Undelivered::Gone("not registered any more".into()))
642 },
643 15,
644 Duration::from_secs(2),
645 )
646 .await;
647 assert_eq!((r, calls), (Err("not registered any more".to_string()), 1));
648 }
649
650 #[test]
651 fn the_note_is_a_system_note() {
652 let text = note_text(&up("0.59.26", "0.59.27", 1_792_000_000_000, &[]).unwrap());
653 assert!(text.starts_with("[AgentMux] AgentMux was upgraded from 0.59.26 to 0.59.27 at "), "{text}");
654 assert!(text.contains("Your session resumed; nothing is needed from you. Its tools may have changed: "), "{text}");
655 assert!(!text.contains("load it again"), "{text}");
657 assert!(text.contains("loading it again returns the old one"), "{text}");
658 assert!(text.ends_with("a tool you have not loaded yet shows the new description."), "{text}");
659 }
660
661 #[test]
662 fn the_agents_a_quit_cut_off_are_kept_for_an_hour_and_each_leaves_the_list_once_told() {
663 let dir = tempfile::tempdir().unwrap();
664 let hour = PENDING_FOR.as_millis() as i64;
665 assert_eq!(read_interrupted(dir.path(), 5), Interrupted::default());
667 record_interrupted(dir.path(), &["agent-a".into(), "agent-b".into()], 1_000);
668 assert_eq!(read_interrupted(dir.path(), 2_000).agents, vec!["agent-a".to_string(), "agent-b".to_string()]);
669 assert_eq!(read_interrupted(dir.path(), 2_000).at, 1_000);
670 record_continued(dir.path(), "agent-a");
672 assert_eq!(read_interrupted(dir.path(), 2_000).agents, vec!["agent-b".to_string()]);
673 record_continued(dir.path(), "agent-b");
674 assert!(!dir.path().join(INTERRUPTED_FILE).exists());
675 record_interrupted(dir.path(), &["agent-a".into()], 1_000);
677 assert_eq!(read_interrupted(dir.path(), 1_000 + hour), Interrupted::default());
678 record_continued(dir.path(), "agent-a");
679 record_interrupted(dir.path(), &["agent-b".into()], 5_000);
681 record_interrupted(dir.path(), &["agent-c".into(), "agent-b".into()], 5_100);
682 record_interrupted(dir.path(), &[], 5_200);
683 let list = read_interrupted(dir.path(), 5_300);
684 assert_eq!(list.agents, vec!["agent-b".to_string(), "agent-c".to_string()]);
685 assert_eq!(list.at, 5_100);
686 }
687
688 #[test]
689 fn an_unreadable_interrupted_list_is_none() {
690 let dir = tempfile::tempdir().unwrap();
691 std::fs::write(dir.path().join(INTERRUPTED_FILE), b"not json").unwrap();
692 assert_eq!(read_interrupted(dir.path(), 1), Interrupted::default());
693 }
694
695 #[test]
696 fn a_cut_off_turn_is_told_to_carry_on_and_says_why() {
697 let upgraded = up("0.60.3", "0.60.4", 1_792_000_000_000, &[]).unwrap();
698 let after_upgrade = continue_text(Some(&upgraded), 1_792_000_000_000);
699 assert!(after_upgrade.starts_with("[AgentMux] AgentMux was upgraded from 0.60.3 to 0.60.4 at "), "{after_upgrade}");
700 assert!(after_upgrade.contains(" while you were working; your last turn was cut off mid-tool. "), "{after_upgrade}");
701 assert!(after_upgrade.contains("loading it again returns the old one"), "{after_upgrade}");
702 assert!(!after_upgrade.contains("load it again"), "{after_upgrade}");
703 assert!(after_upgrade.ends_with("Check the state of what you were doing and carry on."), "{after_upgrade}");
704 assert!(!after_upgrade.contains("nothing is needed from you"), "{after_upgrade}");
705 let after_restart = continue_text(None, 1_792_000_000_000);
706 assert!(after_restart.starts_with("[AgentMux] AgentMux restarted at "), "{after_restart}");
707 assert!(after_restart.ends_with("Check the state of what you were doing and carry on."), "{after_restart}");
708 assert!(!after_restart.contains("upgraded"), "{after_restart}");
709 for text in [&after_upgrade, &after_restart, ¬e_text(&upgraded)] {
711 assert!(!text.contains(" "), "{text}");
712 }
713 }
714
715 #[tokio::test]
716 async fn the_agent_a_pane_runs_is_read_from_its_block() {
717 use crate::backend::obj::Block;
718 let state = crate::test_support::core_parts();
719 let mut agent = Block { oid: "with-agent".into(), ..Default::default() };
720 agent.meta.insert("agentId".into(), serde_json::json!(" def-1 "));
721 state.mstore.insert(&mut agent).unwrap();
722 let mut shell = Block { oid: "shell".into(), ..Default::default() };
723 state.mstore.insert(&mut shell).unwrap();
724 assert_eq!(agent_id_of(&state.mstore, "with-agent"), "def-1");
725 assert_eq!(agent_id_of(&state.mstore, "shell"), "");
726 assert_eq!(agent_id_of(&state.mstore, "no-such-block"), "");
727 }
728}