Skip to main content

agentmux_srv_core/backend/
agent_api_retry.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Claude CLI request that is being retried, from the CLI's own frames.
5//!
6//! When a request to the API fails in a way the CLI treats as transient (no
7//! connection, a 5xx), it waits and tries again, up to its own limit, and
8//! writes one `system`/`api_retry` frame per attempt:
9//! `{attempt, max_retries, retry_delay_ms, error_status, error}`. With the
10//! network down that is minutes of a busy-looking pane with nothing else on
11//! stdout, so the pane shows the retry, with Stop.
12//!
13//! Published as the per-pane `agent-api-retry` event, and answered for a pane
14//! that opens mid-retry by `agentapiretry`. Cleared by the next frame that is
15//! neither `system` nor `user` (a reply arrived, or the turn's `result`), and
16//! when the stdout reader ends, however it ends ([`ApiRetryReader`]).
17//!
18//! The wait goes out as time remaining, computed when srv sends it, never as
19//! a deadline: srv's clock and the renderer's need not agree. So the event is
20//! not persisted (a replay would carry a stale remainder); srv keeps the
21//! current retry here instead. Every change carries a rising `revision`, and
22//! the pane applies only a newer one than it has: events and the
23//! `agentapiretry` answer can arrive out of order.
24
25use std::collections::HashMap;
26use std::sync::{Arc, LazyLock, Mutex};
27
28use serde_json::Value;
29
30use crate::backend::mps::Broker;
31
32/// One retry the CLI is waiting on, as the pane gets it.
33#[derive(Debug, Clone, PartialEq, serde::Serialize, ts_rs::TS)]
34#[ts(export, export_to = "../../../frontend/types/rpc/")]
35#[serde(rename_all = "camelCase")]
36pub struct ApiRetryState {
37    /// The CLI's retry count, from 1, out of `max_retries`.
38    pub attempt: u32,
39    pub max_retries: u32,
40    /// How long until the next attempt, as of sending; the receiver adds
41    /// its own clock.
42    #[ts(type = "number")]
43    pub retry_in_ms: u64,
44    /// The HTTP status of the failed request; `null` when none came back
45    /// (the connection itself failed).
46    pub error_status: Option<u16>,
47    /// The CLI's error kind (`"unknown"` for a connection failure).
48    pub error: Option<String>,
49}
50
51/// The `agent-api-retry` event's payload (`mps_events::AgentApiRetry`), and
52/// `agentapiretry`'s answer: the retry in progress, or `null` when none is.
53#[derive(Debug, Clone, PartialEq, serde::Serialize, ts_rs::TS)]
54#[ts(export, export_to = "../../../frontend/types/rpc/")]
55pub struct ApiRetryEvent {
56    /// Rises with every change, for every pane; only an order, not a time.
57    #[ts(type = "number")]
58    pub revision: u64,
59    pub retry: Option<ApiRetryState>,
60}
61
62/// `agentapiretry`'s request: the pane asking.
63#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ts_rs::TS)]
64#[ts(export, export_to = "../../../frontend/types/rpc/")]
65pub struct CommandAgentApiRetryData {
66    pub blockid: String,
67}
68
69/// One retry the CLI is waiting on. Kept by srv only: what goes out is
70/// [`ApiRetryState`], with the time remaining.
71#[derive(Debug, Clone, PartialEq)]
72struct PendingRetry {
73    attempt: u32,
74    max_retries: u32,
75    /// When the CLI makes the next attempt, on srv's own clock. Compared
76    /// only with srv's clock, in [`PendingRetry::as_of`]; never sent.
77    due_srv_ms: i64,
78    error_status: Option<u16>,
79    error: Option<String>,
80}
81
82impl PendingRetry {
83    /// The retry as sent when srv's clock reads `srv_now_ms`.
84    fn as_of(&self, srv_now_ms: i64) -> ApiRetryState {
85        ApiRetryState {
86            attempt: self.attempt,
87            max_retries: self.max_retries,
88            retry_in_ms: u64::try_from(self.due_srv_ms.saturating_sub(srv_now_ms)).unwrap_or(0),
89            error_status: self.error_status,
90            error: self.error.clone(),
91        }
92    }
93}
94
95/// What a frame changes about the pane's retry state.
96#[derive(Debug, Clone, PartialEq)]
97enum ApiRetryUpdate {
98    Set(PendingRetry),
99    Clear,
100}
101
102/// The retry an `api_retry` frame announces, or `None` for any other frame.
103fn retry_from_frame(frame: &Value, srv_now_ms: i64) -> Option<PendingRetry> {
104    if frame.get("type").and_then(Value::as_str) != Some("system")
105        || frame.get("subtype").and_then(Value::as_str) != Some("api_retry")
106    {
107        return None;
108    }
109    let num = |key: &str| frame.get(key).and_then(Value::as_u64);
110    let delay_ms = i64::try_from(num("retry_delay_ms").unwrap_or(0)).unwrap_or(i64::MAX);
111    Some(PendingRetry {
112        attempt: u32::try_from(num("attempt")?).ok()?,
113        max_retries: u32::try_from(num("max_retries").unwrap_or(0)).unwrap_or(u32::MAX),
114        due_srv_ms: srv_now_ms.saturating_add(delay_ms),
115        error_status: num("error_status").and_then(|s| u16::try_from(s).ok()),
116        error: frame
117            .get("error")
118            .and_then(Value::as_str)
119            .filter(|e| !e.is_empty())
120            .map(str::to_string),
121    })
122}
123
124/// One stdout reader's view of whether its CLI is retrying, so a clear is
125/// sent once, not for every frame.
126#[derive(Debug, Default)]
127struct ApiRetryTracker {
128    active: bool,
129}
130
131impl ApiRetryTracker {
132    /// The update `frame` makes, if any. A `user` frame doesn't clear: the
133    /// CLI echoes a message it was sent mid-turn, and that is no reply.
134    fn observe(&mut self, frame: &Value, srv_now_ms: i64) -> Option<ApiRetryUpdate> {
135        if let Some(retry) = retry_from_frame(frame, srv_now_ms) {
136            self.active = true;
137            return Some(ApiRetryUpdate::Set(retry));
138        }
139        let kind = frame.get("type").and_then(Value::as_str);
140        if self.active && !matches!(kind, Some("system") | Some("user")) {
141            self.active = false;
142            return Some(ApiRetryUpdate::Clear);
143        }
144        None
145    }
146
147    /// The reader ended: a retry still shown is over.
148    fn finish(&mut self) -> Option<ApiRetryUpdate> {
149        std::mem::take(&mut self.active).then_some(ApiRetryUpdate::Clear)
150    }
151}
152
153/// The retry each pane shows, and which process generation it came from.
154#[derive(Debug)]
155struct ApiRetryRegistry {
156    revision: u64,
157    by_block: HashMap<String, (u64, PendingRetry)>,
158}
159
160impl ApiRetryRegistry {
161    /// `revision` starts from srv's start time (µs) rather than 0, so a pane
162    /// that outlives an srv restart still sees the new srv's events as newer.
163    fn new(first_revision: u64) -> Self {
164        Self { revision: first_revision, by_block: HashMap::new() }
165    }
166
167    /// Applies an update from the stdout reader of process `generation`,
168    /// `current` being the controller's generation now; returns the event to
169    /// publish, if the pane's state changed. A replaced process's reader can
170    /// still be draining its pipe: it may clear only a retry it set itself,
171    /// and may not set one, or a stale row would offer to stop the new process.
172    fn apply(
173        &mut self,
174        block_id: &str,
175        generation: u64,
176        current: u64,
177        update: ApiRetryUpdate,
178        srv_now_ms: i64,
179    ) -> Option<ApiRetryEvent> {
180        let retry = match update {
181            ApiRetryUpdate::Set(retry) if generation == current => {
182                let sent = retry.as_of(srv_now_ms);
183                self.by_block.insert(block_id.to_string(), (generation, retry));
184                Some(sent)
185            }
186            ApiRetryUpdate::Set(_) => return None,
187            ApiRetryUpdate::Clear => {
188                if self.by_block.get(block_id).is_none_or(|(g, _)| *g != generation) {
189                    return None;
190                }
191                self.by_block.remove(block_id);
192                None
193            }
194        };
195        self.revision += 1;
196        Some(ApiRetryEvent { revision: self.revision, retry })
197    }
198
199    /// The pane's retry as of `srv_now_ms`, at the current revision.
200    fn current(&self, block_id: &str, srv_now_ms: i64) -> ApiRetryEvent {
201        ApiRetryEvent {
202            revision: self.revision,
203            retry: self.by_block.get(block_id).map(|(_, retry)| retry.as_of(srv_now_ms)),
204        }
205    }
206}
207
208static REGISTRY: LazyLock<Mutex<ApiRetryRegistry>> = LazyLock::new(|| {
209    let start_us = u64::try_from(agentmux_common::time::now_ms()).unwrap_or(0).saturating_mul(1000);
210    Mutex::new(ApiRetryRegistry::new(start_us))
211});
212
213/// Records an update and publishes the change, if any.
214fn publish(broker: Option<&Broker>, block_id: &str, generation: u64, current: u64, update: ApiRetryUpdate) {
215    let now = agentmux_common::time::now_ms();
216    let event = REGISTRY
217        .lock()
218        .unwrap_or_else(|e| e.into_inner())
219        .apply(block_id, generation, current, update, now);
220    if let (Some(event), Some(broker)) = (event, broker) {
221        broker.publish_event::<crate::backend::mps_events::AgentApiRetry>(&event, vec![format!("block:{block_id}")], 0);
222    }
223}
224
225/// `agentapiretry`: the pane's retry as of now.
226pub fn current_api_retry(block_id: &str) -> ApiRetryEvent {
227    REGISTRY
228        .lock()
229        .unwrap_or_else(|e| e.into_inner())
230        .current(block_id, agentmux_common::time::now_ms())
231}
232
233/// One stdout reader's part in its pane's retry state. Dropping it clears a
234/// retry it set, so a reader that ends any way, including aborted mid-read
235/// (`process_waiter.rs` `settle_reader_tasks`), never leaves one behind.
236pub struct ApiRetryReader {
237    block_id: String,
238    generation: u64,
239    broker: Option<Arc<Broker>>,
240    tracker: ApiRetryTracker,
241}
242
243impl ApiRetryReader {
244    pub fn new(block_id: &str, generation: u64, broker: Option<Arc<Broker>>) -> Self {
245        Self { block_id: block_id.to_string(), generation, broker, tracker: ApiRetryTracker::default() }
246    }
247
248    /// Reads one stdout frame. `current` gives the controller's process
249    /// generation now; asked only when the frame changes something.
250    pub fn observe(&mut self, frame: &Value, current: impl FnOnce() -> u64) {
251        if let Some(update) = self.tracker.observe(frame, agentmux_common::time::now_ms()) {
252            publish(self.broker.as_deref(), &self.block_id, self.generation, current(), update);
253        }
254    }
255}
256
257impl Drop for ApiRetryReader {
258    fn drop(&mut self) {
259        if let Some(update) = self.tracker.finish() {
260            // A clear checks only that this generation set the retry.
261            publish(self.broker.as_deref(), &self.block_id, self.generation, self.generation, update);
262        }
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269    use serde_json::json;
270
271    const NOW: i64 = 1_800_000_000_000;
272
273    fn retry_frame() -> Value {
274        json!({
275            "type": "system", "subtype": "api_retry", "attempt": 3, "max_retries": 10,
276            "retry_delay_ms": 2238, "error_status": null, "error": "unknown",
277            "session_id": "s", "uuid": "u",
278        })
279    }
280
281    fn pending(attempt: u32) -> PendingRetry {
282        PendingRetry { attempt, max_retries: 10, due_srv_ms: NOW + 10_000, error_status: None, error: None }
283    }
284
285    #[test]
286    fn reads_the_clis_retry_frame() {
287        assert_eq!(
288            retry_from_frame(&retry_frame(), NOW),
289            Some(PendingRetry {
290                attempt: 3,
291                max_retries: 10,
292                due_srv_ms: NOW + 2238,
293                error_status: None,
294                error: Some("unknown".into()),
295            })
296        );
297    }
298
299    #[test]
300    fn keeps_an_http_status() {
301        let mut frame = retry_frame();
302        frame["error_status"] = json!(529);
303        frame["error"] = json!("overloaded_error");
304        let retry = retry_from_frame(&frame, NOW).unwrap();
305        assert_eq!(retry.error_status, Some(529));
306        assert_eq!(retry.error.as_deref(), Some("overloaded_error"));
307    }
308
309    #[test]
310    fn other_frames_are_not_retries() {
311        assert_eq!(retry_from_frame(&json!({ "type": "system", "subtype": "init" }), NOW), None);
312        assert_eq!(retry_from_frame(&json!({ "type": "assistant", "subtype": "api_retry" }), NOW), None);
313        // No attempt number: not a frame this can describe.
314        assert_eq!(retry_from_frame(&json!({ "type": "system", "subtype": "api_retry" }), NOW), None);
315    }
316
317    #[test]
318    fn a_retry_sets_and_the_next_reply_clears_once() {
319        let mut t = ApiRetryTracker::default();
320        assert!(matches!(t.observe(&retry_frame(), NOW), Some(ApiRetryUpdate::Set(r)) if r.attempt == 3));
321        // Neither a system frame nor an echoed user message is a reply.
322        assert_eq!(t.observe(&json!({ "type": "system", "subtype": "status" }), NOW), None);
323        assert_eq!(t.observe(&json!({ "type": "user", "message": {} }), NOW), None);
324        assert_eq!(t.observe(&json!({ "type": "stream_event", "event": {} }), NOW), Some(ApiRetryUpdate::Clear));
325        assert_eq!(t.observe(&json!({ "type": "assistant", "message": {} }), NOW), None);
326    }
327
328    #[test]
329    fn the_turns_result_clears() {
330        let mut t = ApiRetryTracker::default();
331        t.observe(&retry_frame(), NOW);
332        let result = json!({ "type": "result", "is_error": true, "result": "API Error: Connection refused" });
333        assert_eq!(t.observe(&result, NOW), Some(ApiRetryUpdate::Clear));
334    }
335
336    #[test]
337    fn nothing_to_clear_without_a_retry() {
338        let mut t = ApiRetryTracker::default();
339        assert_eq!(t.observe(&json!({ "type": "result" }), NOW), None);
340        assert_eq!(t.finish(), None);
341    }
342
343    #[test]
344    fn the_reader_ending_clears_a_retry_still_shown() {
345        let mut t = ApiRetryTracker::default();
346        t.observe(&retry_frame(), NOW);
347        assert_eq!(t.finish(), Some(ApiRetryUpdate::Clear));
348        assert_eq!(t.finish(), None);
349    }
350
351    #[test]
352    fn the_wait_is_sent_as_time_remaining_when_sent() {
353        let mut r = ApiRetryRegistry::new(0);
354        let sent = r.apply("b", 1, 1, ApiRetryUpdate::Set(pending(3)), NOW).unwrap();
355        assert_eq!(sent.retry.unwrap().retry_in_ms, 10_000);
356        // A pane opening 4 s later is told 6 s, and nothing once it is due.
357        assert_eq!(r.current("b", NOW + 4_000).retry.unwrap().retry_in_ms, 6_000);
358        assert_eq!(r.current("b", NOW + 60_000).retry.unwrap().retry_in_ms, 0);
359        assert_eq!(r.current("other", NOW).retry, None);
360    }
361
362    #[test]
363    fn every_change_raises_the_revision_and_reads_report_it() {
364        let mut r = ApiRetryRegistry::new(100);
365        let set = r.apply("b", 1, 1, ApiRetryUpdate::Set(pending(3)), NOW).unwrap();
366        assert_eq!(set.revision, 101);
367        assert_eq!(r.current("b", NOW).revision, 101);
368        let again = r.apply("b", 1, 1, ApiRetryUpdate::Set(pending(4)), NOW).unwrap();
369        let cleared = r.apply("b", 1, 1, ApiRetryUpdate::Clear, NOW).unwrap();
370        assert!(set.revision < again.revision && again.revision < cleared.revision);
371        assert_eq!(r.current("b", NOW), ApiRetryEvent { revision: cleared.revision, retry: None });
372        // A change that changes nothing takes no revision.
373        assert_eq!(r.apply("b", 1, 1, ApiRetryUpdate::Clear, NOW), None);
374        assert_eq!(r.current("b", NOW).revision, cleared.revision);
375    }
376
377    #[test]
378    fn a_replaced_process_changes_nothing_of_its_replacements() {
379        let mut r = ApiRetryRegistry::new(0);
380        r.apply("b", 2, 2, ApiRetryUpdate::Set(pending(5)), NOW);
381        // Generation 1's reader, still draining after generation 2 started.
382        assert_eq!(r.apply("b", 1, 2, ApiRetryUpdate::Set(pending(9)), NOW), None);
383        assert_eq!(r.apply("b", 1, 2, ApiRetryUpdate::Clear, NOW), None);
384        assert_eq!(r.current("b", NOW).retry.unwrap().attempt, 5);
385    }
386
387    #[test]
388    fn a_replaced_process_still_clears_a_retry_it_set() {
389        // Otherwise a row from the old process would stay until the new one retried.
390        let mut r = ApiRetryRegistry::new(0);
391        r.apply("b", 1, 1, ApiRetryUpdate::Set(pending(3)), NOW);
392        assert_eq!(r.apply("b", 1, 2, ApiRetryUpdate::Clear, NOW).unwrap().retry, None);
393        assert_eq!(r.current("b", NOW).retry, None);
394    }
395
396    #[tokio::test]
397    async fn an_aborted_reader_clears_the_retry_it_set() {
398        let block = "api-retry-test-aborted-reader";
399        let reading = tokio::spawn(async move {
400            let mut reader = ApiRetryReader::new(block, 1, None);
401            reader.observe(&retry_frame(), || 1);
402            // Blocked on a pipe a descendant process holds open.
403            std::future::pending::<()>().await;
404        });
405        for _ in 0..1000 {
406            if current_api_retry(block).retry.is_some() {
407                break;
408            }
409            tokio::task::yield_now().await;
410        }
411        assert!(current_api_retry(block).retry.is_some());
412        reading.abort();
413        assert!(reading.await.unwrap_err().is_cancelled());
414        assert_eq!(current_api_retry(block).retry, None);
415    }
416
417    #[test]
418    fn the_event_serializes_camel_case_and_null_when_cleared() {
419        let set = ApiRetryEvent { revision: 7, retry: Some(pending(3).as_of(NOW)) };
420        let v = serde_json::to_value(&set).unwrap();
421        assert_eq!(v["retry"]["maxRetries"], json!(10));
422        assert_eq!(v["retry"]["retryInMs"], json!(10_000));
423        assert_eq!(v["retry"]["errorStatus"], Value::Null);
424        assert_eq!(v["retry"].as_object().unwrap().len(), 5, "no srv-clock time on the wire: {v}");
425        assert_eq!(
426            serde_json::to_value(ApiRetryEvent { revision: 8, retry: None }).unwrap(),
427            json!({ "revision": 8, "retry": null })
428        );
429    }
430}