agentmux_srv_core/backend/
background_task_pid.rs1use std::sync::Arc;
19
20use agentmux_common::client_events::ToolChunk;
21use serde_json::Value;
22
23use super::background_task_feed::publish_background_task_updated;
24use super::mps::{Broker, MuxEvent};
25use super::mps_events::{Event, ToolChunk as ToolChunkEvent};
26use super::pending_background_pids::PendingBackgroundPids;
27use super::storage::store::Store;
28
29#[derive(Debug, PartialEq, Eq)]
31pub(crate) struct PidReport {
32 pub block_id: String,
33 pub tool_id: String,
34 pub pid: i64,
35}
36
37pub(crate) fn pid_in(event: &str, scopes: &[String], data: Option<&Value>) -> Option<PidReport> {
39 if event != <ToolChunkEvent as Event>::NAME {
40 return None;
41 }
42 let ToolChunk::Pid { tool_id, pid, .. } = serde_json::from_value(data?.clone()).ok()? else {
43 return None;
44 };
45 let block_id = scopes.iter().find_map(|s| s.strip_prefix("block:"))?.to_string();
46 Some(PidReport { block_id, tool_id, pid: i64::from(pid) })
47}
48
49pub fn file_pid(store: &Store, broker: Option<&Broker>, block_id: &str, tool_id: &str, pid: i64, now_ms: i64) {
52 let filed = PendingBackgroundPids::global().set_or_stash(tool_id, pid, now_ms, |pid| store.background_task_set_pid(tool_id, pid));
53 match filed {
54 Ok(()) => {
55 if let Some(broker) = broker {
56 publish_background_task_updated(broker, block_id);
57 }
58 }
59 Err(e) => tracing::warn!(target: "background_tasks", node_id = %tool_id, error = %e, "failed to record background task pid in the durable registry"),
60 }
61}
62
63pub fn apply_stashed(store: &Store, tool_id: &str, now_ms: i64) {
65 let applied = PendingBackgroundPids::global().observe_and_apply(tool_id, now_ms, |pid| store.background_task_set_pid(tool_id, pid));
66 if let Err(e) = applied {
67 tracing::warn!(target: "background_tasks", node_id = %tool_id, error = %e, "failed to apply a pid stashed ahead of this task's registry row");
68 }
69}
70
71pub fn install(broker: Arc<Broker>, store: Arc<Store>) {
73 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<PidReport>();
74 broker.add_observer(Arc::new(move |ev: &MuxEvent| {
76 if let Some(report) = pid_in(&ev.event, &ev.scopes, ev.data.as_ref()) {
77 let _ = tx.send(report);
78 }
79 }));
80 let notify = Arc::clone(&broker);
81 tokio::spawn(async move {
82 while let Some(report) = rx.recv().await {
83 let (store, broker) = (Arc::clone(&store), Arc::clone(¬ify));
84 let _ = tokio::task::spawn_blocking(move || {
85 file_pid(&store, Some(&broker), &report.block_id, &report.tool_id, report.pid, agentmux_common::time::now_ms());
86 })
87 .await;
88 }
89 });
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95 use crate::backend::background_task_feed::TaskFeed;
96 use serde_json::json;
97
98 fn pid_chunk(tool_id: &str, pid: u32) -> Value {
99 json!({ "op": "pid", "tool_id": tool_id, "pid": pid, "timestamp": 7 })
100 }
101
102 fn scopes() -> Vec<String> {
103 vec!["block:blk".to_string()]
104 }
105
106 fn store() -> Store {
107 Store::open(std::path::Path::new(":memory:")).unwrap()
108 }
109
110 #[test]
111 fn a_pid_chunk_of_a_pane_is_a_report_and_nothing_else_is() {
112 let got = pid_in("tool_chunk", &scopes(), Some(&pid_chunk("toolu_1", 42)));
113 assert_eq!(got, Some(PidReport { block_id: "blk".into(), tool_id: "toolu_1".into(), pid: 42 }));
114 let line = json!({ "op": "chunk", "tool_id": "toolu_1", "kind": "stdout", "content": "x\n", "timestamp": 5 });
115 let exit = json!({ "op": "terminal", "tool_id": "toolu_1", "exit_code": 0, "timestamp": 6 });
116 assert_eq!(pid_in("tool_chunk", &scopes(), Some(&line)), None);
117 assert_eq!(pid_in("tool_chunk", &scopes(), Some(&exit)), None);
118 assert_eq!(pid_in("tool_chunk", &scopes(), None), None);
119 assert_eq!(pid_in("agents:changed", &scopes(), Some(&pid_chunk("toolu_1", 42))), None, "another event");
120 assert_eq!(pid_in("tool_chunk", &[], Some(&pid_chunk("toolu_1", 42))), None, "no pane to tell");
121 }
122
123 #[test]
124 fn a_pid_filed_after_its_row_is_recorded_at_once() {
125 let s = store();
126 s.background_task_observe("pid_after_row", "blk", "task dev", 1000, 1000).unwrap();
127 file_pid(&s, None, "blk", "pid_after_row", 4242, 2000);
128 assert_eq!(s.background_task_get("pid_after_row").unwrap().unwrap().pid, Some(4242));
129 }
130
131 #[test]
134 fn a_pid_that_beats_a_row_made_by_the_task_feed_is_applied_when_the_row_appears() {
135 let s = store();
136 file_pid(&s, None, "blk", "toolu_nopane", 777, 1000);
137 assert!(s.background_task_get("toolu_nopane").unwrap().is_none(), "no row yet: the pid waits");
138
139 let started = json!({ "type": "system", "subtype": "task_started", "task_id": "bgtask1", "tool_use_id": "toolu_nopane",
140 "task_type": "local_bash", "description": "task dev", "is_backgrounded": true });
141 let mut feed = TaskFeed::default();
142 assert!(feed.apply(&s, None, "blk", &started, 2000), "the feed makes the row");
143 assert_eq!(s.background_task_get("toolu_nopane").unwrap().unwrap().pid, Some(777));
144 }
145
146 #[test]
147 fn a_stashed_pid_is_applied_once() {
148 let s = store();
149 file_pid(&s, None, "blk", "once", 5, 1000);
150 s.background_task_observe("once", "blk", "build", 1000, 1000).unwrap();
151 apply_stashed(&s, "once", 1500);
152 assert_eq!(s.background_task_get("once").unwrap().unwrap().pid, Some(5));
153 s.background_task_set_pid("once", 9).unwrap();
154 apply_stashed(&s, "once", 1600);
155 assert_eq!(s.background_task_get("once").unwrap().unwrap().pid, Some(9), "the pen was emptied");
156 }
157}