Skip to main content

agentmux_srv/server/account_episodes/
resume.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! After a confirmed sign-in, an agent whose last turn failed on the expired login is told, and answers
5//! with where it stands (task #2458).
6//!
7//! Clearing the stored failure ([`super::clear_signed_out`]) lifts the error from the pane and wakes
8//! the messages held for it, but a pane with nothing held sat there: the turn that failed never ran
9//! again, and the person had to type "u there". Each pane that was cleared of an Auth failure now gets
10//! one `[AgentMux]` message that starts a turn: when it signed in, when the turn failed, and to carry on
11//! and say in a line or two where things stand. The input that started the failed turn is not sent again
12//! because AgentMux does not have it for every kind (a CLI's own background-command completion is never
13//! seen here), and the agent's session already holds it: the note is the same for all of them.
14//!
15//! - **Only a pane whose last turn failed on the login** (the stored failure is `Auth`), and not one
16//!   already in a turn: a pane that did not fail gets nothing.
17//! - **Paced**: [`BATCH`] panes at a time, [`BATCH_GAP`] apart, since many agents share one account and
18//!   each note starts a model turn.
19//! - **Once**: a sign-in is often reported twice (the OAuth handler and the window), so a pane told in
20//!   the last [`ONCE_MS`] is not told again.
21//! - A pane with no controller (a stopped agent) is not started; the note waits for its next turn.
22//!   A one-shot (container) pane gets a turn started the way any message to it does.
23
24use std::collections::HashMap;
25use std::sync::{Mutex, OnceLock};
26use std::time::Duration;
27
28use tokio::task::JoinSet;
29
30/// How many panes are told at once.
31pub(super) const BATCH: usize = 3;
32
33/// The wait between groups.
34pub(super) const BATCH_GAP: Duration = Duration::from_secs(2);
35
36/// A pane told this recently is not told again for the same sign-in.
37const ONCE_MS: i64 = 60_000;
38
39/// The held note's key: a newer one replaces an older one for the pane.
40const NOTE_KEY: &str = "signed-in-again";
41
42/// A pane whose last turn failed on the expired login, as it was when the sign-in cleared it.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub(super) struct Failed {
45    pub block_id: String,
46    /// When the failure was recorded (unix ms), if it says.
47    pub failed_at_ms: Option<u64>,
48}
49
50/// The note for one pane: what happened, and what is asked of the agent.
51pub(super) fn note_for(signed_in_ms: i64, failed_at_ms: Option<u64>) -> String {
52    use crate::muxbus::delivery_status::notes::hhmm;
53    let turn = match failed_at_ms {
54        Some(at) => format!("Your turn at {}", hhmm(i64::try_from(at).unwrap_or(0))),
55        None => "Your last turn".to_string(),
56    };
57    format!(
58        "Signed in again at {}. {turn} did not run because the login had expired. Carry on from where you were and say in a line or two where things stand.",
59        hhmm(signed_in_ms)
60    )
61}
62
63/// `failed` in groups of [`BATCH`], in the order given.
64pub(super) fn batches(failed: Vec<Failed>) -> Vec<Vec<Failed>> {
65    failed.chunks(BATCH).map(<[Failed]>::to_vec).collect()
66}
67
68/// `failed` without the panes told within [`ONCE_MS`] of `now_ms`, which are recorded as told now.
69pub(super) fn not_just_told(told: &mut HashMap<String, i64>, failed: Vec<Failed>, now_ms: i64) -> Vec<Failed> {
70    told.retain(|_, at| now_ms - *at < ONCE_MS);
71    failed
72        .into_iter()
73        .filter(|f| {
74            if told.contains_key(&f.block_id) {
75                return false;
76            }
77            told.insert(f.block_id.clone(), now_ms);
78            true
79        })
80        .collect()
81}
82
83/// What was done for one pane.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85enum Told {
86    /// The note started a turn.
87    Turn,
88    /// The pane is not running; the note waits for its next turn.
89    Held,
90    /// The pane is in a turn already; it has the sign-in, so nothing is added.
91    Busy,
92    /// The turn could not be started; the note waits for the next one.
93    Failed,
94}
95
96/// Tell one pane. Blocking: starting a turn can wait for a process.
97fn tell(block_id: &str, text: &str) -> Told {
98    let Some(status) = crate::backend::blockcontroller::get_block_controller_status(block_id) else {
99        crate::backend::blockcontroller::system_note_into_turn_or_hold(block_id, NOTE_KEY, text);
100        return Told::Held;
101    };
102    if status.turn_active {
103        return Told::Busy;
104    }
105    let marked = crate::backend::reactive::sanitize::with_system_note_marker(text);
106    match crate::backend::reactive::get_global_handler().send_system_turn(block_id, &marked) {
107        Ok(crate::backend::reactive::SenderDelivery::Pty) => {
108            // A terminal agent takes no message of ours: the note waits for its next turn.
109            crate::backend::blockcontroller::system_note_into_turn_or_hold(block_id, NOTE_KEY, text);
110            Told::Held
111        }
112        Ok(_) => Told::Turn,
113        Err(e) => {
114            tracing::warn!(block_id = %block_id, error = %e, "sign-in: couldn't start the turn that tells an agent it is signed in; the note waits");
115            crate::backend::blockcontroller::system_note_into_turn_or_hold(block_id, NOTE_KEY, text);
116            Told::Failed
117        }
118    }
119}
120
121async fn run(failed: Vec<Failed>, signed_in_ms: i64) {
122    for (i, group) in batches(failed).into_iter().enumerate() {
123        if i > 0 {
124            tokio::time::sleep(BATCH_GAP).await;
125        }
126        let mut set = JoinSet::new();
127        for f in group {
128            let text = note_for(signed_in_ms, f.failed_at_ms);
129            set.spawn_blocking(move || (tell(&f.block_id, &text), f.block_id));
130        }
131        while let Some(done) = set.join_next().await {
132            if let Ok((told, block_id)) = done {
133                tracing::info!(block_id = %block_id, ?told, "sign-in: an agent whose turn failed on the login was told");
134            }
135        }
136    }
137}
138
139/// Tell each of `failed`, paced and once, in the background. Does nothing outside a runtime.
140pub(super) fn start(failed: Vec<Failed>, signed_in_ms: i64) {
141    static TOLD: OnceLock<Mutex<HashMap<String, i64>>> = OnceLock::new();
142    let failed = not_just_told(&mut TOLD.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner()), failed, signed_in_ms);
143    if failed.is_empty() {
144        return;
145    }
146    let Ok(handle) = tokio::runtime::Handle::try_current() else {
147        tracing::warn!(panes = failed.len(), "sign-in: no runtime to tell the signed-in agents on");
148        return;
149    };
150    tracing::info!(panes = failed.len(), batch = BATCH, gap_ms = BATCH_GAP.as_millis() as u64, "sign-in: telling the agents whose turn failed on the login");
151    handle.spawn(run(failed, signed_in_ms));
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    fn failed(ids: &[&str]) -> Vec<Failed> {
159        ids.iter().map(|id| Failed { block_id: id.to_string(), failed_at_ms: Some(1_000) }).collect()
160    }
161
162    #[test]
163    fn the_note_says_when_it_signed_in_and_which_turn_did_not_run_and_asks_for_the_status() {
164        let note = note_for(1_700_000_100_000, Some(1_700_000_000_000));
165        assert!(note.starts_with("Signed in again at "), "{note}");
166        assert!(note.contains("Your turn at ") && note.contains("did not run because the login had expired"), "{note}");
167        assert!(note.ends_with("say in a line or two where things stand."), "{note}");
168        let unknown = note_for(1_700_000_100_000, None);
169        assert!(unknown.contains("Your last turn did not run"), "{unknown}");
170    }
171
172    #[test]
173    fn panes_are_told_a_few_at_a_time_in_the_order_they_failed_in() {
174        let groups = batches(failed(&["a", "b", "c", "d", "e", "f", "g"]));
175        let ids: Vec<Vec<&str>> = groups.iter().map(|g| g.iter().map(|f| f.block_id.as_str()).collect()).collect();
176        assert_eq!(ids, [vec!["a", "b", "c"], vec!["d", "e", "f"], vec!["g"]]);
177        assert!(groups.iter().all(|g| g.len() <= BATCH));
178        assert!(batches(Vec::new()).is_empty(), "no pane failed: nothing to tell");
179    }
180
181    #[test]
182    fn a_pane_told_a_moment_ago_is_not_told_again_but_is_after_a_while() {
183        let mut told = HashMap::new();
184        assert_eq!(not_just_told(&mut told, failed(&["a", "b"]), 1_000).len(), 2);
185        assert!(not_just_told(&mut told, failed(&["a", "b"]), 2_000).is_empty(), "the second report of the same sign-in");
186        assert_eq!(not_just_told(&mut told, failed(&["a", "c"]), 3_000), failed(&["c"]));
187        assert_eq!(not_just_told(&mut told, failed(&["a"]), 1_000 + ONCE_MS).len(), 1, "a later failure is told");
188    }
189
190    #[test]
191    fn a_pane_with_no_controller_keeps_the_note_for_its_next_turn_and_is_not_started() {
192        let block = format!("resume-test-{}", uuid::Uuid::new_v4());
193        assert_eq!(tell(&block, "Signed in again at 09:05."), Told::Held);
194        let (message, _held) = crate::backend::reactive::held_notes::attach(&block, "hello");
195        assert!(message.contains("Signed in again at 09:05."), "{message}");
196    }
197}