Skip to main content

agentmux_launcher/
incidents.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The recoveries only the launcher sees, kept for the user
5//! (docs/specs/SPEC_RECOVERY_NOTICES_AND_TOASTS_2026_10_16.md ยง4.4, Phase C):
6//! the window process restarted after it stopped, with or without graphics
7//! acceleration; the background service restarted; and AgentMux giving up.
8//!
9//! Written to the same file the host keeps (`agentmux_common::incidents`)
10//! before the replacement starts, so its first window lists the incident and
11//! shows its notice; after a give-up, the next start does. Each `did` line is
12//! something this path did.
13
14use std::path::{Path, PathBuf};
15use std::sync::OnceLock;
16
17use agentmux_common::incidents::Incident;
18
19static PATH: OnceLock<PathBuf> = OnceLock::new();
20
21/// Start recording in `data_dir`, the folder the host records in too.
22pub fn init(data_dir: &Path) {
23    let _ = PATH.set(data_dir.join(agentmux_common::incidents::FILE_NAME));
24}
25
26/// Record `incident` (built by one of the functions below). Best-effort: a
27/// failure is logged, never raised, since the callers are recovery paths.
28pub fn record(incident: &Incident) {
29    use crate::logging::log;
30    log(&format!("[incident] {}: {}", incident.kind, incident.what));
31    if let Some(path) = PATH.get() {
32        if let Err(e) = agentmux_common::incidents::append(path, incident) {
33            log(&format!("[incident] couldn't write the incident log: {e}"));
34        }
35    }
36}
37
38const REOPENED: &str = "AgentMux reopened your windows, tabs and panes.";
39const AGENTS_KEPT: &str = "Every agent kept running: agents don't run in the window.";
40const SAVED_FOR_NEXT_START: &str = "Your windows, tabs and panes are saved, and come back when you start AgentMux.";
41
42/// Why a process exited, from its exit code: the Windows faults AgentMux sees
43/// in words, any other code as it is. `None` for a plain failure exit (1),
44/// which says nothing.
45pub fn exit_cause(code: i32) -> Option<String> {
46    let words = match code as u32 {
47        1 => return None,
48        0xC000_0005 => "an access violation",
49        0xC000_0409 => "a failed safety check",
50        0xC000_00FD => "a stack overflow",
51        0xC000_0374 => "heap corruption",
52        0xC000_0017 | 0xE000_0008 => return Some("It ran out of memory.".to_string()),
53        0xC000_013A => return Some("It was ended with Ctrl+C or by Windows shutting it down.".to_string()),
54        // TerminateProcess's usual code: Task Manager, Stop-Process, a security tool.
55        0xFFFF_FFFF => return Some("Its process was ended from outside AgentMux, for example by Task Manager or a security tool.".to_string()),
56        _ => return Some(format!("It exited with code {:#X}.", code as u32)),
57    };
58    Some(format!("A fault in its process stopped it ({words}, {:#X}).", code as u32))
59}
60
61/// The window process stopped and the launcher started it again; with
62/// `safe_mode`, without graphics acceleration, because it stopped the same
63/// way twice in a row.
64pub fn host_restarted(code: i32, safe_mode: bool) -> Incident {
65    let mut i = if safe_mode {
66        let mut i = Incident::new("host_restarted_safe_mode", "AgentMux restarted without graphics acceleration", "launcher");
67        i.cause = Some(format!(
68            "Its window process stopped the same way twice in a row, so AgentMux turned graphics acceleration off to get it running.{}",
69            exit_cause(code).map(|c| format!(" {c}")).unwrap_or_default()
70        ));
71        i
72    } else {
73        let mut i = Incident::new("host_restarted", "AgentMux restarted its window after it stopped unexpectedly", "launcher");
74        i.cause = exit_cause(code);
75        i
76    };
77    i.did = vec![REOPENED.to_string(), AGENTS_KEPT.to_string()];
78    if safe_mode {
79        i.did.push("Graphics acceleration comes back the next time you start AgentMux.".to_string());
80    }
81    i
82}
83
84/// The window process stopped because the computer ran out of memory, and
85/// the launcher started it again once memory was back, without graphics
86/// acceleration.
87pub fn host_restarted_low_memory() -> Incident {
88    let mut i = Incident::new("host_restarted_safe_mode", "AgentMux restarted after the computer ran out of memory", "launcher");
89    i.cause = Some("The computer had no memory left to give its window process.".to_string());
90    i.did = vec![
91        "AgentMux waited for memory to free up, then reopened your windows, tabs and panes.".to_string(),
92        AGENTS_KEPT.to_string(),
93        "It runs without graphics acceleration, which uses less memory, until you next start it.".to_string(),
94    ];
95    i
96}
97
98/// Why srv stopped before the launcher started it again.
99#[derive(Debug, Clone, Copy)]
100pub enum SrvStop {
101    /// It exited, with this code.
102    Exited(i32),
103    /// A signal ended it (Unix), with the signal's number and name ("" if it has none).
104    #[cfg_attr(windows, allow(dead_code))]
105    Signal(i32, &'static str),
106    /// The computer ran out of memory; the launcher waited for it.
107    LowMemory,
108    /// It stopped answering, and the launcher ended it.
109    Unresponsive,
110}
111
112/// srv stopped and the launcher started it again (then the window, which
113/// was connected to the old one).
114pub fn srv_restarted(why: SrvStop) -> Incident {
115    let mut i = Incident::new("srv_restarted", "AgentMux's background service restarted", "launcher");
116    i.cause = match why {
117        SrvStop::Exited(code) => exit_cause(code),
118        SrvStop::Signal(sig, "") => Some(format!("Its process was ended by signal {sig}.")),
119        SrvStop::Signal(sig, name) => Some(format!("Its process was ended by signal {sig} ({name}).")),
120        SrvStop::LowMemory => Some("The computer ran out of memory.".to_string()),
121        SrvStop::Unresponsive => Some("It stopped answering, so AgentMux ended it.".to_string()),
122    };
123    i.did = vec![
124        match why {
125            SrvStop::LowMemory => "AgentMux waited for memory to free up, then started the service again.",
126            _ => "AgentMux started the service again.",
127        }
128        .to_string(),
129        REOPENED.to_string(),
130    ];
131    i.lost = vec!["An agent's turn that was under way may have been cut off; its conversation is saved.".to_string()];
132    i
133}
134
135/// The launcher stopped trying: the computer stayed out of memory.
136pub fn memory_give_up() -> Incident {
137    let mut i = Incident::new("memory_give_up", "AgentMux stopped: the computer was out of memory", "launcher");
138    i.cause = Some("Memory didn't free up, and starting again would only have failed again.".to_string());
139    i.did = vec![SAVED_FOR_NEXT_START.to_string()];
140    i
141}
142
143/// The launcher stopped trying: `what` kept stopping, `restarts` times within
144/// `window_secs`.
145pub fn crash_give_up(what: GaveUpOn, code: i32, restarts: usize, window_secs: u64) -> Incident {
146    let (kind, title) = match what {
147        GaveUpOn::Window => ("host_give_up", "AgentMux stopped: its window process kept crashing"),
148        GaveUpOn::Service => ("srv_give_up", "AgentMux stopped: its background service kept crashing"),
149    };
150    let mut i = Incident::new(kind, title, "launcher");
151    i.cause = Some(format!(
152        "It stopped {restarts} times in {window_secs} seconds, so AgentMux stopped restarting it.{}",
153        exit_cause(code).map(|c| format!(" The last time: {c}")).unwrap_or_default()
154    ));
155    i.did = vec![SAVED_FOR_NEXT_START.to_string()];
156    i
157}
158
159/// Which process a give-up was about.
160#[derive(Debug, Clone, Copy)]
161pub enum GaveUpOn {
162    Window,
163    Service,
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn exit_codes_become_words_and_an_unknown_one_is_named() {
172        assert_eq!(exit_cause(0xC000_0005u32 as i32).as_deref(), Some("A fault in its process stopped it (an access violation, 0xC0000005)."));
173        assert_eq!(exit_cause(0xE000_0008u32 as i32).as_deref(), Some("It ran out of memory."));
174        assert_eq!(exit_cause(1), None, "a plain failure says nothing");
175        // Seen in a dev build: the host ended with Stop-Process.
176        assert!(exit_cause(-1).unwrap().starts_with("Its process was ended from outside AgentMux"));
177        assert_eq!(exit_cause(42).as_deref(), Some("It exited with code 0x2A."));
178    }
179
180    #[test]
181    fn a_restart_says_what_was_reopened_and_safe_mode_says_why_and_until_when() {
182        let plain = host_restarted(0xC000_0005u32 as i32, false);
183        assert_eq!(plain.kind, "host_restarted");
184        assert_eq!(plain.did, vec![REOPENED.to_string(), AGENTS_KEPT.to_string()]);
185        let safe = host_restarted(1, true);
186        assert_eq!(safe.kind, "host_restarted_safe_mode");
187        assert!(safe.cause.as_deref().unwrap().starts_with("Its window process stopped the same way twice"));
188        assert!(safe.did.last().unwrap().contains("next time you start AgentMux"));
189    }
190
191    #[test]
192    fn a_service_restart_says_a_turn_may_have_been_cut_off() {
193        let i = srv_restarted(SrvStop::Exited(0xC000_0409u32 as i32));
194        assert_eq!(i.kind, "srv_restarted");
195        assert_eq!(i.cause.as_deref(), Some("A fault in its process stopped it (a failed safety check, 0xC0000409)."));
196        assert_eq!(i.lost.len(), 1);
197        assert_eq!(srv_restarted(SrvStop::LowMemory).cause.as_deref(), Some("The computer ran out of memory."));
198        assert_eq!(
199            srv_restarted(SrvStop::Signal(9, "SIGKILL")).cause.as_deref(),
200            Some("Its process was ended by signal 9 (SIGKILL).")
201        );
202        assert_eq!(srv_restarted(SrvStop::Signal(31, "")).cause.as_deref(), Some("Its process was ended by signal 31."));
203        assert_eq!(srv_restarted(SrvStop::Unresponsive).cause.as_deref(), Some("It stopped answering, so AgentMux ended it."));
204    }
205
206    #[test]
207    fn a_give_up_says_how_often_and_that_the_layout_is_saved() {
208        let i = crash_give_up(GaveUpOn::Window, 1, 3, 60);
209        assert_eq!(i.kind, "host_give_up");
210        assert_eq!(i.cause.as_deref(), Some("It stopped 3 times in 60 seconds, so AgentMux stopped restarting it."));
211        assert_eq!(i.did, vec![SAVED_FOR_NEXT_START.to_string()]);
212        assert_eq!(crash_give_up(GaveUpOn::Service, 1, 5, 30).kind, "srv_give_up");
213        assert_eq!(memory_give_up().kind, "memory_give_up");
214    }
215
216    #[test]
217    fn incidents_land_in_the_data_folders_file() {
218        let dir = tempfile::tempdir().unwrap();
219        let path = dir.path().join(agentmux_common::incidents::FILE_NAME);
220        agentmux_common::incidents::append(&path, &host_restarted(1, false)).unwrap();
221        let got = agentmux_common::incidents::read(&path, 10);
222        assert_eq!(got.len(), 1);
223        assert!(got[0].evidence.as_deref().unwrap().starts_with("launcher log, "));
224    }
225}