Skip to main content

agentmux_srv_core/backend/storage/
background_tasks.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Durable registry of declared long-running (`run_in_background: true`)
5//! tasks attached to a block. See `db_background_tasks` in migrations.rs
6//! (`OBJECT_SCHEMA_VERSION` v20) and
7//! docs/status/STATUS_ATTACHED_TASK_AXIS_AND_DEV_LOOP_2026_08_15.md.
8//!
9//! This exists because the frontend's own signal chain for "is a
10//! long-running task attached to this pane" — transcript replay →
11//! in-memory reducer slice → `DockSnapshotCache` — is entirely ephemeral:
12//! scoped to one open tab, and (for the srv-side `DockSnapshotCache` mirror)
13//! silently evicted after one hour regardless of whether the task is still
14//! genuinely running. A `task dev` session in this repo's own retros has
15//! run 12+ hours. `id` mirrors the frontend's dock `node_id` (normally the
16//! originating tool_use_id) so rows join cleanly with dock data.
17
18use rusqlite::params;
19
20use super::error::StoreError;
21use super::store::Store;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum BackgroundTaskStatus {
25    Running,
26    Done,
27    Error,
28    Stopped,
29}
30
31impl BackgroundTaskStatus {
32    pub fn as_str(self) -> &'static str {
33        match self {
34            BackgroundTaskStatus::Running => "running",
35            BackgroundTaskStatus::Done => "done",
36            BackgroundTaskStatus::Error => "error",
37            BackgroundTaskStatus::Stopped => "stopped",
38        }
39    }
40
41    /// Unrecognized values fall back to `Running` — same "never claim
42    /// running-forever silently disappears, never claim a live task is
43    /// terminal on a parse hiccup" posture as the rest of this feature
44    /// area (`isAcceptedBackgroundLaunch`'s "unrecognized → stopped, never
45    /// running-forever" rule is about outgoing classification; this is the
46    /// inverse case of reading a row back, where erring toward "still
47    /// live" is the safer default for a status this registry itself wrote).
48    pub fn from_str(s: &str) -> Self {
49        match s {
50            "done" => BackgroundTaskStatus::Done,
51            "error" => BackgroundTaskStatus::Error,
52            "stopped" => BackgroundTaskStatus::Stopped,
53            _ => BackgroundTaskStatus::Running,
54        }
55    }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct BackgroundTask {
60    pub id: String,
61    pub block_id: String,
62    pub label: String,
63    pub pid: Option<i64>,
64    pub started_at_ms: i64,
65    pub status: BackgroundTaskStatus,
66    pub last_seen_ms: i64,
67    pub ended_at_ms: Option<i64>,
68    /// The Agent call (`tool_use_id`) whose subagent launched this task, or
69    /// `None` for the agent's own. Schema v41.
70    pub owner_tool_use_id: Option<String>,
71}
72
73/// The label a row has until something describes the call: the renderer's tool name.
74pub const GENERIC_LABEL: &str = "Bash";
75
76const COLUMNS: &str =
77    "id, block_id, label, pid, started_at_ms, status, last_seen_ms, ended_at_ms, owner_tool_use_id";
78
79impl Store {
80    /// Create the row if it doesn't exist yet (status `running`), and
81    /// refresh `last_seen_ms` — but only while the row is still `running`.
82    /// Never resurrects a row a concurrent `background_task_complete` call
83    /// already marked terminal; the terminal status is left untouched.
84    pub fn background_task_observe(
85        &self,
86        id: &str,
87        block_id: &str,
88        label: &str,
89        started_at_ms: i64,
90        now_ms: i64,
91    ) -> Result<(), StoreError> {
92        let conn = self.conn.lock().unwrap();
93        conn.execute(
94            "INSERT OR IGNORE INTO db_background_tasks
95                (id, block_id, label, pid, started_at_ms, status, last_seen_ms, ended_at_ms)
96             VALUES (?1, ?2, ?3, NULL, ?4, 'running', ?5, NULL)",
97            params![id, block_id, label, started_at_ms, now_ms],
98        )?;
99        conn.execute(
100            "UPDATE db_background_tasks SET last_seen_ms = ?1 WHERE id = ?2 AND status = 'running'",
101            params![now_ms, id],
102        )?;
103        // What the container agent said about the call, filed before this row existed, replaces the generic label.
104        conn.execute(
105            "UPDATE db_background_tasks
106             SET label = (SELECT c.description FROM db_background_container_calls c
107                          WHERE c.block_id = db_background_tasks.block_id AND c.id = db_background_tasks.id)
108             WHERE id = ?1 AND label = ?2
109               AND EXISTS (SELECT 1 FROM db_background_container_calls c
110                           WHERE c.block_id = db_background_tasks.block_id AND c.id = db_background_tasks.id
111                             AND c.description IS NOT NULL)",
112            params![id, GENERIC_LABEL],
113        )?;
114        Ok(())
115    }
116
117    /// Give the row `id` of `block_id` the call's own `label` when it still has the renderer's generic one
118    /// (the CLI's own description, set by [`Self::background_task_describe`], is never replaced). `false`
119    /// when there is no such row or its label is already specific.
120    pub fn background_task_describe_if_generic(&self, block_id: &str, id: &str, label: &str) -> Result<bool, StoreError> {
121        let conn = self.conn.lock().unwrap();
122        let rows = conn.execute(
123            "UPDATE db_background_tasks SET label = ?1 WHERE id = ?2 AND block_id = ?3 AND label = ?4",
124            params![label, id, block_id, GENERIC_LABEL],
125        )?;
126        Ok(rows > 0)
127    }
128
129    /// Record the OS pid once known (bashwrap/process_tracker learn it
130    /// after the task has already been observed as declared-background).
131    /// No-op (returns `false`) if the row doesn't exist.
132    pub fn background_task_set_pid(&self, id: &str, pid: i64) -> Result<bool, StoreError> {
133        let conn = self.conn.lock().unwrap();
134        let rows = conn.execute(
135            "UPDATE db_background_tasks SET pid = ?1 WHERE id = ?2",
136            params![pid, id],
137        )?;
138        Ok(rows > 0)
139    }
140
141    /// Mark a task terminal. Idempotent — calling this again on an already-
142    /// terminal row just overwrites the status/ended_at (last write wins),
143    /// which only matters if two different terminal signals race, an edge
144    /// case not worth a CAS for a status transition with no live consumer
145    /// depending on "first terminal write wins" today.
146    pub fn background_task_complete(
147        &self,
148        id: &str,
149        status: BackgroundTaskStatus,
150        ended_at_ms: i64,
151    ) -> Result<bool, StoreError> {
152        let conn = self.conn.lock().unwrap();
153        let rows = conn.execute(
154            "UPDATE db_background_tasks
155             SET status = ?1, ended_at_ms = ?2, last_seen_ms = ?2
156             WHERE id = ?3",
157            params![status.as_str(), ended_at_ms, id],
158        )?;
159        Ok(rows > 0)
160    }
161
162    /// End a task that is still `running`, leaving a row that already ended as it is. For what has to
163    /// decide from a list it read earlier (the liveness sweep): a real `done` or `error` that arrived
164    /// since must not be overwritten. `false` when the row is gone or was no longer running.
165    pub fn background_task_end_if_running(
166        &self,
167        id: &str,
168        status: BackgroundTaskStatus,
169        ended_at_ms: i64,
170    ) -> Result<bool, StoreError> {
171        let conn = self.conn.lock().unwrap();
172        let rows = conn.execute(
173            "UPDATE db_background_tasks
174             SET status = ?1, ended_at_ms = ?2, last_seen_ms = ?2
175             WHERE id = ?3 AND status = 'running'",
176            params![status.as_str(), ended_at_ms, id],
177        )?;
178        Ok(rows > 0)
179    }
180
181    /// End every `running` row of `block_id` that has no pid, each at its own last sighting, and return how many
182    /// ended. For a pane whose processes ran somewhere that is gone (a container that was started again or made
183    /// anew): a row with no pid can't be checked, so nothing else would ever say it ended. Ending it at its last
184    /// sighting, not now, keeps a long-dead task from reading as one that just stopped. A row with a pid is left
185    /// to the liveness sweep.
186    pub fn background_task_end_unchecked_for_block(&self, block_id: &str) -> Result<usize, StoreError> {
187        let conn = self.conn.lock().unwrap();
188        let rows = conn.execute(
189            "UPDATE db_background_tasks
190             SET status = 'stopped', ended_at_ms = last_seen_ms
191             WHERE block_id = ?1 AND status = 'running' AND pid IS NULL",
192            params![block_id],
193        )?;
194        Ok(rows)
195    }
196
197    pub fn background_task_get(&self, id: &str) -> Result<Option<BackgroundTask>, StoreError> {
198        let conn = self.conn.lock().unwrap();
199        let mut stmt = conn.prepare(&format!("SELECT {COLUMNS} FROM db_background_tasks WHERE id = ?1"))?;
200        let mut rows = stmt.query_map(params![id], map_row)?;
201        match rows.next() {
202            Some(r) => Ok(Some(r?)),
203            None => Ok(None),
204        }
205    }
206
207    pub fn background_task_list_for_block(&self, block_id: &str) -> Result<Vec<BackgroundTask>, StoreError> {
208        let conn = self.conn.lock().unwrap();
209        let mut stmt = conn.prepare(&format!(
210            "SELECT {COLUMNS} FROM db_background_tasks WHERE block_id = ?1 ORDER BY started_at_ms ASC"
211        ))?;
212        let iter = stmt.query_map(params![block_id], map_row)?;
213        iter.collect::<Result<Vec<_>, _>>().map_err(Into::into)
214    }
215
216    /// Global — every still-`running` row across every block. Used by
217    /// Swarm-style fleet views and reconnect/history-restore, where the
218    /// caller doesn't yet know which block(s) to ask about.
219    pub fn background_task_list_running(&self) -> Result<Vec<BackgroundTask>, StoreError> {
220        let conn = self.conn.lock().unwrap();
221        let mut stmt = conn.prepare(&format!(
222            "SELECT {COLUMNS} FROM db_background_tasks WHERE status = 'running' ORDER BY started_at_ms ASC"
223        ))?;
224        let iter = stmt.query_map([], map_row)?;
225        iter.collect::<Result<Vec<_>, _>>().map_err(Into::into)
226    }
227
228    /// Every block's `running` rows plus those that ended at or after
229    /// `ended_since_ms` — what a fleet view (Swarm) shows: live work, and
230    /// finished work for as long as it keeps showing a finished row.
231    pub fn background_task_list_fleet(&self, ended_since_ms: i64) -> Result<Vec<BackgroundTask>, StoreError> {
232        let conn = self.conn.lock().unwrap();
233        let mut stmt = conn.prepare(&format!(
234            "SELECT {COLUMNS} FROM db_background_tasks
235             WHERE status = 'running' OR ended_at_ms >= ?1
236             ORDER BY started_at_ms ASC"
237        ))?;
238        let iter = stmt.query_map(params![ended_since_ms], map_row)?;
239        iter.collect::<Result<Vec<_>, _>>().map_err(Into::into)
240    }
241
242    /// Record what the CLI says about a task: its description (replacing a
243    /// generic label such as the renderer's "Bash") and the subagent that
244    /// owns it. The owner is only ever filled in, never cleared or changed.
245    /// No-op (`false`) if the row doesn't exist.
246    pub fn background_task_describe(
247        &self,
248        id: &str,
249        label: &str,
250        owner_tool_use_id: Option<&str>,
251    ) -> Result<bool, StoreError> {
252        let conn = self.conn.lock().unwrap();
253        let rows = conn.execute(
254            "UPDATE db_background_tasks
255             SET label = ?1, owner_tool_use_id = COALESCE(owner_tool_use_id, ?2)
256             WHERE id = ?3",
257            params![label, owner_tool_use_id, id],
258        )?;
259        Ok(rows > 0)
260    }
261}
262
263fn map_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<BackgroundTask> {
264    let status: String = row.get(5)?;
265    Ok(BackgroundTask {
266        id: row.get(0)?,
267        block_id: row.get(1)?,
268        label: row.get(2)?,
269        pid: row.get(3)?,
270        started_at_ms: row.get(4)?,
271        status: BackgroundTaskStatus::from_str(&status),
272        last_seen_ms: row.get(6)?,
273        ended_at_ms: row.get(7)?,
274        owner_tool_use_id: row.get(8)?,
275    })
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281
282    fn object_store() -> Store {
283        Store::open(std::path::Path::new(":memory:")).unwrap()
284    }
285
286    #[test]
287    fn observe_creates_a_running_row() {
288        let store = object_store();
289        store.background_task_observe("t1", "block-a", "task dev", 1000, 1000).unwrap();
290        let task = store.background_task_get("t1").unwrap().unwrap();
291        assert_eq!(task.block_id, "block-a");
292        assert_eq!(task.label, "task dev");
293        assert_eq!(task.status, BackgroundTaskStatus::Running);
294        assert_eq!(task.started_at_ms, 1000);
295        assert_eq!(task.last_seen_ms, 1000);
296        assert_eq!(task.pid, None);
297        assert_eq!(task.ended_at_ms, None);
298    }
299
300    #[test]
301    fn observe_is_idempotent_and_refreshes_last_seen() {
302        let store = object_store();
303        store.background_task_observe("t1", "block-a", "task dev", 1000, 1000).unwrap();
304        store.background_task_observe("t1", "block-a", "task dev", 1000, 5000).unwrap();
305        let task = store.background_task_get("t1").unwrap().unwrap();
306        // started_at_ms is NOT overwritten by a repeat observe (INSERT OR
307        // IGNORE leaves the original row alone) — only last_seen_ms moves.
308        assert_eq!(task.started_at_ms, 1000);
309        assert_eq!(task.last_seen_ms, 5000);
310    }
311
312    #[test]
313    fn observe_never_resurrects_a_completed_task() {
314        let store = object_store();
315        store.background_task_observe("t1", "block-a", "task dev", 1000, 1000).unwrap();
316        store.background_task_complete("t1", BackgroundTaskStatus::Done, 2000).unwrap();
317        // A late/duplicate push racing after completion must not flip the
318        // task back to "running" or move its last_seen_ms.
319        store.background_task_observe("t1", "block-a", "task dev", 1000, 9000).unwrap();
320        let task = store.background_task_get("t1").unwrap().unwrap();
321        assert_eq!(task.status, BackgroundTaskStatus::Done);
322        assert_eq!(task.last_seen_ms, 2000);
323    }
324
325    #[test]
326    fn end_if_running_ends_a_running_row_and_leaves_an_ended_one_alone() {
327        let store = object_store();
328        store.background_task_observe("t1", "block-a", "task dev", 1000, 1000).unwrap();
329        assert!(store.background_task_end_if_running("t1", BackgroundTaskStatus::Stopped, 4000).unwrap());
330        let task = store.background_task_get("t1").unwrap().unwrap();
331        assert_eq!((task.status, task.ended_at_ms), (BackgroundTaskStatus::Stopped, Some(4000)));
332
333        store.background_task_observe("t2", "block-a", "build", 1000, 1000).unwrap();
334        store.background_task_complete("t2", BackgroundTaskStatus::Done, 2000).unwrap();
335        assert!(!store.background_task_end_if_running("t2", BackgroundTaskStatus::Stopped, 9000).unwrap());
336        assert_eq!(store.background_task_get("t2").unwrap().unwrap().status, BackgroundTaskStatus::Done);
337        assert!(!store.background_task_end_if_running("missing", BackgroundTaskStatus::Stopped, 9000).unwrap());
338    }
339
340    #[test]
341    fn complete_marks_terminal_and_returns_true_when_row_exists() {
342        let store = object_store();
343        store.background_task_observe("t1", "block-a", "task dev", 1000, 1000).unwrap();
344        let changed = store.background_task_complete("t1", BackgroundTaskStatus::Error, 4000).unwrap();
345        assert!(changed);
346        let task = store.background_task_get("t1").unwrap().unwrap();
347        assert_eq!(task.status, BackgroundTaskStatus::Error);
348        assert_eq!(task.ended_at_ms, Some(4000));
349    }
350
351    #[test]
352    fn complete_returns_false_for_unknown_id() {
353        let store = object_store();
354        assert!(!store.background_task_complete("nope", BackgroundTaskStatus::Done, 1).unwrap());
355    }
356
357    #[test]
358    fn set_pid_updates_existing_row_and_no_ops_for_unknown_id() {
359        let store = object_store();
360        store.background_task_observe("t1", "block-a", "task dev", 1000, 1000).unwrap();
361        assert!(store.background_task_set_pid("t1", 4242).unwrap());
362        assert_eq!(store.background_task_get("t1").unwrap().unwrap().pid, Some(4242));
363        assert!(!store.background_task_set_pid("nope", 1).unwrap());
364    }
365
366    #[test]
367    fn get_returns_none_for_unknown_id() {
368        let store = object_store();
369        assert!(store.background_task_get("nope").unwrap().is_none());
370    }
371
372    #[test]
373    fn list_for_block_only_returns_that_blocks_tasks_in_start_order() {
374        let store = object_store();
375        store.background_task_observe("t1", "block-a", "first", 1000, 1000).unwrap();
376        store.background_task_observe("t2", "block-b", "other-block", 1500, 1500).unwrap();
377        store.background_task_observe("t3", "block-a", "second", 2000, 2000).unwrap();
378        let tasks = store.background_task_list_for_block("block-a").unwrap();
379        let ids: Vec<&str> = tasks.iter().map(|t| t.id.as_str()).collect();
380        assert_eq!(ids, vec!["t1", "t3"]);
381    }
382
383    #[test]
384    fn list_running_excludes_terminal_tasks_across_all_blocks() {
385        let store = object_store();
386        store.background_task_observe("t1", "block-a", "still running", 1000, 1000).unwrap();
387        store.background_task_observe("t2", "block-b", "finished", 1000, 1000).unwrap();
388        store.background_task_complete("t2", BackgroundTaskStatus::Done, 2000).unwrap();
389        let running = store.background_task_list_running().unwrap();
390        let ids: Vec<&str> = running.iter().map(|t| t.id.as_str()).collect();
391        assert_eq!(ids, vec!["t1"]);
392    }
393
394    #[test]
395    fn status_round_trips_through_str_conversion() {
396        for s in [
397            BackgroundTaskStatus::Running,
398            BackgroundTaskStatus::Done,
399            BackgroundTaskStatus::Error,
400            BackgroundTaskStatus::Stopped,
401        ] {
402            assert_eq!(BackgroundTaskStatus::from_str(s.as_str()), s);
403        }
404    }
405
406    #[test]
407    fn unrecognized_status_string_defaults_to_running() {
408        assert_eq!(BackgroundTaskStatus::from_str("garbage"), BackgroundTaskStatus::Running);
409    }
410
411    /// Survives a fresh `Store::open` against the same file — proves the
412    /// row is actually durable (the whole point of this table existing
413    /// instead of another in-memory cache), not just readable within one
414    /// connection's lifetime.
415    #[test]
416    fn survives_reopening_the_store() {
417        let tmp = tempfile::NamedTempFile::new().unwrap();
418        {
419            let store = Store::open(tmp.path()).unwrap();
420            store.background_task_observe("t1", "block-a", "task dev", 1000, 1000).unwrap();
421        }
422        let reopened = Store::open(tmp.path()).unwrap();
423        let task = reopened.background_task_get("t1").unwrap().unwrap();
424        assert_eq!(task.label, "task dev");
425        assert_eq!(task.status, BackgroundTaskStatus::Running);
426    }
427
428    #[test]
429    fn describe_replaces_the_label_and_fills_the_owner_once() {
430        let store = object_store();
431        store.background_task_observe("t1", "block-a", "Bash", 1000, 1000).unwrap();
432        assert_eq!(store.background_task_get("t1").unwrap().unwrap().owner_tool_use_id, None);
433
434        assert!(store.background_task_describe("t1", "Background wait", Some("toolu_agent")).unwrap());
435        let task = store.background_task_get("t1").unwrap().unwrap();
436        assert_eq!((task.label.as_str(), task.owner_tool_use_id.as_deref()), ("Background wait", Some("toolu_agent")));
437
438        // A later description without an owner, or with a different one,
439        // never clears or moves the owner.
440        store.background_task_describe("t1", "Background wait", None).unwrap();
441        store.background_task_describe("t1", "Background wait", Some("toolu_other")).unwrap();
442        assert_eq!(store.background_task_get("t1").unwrap().unwrap().owner_tool_use_id.as_deref(), Some("toolu_agent"));
443
444        assert!(!store.background_task_describe("missing", "x", None).unwrap());
445    }
446
447    #[test]
448    fn list_fleet_returns_running_rows_and_recently_ended_ones_across_blocks() {
449        let store = object_store();
450        store.background_task_observe("live", "block-a", "live", 100, 100).unwrap();
451        store.background_task_observe("recent", "block-b", "recent", 110, 110).unwrap();
452        store.background_task_observe("old", "block-b", "old", 50, 50).unwrap();
453        store.background_task_complete("recent", BackgroundTaskStatus::Done, 900).unwrap();
454        store.background_task_complete("old", BackgroundTaskStatus::Error, 200).unwrap();
455
456        let ids: Vec<String> = store.background_task_list_fleet(500).unwrap().into_iter().map(|t| t.id).collect();
457        assert_eq!(ids, vec!["live".to_string(), "recent".to_string()]);
458    }
459}