1use std::sync::Arc;
14
15use agentmux_common::client_events::ToolChunk;
16use serde_json::Value;
17
18use super::background_task_feed::publish_background_task_updated;
19use super::mps::{Broker, MuxEvent};
20use super::mps_events::{Event, ToolChunk as ToolChunkEvent};
21use super::storage::background_tasks::BackgroundTaskStatus;
22use super::storage::store::Store;
23
24#[derive(Debug, PartialEq, Eq)]
26pub(crate) struct Exit {
27 pub block_id: String,
28 pub tool_id: String,
29 pub exit_code: i32,
30 pub at_ms: i64,
31}
32
33pub(crate) fn exit_in(event: &str, scopes: &[String], data: Option<&Value>) -> Option<Exit> {
35 if event != <ToolChunkEvent as Event>::NAME {
36 return None;
37 }
38 let ToolChunk::Terminal { tool_id, exit_code, timestamp } = serde_json::from_value(data?.clone()).ok()? else {
39 return None;
40 };
41 let block_id = scopes.iter().find_map(|s| s.strip_prefix("block:"))?.to_string();
42 Some(Exit { block_id, tool_id, exit_code, at_ms: i64::try_from(timestamp).unwrap_or(i64::MAX) })
43}
44
45pub(crate) fn status_for(exit_code: i32) -> BackgroundTaskStatus {
48 match exit_code {
49 0 => BackgroundTaskStatus::Done,
50 c if c < 0 || matches!(c, 130 | 137 | 143) => BackgroundTaskStatus::Stopped,
51 _ => BackgroundTaskStatus::Error,
52 }
53}
54
55fn end_row(store: &Store, exit: &Exit) -> bool {
57 match store.background_task_end_if_running(&exit.tool_id, status_for(exit.exit_code), exit.at_ms) {
58 Ok(ended) => ended,
59 Err(e) => {
60 tracing::warn!(target: "background_tasks", node_id = %exit.tool_id, error = %e, "could not end a background task from its exit");
61 false
62 }
63 }
64}
65
66pub fn end_for_restarted_container(store: &Store, broker: &Broker, block_id: &str) -> usize {
71 match store.background_task_end_unchecked_for_block(block_id) {
72 Ok(0) => 0,
73 Ok(ended) => {
74 tracing::info!(target: "background_tasks", block_id, ended, "a container started again: its background tasks are over");
75 publish_background_task_updated(broker, block_id);
76 ended
77 }
78 Err(e) => {
79 tracing::warn!(target: "background_tasks", block_id, error = %e, "could not end the background tasks of a restarted container");
80 0
81 }
82 }
83}
84
85pub fn install(broker: Arc<Broker>, store: Arc<Store>) {
87 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Exit>();
88 broker.add_observer(Arc::new(move |ev: &MuxEvent| {
91 if let Some(exit) = exit_in(&ev.event, &ev.scopes, ev.data.as_ref()) {
92 let _ = tx.send(exit);
93 }
94 }));
95 let notify = Arc::clone(&broker);
96 tokio::spawn(async move {
97 while let Some(exit) = rx.recv().await {
98 let store = Arc::clone(&store);
99 let ended = tokio::task::spawn_blocking(move || end_row(&store, &exit).then_some(exit.block_id)).await;
100 if let Ok(Some(block_id)) = ended {
101 publish_background_task_updated(¬ify, &block_id);
102 }
103 }
104 });
105}
106
107#[cfg(test)]
108mod tests {
109 use super::*;
110 use serde_json::json;
111
112 fn terminal(code: i32) -> Value {
113 json!({ "op": "terminal", "tool_id": "toolu_1", "exit_code": code, "timestamp": 5000 })
114 }
115
116 fn scopes() -> Vec<String> {
117 vec!["block:b1".to_string()]
118 }
119
120 #[test]
121 fn a_terminal_chunk_of_a_pane_is_an_exit() {
122 let got = exit_in("tool_chunk", &scopes(), Some(&terminal(3)));
123 assert_eq!(got, Some(Exit { block_id: "b1".into(), tool_id: "toolu_1".into(), exit_code: 3, at_ms: 5000 }));
124 }
125
126 #[test]
127 fn nothing_else_is_an_exit() {
128 let line = json!({ "op": "chunk", "tool_id": "toolu_1", "kind": "stdout", "content": "x\n", "timestamp": 5 });
129 let pid = json!({ "op": "pid", "tool_id": "toolu_1", "pid": 42, "timestamp": 7 });
130 assert_eq!(exit_in("tool_chunk", &scopes(), Some(&line)), None);
131 assert_eq!(exit_in("tool_chunk", &scopes(), Some(&pid)), None);
132 assert_eq!(exit_in("tool_chunk", &scopes(), None), None);
133 assert_eq!(exit_in("agents:changed", &scopes(), Some(&terminal(0))), None, "another event");
134 assert_eq!(exit_in("tool_chunk", &[], Some(&terminal(0))), None, "no pane to tell");
135 }
136
137 #[test]
138 fn the_exit_code_decides_how_the_row_ends() {
139 assert_eq!(status_for(0), BackgroundTaskStatus::Done);
140 assert_eq!(status_for(1), BackgroundTaskStatus::Error);
141 assert_eq!(status_for(2), BackgroundTaskStatus::Error);
142 for signalled in [-1, 130, 137, 143] {
143 assert_eq!(status_for(signalled), BackgroundTaskStatus::Stopped, "{signalled}");
144 }
145 }
146
147 fn running_row(store: &Store, id: &str) {
148 store.background_task_observe(id, "b1", "task dev", 1000, 1000).unwrap();
149 }
150
151 #[test]
152 fn a_running_row_ends_at_the_exit_with_its_status() {
153 let store = Store::open(std::path::Path::new(":memory:")).unwrap();
154 running_row(&store, "toolu_1");
155 let exit = exit_in("tool_chunk", &scopes(), Some(&terminal(1))).unwrap();
156 assert!(end_row(&store, &exit));
157 let row = store.background_task_get("toolu_1").unwrap().unwrap();
158 assert_eq!((row.status, row.ended_at_ms), (BackgroundTaskStatus::Error, Some(5000)));
159 }
160
161 #[test]
162 fn a_call_with_no_row_and_a_row_the_cli_already_ended_are_left_alone() {
163 let store = Store::open(std::path::Path::new(":memory:")).unwrap();
164 let exit = exit_in("tool_chunk", &scopes(), Some(&terminal(0))).unwrap();
165 assert!(!end_row(&store, &exit), "a foreground call has no row");
166
167 running_row(&store, "toolu_1");
168 store.background_task_complete("toolu_1", BackgroundTaskStatus::Stopped, 4000).unwrap();
169 assert!(!end_row(&store, &exit));
170 let row = store.background_task_get("toolu_1").unwrap().unwrap();
171 assert_eq!((row.status, row.ended_at_ms), (BackgroundTaskStatus::Stopped, Some(4000)));
172 }
173
174 fn state(store: &Store, id: &str) -> (BackgroundTaskStatus, Option<i64>) {
175 let row = store.background_task_get(id).unwrap().unwrap();
176 (row.status, row.ended_at_ms)
177 }
178
179 #[test]
180 fn a_restarted_container_ends_its_panes_unchecked_rows_at_their_last_sighting() {
181 let store = Store::open(std::path::Path::new(":memory:")).unwrap();
182 let broker = Broker::new();
183 store.background_task_observe("old_1", "b1", "Bash", 1000, 1000).unwrap();
185 store.background_task_observe("old_2", "b1", "Bash", 2000, 2500).unwrap();
186 assert_eq!(end_for_restarted_container(&store, &broker, "b1"), 2);
187 assert_eq!(state(&store, "old_1"), (BackgroundTaskStatus::Stopped, Some(1000)));
188 assert_eq!(state(&store, "old_2"), (BackgroundTaskStatus::Stopped, Some(2500)));
189 assert_eq!(end_for_restarted_container(&store, &broker, "b1"), 0, "a second start finds nothing to end");
190 }
191
192 #[test]
193 fn a_restarted_container_leaves_other_panes_ended_rows_and_rows_with_a_pid_alone() {
194 let store = Store::open(std::path::Path::new(":memory:")).unwrap();
195 let broker = Broker::new();
196 store.background_task_observe("other_pane", "b2", "Bash", 1000, 1000).unwrap();
197 store.background_task_observe("done", "b1", "Bash", 1000, 1000).unwrap();
198 store.background_task_complete("done", BackgroundTaskStatus::Done, 4000).unwrap();
199 store.background_task_observe("host_task", "b1", "task dev", 1000, 1000).unwrap();
200 store.background_task_set_pid("host_task", 4242).unwrap();
201 assert_eq!(end_for_restarted_container(&store, &broker, "b1"), 0);
202 assert_eq!(state(&store, "other_pane").0, BackgroundTaskStatus::Running);
203 assert_eq!(state(&store, "done"), (BackgroundTaskStatus::Done, Some(4000)));
204 assert_eq!(state(&store, "host_task").0, BackgroundTaskStatus::Running, "the sweep checks a pid");
205 }
206}