Skip to main content

SubagentWatcher

Struct SubagentWatcher 

Source
pub struct SubagentWatcher { /* private fields */ }

Implementations§

Source§

impl SubagentWatcher

Source

pub fn events_census(&self) -> Held

The events kept for every subagent of every watched session: how many, for how many subagents, and an estimate of their bytes. For the srv memory log line (mem_census).

Source

pub fn list_active(&self) -> Vec<SubAgent>

List all subagents across all sessions (sync — safe to call from RPC dispatch).

Source

pub fn list_dispatches(&self) -> Vec<AgentDispatch>

List all tracked dispatches — both kinds (sync — safe to call from RPC dispatch). Workflow-kind dispatches come from tracked DispatchState; Solo-kind dispatches have no persistent state of their own and are synthesized 1:1 from every loose SubAgent (SPEC §5/§8) — this is what gives every solo Task-tool call a real, backend-issued container it never had before.

Source

pub fn get_history(&self, agent_id: &str, limit: usize) -> Vec<SubagentEvent>

The newest limit events of a subagent (sync — safe to call from RPC dispatch). A running subagent’s come from memory. A finished one’s are read from its transcript, as far as the watcher has read it: one file read when someone opens it, in place of holding every finished subagent’s events for the life of the process.

Source

pub fn get_info(&self, agent_id: &str) -> Option<SubAgent>

Get info for a single subagent (sync — safe to call from RPC dispatch). Targeted counterpart of list_active() — a subagent pane reopened after its subagent:spawned event already fired needs its info once, at mount; scanning + cloning every active subagent across every session for that is wasteful when the caller already knows the id.

Source

pub fn set_display_name(&self, agent_id: &str, display_name: &str) -> bool

Set a subagent’s Haiku-generated display name and broadcast subagent:named so every client watching this session picks up the result, not just the one that triggered the naming call. Returns false if the subagent isn’t tracked (e.g. it aged out between the RPC firing and resolving) — the caller should treat that as a no-op, not an error.

A name already set is kept: the parent’s description can land in a late sidecar while this call runs, and it is the better name. Nothing is broadcast then.

Source

pub fn set_dispatch_name(&self, dispatch_id: &str, name: &str) -> bool

Set a Workflow-kind dispatch’s Haiku-generated name and broadcast dispatch:updated so every client watching this session picks up the result. Mirrors set_display_name one level up — see that method’s doc comment for the “found=false is a safe no-op” convention. Only Workflow-kind dispatches store a dispatch_name here; a Solo dispatch’s name IS its one member’s display_name (solo_dispatch reads it straight through), so set_display_name already covers the Solo case — this method is never called for a solo: dispatch_id.

Source

pub async fn resolve_unnamed_backlog(self: Arc<Self>)

Bounded, rate-limited burst that resolves names for whatever’s currently unnamed in the backfilled/historical backlog (select_unnamed_backlog) — fired only via the ("subagent", "ResolveUnnamedBacklog") RPC, itself only ever called from SwarmViewModel’s constructor (i.e. a human actually opening the Swarm pane), never from the headless per-agent-pane backfill scan — that path stays exactly as live-gated as before (see process_jsonl_change’s doc comment and docs/retro/retro-subagent-backfill-storm-oom-2026-07-17.md).

Deliberately separate from trigger_eager_naming’s live path: runs as background work (limits::Class::Background), so it never queues ahead of a name or title the user is waiting on.

Source§

impl SubagentWatcher

Source

pub fn scan_session_subagents( &self, parent_agent: &str, parent_block_id: &str, config_dir: &Path, session_id: &str, )

Backfill subagents that already existed before this pane (re)opened, scoped to exactly the ONE session being resumed — not this agent identity’s entire history. Called from handle_reactive_register when the block being registered already has a persisted agent:sessionid (i.e. it’s resuming a prior conversation, not starting fresh); a brand-new session has nothing to backfill.

