Skip to main content

agentmux_srv_core/backend/
dock_snapshot.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! In-memory, latest-per-block cache of Activity Dock `ToolNode` status
5//! deltas, pushed from the frontend as they happen. Backs `muxspect dock`
6//! (read) and `muxspect dock clear` (write).
7//!
8//! See `docs/specs/SPEC_MUXSPECT_DOCK_DIAGNOSIS_AND_REMEDIATION_2026_08_06.md`
9//! §3.1. Never persisted — this mirrors the dock's own nature: if no
10//! renderer is currently attached to a block, there is nothing live to
11//! report, and losing this cache on restart is correct, not a bug.
12
13use std::collections::HashMap;
14
15use parking_lot::Mutex;
16use serde::Serialize;
17
18/// One `ToolNode`'s last-known status, as reported by the renderer that
19/// owns it. `observed_at` is stamped on receipt by the server (not trusted
20/// from the client) so `muxspect dock`'s age computation is consistent
21/// even if the renderer's clock is skewed.
22#[derive(Debug, Clone, Serialize)]
23pub struct DockNodeSnapshot {
24    pub node_id: String,
25    pub tool_name: String,
26    pub status: String,
27    /// `ToolNode.timestamp` (ms) — when the tool call was initiated,
28    /// per the renderer. `None` if the pushing client didn't have one.
29    pub timestamp: Option<i64>,
30    /// Server-side receipt time (ms) — used for age, not `timestamp`,
31    /// so a slow/backed-up push doesn't understate how stale the
32    /// snapshot itself is.
33    pub observed_at: i64,
34    /// Whether `params.run_in_background` was `true` on this call (Bash
35    /// only; `None` for every other tool). `status` above is the RAW
36    /// `ToolNode` status, which for an accepted background launch is
37    /// terminal ("success") within ~a second — it does NOT reflect
38    /// whether the dock is still showing this row as `running` while it
39    /// awaits a `<task-notification>` (that reclassification happens
40    /// entirely client-side in `tool-adapter.ts`'s `toolActivities`,
41    /// which the server has no visibility into). This flag exists so a
42    /// human reading `muxspect dock` output isn't misled by `status:
43    /// success` into assuming the dock row is finished too — see issue
44    /// #2518, where exactly that gap let 11 of 17 backgrounded calls in
45    /// one session get stuck `running` in the actual UI while this raw
46    /// snapshot showed them as long-since `success`.
47    pub run_in_background: Option<bool>,
48}
49
50/// One block's tracked nodes, keyed by node id so a later delta for the
51/// same node overwrites rather than accumulates.
52type BlockNodes = HashMap<String, DockNodeSnapshot>;
53
54/// How long a node is kept without a fresh push, whatever its status. A node's resolution is pushed
55/// back by the renderer (`agent-document-store.ts`'s `pushResolvedDockNodes`, on every known
56/// resolution path); this is the bound for a path that is not one of those, and for a node nobody
57/// asks about again. One hour comfortably exceeds any legitimate single tool-call duration.
58const MAX_NODE_AGE_MS: i64 = 60 * 60 * 1000;
59
60/// The whole cache is swept for old nodes at most this often, when a node is pushed. A read
61/// (`get`) only ever cleaned the block it was asked about, and almost no block is ever asked about:
62/// without the sweep every tool call of every agent stayed for the life of the process.
63const SWEEP_EVERY_MS: i64 = 5 * 60 * 1000;
64
65#[derive(Default)]
66struct Inner {
67    blocks: HashMap<String, BlockNodes>,
68    /// When the cache was last swept, by the pushed nodes' own stamps.
69    swept_at: i64,
70}
71
72impl Inner {
73    /// Drop every node older than `MAX_NODE_AGE_MS` as of `now_ms`, and every block left with none.
74    fn sweep(&mut self, now_ms: i64) {
75        self.blocks.retain(|_, nodes| {
76            nodes.retain(|_, n| now_ms.saturating_sub(n.observed_at) < MAX_NODE_AGE_MS);
77            !nodes.is_empty()
78        });
79        self.swept_at = now_ms;
80    }
81}
82
83#[derive(Default)]
84pub struct DockSnapshotCache {
85    inner: Mutex<Inner>,
86}
87
88impl DockSnapshotCache {
89    pub fn new() -> Self {
90        Self::default()
91    }
92
93    /// How many nodes are kept, for how many blocks, and an estimate of their bytes. For the
94    /// `srv memory` log line (`mem_census`).
95    pub fn census(&self) -> crate::backend::mem_census::Held {
96        let guard = self.inner.lock();
97        let mut held = crate::backend::mem_census::Held {
98            name: "tool status cache".to_string(),
99            groups: guard.blocks.len() as u64,
100            ..Default::default()
101        };
102        for nodes in guard.blocks.values() {
103            held.count += nodes.len() as u64;
104            // The node id is held twice: in the node and as its key.
105            held.bytes += nodes
106                .values()
107                .map(|n| std::mem::size_of::<DockNodeSnapshot>() + 2 * n.node_id.capacity() + n.tool_name.capacity() + n.status.capacity())
108                .sum::<usize>() as u64;
109        }
110        held
111    }
112
113    /// Record (or overwrite) one node's latest status for `block_id`. Every `SWEEP_EVERY_MS` a push
114    /// also drops what has aged out anywhere in the cache, judged by this node's stamp: the cache
115    /// then holds at most the last hour's nodes, and a walk of it every five minutes is the cost.
116    pub fn push_delta(&self, block_id: &str, node: DockNodeSnapshot) {
117        let mut guard = self.inner.lock();
118        let now_ms = node.observed_at;
119        if now_ms.saturating_sub(guard.swept_at) >= SWEEP_EVERY_MS {
120            guard.sweep(now_ms);
121        }
122        guard.blocks.entry(block_id.to_string()).or_default().insert(node.node_id.clone(), node);
123    }
124
125    /// All tracked nodes for `block_id` younger than `MAX_NODE_AGE_MS` as
126    /// of `now_ms`, or empty if none/unknown block. Evicts anything older
127    /// in that block as a side effect, and the block with its last node.
128    pub fn get(&self, block_id: &str, now_ms: i64) -> Vec<DockNodeSnapshot> {
129        let mut guard = self.inner.lock();
130        let Some(nodes) = guard.blocks.get_mut(block_id) else { return Vec::new() };
131        nodes.retain(|_, n| now_ms.saturating_sub(n.observed_at) < MAX_NODE_AGE_MS);
132        let found: Vec<DockNodeSnapshot> = nodes.values().cloned().collect();
133        if found.is_empty() {
134            guard.blocks.remove(block_id);
135        }
136        found
137    }
138
139    /// Whether `node_id` is currently tracked for `block_id` — used to
140    /// validate a `dock clear` request before publishing the clear event,
141    /// so muxspect can distinguish "cleared" from "no such node."
142    pub fn has_node(&self, block_id: &str, node_id: &str) -> bool {
143        let guard = self.inner.lock();
144        guard.blocks.get(block_id).is_some_and(|m| m.contains_key(node_id))
145    }
146
147    /// Drop a node from the cache — called once a `dock clear` has been
148    /// published, so a subsequent `dock` read doesn't keep showing a node
149    /// that was just cleared (the clearing renderer flips it to
150    /// `"canceled"` locally, but this cache has no way to observe that
151    /// without another push; removing it here is simpler and correct
152    /// either way — a canceled node isn't "stuck" and doesn't need to
153    /// keep appearing in diagnosis output).
154    pub fn remove_node(&self, block_id: &str, node_id: &str) {
155        let mut guard = self.inner.lock();
156        if let Some(nodes) = guard.blocks.get_mut(block_id) {
157            nodes.remove(node_id);
158            if nodes.is_empty() {
159                guard.blocks.remove(block_id);
160            }
161        }
162    }
163
164    /// Drop every tracked node for `block_id`: its pane is gone (`sagas::close_pane::finish_close`).
165    /// A status pushed for it afterwards (a renderer still settling) ages out with the sweep.
166    pub fn evict_block(&self, block_id: &str) {
167        self.inner.lock().blocks.remove(block_id);
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    fn node(id: &str, status: &str) -> DockNodeSnapshot {
176        DockNodeSnapshot {
177            node_id: id.to_string(),
178            tool_name: "Bash".to_string(),
179            status: status.to_string(),
180            timestamp: Some(1000),
181            observed_at: 2000,
182            run_in_background: None,
183        }
184    }
185
186    #[test]
187    fn the_census_counts_every_node_of_every_block() {
188        let cache = DockSnapshotCache::new();
189        assert_eq!(cache.census().count, 0);
190        cache.push_delta("block-a", node("n1", "running"));
191        cache.push_delta("block-a", node("n2", "done"));
192        cache.push_delta("block-b", node("n1", "done"));
193        // The same node again replaces it.
194        cache.push_delta("block-b", node("n1", "error"));
195        let held = cache.census();
196        assert_eq!((held.groups, held.count), (2, 3));
197        assert!(held.bytes >= 3 * std::mem::size_of::<DockNodeSnapshot>() as u64, "{held:?}");
198    }
199
200    #[test]
201    fn get_on_unknown_block_is_empty() {
202        let cache = DockSnapshotCache::new();
203        assert!(cache.get("no-such-block", 2000).is_empty());
204    }
205
206    #[test]
207    fn push_then_get_round_trips() {
208        let cache = DockSnapshotCache::new();
209        cache.push_delta("block-1", node("n1", "running"));
210        let got = cache.get("block-1", 2000);
211        assert_eq!(got.len(), 1);
212        assert_eq!(got[0].node_id, "n1");
213        assert_eq!(got[0].status, "running");
214    }
215
216    #[test]
217    fn run_in_background_round_trips() {
218        let cache = DockSnapshotCache::new();
219        let mut n = node("n1", "success");
220        n.run_in_background = Some(true);
221        cache.push_delta("block-1", n);
222        assert_eq!(cache.get("block-1", 2000)[0].run_in_background, Some(true));
223    }
224
225    #[test]
226    fn later_delta_for_same_node_overwrites() {
227        let cache = DockSnapshotCache::new();
228        cache.push_delta("block-1", node("n1", "running"));
229        cache.push_delta("block-1", node("n1", "success"));
230        let got = cache.get("block-1", 2000);
231        assert_eq!(got.len(), 1);
232        assert_eq!(got[0].status, "success");
233    }
234
235    #[test]
236    fn different_nodes_coexist() {
237        let cache = DockSnapshotCache::new();
238        cache.push_delta("block-1", node("n1", "running"));
239        cache.push_delta("block-1", node("n2", "success"));
240        assert_eq!(cache.get("block-1", 2000).len(), 2);
241    }
242
243    #[test]
244    fn get_evicts_entries_older_than_max_age() {
245        let cache = DockSnapshotCache::new();
246        cache.push_delta("block-1", node("n1", "running")); // observed_at: 2000
247        // Just under the 1h cap — still present.
248        assert_eq!(cache.get("block-1", 2000 + MAX_NODE_AGE_MS - 1).len(), 1);
249        // At/past the cap — evicted, regardless of status.
250        assert!(cache.get("block-1", 2000 + MAX_NODE_AGE_MS).is_empty());
251    }
252
253    #[test]
254    fn get_eviction_is_per_node_not_whole_block() {
255        let cache = DockSnapshotCache::new();
256        cache.push_delta("block-1", node("old", "running")); // observed_at: 2000
257        let mut fresh = node("fresh", "running");
258        fresh.observed_at = 2000 + MAX_NODE_AGE_MS - 1;
259        cache.push_delta("block-1", fresh);
260        let got = cache.get("block-1", 2000 + MAX_NODE_AGE_MS);
261        assert_eq!(got.len(), 1);
262        assert_eq!(got[0].node_id, "fresh");
263    }
264
265    #[test]
266    fn a_push_sweeps_what_aged_out_in_every_block_but_not_more_often_than_every_five_minutes() {
267        let cache = DockSnapshotCache::new();
268        let at = |id: &str, observed_at: i64| DockNodeSnapshot { observed_at, ..node(id, "done") };
269        // The first push sweeps an empty cache, and the sweeps are counted from it.
270        let start = 10 * MAX_NODE_AGE_MS;
271        cache.push_delta("never-read", at("old", start));
272        cache.push_delta("busy", at("old", start + 1));
273        // Under five minutes later nothing is swept, however old a node is by then: none is yet.
274        cache.push_delta("busy", at("mid", start + SWEEP_EVERY_MS - 1));
275        assert_eq!((cache.census().groups, cache.census().count), (2, 3));
276        // An hour on, a push to one block drops the old nodes of both, and the block left empty.
277        cache.push_delta("busy", at("new", start + MAX_NODE_AGE_MS + 1));
278        let held = cache.census();
279        assert_eq!((held.groups, held.count), (1, 2), "{held:?}");
280        let mut left: Vec<String> = cache.get("busy", start + MAX_NODE_AGE_MS + 1).into_iter().map(|n| n.node_id).collect();
281        left.sort();
282        assert_eq!(left, ["mid", "new"]);
283        assert!(!cache.has_node("never-read", "old"));
284    }
285
286    #[test]
287    fn a_block_goes_with_its_last_node() {
288        let cache = DockSnapshotCache::new();
289        cache.push_delta("read-late", node("n1", "running")); // observed_at: 2000
290        cache.push_delta("cleared", node("n1", "running"));
291        assert!(cache.get("read-late", 2000 + MAX_NODE_AGE_MS).is_empty());
292        cache.remove_node("cleared", "n1");
293        assert_eq!(cache.census().groups, 0, "no empty block is left behind");
294    }
295
296    #[test]
297    fn has_node_reflects_current_state() {
298        let cache = DockSnapshotCache::new();
299        assert!(!cache.has_node("block-1", "n1"));
300        cache.push_delta("block-1", node("n1", "running"));
301        assert!(cache.has_node("block-1", "n1"));
302        assert!(!cache.has_node("block-1", "n2"));
303        assert!(!cache.has_node("block-2", "n1"));
304    }
305
306    #[test]
307    fn remove_node_drops_only_that_node() {
308        let cache = DockSnapshotCache::new();
309        cache.push_delta("block-1", node("n1", "running"));
310        cache.push_delta("block-1", node("n2", "running"));
311        cache.remove_node("block-1", "n1");
312        assert!(!cache.has_node("block-1", "n1"));
313        assert!(cache.has_node("block-1", "n2"));
314    }
315
316    #[test]
317    fn remove_node_on_unknown_block_is_a_no_op() {
318        let cache = DockSnapshotCache::new();
319        cache.remove_node("no-such-block", "n1"); // must not panic
320    }
321
322    #[test]
323    fn evict_block_drops_everything_for_that_block_only() {
324        let cache = DockSnapshotCache::new();
325        cache.push_delta("block-1", node("n1", "running"));
326        cache.push_delta("block-2", node("n1", "running"));
327        cache.evict_block("block-1");
328        assert!(cache.get("block-1", 2000).is_empty());
329        assert_eq!(cache.get("block-2", 2000).len(), 1);
330    }
331}