Skip to main content

agentmux_srv_core/backend/subagent_watcher/
query.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Query/naming API: `list_active`/`list_dispatches`/`solo_dispatch`/
5//! `get_history`/`get_info`/`set_display_name`/`set_dispatch_name`/
6//! `trigger_eager_naming` — the read-mostly surface RPC dispatch calls into,
7//! plus the eager Haiku-naming trigger fired from `jsonl::process_jsonl_change`.
8
9use super::types::*;
10use super::SubagentWatcher;
11
12impl SubagentWatcher {
13    /// The events kept for every subagent of every watched session: how many, for how many
14    /// subagents, and an estimate of their bytes. For the `srv memory` log line (`mem_census`).
15    pub fn events_census(&self) -> crate::backend::mem_census::Held {
16        use crate::backend::mem_census::{subagent_event_bytes, Held};
17        let sessions = self.sessions.lock().unwrap();
18        let mut held = Held { name: "subagent events".to_string(), ..Held::default() };
19        for state in sessions.values().flat_map(|session| session.subagents.values()) {
20            let content: usize = state.events.iter().map(subagent_event_bytes).sum();
21            held.groups += 1;
22            held.count += state.events.len() as u64;
23            held.bytes += (state.events.capacity() * std::mem::size_of::<SubagentEvent>() + content) as u64;
24        }
25        held
26    }
27
28    /// List all subagents across all sessions (sync — safe to call from RPC dispatch).
29    pub fn list_active(&self) -> Vec<SubAgent> {
30        let sessions = self.sessions.lock().unwrap();
31        let mut result = Vec::new();
32        for session in sessions.values() {
33            for state in session.subagents.values() {
34                result.push(state.info.clone());
35            }
36        }
37        result.sort_by(|a, b| b.last_event_at.cmp(&a.last_event_at));
38        result
39    }
40
41    /// List all tracked dispatches — both kinds (sync — safe to call from
42    /// RPC dispatch). Workflow-kind dispatches come from tracked
43    /// `DispatchState`; Solo-kind dispatches have no persistent state of
44    /// their own and are synthesized 1:1 from every loose `SubAgent` (SPEC
45    /// §5/§8) — this is what gives every solo Task-tool call a real,
46    /// backend-issued container it never had before.
47    pub fn list_dispatches(&self) -> Vec<AgentDispatch> {
48        let mut result: Vec<AgentDispatch> = {
49            let mut dispatches = self.dispatches.lock().unwrap();
50            dispatches
51                .values_mut()
52                .map(|state| {
53                    Self::refresh_dispatch_status(state);
54                    state.info.clone()
55                })
56                .collect()
57        };
58        let sessions = self.sessions.lock().unwrap();
59        for session in sessions.values() {
60            for state in session.subagents.values() {
61                if let Some(solo) = Self::solo_dispatch(&state.info) {
62                    result.push(solo);
63                }
64            }
65        }
66        result.sort_by(|a, b| b.last_event_at.cmp(&a.last_event_at));
67        result
68    }
69
70    /// Synthesize the `AgentDispatch` for a loose (non-workflow) `SubAgent`.
71    /// `None` for a workflow member — those are represented by their
72    /// tracked `DispatchState` instead, not synthesized per-call.
73    pub(super) fn solo_dispatch(sub: &SubAgent) -> Option<AgentDispatch> {
74        if !sub.dispatch_id.starts_with("solo:") {
75            return None;
76        }
77        // A solo dispatch's status mirrors its one member's directly — the
78        // member IS the dispatch, no separate aggregation to compute. Kept
79        // as three distinct arms (not `done as usize` collapsing Completed/
80        // Abandoned together) so a dead dispatch reads as Abandoned, not
81        // ambiguously "Completed," in the UI. See
82        // docs/specs/SPEC_SWARM_DISPATCH_ATTRIBUTION_AND_LIFECYCLE_2026_08_19.md §3.2.
83        let (status, done) = match sub.status {
84            SubAgentStatus::Completed => (DispatchStatus::Completed, true),
85            SubAgentStatus::Abandoned => (DispatchStatus::Abandoned, true),
86            SubAgentStatus::Active => (DispatchStatus::Running, false),
87        };
88        Some(AgentDispatch {
89            dispatch_id: sub.dispatch_id.clone(),
90            kind: DispatchKind::Solo,
91            parent_agent: sub.parent_agent.clone(),
92            parent_block_id: sub.parent_block_id.clone(),
93            session_id: sub.session_id.clone(),
94            member_count: 1,
95            members_done: done as usize,
96            status,
97            last_event_at: sub.last_event_at,
98            // A solo dispatch's name IS its one member's display_name — no
99            // separate dispatch_name storage needed for the Solo kind (only
100            // Workflow-kind DispatchState carries its own dispatch_name).
101            dispatch_name: sub.display_name.clone(),
102        })
103    }
104
105    /// The newest `limit` events of a subagent (sync — safe to call from RPC dispatch). A running
106    /// subagent's come from memory. A finished one's are read from its transcript, as far as the
107    /// watcher has read it: one file read when someone opens it, in place of holding every finished
108    /// subagent's events for the life of the process.
109    pub fn get_history(&self, agent_id: &str, limit: usize) -> Vec<SubagentEvent> {
110        let (path, read_to) = {
111            let sessions = self.sessions.lock().unwrap();
112            let Some(state) = sessions.values().find_map(|session| session.subagents.get(agent_id)) else {
113                return Vec::new();
114            };
115            if state.events_in_memory() {
116                let start = state.events.len().saturating_sub(limit);
117                return state.events[start..].to_vec();
118            }
119            (std::path::PathBuf::from(&state.info.jsonl_path), state.file_offset)
120        };
121        // The file is read with the lock released.
122        match super::parse::read_events_before(&path, read_to, limit.min(MAX_SUBAGENT_EVENTS)) {
123            Ok(events) => events,
124            Err(e) => {
125                tracing::debug!(agent_id = %agent_id, error = %e, "failed to read a finished subagent's events back from its transcript");
126                Vec::new()
127            }
128        }
129    }
130
131    /// Get info for a single subagent (sync — safe to call from RPC dispatch).
132    /// Targeted counterpart of `list_active()` — a subagent pane reopened
133    /// after its `subagent:spawned` event already fired needs its info once,
134    /// at mount; scanning + cloning every active subagent across every
135    /// session for that is wasteful when the caller already knows the id.
136    pub fn get_info(&self, agent_id: &str) -> Option<SubAgent> {
137        let sessions = self.sessions.lock().unwrap();
138        for session in sessions.values() {
139            if let Some(state) = session.subagents.get(agent_id) {
140                return Some(state.info.clone());
141            }
142        }
143        None
144    }
145
146    /// Set a subagent's Haiku-generated display name and broadcast
147    /// `subagent:named` so every client watching this session picks up the
148    /// result, not just the one that triggered the naming call. Returns
149    /// `false` if the subagent isn't tracked (e.g. it aged out between the
150    /// RPC firing and resolving) — the caller should treat that as a no-op,
151    /// not an error.
152    ///
153    /// A name already set is kept: the parent's description can land in a late
154    /// sidecar while this call runs, and it is the better name. Nothing is
155    /// broadcast then.
156    pub fn set_display_name(&self, agent_id: &str, display_name: &str) -> bool {
157        // Captured alongside the mutation itself (not re-looked-up after
158        // unlocking) — this is the exact moment a NAME-based grouping key is
159        // born, so the fields that decide which group it lands in
160        // (dispatch_id, parent_block_id) need to be logged from the same
161        // locked read that set it, not a racy re-fetch.
162        let mut found_context: Option<(String, String, String)> = None;
163        let found = {
164            let mut sessions = self.sessions.lock().unwrap();
165            let mut found = false;
166            for session in sessions.values_mut() {
167                if let Some(state) = session.subagents.get_mut(agent_id) {
168                    found = true;
169                    if state.info.display_name.is_some() {
170                        break;
171                    }
172                    state.info.display_name = Some(display_name.to_string());
173                    found_context = Some((
174                        state.info.parent_block_id.clone(),
175                        state.info.session_id.clone(),
176                        state.info.dispatch_id.clone(),
177                    ));
178                    break;
179                }
180            }
181            found
182        };
183        // Mutex released here — broadcast outside the lock
184
185        if let Some((parent_block_id, session_id, dispatch_id)) = &found_context {
186            tracing::info!(
187                agent_id = %agent_id,
188                display_name = %display_name,
189                parent_block_id = %parent_block_id,
190                session_id = %session_id,
191                dispatch_id = %dispatch_id,
192                "subagent display_name resolved"
193            );
194        }
195
196        if found_context.is_some() {
197            self.broadcast_subagent_named(agent_id, display_name);
198        }
199        found
200    }
201
202    /// Set a Workflow-kind dispatch's Haiku-generated name and broadcast
203    /// `dispatch:updated` so every client watching this session picks up the
204    /// result. Mirrors `set_display_name` one level up — see that method's
205    /// doc comment for the "found=false is a safe no-op" convention. Only
206    /// Workflow-kind dispatches store a `dispatch_name` here; a Solo
207    /// dispatch's name IS its one member's `display_name` (`solo_dispatch`
208    /// reads it straight through), so `set_display_name` already covers the
209    /// Solo case — this method is never called for a `solo:` dispatch_id.
210    pub fn set_dispatch_name(&self, dispatch_id: &str, name: &str) -> bool {
211        let info = {
212            let mut dispatches = self.dispatches.lock().unwrap();
213            match dispatches.get_mut(dispatch_id) {
214                Some(state) => {
215                    state.info.dispatch_name = Some(name.to_string());
216                    Some(state.info.clone())
217                }
218                None => None,
219            }
220        };
221        // Mutex released here — broadcast outside the lock
222
223        let Some(info) = info else { return false };
224        tracing::info!(
225            dispatch_id = %dispatch_id,
226            dispatch_name = %name,
227            parent_block_id = %info.parent_block_id,
228            session_id = %info.session_id,
229            "dispatch display_name resolved"
230        );
231        self.broadcast_dispatch_updated(&info);
232        true
233    }
234
235    /// Test-only accessor for `naming_triggered` — lets tests assert the
236    /// dedup gate claimed (or didn't claim) a given dispatch_id without
237    /// needing a real `Arc<Self>`/spawned task (see `trigger_eager_naming`'s
238    /// doc comment below for why `naming_triggered_contains` alone, not the
239    /// full eager-naming flow, is what unit tests can exercise).
240    #[cfg(test)]
241    pub(crate) fn naming_triggered_contains(&self, dispatch_id: &str) -> bool {
242        self.naming_triggered.lock().unwrap().contains(dispatch_id)
243    }
244
245    /// How long a solo subagent's eager name waits for a late `.meta.json`, whose
246    /// description makes the model call unnecessary.
247    pub(super) const SIDECAR_GRACE: std::time::Duration = std::time::Duration::from_secs(3);
248
249    /// Fire the one eager Haiku-naming call for a dispatch's first-observed
250    /// live spawn (issue: SPEC_SWARM_DISPATCH_NAMING_AND_ROW_MODEL_2026_07_19).
251    /// Caller (`process_jsonl_change`) has already atomically claimed
252    /// `dispatch_id` in `naming_triggered` before calling this — this method
253    /// itself does no further dedup.
254    ///
255    /// Upgrades `self_ref` to a real `Arc<Self>` to move into the spawned
256    /// task; silently no-ops if this watcher was built via bare `new()`
257    /// (most unit tests) rather than `spawn()` — there is no Arc to upgrade
258    /// to in that case, matching this module's "untracked -> safe no-op"
259    /// convention rather than panicking.
260    pub(super) fn trigger_eager_naming(&self, dispatch_id: String, first_member_agent_id: String, is_workflow: bool) {
261        let Some(watcher) = self.self_ref.lock().unwrap().as_ref().and_then(|w| w.upgrade()) else {
262            return;
263        };
264        tokio::spawn(async move {
265            if is_workflow {
266                crate::ambient::tasks::generate_dispatch_name(
267                    &watcher.mstore,
268                    &watcher,
269                    &dispatch_id,
270                    &first_member_agent_id,
271                    crate::ambient::limits::Class::Interactive,
272                ).await;
273            } else {
274                // The transcript is often seen before its sidecar, whose
275                // description names the subagent for free; give it time to land.
276                tokio::time::sleep(Self::SIDECAR_GRACE).await;
277                crate::ambient::tasks::generate_subagent_name(
278                    &watcher.mstore,
279                    &watcher,
280                    &first_member_agent_id,
281                    crate::ambient::limits::Class::Interactive,
282                ).await;
283            }
284        });
285    }
286
287    /// Select up to `limit` currently-unnamed subagents/dispatches for the
288    /// bounded backfill-naming pass (`resolve_unnamed_backlog`), most
289    /// recently-active first, and atomically claim each selected item in
290    /// `naming_triggered` before returning it — reusing the exact dedup
291    /// structure the live eager-naming path already uses
292    /// (`jsonl::process_jsonl_change`), so this can never double-name
293    /// something, race with a live spawn of the same dispatch, or need a
294    /// second `HashSet`. Because the claim is permanent, calling this again
295    /// (a second Swarm-pane-open before an earlier batch finishes, or after
296    /// it drains) never re-selects anything already claimed — this is what
297    /// makes `resolve_unnamed_backlog` safe to fire on every pane open with
298    /// no extra debounce.
299    ///
300    /// Deliberately never holds `sessions`/`dispatches` and `naming_triggered`
301    /// locked at the same time — mirrors `process_jsonl_change`'s own
302    /// convention (see its "Mutex released here" comment).
303    pub(super) fn select_unnamed_backlog(&self, limit: usize) -> Vec<BacklogNamingItem> {
304        let mut candidates: Vec<(u64, BacklogNamingItem)> = {
305            let sessions = self.sessions.lock().unwrap();
306            sessions
307                .values()
308                .flat_map(|s| s.subagents.values())
309                .filter(|state| {
310                    state.info.display_name.is_none() && state.info.dispatch_id.starts_with("solo:")
311                })
312                .map(|state| {
313                    (
314                        state.info.last_event_at,
315                        BacklogNamingItem::Solo { agent_id: state.info.agent_id.clone() },
316                    )
317                })
318                .collect()
319        };
320
321        let unnamed_workflows: Vec<(String, u64)> = {
322            let dispatches = self.dispatches.lock().unwrap();
323            dispatches
324                .values()
325                .map(|state| &state.info)
326                .filter(|info| info.kind == DispatchKind::Workflow && info.dispatch_name.is_none())
327                .map(|info| (info.dispatch_id.clone(), info.last_event_at))
328                .collect()
329        };
330
331        if !unnamed_workflows.is_empty() {
332            let sessions = self.sessions.lock().unwrap();
333            for (dispatch_id, last_event_at) in unnamed_workflows {
334                let representative = sessions
335                    .values()
336                    .flat_map(|s| s.subagents.values())
337                    .find(|state| state.info.dispatch_id == dispatch_id)
338                    .map(|state| state.info.agent_id.clone());
339                if let Some(representative_agent_id) = representative {
340                    candidates.push((
341                        last_event_at,
342                        BacklogNamingItem::Workflow { dispatch_id, representative_agent_id },
343                    ));
344                }
345            }
346        }
347
348        candidates.sort_by(|a, b| b.0.cmp(&a.0));
349
350        let mut naming_triggered = self.naming_triggered.lock().unwrap();
351        let mut selected = Vec::with_capacity(limit.min(candidates.len()));
352        for (_, item) in candidates {
353            if selected.len() >= limit {
354                break;
355            }
356            if naming_triggered.insert(item.dispatch_id()) {
357                selected.push(item);
358            }
359        }
360        selected
361    }
362
363    /// Bounded, rate-limited burst that resolves names for whatever's
364    /// currently unnamed in the backfilled/historical backlog
365    /// (`select_unnamed_backlog`) — fired only via the
366    /// `("subagent", "ResolveUnnamedBacklog")` RPC, itself only ever called
367    /// from `SwarmViewModel`'s constructor (i.e. a human actually opening
368    /// the Swarm pane), never from the headless per-agent-pane backfill
369    /// scan — that path stays exactly as `live`-gated as before (see
370    /// `process_jsonl_change`'s doc comment and
371    /// docs/retro/retro-subagent-backfill-storm-oom-2026-07-17.md).
372    ///
373    /// Deliberately separate from `trigger_eager_naming`'s live path: runs as
374    /// background work (`limits::Class::Background`), so it never queues ahead
375    /// of a name or title the user is waiting on.
376    pub async fn resolve_unnamed_backlog(self: std::sync::Arc<Self>) {
377        let items = self.select_unnamed_backlog(BACKLOG_NAMING_BATCH_LIMIT);
378        for item in items {
379            let watcher = std::sync::Arc::clone(&self);
380            tokio::spawn(async move {
381                match item {
382                    BacklogNamingItem::Solo { agent_id } => {
383                        crate::ambient::tasks::generate_subagent_name(
384                            &watcher.mstore,
385                            &watcher,
386                            &agent_id,
387                            crate::ambient::limits::Class::Background,
388                        )
389                        .await;
390                    }
391                    BacklogNamingItem::Workflow { dispatch_id, representative_agent_id } => {
392                        crate::ambient::tasks::generate_dispatch_name(
393                            &watcher.mstore,
394                            &watcher,
395                            &dispatch_id,
396                            &representative_agent_id,
397                            crate::ambient::limits::Class::Background,
398                        )
399                        .await;
400                    }
401                }
402            });
403        }
404    }
405}