Searches only the top level of config_dir/projects/* for a child directory literally named session_id (the nested-per-session layout observed in practice: projects/<ws>/<session-uuid>/subagents/) — cheap, since an agent identity typically has few distinct project dirs. Older/flat-layout installs where subagents/ sits directly under the project dir with no session-level folder have no way to isolate one session’s subagents from another’s at the filesystem level; in that case this intentionally finds nothing rather than falling back to scanning everything.

Source§

impl SubagentWatcher

Source

pub fn new( event_bus: Arc<EventBus>, mstore: Arc<Store>, id_store: Arc<Store>, identity_store: Arc<Store>, ) -> Self

Source

pub fn set_broker(&self, broker: Arc<Broker>)

Wire in the shared MPS broker post-construction (bootstrap only) – see the broker field’s own doc comment for why this is optional and set separately rather than a constructor parameter.

Source

pub fn spawn( event_bus: Arc<EventBus>, mstore: Arc<Store>, id_store: Arc<Store>, identity_store: Arc<Store>, ) -> Arc<Self> ⓘ

Create a new SubagentWatcher and return it wrapped in Arc. Also starts the background flush loop for coalesced dispatch activity (SPEC §7) — runs for the lifetime of the process, mirroring watch_agent’s existing tokio::spawn pattern.

Source

pub fn watch_agent( self: &Arc<Self>, agent_id: &str, parent_block_id: &str, config_dir: PathBuf, )

Start watching a Claude Code agent’s session directory for subagent files. Spawns a background tokio task for debounced file event processing.

parent_block_id is the pane/block that owns this Claude instance (from the reactive register request). It is stamped onto every emitted subagent event so the frontend can route the ⚡ panel to the originating pane only, instead of every agent pane rendering every subagent globally.

Note: the watcher dedupes by agent_id, so if the same agent_id is registered from two blocks, events carry the first registrant’s block id. That edge case (same instance name in two panes) is rare; the common leak — a terminal Claude’s subagents showing up in unrelated agent panes — is fully fixed because the terminal block id never matches an agent pane.

Source

pub fn recheck_config_dir( self: &Arc<Self>, agent_id: &str, new_config_dir: PathBuf, )

Re-resolve and, if the answer changed, re-point an already-watched agent’s filesystem watch at a corrected directory. watch_agent’s own config-dir resolution only ever runs ONCE per agent, at the reactive-register handshake — before this agent’s identity binding is necessarily committed to the DB yet (a genuinely observed race: a fresh agent launch’s reactive-register can fire before the launch flow’s own account-bind write lands, landing on a stale/ambient cmd:env snapshot instead of the real identity-bound directory). If that race is lost, the watcher previously had no correction mechanism at all — nothing else ever calls watch_agent again for an already-registered pane, so it silently watched the wrong directory, forever, for the rest of that pane’s life. Called from watch_agent itself (a post-insert self-check) and from the identity-bind RPC handlers (server/app_api/identity.rs, server/agent_handlers/identity.rs) via recheck_all_watched_agents below, right after a successful agent_identity_link write.

No-op if agent_id isn’t currently watched (nothing to correct — its next real registration resolves fresh, by-then-committed bindings correctly on its own) or if the newly-resolved directory is unchanged. See docs/reports/REPORT_SWARM_SUBAGENT_WATCHER_ONE_SHOT_RESOLUTION_RACE_2026_09_04.md.

Source

pub fn recheck_all_watched_agents(self: &Arc<Self>)

Re-check every currently-watched agent’s Claude config dir against a fresh identity resolution, re-pointing (recheck_config_dir) any whose resolution changed. Cheap and safe to call from anywhere an identity/account binding just changed — the number of currently- watched agents on a single instance is small, and this only runs on the rare bind/rebind path, never per-turn.

Source

pub fn unwatch_agent(&self, agent_id: &str, block_id: Option<&str>)

Stop watching an agent from the graceful /agentmux/reactive/unregister path: remove block_id as a dependent of its watcher (same mechanism as unwatch_block, keyed by agent_id first since that’s what the caller has), tearing down the underlying filesystem watcher — which closes the debounce channel, so the processing task self-terminates on its next rx.recv() returning None — only once no block depends on it anymore. Idempotent: a no-op if the agent isn’t currently watched.

block_id is None when the reactive registry has no record of this agent_id (already unregistered, or never registered) — nothing to disassociate in that case, so the watcher-teardown step is skipped entirely rather than guessing.

watch_agent dedupes by agent_id: two blocks registering the same agent_id share one WatchedAgent entry. Removing that whole entry unconditionally here (as this method used to) killed the shared watcher — and with it, live tracking — for every OTHER still-open block sharing that agent identity the moment any ONE of them gracefully closed, since this is the primary, far-more-common teardown path (unwatch_block only covers the crash/API-delete backstop). See WatchedAgent::parent_block_ids’s doc comment and docs/retro/retro-subagent-watcher-shared-dir-fanout-and-leak-2026-07-23.md.

Without this, watched_agents was push-only: every distinct agent that ever ran leaked one OS watch handle + channel + idle task for the rest of the process lifetime, even after its pane/agent was deleted.

Also prunes sessions, dispatches, and pending_activity: every entry whose owner is this agent (SubAgent/AgentDispatch’s parent_agent, PendingDispatchActivity.parent_agent), and any session left with no subagents afterward. The parent agent is gone, so nothing can query this data again — it was previously left as plain data forever, growing these maps by one entry set per distinct agent that ever ran a subagent. (dispatches/pending_activity pruning added alongside prune_block’s block-scoped equivalent, below — this method previously only pruned sessions, silently leaking a Workflow-kind DispatchState for the agent’s lifetime.)

Source

pub fn prune_block(&self, block_id: &str) -> bool

Prune every subagent, dispatch, and buffered activity entry owned by block_id — the block-scoped counterpart of unwatch_agent’s agent-scoped pruning, above. This is the robust backstop: it runs from a srv_events_tx subscriber reacting to Event::BlockDeleted/ TabDeleted/WorkspaceDeleted (see spawn_block_prune_subscriber below), independent of whether the frontend’s normal /agentmux/reactive/unregister teardown path (which drives unwatch_agent) actually fires for this close — that path depends on a live renderer’s TermWrap.dispose() completing an async fetch, which an API-driven delete, a tab/workspace cascade delete, or a crash can all skip. Without this, closing an agent pane left its Swarm-pane row (and any subagents/dispatches under it) visible until the whole app/srv restarted — ListActive/ListDispatches kept returning them forever, and the frontend’s buildTree() has a parentIds fallback (swarm-model.ts) that renders a row for any block_id it still sees in the subagent list, with no complementary removal path of its own.

Block-scoped (not agent-name-scoped like unwatch_agent) so this also correctly handles an agent identity reused across multiple blocks over time — pruning by parent_block_id can never touch a different, still-live block that happens to share an agent name.

Also tears down this block’s own filesystem watcher (unwatch_block, below) — without this, prune_block only cleared the DERIVED subagent/dispatch state at the moment it ran, while the underlying notify watcher (and its dedicated tokio task, keyed by parent_block_id) kept running indefinitely, silently re-creating fresh entries for this closed block the next time any OTHER agent sharing its watched directory wrote to its own subagent transcript — see session_belongs_to_block’s doc comment and docs/retro/retro-subagent-watcher-shared-dir-fanout-and-leak-2026-07-23.md.

Returns whether any DERIVED state was actually pruned, so the caller only broadcasts a refresh when there’s something for clients to refresh — independent of whether a watcher also got torn down.

Source

pub fn prune_block_and_notify(&self, block_id: &str)

Prune block_id and broadcast subagent:block_pruned if anything was actually removed — the combined operation spawn_block_prune_ subscriber calls per cascaded block_id.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync> ⓘ

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more