Skip to main content

agentmux_srv_core/backend/
background_task_pid.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Files a background task's pid in `db_background_tasks` from srv itself
5//! (`docs/specs/SPEC_BACKGROUND_TASK_STRUCTURED_FEED_AND_SWARM_OWNERSHIP_2026_09_27.md` ยง5, first bullet;
6//! `docs/specs/SPEC_BACKGROUND_TASK_PID_CAPTURE_2026_08_20.md`).
7//!
8//! `agentmux-bashwrap` publishes a `pid` chunk when the command it runs starts. Only an open agent pane used to
9//! read it, and relayed it to srv: with the pane closed or parked the row never got its pid, and the liveness sweep
10//! (`background_task_sweep`) had nothing to check it by. The chunk is on the broker whether or not a pane is open, so
11//! srv reads it there.
12//!
13//! The pid usually beats its row: bashwrap publishes it at its own start, and the row is made when the CLI's task
14//! feed (in the stdout reader, which needs no pane) or the pane's `docknodestatus` first sees the call run in the
15//! background. A pid that finds no row waits in the process-wide pen (`PendingBackgroundPids`), and whoever makes the
16//! row applies it ([`apply_stashed`]).
17
18use 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/// A command's pid: the pane's block, the call's id (the row's id) and the process id.
30#[derive(Debug, PartialEq, Eq)]
31pub(crate) struct PidReport {
32    pub block_id: String,
33    pub tool_id: String,
34    pub pid: i64,
35}
36
37/// The pid in a broker event, if it is a `pid` chunk published for a pane.
38pub(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
49/// Record `pid` on the row `tool_id`, or keep it in the pen until that row exists. Tells the pane to re-read when
50/// `broker` is given. Blocking: a store write.
51pub 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
63/// The row `tool_id` now exists: give it the pid that came before it, if one did. Blocking: a store write.
64pub 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
71/// Start listening. Called once, with the app's broker and store.
72pub fn install(broker: Arc<Broker>, store: Arc<Store>) {
73    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<PidReport>();
74    // Observers run inside `Broker::publish`, under its locks: parse and hand off only.
75    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(&notify));
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    // The case of a task started while no pane shows the agent: no `docknodestatus` ever comes, so the row is made by
132    // the CLI's task feed in the stdout reader, after the pid that bashwrap published when the command started.
133    #[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}