Skip to main content

agentmux_srv_core/backend/
upgrade_notice.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The note each agent gets when it resumes after AgentMux was upgraded
5//! (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` §5.2,
6//! phase 4b): `[AgentMux] AgentMux was upgraded from 0.59.26 to 0.59.27 …`,
7//! once per agent, with the first message it gets after it resumes: the note
8//! asks nothing of it, so it starts no turn (`reactive::held_notes`). The
9//! agent that asked for the upgrade (`App` `upgrade`) gets it too, which is
10//! how it learns it is done.
11//!
12//! srv records the version it runs in the channel folder ([`RECORD_FILE`],
13//! like `cli_notice`'s CLI versions): an installed build's data folder is
14//! per version, so the new version's own would read as a first start. A
15//! start on a newer version than the one recorded is an upgrade; a first
16//! start, the same version or an older one (a downgrade, or the older build
17//! started again) is not. The record keeps the upgrade, and the agents already
18//! told, for [`PENDING_FOR`]: a crash or another restart soon after still
19//! tells the agents not yet told, and never one twice. An agent is named by its
20//! definition id, not its pane: a quit deletes the panes, and a restart restores
21//! each agent into a pane with a new id.
22//!
23//! Every agent that registers with the reactive handler, whatever runs it, is
24//! a candidate ([`on_registered`]): the note goes to one whose pane has a
25//! session (`agent:sessionid`) as it registers, i.e. a resumed one, not a new
26//! pane. That is read from its block then ([`has_session`]), not from a list
27//! made at start: the quit that precedes an upgrade deletes the panes, and the
28//! next start restores them into new blocks once srv is up.
29
30use std::collections::HashSet;
31use std::path::{Path, PathBuf};
32use std::sync::{Arc, Mutex, OnceLock};
33use std::time::Duration;
34
35use serde::{Deserialize, Serialize};
36
37/// The last AgentMux version this channel ran, in its folder.
38pub const RECORD_FILE: &str = "agentmux-last-version.json";
39/// How long after an upgrade resumed agents are still told.
40pub const PENDING_FOR: Duration = Duration::from_secs(60 * 60);
41/// Where the note waits for the agent's next turn.
42const NOTE_KEY: &str = "upgrade";
43/// How long after registering an agent is told, so its spawn has settled.
44const SETTLE: Duration = Duration::from_secs(1);
45/// A restored pane's controller can come up after the pane registers, so a
46/// note that finds none is tried again, this often, up to [`RETRIES`] times.
47pub(crate) const RETRY_GAP: Duration = Duration::from_secs(2);
48pub(crate) const RETRIES: u32 = 15;
49/// The agents whose turn was running when AgentMux last quit, in the channel
50/// folder ([`record_interrupted`]).
51pub 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    /// Set while the upgrade to `version` is still being announced.
58    #[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    /// Panes already told about it.
63    #[serde(default, skip_serializing_if = "Vec::is_empty")]
64    notified: Vec<String>,
65}
66
67/// The agents (by definition id, `agentId` in their pane's meta) whose turn
68/// was in flight when the last quit began, and when. A pane's block id is new
69/// after a restore, the agent's id is not.
70#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
71struct Interrupted {
72    at: i64,
73    agents: Vec<String>,
74}
75
76/// This start is (still announcing) an upgrade from `from` to `to`, made at
77/// `at_ms`; `notified` are the panes told already.
78#[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
90/// Replace the record (`std::fs::rename` replaces an existing file on
91/// Windows too: `MoveFileExW` with `MOVEFILE_REPLACE_EXISTING`).
92fn 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
104/// Record that `version` started at `now_ms`, and return the upgrade being
105/// announced, if any: this start's, or one made less than [`PENDING_FOR`]
106/// ago on this same version. A record that can't be read or written is
107/// logged and treated as none: at worst a note is missed.
108pub 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
137/// At quit, as each agent is closed (or all that are left when srv exits): add
138/// the ones with a turn in flight (`agents`, their ids) to the list the next
139/// start tells to carry on. A quit closes its agents one by one, so this adds
140/// to what the quit has recorded so far (a list over an hour old is dropped
141/// first). Unlike a note held for a turn, an interrupted turn is never
142/// continued by the CLI by itself on `--resume`.
143pub 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
170/// The list [`record_interrupted`] left, if it is less than [`PENDING_FOR`]
171/// old; empty otherwise (a quit long ago is not news).
172fn 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
180/// `agent` has been told to carry on: take it off the list.
181fn 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
192/// Serializes read-modify-write of the record: panes resume together.
193static RECORD_LOCK: Mutex<()> = Mutex::new(());
194
195/// Add `block_id` to the panes told, in the record.
196fn 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
206/// " at 14:17", the local time of `ms`.
207fn 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
213/// The tools line. The resumed session keeps the description of every tool the
214/// agent loaded before the upgrade, and loading it again returns that same old
215/// description: the CLI stores the loaded schema in the conversation and serves
216/// it from there, although the tool server it started after the upgrade lists
217/// the new one (measured on 0.60.26 -> 0.60.27: Tasks had no `handback`, while a
218/// tool not loaded before, Browser, came back with its new schema). So "load it
219/// again" cannot refresh it. A parameter the old description lacks is still
220/// passed through (the CLI does not reject it), and a tool not loaded yet is new.
221const 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
223/// The note, with the upgrade's local time.
224pub 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
233/// What an agent whose turn was cut off by the quit is told: unlike
234/// [`note_text`], it asks something of it, so it starts a turn. `upgrade` is
235/// the upgrade this start made, if any; `quit_ms` when AgentMux quit.
236pub 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    /// The upgrade being announced, if this start made one (or one soon before).
253    upgraded: Option<Upgraded>,
254    /// The agents whose turn the last quit cut off, not yet told to carry on,
255    /// and when it quit.
256    interrupted: Mutex<HashSet<String>>,
257    quit_ms: i64,
258    dir: PathBuf,
259    /// Where a pane's block says whether it has a session ([`has_session`]).
260    store: Arc<crate::backend::storage::store::Store>,
261    noted: Mutex<HashSet<String>>,
262    /// The agents already told of this upgrade (or being told), by [`told_key`]: the agent, not its pane, because a
263    /// quit deletes the panes and a restart restores each agent into a pane with a new id.
264    told: Mutex<HashSet<String>>,
265    /// Panes being (or already) told to carry on. Apart from `noted`: a pane
266    /// told of an upgrade earlier (and kept across a later restart on the
267    /// same version) still gets told its turn was cut off.
268    continuing: Mutex<HashSet<String>>,
269}
270
271static STATE: OnceLock<Option<State>> = OnceLock::new();
272
273/// This start of srv: its version, when it began and, only when this very start made an upgrade, the version it came from.
274/// A restart soon after an upgrade is no new upgrade, though the note to the agents still counts it as one.
275#[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
284/// How this srv started, once [`init`] has run: what an `app.started` event says.
285pub fn this_start() -> Option<Started> {
286    STARTED.get().cloned()
287}
288
289/// At srv start (`bootstrap::background`): record this version and remember
290/// whether an upgrade is being announced and which agents' turns the last quit
291/// cut off.
292pub 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            // Said once, by the start that made the upgrade: a restart within the hour still tells the agents not yet
308            // told, but it has no news to log.
309            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            // This start made the upgrade: its data must be the previous version's,
315            // or nothing that version's quit saved (windows, tabs, panes) comes back.
316            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
342/// The agent definition a pane runs (`agentId` in its meta); empty for a pane
343/// that is no agent's.
344fn 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
353/// Whether the pane `block_id` has a session (`agent:sessionid`) now: it is a
354/// resumed one. Asked as the pane registers, not when srv starts: a graceful
355/// quit, an upgrade's, deletes the panes, and the next start restores them
356/// into blocks with new ids (carrying their session) after srv is up, so a list
357/// read at start would never hold them. A pane opened after the upgrade gets
358/// its session only with its first turn, after it registered.
359fn 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
367/// What the record and the told list call an agent: its definition id, which a restored pane keeps, else the pane's
368/// block id (a pane that is no agent's).
369fn told_key(agent: &str, block_id: &str) -> String {
370    if agent.is_empty() { block_id.to_string() } else { agent.to_string() }
371}
372
373/// Takes `key` as told: `true` for the first caller, `false` when the agent was told already (or is being told).
374fn 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
378/// Why a note wasn't delivered: the pane is gone, or it may be ready later.
379pub enum Undelivered {
380    Gone(String),
381    Retry(String),
382}
383
384/// `deliver` until it succeeds, at most `attempts` times, `gap` apart; the
385/// last error when none does. A pane that is gone isn't waited for.
386pub 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
405/// An agent registered in `block_id` (any controller). If an upgrade is being
406/// announced and the pane is a resumed one not yet told, tell it, once; if its
407/// turn was cut off by the quit, tell it to carry on instead, which starts a
408/// turn. Called under the handler lock: no I/O here (the pane's block is read,
409/// and the note sent, from a task of its own).
410pub 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        // A new pane: no session yet, and no note; one that registers again
428        // later, with a session by then, is told then.
429        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        // Once per agent per upgrade: an agent told in an earlier pane (a restart restores it into a new one) is not told again.
445        let key = told_key(&agent, &block_id);
446        let mut claimed_here = false;
447        let text = if cut_off {
448            // The carry-on text also says what happened, so the agent needs no note after it.
449            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                // A turn cut off is continued now; a resumed idle agent is
473                // told with its next message.
474                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                // A cut-off turn was continued now; anyone else's note is held, and goes with its next message.
484                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                // Not told: the next registration tries again.
497                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        // First start: recorded, nothing to say.
518        assert_eq!(observe_start(dir.path(), "0.59.26", 1), None);
519        // The same version again.
520        assert_eq!(observe_start(dir.path(), "0.59.26", 2), None);
521        // Upgraded.
522        assert_eq!(observe_start(dir.path(), "0.59.27", 3), up("0.59.26", "0.59.27", 3, &[]));
523        // The older build started again isn't one, and the newer one after it
524        // is, from the older.
525        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        // A crash, then a restart soon after: still announcing, block-a told.
538        assert_eq!(observe_start(dir.path(), "0.59.27", 2_000), up("0.59.26", "0.59.27", 1_000, &["block-a"]));
539        // An hour after the upgrade, it's just this version starting.
540        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        // First start on the new version: the agent resumes in pane "before" and is told; the record keeps who.
551        assert!(claim_told(&told, &told_key("def-a", "before")));
552        record_notified(dir.path(), &told_key("def-a", "before"));
553        // A restart soon after: the quit deleted the panes, and the agent comes back in pane "after".
554        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        // A third restart: still once.
559        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        // Agent a resumed and was told; agent b was stopped.
569        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        // A pane that is no agent's is told by its block id.
576        assert_eq!(told_key("", "pane-4"), "pane-4");
577        // Past the hour nothing is announced, so nobody is told and the start has no upgrade to log.
578        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        // Created after "start", as a restore does with a quit's saved panes.
602        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        // Never ready: the last error, after every attempt.
625        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        // A pane that is gone isn't waited for.
637        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        // Loading a tool again does not refresh one loaded before the upgrade, so the note must not say it does.
656        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        // Nothing recorded: nothing to say.
666        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        // Told: it leaves the list, the other stays, and the file goes with the last one.
671        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        // An hour later a list is stale.
676        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        // A quit closes its agents one by one: each adds to the list, and none changes nothing.
680        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        // Read by the agent as written: one space between words.
710        for text in [&after_upgrade, &after_restart, &note_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}