Skip to main content

agentmux_srv_core/backend/reactive/
activity_watcher.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Empty-title recovery: a running agent with conversation and no usable
5//! session title gets one, written straight to its block's
6//! `term:ambient_summary`, which the pane header and the Swarm row read.
7//!
8//! The title is otherwise computed only when a human submits a message
9//! (`useAgentActivitySummary.ts`). An agent driven by jekts or tool work, one
10//! reattached mid-turn, or one whose title call failed or abstained could sit on
11//! an empty title for as long as it ran. This sweep is the second route.
12//!
13//! It replaces what this module used to do: a "what is being worked on" summary
14//! every 20 s for every running agent, published as an `agent:summary` event that
15//! nothing subscribed to, so every call was spent and its output went nowhere.
16//! Now an agent that already has a title costs nothing here.
17//! docs/specs/SPEC_AMBIENT_SWARM_SUMMARY_HARDENING_2026_10_02.md sections 2.1
18//! (defects 2 and 5), 5.6 and 5.7.
19//!
20//! Each call goes through `crate::ambient::tasks::generate_recovered_title`, so
21//! the Ambient Model Call gateway admits, cancels and accounts for it under its
22//! own purpose tag, distinct from the pane's own title request.
23//!
24//! Cost controls:
25//!   - only agents whose controller is running (`STATUS_RUNNING`) and that have no usable title;
26//!   - no agent on a model server of its own or on a model route ([`crate::ambient::cli::recovery_skips`]);
27//!   - only agents whose `output` is in a shape the digest can read
28//!     (`digest::reads_output_format`); another provider's file holds no
29//!     conversation it can find;
30//!   - only when the block's `output` has grown since the last completed attempt;
31//!   - at most [`MAX_ATTEMPTS`] completed attempts per block while the title stays
32//!     empty, counted again from zero once a title exists, so an agent whose
33//!     activity never shows what the work is (the model abstains) stops costing;
34//!   - no conversation in the digest means no call at all (`digest` returns
35//!     `None` for activity with no user or assistant text);
36//!   - a call that fails (the CLI could not run, exited badly or timed out) is tried again only
37//!     after a wait that doubles with each failure in a row ([`backoff_ticks`]), up to half an hour,
38//!     counted from when the failed call ends;
39//!   - one call in flight per block, waiting in the background class's queue
40//!     (`ambient::limits`) across all blocks;
41//!   - per-block bookkeeping is pruned each tick against the registration list.
42
43use std::collections::{HashMap, HashSet};
44use std::sync::atomic::{AtomicU64, Ordering};
45use std::sync::{Arc, Mutex};
46use std::time::Duration;
47
48use tokio::time::interval;
49
50use crate::ambient::digest;
51use crate::ambient::tasks::Recovery;
52use crate::ambient::title::{store_title, Replace, META_TITLE};
53use crate::ambient::validate::is_usable_title;
54use crate::backend::blockcontroller::core::broadcast_block_update;
55use crate::backend::blockcontroller::{get_block_controller_status, STATUS_RUNNING};
56use crate::backend::eventbus::EventBus;
57use crate::backend::obj::{self, Block};
58use crate::backend::storage::filestore::FileStore;
59use crate::backend::storage::store::Store;
60
61use super::get_global_handler;
62
63/// How often to sweep registered agents.
64const SWEEP_INTERVAL_SECS: u64 = 20;
65
66/// Completed attempts per block while its title stays empty. Bounded, as the
67/// `lys` design bounds its retries (spec section 3, research point 2).
68pub(crate) const MAX_ATTEMPTS: u32 = 3;
69
70/// Word budget for a recovered title: within the range the pane's own request
71/// uses (5 to 12, by pane width), so a recovered title looks like any other.
72const WORD_TARGET: u32 = 8;
73
74/// Per-block state the sweep keeps between ticks.
75#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
76pub(crate) struct Attempts {
77    /// Completed (billed) attempts since the title was last seen non-empty.
78    pub count: u32,
79    /// The `output` size at the last completed attempt.
80    pub last_size: Option<i64>,
81    /// Calls that failed in a row, since one last completed.
82    pub failures: u32,
83    /// The first tick a block whose call failed may be tried again.
84    pub retry_at_tick: u64,
85}
86
87impl Attempts {
88    /// A call failed, and the sweep is at `tick` as it ends: wait longer than after the last failure before the next try. The wait runs from the end of the call, not from the tick that started it, which a call that queued or ran long may be many ticks behind.
89    fn failed(&mut self, tick: u64) {
90        self.failures += 1;
91        self.retry_at_tick = tick + backoff_ticks(self.failures);
92    }
93
94    /// A call completed with the output at `size`; returns the attempts used. The failure streak ends.
95    fn completed(&mut self, size: i64) -> u32 {
96        self.count += 1;
97        self.last_size = Some(size);
98        self.failures = 0;
99        self.retry_at_tick = 0;
100        self.count
101    }
102}
103
104/// How many ticks to wait after `failures` failed calls in a row: three (a minute), doubling, at most 90 (half an hour).
105pub(crate) fn backoff_ticks(failures: u32) -> u64 {
106    if failures == 0 {
107        return 0;
108    }
109    (3u64 << (failures - 1).min(5)).min(90)
110}
111
112/// A call for `block_id` failed: start its wait from the sweep's tick now (`clock`), not from the tick the call was dispatched at.
113fn record_failure(attempts: &Mutex<HashMap<String, Attempts>>, block_id: &str, clock: &AtomicU64) {
114    let now = clock.load(Ordering::Relaxed);
115    attempts.lock().unwrap().entry(block_id.to_string()).or_default().failed(now);
116}
117
118/// Why a block is not attempted at `tick`, or `None` to attempt it. Pure, so the
119/// cost rules are testable without a model, a store or a clock.
120pub(crate) fn skip_reason(has_title: bool, attempts: Attempts, output_size: i64, tick: u64) -> Option<&'static str> {
121    if has_title {
122        return Some("has a title");
123    }
124    if attempts.count >= MAX_ATTEMPTS {
125        return Some("attempts exhausted");
126    }
127    if tick < attempts.retry_at_tick {
128        return Some("backing off after a failed call");
129    }
130    if attempts.last_size == Some(output_size) {
131        return Some("no new output");
132    }
133    None
134}
135
136/// Run the recovery sweep. Never returns.
137pub async fn run_agent_summary_loop(mstore: Arc<Store>, filestore: Arc<FileStore>, event_bus: Arc<EventBus>) {
138    let mut ticker = interval(Duration::from_secs(SWEEP_INTERVAL_SECS));
139    let attempts: Arc<Mutex<HashMap<String, Attempts>>> = Arc::new(Mutex::new(HashMap::new()));
140    // One call per block at a time: a slow call (up to the CLI timeout) must not
141    // be dispatched again by the next tick. Every insert has a matching remove.
142    let in_flight: Arc<Mutex<HashSet<String>>> = Arc::new(Mutex::new(HashSet::new()));
143    // The sweep count: the gateway's generation only has to increase per (block, purpose), and a call that ends later reads it to start its failure wait.
144    let clock = Arc::new(AtomicU64::new(0));
145
146    loop {
147        ticker.tick().await;
148        let tick = clock.fetch_add(1, Ordering::Relaxed) + 1;
149
150        let agents = get_global_handler().list_agents();
151        let registered: HashSet<String> = agents.iter().map(|a| a.block_id.clone()).collect();
152        attempts.lock().unwrap().retain(|block_id, _| registered.contains(block_id));
153
154        for agent in agents {
155            let block_id = agent.block_id.clone();
156
157            let Some(status) = get_block_controller_status(&block_id) else {
158                continue;
159            };
160            if status.shellprocstatus != STATUS_RUNNING || !status.is_agent_pane {
161                continue;
162            }
163            let Ok(Some(block)) = mstore.get::<Block>(&block_id) else {
164                continue;
165            };
166            let has_title = is_usable_title(&obj::meta_get_string(&block.meta, META_TITLE, ""));
167            if has_title {
168                // A title exists: the budget starts over if it is ever lost.
169                attempts.lock().unwrap().remove(&block_id);
170                continue;
171            }
172            // None for an agent on a model server of its own (no ambient call is made) or on a model route: nothing to try, nothing to count as failed.
173            let readable = digest::reads_output_format(&obj::meta_get_string(&block.meta, "agentOutputFormat", ""));
174            if !readable || crate::ambient::cli::recovery_skips(&block.meta) {
175                continue;
176            }
177            // The agent's own zone when it has content (the copy the pane reads),
178            // else the block's: the size is the "changed since" gate.
179            let Some((output_size, _)) =
180                crate::backend::transcript::source::TranscriptSource::resolve(&filestore, &mstore, &block_id).stat()
181            else {
182                continue;
183            };
184            let state = attempts.lock().unwrap().get(&block_id).copied().unwrap_or_default();
185            if skip_reason(false, state, output_size, tick).is_some() {
186                continue;
187            }
188            if !in_flight.lock().unwrap().insert(block_id.clone()) {
189                continue;
190            }
191
192            let mstore = mstore.clone();
193            let filestore = filestore.clone();
194            let event_bus = event_bus.clone();
195            let (attempts, in_flight, clock) = (attempts.clone(), in_flight.clone(), clock.clone());
196
197            tokio::spawn(async move {
198                let result =
199                    crate::ambient::tasks::generate_recovered_title(&mstore, &filestore, &block_id, tick, WORD_TARGET)
200                        .await;
201                in_flight.lock().unwrap().remove(&block_id);
202
203                // `NotRun`: nothing ran (no conversation in the digest, no CLI path, superseded): not an
204                // attempt, and a later tick may try again. `Failed`: the block waits before its next try.
205                let generated = match result {
206                    Recovery::NotRun => return,
207                    Recovery::Failed => return record_failure(&attempts, &block_id, &clock),
208                    Recovery::Done(generated) => generated,
209                };
210                let attempt = attempts.lock().unwrap().entry(block_id.clone()).or_default().completed(output_size);
211
212                let Some(title) = generated.text else {
213                    tracing::info!(
214                        block_id = %block_id,
215                        attempt,
216                        max = MAX_ATTEMPTS,
217                        "ambient: title recovery produced nothing usable (abstained or rejected)"
218                    );
219                    return;
220                };
221                // The pane's own request can win the race; it is the better source.
222                match store_title(&mstore, &block_id, &title, Replace::IfEmpty, None, || true) {
223                    Ok(true) => {
224                        tracing::info!(block_id = %block_id, attempt, title = %title, "ambient: recovered a missing session title");
225                        broadcast_block_update(&mstore, &event_bus, &block_id);
226                    }
227                    Ok(false) => {
228                        tracing::debug!(block_id = %block_id, "ambient: a title appeared while recovery ran; kept it");
229                    }
230                    Err(e) => {
231                        tracing::warn!(block_id = %block_id, error = %e, "ambient: could not store a recovered title");
232                    }
233                }
234            });
235        }
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242
243    fn tried(count: u32, last_size: i64) -> Attempts {
244        Attempts { count, last_size: Some(last_size), ..Attempts::default() }
245    }
246
247    #[test]
248    fn an_agent_with_a_title_costs_nothing() {
249        assert_eq!(skip_reason(true, Attempts::default(), 100, 1), Some("has a title"));
250    }
251
252    #[test]
253    fn an_untitled_agent_is_tried_once_per_growth_of_its_output() {
254        assert_eq!(skip_reason(false, Attempts::default(), 100, 1), None, "first try");
255        assert_eq!(skip_reason(false, tried(1, 100), 100, 1), Some("no new output"));
256        assert_eq!(skip_reason(false, tried(1, 100), 250, 1), None, "new output, try again");
257    }
258
259    #[test]
260    fn attempts_are_bounded_while_the_title_stays_empty() {
261        assert_eq!(skip_reason(false, tried(MAX_ATTEMPTS - 1, 1), 2, 1), None);
262        assert_eq!(skip_reason(false, tried(MAX_ATTEMPTS, 1), 2, 1), Some("attempts exhausted"));
263    }
264
265    #[test]
266    fn a_failed_call_waits_longer_each_time_up_to_half_an_hour() {
267        let waits: Vec<u64> = (0..9).map(backoff_ticks).collect();
268        assert_eq!(waits, vec![0, 3, 6, 12, 24, 48, 90, 90, 90]);
269        assert_eq!(backoff_ticks(u32::MAX), 90, "a long streak does not overflow");
270    }
271
272    #[test]
273    fn a_block_whose_call_failed_is_not_tried_again_until_its_wait_is_over() {
274        let failed = Attempts { failures: 1, retry_at_tick: 10 + backoff_ticks(1), ..Attempts::default() };
275        assert_eq!(skip_reason(false, failed, 100, 11), Some("backing off after a failed call"));
276        assert_eq!(skip_reason(false, failed, 100, 12), Some("backing off after a failed call"));
277        assert_eq!(skip_reason(false, failed, 100, 13), None, "three ticks (a minute) later");
278        // New output does not shorten the wait: it was the CLI that failed, not the conversation.
279        assert_eq!(skip_reason(false, failed, 9_999, 11), Some("backing off after a failed call"));
280    }
281
282    #[test]
283    fn the_wait_starts_when_the_failed_call_ends_not_when_it_was_dispatched() {
284        let attempts = Mutex::new(HashMap::new());
285        // Dispatched at tick 10; it queued and ran for four ticks, and fails at tick 14.
286        let clock = AtomicU64::new(10);
287        clock.store(14, Ordering::Relaxed);
288        record_failure(&attempts, "b", &clock);
289        let state = attempts.lock().unwrap().get("b").copied().unwrap();
290        assert_eq!(state.failures, 1);
291        assert_eq!(state.retry_at_tick, 14 + backoff_ticks(1));
292        // The next sweep after the failure is no retry; the full first wait still applies.
293        assert_eq!(skip_reason(false, state, 100, 15), Some("backing off after a failed call"));
294        assert_eq!(skip_reason(false, state, 100, 16), Some("backing off after a failed call"));
295        assert_eq!(skip_reason(false, state, 100, 17), None);
296        // A second failure in a row waits longer, again from its own end.
297        clock.store(30, Ordering::Relaxed);
298        record_failure(&attempts, "b", &clock);
299        assert_eq!(attempts.lock().unwrap().get("b").unwrap().retry_at_tick, 30 + backoff_ticks(2));
300    }
301}