Skip to main content

agentmux_srv_core/backend/
agent_state.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Whether each agent is working, waiting on the user, idle, stopped or
5//! failed, and since when: the `agent_status` the LAN fleet feed,
6//! `GET /agentmux/reactive/agent-names` and (through the feed's snapshot) the
7//! cloud presence record carry (agentmux-mobile's
8//! SPEC_AGENT_STATUS_AND_LIVE_PANE_FEED_2026_10_07 §3, §13.1).
9//!
10//! [`decide`] is the rule, pure; [`current_state`] reads its inputs from the
11//! block's controller and the block's meta; a [`SinceTracker`] remembers when
12//! each block's state began. Every caller goes through
13//! [`agent_status_of_block`] or a [`SinceTracker`] of its own, so the feed
14//! and the names route agree on `since_ms`.
15//!
16//! `limited` and `signed_out` are an agent that is alive but can't work: its
17//! last run ended on the plan's usage limit or a refused sign-in
18//! (`docs/specs/SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md` §3). Read them through
19//! [`unavailable_of_block`], so no caller re-derives the rule.
20
21use std::collections::HashMap;
22use std::sync::LazyLock;
23
24use serde::{Deserialize, Serialize};
25
26use crate::agents::failure::FailureClass;
27use crate::backend::blockcontroller;
28use crate::backend::obj::Block;
29use crate::backend::storage::store::Store;
30
31/// Block meta the agent pane sets while a question waits for the user.
32pub const META_AWAITING_USER: &str = "term:awaiting_user";
33
34/// The account a pane's run launched on, written at spawn
35/// (`build_persistent_spawn_env`), so a failure that run records counts
36/// against that account even after the agent is linked to another
37/// ([`run_accounts_of_block`]).
38pub const RUN_ACCOUNT_META_KEY: &str = "agent:run_account";
39
40/// Written by the agent pane's launch when it stops at "needs sign-in", and
41/// cleared once the pane registers its controller. Such a pane has no
42/// controller, so nothing else says why: a message to it failed with "no
43/// controller for block" instead of being held for the sign-in
44/// ([`current_state_at`], [`unavailable_of_block`]).
45pub const LAUNCH_BLOCKED_META_KEY: &str = "agent:launch_blocked";
46
47/// When (unix ms) the launch stopped there.
48pub const LAUNCH_BLOCKED_AT_META_KEY: &str = "agent:launch_blocked_at_ms";
49
50/// The [`LAUNCH_BLOCKED_META_KEY`] value for a launch waiting on a sign-in.
51pub const LAUNCH_BLOCKED_SIGN_IN: &str = "sign_in";
52
53/// The pane's launch stopped at "needs sign-in" and has not registered since.
54fn launch_blocked_on_sign_in(block: &Block) -> bool {
55    crate::backend::obj::meta_get_string(&block.meta, LAUNCH_BLOCKED_META_KEY, "") == LAUNCH_BLOCKED_SIGN_IN
56}
57
58/// An agent's state as the wire reports it.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
60#[ts(export, export_to = "../../../frontend/types/rpc/")]
61#[serde(rename_all = "lowercase")]
62pub enum AgentState {
63    Working,
64    /// A turn is running and a question waits for the user.
65    Waiting,
66    Idle,
67    /// The process exited cleanly.
68    Stopped,
69    /// The process exited with an error.
70    Error,
71    /// Its last run ended on the plan's usage limit, which hasn't reset.
72    Limited,
73    /// Its last run ended on refused credentials, or no account to run on.
74    #[serde(rename = "signed_out")]
75    SignedOut,
76}
77
78impl AgentState {
79    pub fn as_str(self) -> &'static str {
80        match self {
81            Self::Working => "working",
82            Self::Waiting => "waiting",
83            Self::Idle => "idle",
84            Self::Stopped => "stopped",
85            Self::Error => "error",
86            Self::Limited => "limited",
87            Self::SignedOut => "signed_out",
88        }
89    }
90}
91
92/// A state and when it began (unix ms, this machine's clock).
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
94pub struct AgentStatus {
95    pub state: AgentState,
96    pub since_ms: u64,
97}
98
99/// What [`decide`] looks at, as read from the controller and the block.
100#[derive(Debug, Clone, Copy, Default)]
101pub struct StateInputs<'a> {
102    pub controller_type: &'a str,
103    /// `BlockControllerRuntimeStatus::turn_active`; an absent field is false.
104    pub turn_active: bool,
105    /// `shellprocstatus`: `init`, `running` or `done`.
106    pub process_status: &'a str,
107    pub exit_code: i32,
108    pub awaiting_user: bool,
109    /// The class and reset (unix ms) of the block's `agent:last_failure`.
110    pub failure: Option<(FailureClass, Option<u64>)>,
111    /// This machine's clock, unix ms, for the reset.
112    pub now_ms: u64,
113}
114
115/// The state, or `None` when nothing tracks this agent's turns (a terminal
116/// pane: `shell` / `cmd`, or any controller that isn't an agent's) or its
117/// process state is unknown. Saying nothing beats a wrong `idle`.
118///
119/// A turn wins over everything, as in the process broker's `lifecycle_from`:
120/// a turn that runs is evidence the agent can work. Then a usage limit that
121/// hasn't reset (or whose reset isn't known) is `limited`, and a refused
122/// sign-in `signed_out`, whatever the process state: anything started on that
123/// account fails the same way. Other failure classes are transient and don't
124/// change the state. The `subprocess` controller runs one process per turn, so
125/// its process exiting cleanly between turns is `idle`, not `stopped`.
126pub fn decide(inputs: &StateInputs) -> Option<AgentState> {
127    let per_turn_process = match inputs.controller_type {
128        blockcontroller::BLOCK_CONTROLLER_SUBPROCESS => true,
129        blockcontroller::BLOCK_CONTROLLER_PERSISTENT
130        | blockcontroller::BLOCK_CONTROLLER_ACP
131        | blockcontroller::BLOCK_CONTROLLER_MSP
132        | blockcontroller::BLOCK_CONTROLLER_APP_SERVER => false,
133        _ => return None,
134    };
135    if inputs.turn_active {
136        return Some(if inputs.awaiting_user { AgentState::Waiting } else { AgentState::Working });
137    }
138    match inputs.failure {
139        Some((FailureClass::UsageLimit, resets)) if resets.is_none_or(|r| r > inputs.now_ms) => {
140            return Some(AgentState::Limited);
141        }
142        Some((FailureClass::Auth, _)) => return Some(AgentState::SignedOut),
143        _ => {}
144    }
145    match inputs.process_status {
146        blockcontroller::STATUS_RUNNING | blockcontroller::STATUS_INIT => Some(AgentState::Idle),
147        blockcontroller::STATUS_DONE if inputs.exit_code != 0 => Some(AgentState::Error),
148        blockcontroller::STATUS_DONE if per_turn_process => Some(AgentState::Idle),
149        blockcontroller::STATUS_DONE => Some(AgentState::Stopped),
150        _ => None,
151    }
152}
153
154/// The block's state now: its controller's runtime status and the block's
155/// `term:awaiting_user` and `agent:last_failure`. `None` without a controller
156/// (unless its launch stopped at "needs sign-in": `signed_out`), or when the
157/// block can't be read.
158pub fn current_state(mstore: &Store, block_id: &str) -> Option<AgentState> {
159    current_state_at(mstore, block_id, agentmux_common::time::now_ms_u64())
160}
161
162/// Whether the agent in `block_id` is in a turn: working, or waiting on a question. The one definition
163/// of "not between turns", for everything that waits for a turn to end before it restarts a pane
164/// (an account move, a prepared change).
165pub fn in_turn(mstore: &Store, block_id: &str) -> bool {
166    matches!(current_state(mstore, block_id), Some(AgentState::Working | AgentState::Waiting))
167}
168
169/// [`current_state`] at `now_ms`.
170pub fn current_state_at(mstore: &Store, block_id: &str, now_ms: u64) -> Option<AgentState> {
171    let Some(controller) = blockcontroller::get_controller(block_id) else {
172        let block = mstore.get::<Block>(block_id).ok()??;
173        return launch_blocked_on_sign_in(&block).then_some(AgentState::SignedOut);
174    };
175    let status = controller.get_runtime_status();
176    let block = mstore.get::<Block>(block_id).ok()??;
177    decide(&StateInputs {
178        controller_type: controller.controller_type(),
179        turn_active: status.turn_active,
180        process_status: &status.shellprocstatus,
181        exit_code: status.shellprocexitcode,
182        // The pane's flag, or srv's own record of a request parked for the user: the second holds
183        // with no window showing the agent (a headless or parked one).
184        awaiting_user: crate::backend::obj::meta_get_bool(&block.meta, META_AWAITING_USER, false) || controller.awaiting_user_reply(),
185        failure: failure_of_block(&block).map(|f| (f.code, f.resets_at_ms)),
186        now_ms,
187    })
188}
189
190/// The parts of a block's `agent:last_failure` the states read. Only these
191/// fields: the stored failure leaves out empty ones that reading the whole
192/// `AgentFailure` back would require.
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct StoredFailure {
195    pub code: FailureClass,
196    pub title: String,
197    pub resets_at_ms: Option<u64>,
198    /// When it was recorded (unix ms); absent on one stored before this field.
199    pub at_ms: Option<u64>,
200}
201
202/// The block's stored failure, or `None` when it has none (or one this build
203/// can't read).
204pub fn failure_of_block(block: &Block) -> Option<StoredFailure> {
205    let f = block.meta.get(blockcontroller::core::META_LAST_FAILURE)?;
206    Some(StoredFailure {
207        code: serde_json::from_value(f.get("code")?.clone()).ok()?,
208        title: f.get("title").and_then(|t| t.as_str()).unwrap_or_default().to_string(),
209        resets_at_ms: f.get("resetsAtMs").and_then(|r| r.as_u64()),
210        at_ms: f.get(blockcontroller::core::META_FAILURE_AT_MS).and_then(|r| r.as_u64()),
211    })
212}
213
214/// An agent that is alive but can't work, and why.
215#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
216pub struct Unavailable {
217    /// `limited` or `signed_out`.
218    pub state: AgentState,
219    pub code: FailureClass,
220    pub title: String,
221    /// When its usage limit lifts (unix ms), when the provider said.
222    pub resets_at_ms: Option<u64>,
223    /// Since when it has been in this state (unix ms).
224    pub since_ms: u64,
225    /// The account its run launched on. Never put in an answer another host
226    /// may receive (MuxAPI, the fleet feed).
227    #[serde(skip)]
228    pub account_id: Option<String>,
229}
230
231impl Unavailable {
232    /// "Out of quota until Sun 7:00 PM", "Out of quota", "Route out of credits" or
233    /// "Needs sign-in", in this machine's time zone. A route out of credits is not a plan's
234    /// quota, and its time is only when a message may try the route again (#47477).
235    pub fn reason(&self) -> String {
236        if self.state == AgentState::Limited && self.title == crate::agents::failure::ROUTE_CREDITS_TITLE {
237            return "Route out of credits".to_string();
238        }
239        match (self.state, self.resets_at_ms.and_then(|ms| chrono::DateTime::from_timestamp_millis(ms as i64))) {
240            (AgentState::SignedOut, _) => "Needs sign-in".to_string(),
241            (_, Some(t)) => format!("Out of quota until {}", t.with_timezone(&chrono::Local).format("%a %-I:%M %p")),
242            (_, None) => "Out of quota".to_string(),
243        }
244    }
245}
246
247/// `Some` when the agent on `block_id` is `limited` or `signed_out` at
248/// `now_ms`. With `identity`, a pane from before `agent:run_account` gets its
249/// agent's current account link.
250pub fn unavailable_of_block(mstore: &Store, identity: Option<&Store>, block_id: &str, now_ms: u64) -> Option<Unavailable> {
251    let state = current_state_at(mstore, block_id, now_ms)?;
252    if !matches!(state, AgentState::Limited | AgentState::SignedOut) {
253        return None;
254    }
255    let block = mstore.get::<Block>(block_id).ok()??;
256    let failure = match failure_of_block(&block) {
257        Some(failure) => failure,
258        // A pane that stopped at "needs sign-in" has run nothing, so no failure of its own.
259        None if state == AgentState::SignedOut && launch_blocked_on_sign_in(&block) => StoredFailure {
260            code: FailureClass::Auth,
261            title: "Needs sign-in".to_string(),
262            resets_at_ms: None,
263            at_ms: block.meta.get(LAUNCH_BLOCKED_AT_META_KEY).and_then(|at| at.as_u64()),
264        },
265        None => return None,
266    };
267    // The failure's own time when it has one: the tracker starts over at every srv start.
268    let tracked = TRACKER.record(block_id, Some(state), now_ms).map_or(now_ms, |s| s.since_ms);
269    let since_ms = failure.at_ms.map_or(tracked, |at| at.min(now_ms));
270    let account_id = match identity {
271        Some(identity) => run_accounts_of_block(identity, &block).into_iter().next(),
272        None => block.meta.get(RUN_ACCOUNT_META_KEY).and_then(|a| a.as_str()).map(str::to_string),
273    };
274    Some(Unavailable { state, code: failure.code, title: failure.title, resets_at_ms: failure.resets_at_ms, since_ms, account_id })
275}
276
277/// The block's state now and, while it is `limited` or `signed_out`, why.
278pub fn state_and_unavailable(mstore: &Store, block_id: &str) -> (Option<AgentState>, Option<Unavailable>) {
279    let state = agent_status_of_block(mstore, block_id).map(|s| s.state);
280    (state, unavailable_of_block(mstore, None, block_id, agentmux_common::time::now_ms_u64()))
281}
282
283/// The accounts a pane's run counts against: `agent:run_account`, the account
284/// it launched on; a pane from before that key falls back to its agent's
285/// current links. One rule for the spawn gate's `account_blocks`,
286/// [`unavailable_of_block`] and the account episodes.
287pub fn run_accounts_of_block(identity: &Store, block: &Block) -> Vec<String> {
288    match block.meta.get(RUN_ACCOUNT_META_KEY).and_then(|a| a.as_str()) {
289        Some(account) => vec![account.to_string()],
290        None => {
291            let agent = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
292            identity.agent_identity_list_for_agent(&agent).unwrap_or_default().into_iter().map(|l| l.account_id).collect()
293        }
294    }
295}
296
297/// When each block's current state began. A state seen for the first time
298/// (srv start, a new agent) begins when it is seen; a state that changes
299/// begins again; `None` forgets the block, so a stopped and restarted agent
300/// does not inherit an old start.
301#[derive(Default)]
302pub struct SinceTracker {
303    by_block: parking_lot::Mutex<HashMap<String, AgentStatus>>,
304}
305
306/// Whether a change from `from` to `to` can make a held message deliverable: the agent left a state
307/// that held messages (out of quota, signed out, not running), or a session that had gone quiet took
308/// a turn (a cold session warming). The one place a state change wakes the held-message replay, so a
309/// path that forgets its own wake is still covered.
310pub fn change_wakes_held(from: AgentState, to: AgentState) -> bool {
311    match from {
312        AgentState::Limited | AgentState::SignedOut | AgentState::Stopped | AgentState::Error => from != to,
313        AgentState::Idle => matches!(to, AgentState::Working | AgentState::Waiting),
314        AgentState::Working | AgentState::Waiting => false,
315    }
316}
317
318impl SinceTracker {
319    /// Record `state` for `block_id` as seen at `now_ms`; returns it with the
320    /// time it began. A change that can make a held message deliverable wakes the replay
321    /// ([`change_wakes_held`]).
322    pub fn record(&self, block_id: &str, state: Option<AgentState>, now_ms: u64) -> Option<AgentStatus> {
323        let mut by_block = self.by_block.lock();
324        let Some(state) = state else {
325            by_block.remove(block_id);
326            return None;
327        };
328        match by_block.get(block_id) {
329            Some(known) if known.state == state => Some(*known),
330            previous => {
331                let wake = previous.is_some_and(|known| change_wakes_held(known.state, state));
332                let status = AgentStatus { state, since_ms: now_ms };
333                by_block.insert(block_id.to_string(), status);
334                if wake {
335                    crate::backend::reactive::held_jekt_wake().notify_one();
336                }
337                Some(status)
338            }
339        }
340    }
341
342    /// Drop every block `keep` rejects (no longer listed).
343    pub fn retain(&self, keep: impl Fn(&str) -> bool) {
344        self.by_block.lock().retain(|block_id, _| keep(block_id));
345    }
346
347    #[cfg(test)]
348    pub fn len(&self) -> usize {
349        self.by_block.lock().len()
350    }
351}
352
353static TRACKER: LazyLock<SinceTracker> = LazyLock::new(SinceTracker::default);
354
355/// The tracker the live fleet source and the names route share.
356pub fn global_tracker() -> &'static SinceTracker {
357    &TRACKER
358}
359
360/// The agent on `block_id`: its state now and since when.
361pub fn agent_status_of_block(mstore: &Store, block_id: &str) -> Option<AgentStatus> {
362    TRACKER.record(block_id, current_state(mstore, block_id), agentmux_common::time::now_ms_u64())
363}
364
365#[cfg(any(test, feature = "test-support"))]
366pub mod test_support {
367    use std::any::Any;
368    use std::sync::Arc;
369
370    use crate::backend::blockcontroller::{BlockControllerRuntimeStatus, BlockInputUnion, Controller};
371    use crate::backend::obj::MetaMapType;
372
373    /// A registered controller that reports a fixed runtime status.
374    pub struct StubController {
375        pub block_id: String,
376        pub controller_type: String,
377        pub status: BlockControllerRuntimeStatus,
378        /// What started the turn in flight, for a test of something gated on it.
379        pub provenance: Option<crate::backend::blockcontroller::health::TurnProvenance>,
380        /// Its turn tracker, for a test of something that reads when it last wrote output.
381        pub tracker: Option<Arc<crate::backend::blockcontroller::health::TurnActivityTracker>>,
382        /// A request parked for the user's answer (`Controller::awaiting_user_reply`).
383        pub awaiting_reply: bool,
384    }
385
386    impl Controller for StubController {
387        fn start(&self, _: MetaMapType, _: Option<serde_json::Value>, _: bool) -> Result<(), String> {
388            Ok(())
389        }
390        fn stop(&self, _: bool, _: &str) -> Result<(), String> {
391            Ok(())
392        }
393        fn get_runtime_status(&self) -> BlockControllerRuntimeStatus {
394            self.status.clone()
395        }
396        fn send_input(&self, _: BlockInputUnion, _: Option<u64>) -> Result<(), String> {
397            Ok(())
398        }
399        fn controller_type(&self) -> &str {
400            &self.controller_type
401        }
402        fn block_id(&self) -> &str {
403            &self.block_id
404        }
405        fn turn_provenance(&self) -> Option<crate::backend::blockcontroller::health::TurnProvenance> {
406            self.provenance.clone()
407        }
408        fn turn_tracker(&self) -> Option<Arc<crate::backend::blockcontroller::health::TurnActivityTracker>> {
409            self.tracker.clone()
410        }
411        fn awaiting_user_reply(&self) -> bool {
412            self.awaiting_reply
413        }
414        fn as_any(&self) -> &dyn Any {
415            self
416        }
417    }
418
419    /// Register a stub on `block_id`; remove it with
420    /// `blockcontroller::delete_controller`.
421    pub fn register_stub(block_id: &str, controller_type: &str, process_status: &str, turn_active: bool) {
422        crate::backend::blockcontroller::register_controller(
423            block_id,
424            Arc::new(StubController {
425                block_id: block_id.to_string(),
426                controller_type: controller_type.to_string(),
427                status: BlockControllerRuntimeStatus {
428                    blockid: block_id.to_string(),
429                    shellprocstatus: process_status.to_string(),
430                    turn_active,
431                    ..Default::default()
432                },
433                provenance: None,
434                tracker: None,
435                awaiting_reply: false,
436            }),
437        );
438    }
439
440    /// [`register_stub`] on a running persistent agent in a turn that has a request parked for the user.
441    pub fn register_awaiting(block_id: &str) {
442        use crate::backend::blockcontroller::{BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING};
443        crate::backend::blockcontroller::register_controller(
444            block_id,
445            Arc::new(StubController {
446                block_id: block_id.to_string(),
447                controller_type: BLOCK_CONTROLLER_PERSISTENT.to_string(),
448                status: BlockControllerRuntimeStatus {
449                    blockid: block_id.to_string(),
450                    shellprocstatus: STATUS_RUNNING.to_string(),
451                    turn_active: true,
452                    ..Default::default()
453                },
454                provenance: None,
455                tracker: None,
456                awaiting_reply: true,
457            }),
458        );
459    }
460
461    /// [`register_stub`] on a running persistent agent between turns, whose last
462    /// output was `quiet_ms` ago.
463    pub fn register_quiet(block_id: &str, quiet_ms: u64) {
464        use crate::backend::blockcontroller::health::TurnActivityTracker;
465        use crate::backend::blockcontroller::{BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING};
466        let then = agentmux_common::time::now_ms_u64().saturating_sub(quiet_ms);
467        let tracker = TurnActivityTracker::with_clock(block_id.to_string(), Box::new(move || then));
468        tracker.note_output();
469        crate::backend::blockcontroller::register_controller(
470            block_id,
471            Arc::new(StubController {
472                block_id: block_id.to_string(),
473                controller_type: BLOCK_CONTROLLER_PERSISTENT.to_string(),
474                status: BlockControllerRuntimeStatus {
475                    blockid: block_id.to_string(),
476                    shellprocstatus: STATUS_RUNNING.to_string(),
477                    turn_active: false,
478                    ..Default::default()
479                },
480                provenance: None,
481                tracker: Some(Arc::new(tracker)),
482                awaiting_reply: false,
483            }),
484        );
485    }
486
487    /// [`register_stub`] on a running persistent agent whose turn in flight
488    /// has `provenance`.
489    pub fn register_turn(block_id: &str, provenance: crate::backend::blockcontroller::health::TurnProvenance) {
490        use crate::backend::blockcontroller::{BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING};
491        crate::backend::blockcontroller::register_controller(
492            block_id,
493            Arc::new(StubController {
494                block_id: block_id.to_string(),
495                controller_type: BLOCK_CONTROLLER_PERSISTENT.to_string(),
496                status: BlockControllerRuntimeStatus {
497                    blockid: block_id.to_string(),
498                    shellprocstatus: STATUS_RUNNING.to_string(),
499                    turn_active: true,
500                    ..Default::default()
501                },
502                provenance: Some(provenance),
503                tracker: None,
504                awaiting_reply: false,
505            }),
506        );
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513    use crate::backend::blockcontroller::{
514        BLOCK_CONTROLLER_ACP, BLOCK_CONTROLLER_APP_SERVER, BLOCK_CONTROLLER_CMD, BLOCK_CONTROLLER_MSP, BLOCK_CONTROLLER_PERSISTENT,
515        BLOCK_CONTROLLER_SHELL, BLOCK_CONTROLLER_SUBPROCESS, STATUS_DONE, STATUS_INIT,
516        STATUS_RUNNING,
517    };
518
519    fn inputs<'a>(controller_type: &'a str, turn_active: bool, process_status: &'a str) -> StateInputs<'a> {
520        StateInputs { controller_type, turn_active, process_status, exit_code: 0, awaiting_user: false, failure: None, now_ms: 1_000 }
521    }
522
523    #[test]
524    fn one_case_per_state() {
525        let p = BLOCK_CONTROLLER_PERSISTENT;
526        assert_eq!(decide(&inputs(p, true, STATUS_RUNNING)), Some(AgentState::Working));
527        assert_eq!(
528            decide(&StateInputs { awaiting_user: true, ..inputs(p, true, STATUS_RUNNING) }),
529            Some(AgentState::Waiting)
530        );
531        assert_eq!(decide(&inputs(p, false, STATUS_RUNNING)), Some(AgentState::Idle));
532        assert_eq!(decide(&inputs(p, false, STATUS_INIT)), Some(AgentState::Idle));
533        assert_eq!(decide(&inputs(p, false, STATUS_DONE)), Some(AgentState::Stopped));
534        assert_eq!(
535            decide(&StateInputs { exit_code: 1, ..inputs(p, false, STATUS_DONE) }),
536            Some(AgentState::Error)
537        );
538    }
539
540    #[test]
541    fn a_question_outside_a_turn_is_not_waiting() {
542        let left_over = StateInputs { awaiting_user: true, ..inputs(BLOCK_CONTROLLER_PERSISTENT, false, STATUS_RUNNING) };
543        assert_eq!(decide(&left_over), Some(AgentState::Idle));
544    }
545
546    #[test]
547    fn absent_turn_active_means_no_turn() {
548        // A turn that ended is an absent field: it deserializes to false.
549        let status: blockcontroller::BlockControllerRuntimeStatus =
550            serde_json::from_value(serde_json::json!({"blockid": "b", "shellprocstatus": "running"})).unwrap();
551        assert!(!status.turn_active);
552        assert_eq!(
553            decide(&inputs(BLOCK_CONTROLLER_PERSISTENT, status.turn_active, &status.shellprocstatus)),
554            Some(AgentState::Idle)
555        );
556    }
557
558    #[test]
559    fn terminal_panes_and_unknown_controllers_report_nothing() {
560        for t in [BLOCK_CONTROLLER_SHELL, BLOCK_CONTROLLER_CMD, "", "future"] {
561            assert_eq!(decide(&inputs(t, false, STATUS_RUNNING)), None, "{t}");
562            assert_eq!(decide(&inputs(t, true, STATUS_RUNNING)), None, "{t} mid-turn");
563        }
564    }
565
566    #[test]
567    fn every_agent_controller_reports_a_state() {
568        for t in [BLOCK_CONTROLLER_PERSISTENT, BLOCK_CONTROLLER_ACP, BLOCK_CONTROLLER_MSP, BLOCK_CONTROLLER_APP_SERVER, BLOCK_CONTROLLER_SUBPROCESS] {
569            assert_eq!(decide(&inputs(t, true, STATUS_RUNNING)), Some(AgentState::Working), "{t}");
570        }
571    }
572
573    #[test]
574    fn an_unknown_process_status_reports_nothing() {
575        assert_eq!(decide(&inputs(BLOCK_CONTROLLER_PERSISTENT, false, "")), None);
576        assert_eq!(decide(&inputs(BLOCK_CONTROLLER_PERSISTENT, false, "weird")), None);
577    }
578
579    #[test]
580    fn a_per_turn_process_exiting_cleanly_is_idle() {
581        let s = BLOCK_CONTROLLER_SUBPROCESS;
582        assert_eq!(decide(&inputs(s, false, STATUS_DONE)), Some(AgentState::Idle));
583        assert_eq!(decide(&StateInputs { exit_code: 2, ..inputs(s, false, STATUS_DONE) }), Some(AgentState::Error));
584    }
585
586    #[test]
587    fn states_serialize_lowercase() {
588        for s in [
589            AgentState::Working,
590            AgentState::Waiting,
591            AgentState::Idle,
592            AgentState::Stopped,
593            AgentState::Error,
594            AgentState::Limited,
595            AgentState::SignedOut,
596        ] {
597            assert_eq!(serde_json::to_value(s).unwrap(), serde_json::json!(s.as_str()));
598        }
599        assert_eq!(
600            serde_json::to_value(AgentStatus { state: AgentState::Working, since_ms: 7 }).unwrap(),
601            serde_json::json!({"state": "working", "since_ms": 7})
602        );
603    }
604
605    #[test]
606    fn since_is_kept_while_the_state_holds_and_reset_on_a_change() {
607        let t = SinceTracker::default();
608        let working = Some(AgentState::Working);
609        assert_eq!(t.record("b", working, 100).unwrap().since_ms, 100, "first seen");
610        assert_eq!(t.record("b", working, 200).unwrap().since_ms, 100, "unchanged");
611        assert_eq!(
612            t.record("b", Some(AgentState::Idle), 300),
613            Some(AgentStatus { state: AgentState::Idle, since_ms: 300 })
614        );
615        assert_eq!(t.record("b", working, 400).unwrap().since_ms, 400, "back to working starts again");
616    }
617
618    #[test]
619    fn only_a_change_that_can_free_a_held_message_wakes_the_replay() {
620        use AgentState::*;
621        for from in [Limited, SignedOut, Stopped, Error] {
622            for to in [Working, Waiting, Idle, Stopped, Error, Limited, SignedOut] {
623                assert_eq!(change_wakes_held(from, to), from != to, "{from:?} -> {to:?}");
624            }
625        }
626        assert!(change_wakes_held(Idle, Working) && change_wakes_held(Idle, Waiting), "a quiet session taking a turn");
627        for to in [Idle, Stopped, Error, Limited, SignedOut] {
628            assert!(!change_wakes_held(Idle, to), "Idle -> {to:?}");
629        }
630        for from in [Working, Waiting] {
631            for to in [Working, Waiting, Idle, Stopped, Error, Limited, SignedOut] {
632                assert!(!change_wakes_held(from, to), "{from:?} -> {to:?}: a running agent was already taking messages");
633            }
634        }
635    }
636
637    #[test]
638    fn no_state_forgets_the_block() {
639        let t = SinceTracker::default();
640        t.record("b", Some(AgentState::Idle), 100);
641        assert_eq!(t.record("b", None, 200), None);
642        assert_eq!(t.len(), 0);
643        assert_eq!(t.record("b", Some(AgentState::Idle), 300).unwrap().since_ms, 300, "not the old start");
644    }
645
646    #[test]
647    fn retain_drops_unlisted_blocks() {
648        let t = SinceTracker::default();
649        t.record("a", Some(AgentState::Idle), 1);
650        t.record("b", Some(AgentState::Idle), 1);
651        t.retain(|b| b == "a");
652        assert_eq!(t.len(), 1);
653        assert_eq!(t.record("a", Some(AgentState::Idle), 5).unwrap().since_ms, 1);
654    }
655
656    /// The full table: turn active × process state × failure class × reset
657    /// (spec §3.2, §10).
658    #[test]
659    fn a_limit_or_a_refused_sign_in_wins_over_the_process_but_not_over_a_turn() {
660        let now = 1_000;
661        let resets = [None, Some(now - 1), Some(now), Some(now + 1)];
662        let classes = [FailureClass::UsageLimit, FailureClass::Auth, FailureClass::RateLimited, FailureClass::Network];
663        for controller in [BLOCK_CONTROLLER_PERSISTENT, BLOCK_CONTROLLER_SUBPROCESS] {
664            for process in [STATUS_RUNNING, STATUS_INIT, STATUS_DONE] {
665                for exit_code in [0, 1] {
666                    let base = StateInputs { exit_code, now_ms: now, ..inputs(controller, false, process) };
667                    let plain = decide(&base);
668                    for class in classes {
669                        for reset in resets {
670                            let failed = StateInputs { failure: Some((class, reset)), ..base };
671                            let mid_turn = StateInputs { turn_active: true, ..failed };
672                            assert_eq!(decide(&mid_turn), Some(AgentState::Working), "a running turn wins: {class:?} {reset:?}");
673                            let expected = match (class, reset) {
674                                (FailureClass::UsageLimit, None) => Some(AgentState::Limited),
675                                (FailureClass::UsageLimit, Some(r)) if r > now => Some(AgentState::Limited),
676                                (FailureClass::Auth, _) => Some(AgentState::SignedOut),
677                                _ => plain,
678                            };
679                            assert_eq!(decide(&failed), expected, "{controller} {process} exit {exit_code} {class:?} {reset:?}");
680                        }
681                    }
682                }
683            }
684        }
685    }
686
687    #[test]
688    fn a_terminal_pane_with_a_failure_still_reports_nothing() {
689        let failed = StateInputs { failure: Some((FailureClass::UsageLimit, None)), ..inputs(BLOCK_CONTROLLER_SHELL, false, STATUS_RUNNING) };
690        assert_eq!(decide(&failed), None);
691    }
692
693    #[test]
694    fn signed_out_round_trips_with_its_underscore() {
695        assert_eq!(serde_json::to_value(AgentState::SignedOut).unwrap(), serde_json::json!("signed_out"));
696        assert_eq!(serde_json::from_value::<AgentState>(serde_json::json!("signed_out")).unwrap(), AgentState::SignedOut);
697        assert_eq!(serde_json::from_value::<AgentState>(serde_json::json!("limited")).unwrap(), AgentState::Limited);
698    }
699
700    #[test]
701    fn the_reason_reads_for_people() {
702        let u = |state, resets_at_ms| Unavailable {
703            state,
704            code: FailureClass::UsageLimit,
705            title: String::new(),
706            resets_at_ms,
707            since_ms: 0,
708            account_id: None,
709        };
710        assert_eq!(u(AgentState::Limited, None).reason(), "Out of quota");
711        assert!(u(AgentState::Limited, Some(1_792_886_400_000)).reason().starts_with("Out of quota until "));
712        assert_eq!(u(AgentState::SignedOut, None).reason(), "Needs sign-in");
713        let mut credits = u(AgentState::Limited, Some(1_792_886_400_000));
714        credits.title = crate::agents::failure::ROUTE_CREDITS_TITLE.to_string();
715        assert_eq!(credits.reason(), "Route out of credits", "a route's balance is not a plan's quota");
716    }
717
718    fn store() -> Store {
719        Store::open_in_memory().expect("in-memory store")
720    }
721
722    fn failure_meta(code: &str, resets_at_ms: Option<u64>) -> serde_json::Value {
723        let mut f = serde_json::json!({"code": code, "title": "Usage limit reached", "detail": "", "retryable": false});
724        if let Some(r) = resets_at_ms {
725            f["resetsAtMs"] = serde_json::json!(r);
726        }
727        f
728    }
729
730    #[test]
731    fn the_state_begins_when_the_failure_was_recorded_not_when_srv_first_saw_it() {
732        let store = store();
733        let now = agentmux_common::time::now_ms_u64();
734        let mut failure = failure_meta("usage_limit", Some(now + 60_000));
735        failure["atMs"] = serde_json::json!(now - 3_600_000);
736        let stored = insert_block(&store, &[(blockcontroller::core::META_LAST_FAILURE, failure)]);
737        test_support::register_stub(&stored, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, false);
738        let u = unavailable_of_block(&store, None, &stored, now).expect("limited");
739        assert_eq!(u.since_ms, now - 3_600_000, "a restart does not move it");
740        let old = insert_block(&store, &[(blockcontroller::core::META_LAST_FAILURE, failure_meta("usage_limit", Some(now + 60_000)))]);
741        test_support::register_stub(&old, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, false);
742        assert_eq!(unavailable_of_block(&store, None, &old, now).expect("limited").since_ms, now, "one stored before the field: first seen");
743    }
744
745    #[test]
746    fn a_stored_failure_carries_the_time_it_was_first_recorded_and_clearing_removes_it() {
747        let store = std::sync::Arc::new(store());
748        let limit = crate::agents::failure::classify(Some(1), None, "You've hit your weekly limit", None);
749        assert_eq!(limit.code, FailureClass::UsageLimit);
750        let persist = |id: &str, f: Option<&crate::agents::failure::AgentFailure>| {
751            blockcontroller::core::persist_last_failure(id, f, &Some(store.clone()), &None);
752        };
753        let stored = |id: &str| failure_of_block(&store.get::<Block>(id).unwrap().unwrap());
754
755        let fresh = insert_block(&store, &[]);
756        persist(&fresh, Some(&limit));
757        assert!(stored(&fresh).expect("stored").at_ms.is_some_and(|at| at > 0), "stamped when first recorded");
758
759        let mut earlier = failure_meta("usage_limit", None);
760        earlier["atMs"] = serde_json::json!(1_234);
761        let hit_again = insert_block(&store, &[(blockcontroller::core::META_LAST_FAILURE, earlier)]);
762        persist(&hit_again, Some(&limit));
763        assert_eq!(stored(&hit_again).unwrap().at_ms, Some(1_234), "the same failure hit again keeps the first time");
764        let transient = crate::agents::failure::classify(Some(1), None, "HTTP 429 rate_limit", None);
765        persist(&hit_again, Some(&transient));
766        assert_ne!(stored(&hit_again).unwrap().at_ms, Some(1_234), "another kind of failure starts over");
767
768        persist(&hit_again, None);
769        assert!(stored(&hit_again).is_none(), "a clean turn clears it");
770    }
771
772    #[test]
773    fn unavailable_of_block_reads_the_stored_failure_and_the_run_account() {
774        let store = store();
775        let now = agentmux_common::time::now_ms_u64();
776        let limited = insert_block(
777            &store,
778            &[
779                (blockcontroller::core::META_LAST_FAILURE, failure_meta("usage_limit", Some(now + 60_000))),
780                (RUN_ACCOUNT_META_KEY, serde_json::json!("acct-1")),
781            ],
782        );
783        test_support::register_stub(&limited, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, false);
784        let u = unavailable_of_block(&store, None, &limited, now).expect("limited");
785        assert_eq!((u.state, u.code, u.resets_at_ms), (AgentState::Limited, FailureClass::UsageLimit, Some(now + 60_000)));
786        assert_eq!(u.title, "Usage limit reached");
787        assert_eq!(u.account_id.as_deref(), Some("acct-1"));
788        let wire = serde_json::to_value(&u).unwrap();
789        assert!(wire.get("account_id").is_none(), "the account never goes on the wire");
790        assert_eq!(wire["state"], serde_json::json!("limited"));
791        assert_eq!(unavailable_of_block(&store, None, &limited, now + 60_001), None, "the reset passed");
792
793        // A pane from before `agent:run_account` gets its agent's link from the
794        // identity store, when one is given; without it, no account.
795        let identity = Store::open_in_memory().expect("in-memory identity store");
796        let signed_out = insert_block(
797            &store,
798            &[(blockcontroller::core::META_LAST_FAILURE, failure_meta("auth", None)), ("agentId", serde_json::json!("agent-x"))],
799        );
800        test_support::register_stub(&signed_out, BLOCK_CONTROLLER_PERSISTENT, STATUS_DONE, false);
801        let u = unavailable_of_block(&store, Some(&identity), &signed_out, now).expect("signed out");
802        assert_eq!(u.state, AgentState::SignedOut);
803        assert_eq!(u.account_id, None, "no link for agent-x");
804        assert_eq!(unavailable_of_block(&store, None, &signed_out, now).unwrap().account_id, None);
805
806        let transient = insert_block(&store, &[(blockcontroller::core::META_LAST_FAILURE, failure_meta("rate_limited", None))]);
807        test_support::register_stub(&transient, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, false);
808        assert_eq!(unavailable_of_block(&store, None, &transient, now), None, "a transient failure leaves it idle");
809        assert_eq!(current_state_at(&store, &transient, now), Some(AgentState::Idle));
810
811        for b in [&limited, &signed_out, &transient] {
812            blockcontroller::delete_controller(b);
813        }
814    }
815
816    fn insert_block(store: &Store, meta: &[(&str, serde_json::Value)]) -> String {
817        let mut block = crate::backend::obj::Block { oid: uuid::Uuid::new_v4().to_string(), ..Default::default() };
818        for (k, v) in meta {
819            block.meta.insert(k.to_string(), v.clone());
820        }
821        store.insert(&mut block).expect("insert block");
822        block.oid
823    }
824
825    #[test]
826    fn a_pane_stopped_at_sign_in_is_signed_out_though_it_has_no_controller() {
827        let store = store();
828        let at = 5_000_u64;
829        let blocked = insert_block(
830            &store,
831            &[
832                (LAUNCH_BLOCKED_META_KEY, serde_json::json!(LAUNCH_BLOCKED_SIGN_IN)),
833                (LAUNCH_BLOCKED_AT_META_KEY, serde_json::json!(at)),
834            ],
835        );
836        assert_eq!(current_state_at(&store, &blocked, 9_000), Some(AgentState::SignedOut));
837        let unavailable = unavailable_of_block(&store, None, &blocked, 9_000).expect("unavailable");
838        assert_eq!(unavailable.state, AgentState::SignedOut);
839        assert_eq!(unavailable.code, FailureClass::Auth);
840        assert_eq!(unavailable.since_ms, at);
841        assert_eq!(unavailable.reason(), "Needs sign-in");
842    }
843
844    #[test]
845    fn a_pane_with_no_controller_and_no_blocked_launch_has_no_state() {
846        let store = store();
847        let plain = insert_block(&store, &[]);
848        assert_eq!(current_state_at(&store, &plain, 9_000), None);
849        assert!(unavailable_of_block(&store, None, &plain, 9_000).is_none());
850        let other = insert_block(&store, &[(LAUNCH_BLOCKED_META_KEY, serde_json::json!("something_else"))]);
851        assert_eq!(current_state_at(&store, &other, 9_000), None);
852    }
853
854    #[test]
855    fn the_blocked_launch_flag_does_not_outlive_a_controller() {
856        let store = store();
857        let blocked = insert_block(&store, &[(LAUNCH_BLOCKED_META_KEY, serde_json::json!(LAUNCH_BLOCKED_SIGN_IN))]);
858        test_support::register_stub(&blocked, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, false);
859        assert_eq!(current_state_at(&store, &blocked, 9_000), Some(AgentState::Idle));
860        assert!(unavailable_of_block(&store, None, &blocked, 9_000).is_none());
861    }
862
863    #[test]
864    fn current_state_reads_the_controller_and_the_block() {
865        let store = store();
866        let asking = insert_block(&store, &[(META_AWAITING_USER, serde_json::json!(true))]);
867        test_support::register_stub(&asking, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, true);
868        assert_eq!(current_state(&store, &asking), Some(AgentState::Waiting));
869
870        let quiet = insert_block(&store, &[]);
871        test_support::register_stub(&quiet, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, false);
872        assert_eq!(current_state(&store, &quiet), Some(AgentState::Idle));
873
874        let terminal = insert_block(&store, &[]);
875        test_support::register_stub(&terminal, BLOCK_CONTROLLER_SHELL, STATUS_RUNNING, false);
876        assert_eq!(current_state(&store, &terminal), None);
877
878        let no_controller = insert_block(&store, &[]);
879        assert_eq!(current_state(&store, &no_controller), None);
880
881        let unreadable = format!("missing-{}", uuid::Uuid::new_v4());
882        test_support::register_stub(&unreadable, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, true);
883        assert_eq!(current_state(&store, &unreadable), None, "the block can't be read");
884
885        for b in [&asking, &quiet, &terminal, &unreadable] {
886            blockcontroller::delete_controller(b);
887        }
888    }
889
890    /// A request parked for the user is srv's own record: the agent reads `waiting` with no pane having
891    /// written its flag (a headless or parked agent), and not outside a turn.
892    #[test]
893    fn a_request_parked_for_the_user_is_waiting_with_no_pane_flag() {
894        let store = store();
895        let parked = insert_block(&store, &[]);
896        test_support::register_awaiting(&parked);
897        assert_eq!(current_state(&store, &parked), Some(AgentState::Waiting));
898        blockcontroller::delete_controller(&parked);
899    }
900
901    /// The rows `frontend/app/store/pane-tab-progress.test.ts` reads too: the pill's rule in the
902    /// frontend follows `decide()` only as long as both pass on the same table.
903    #[test]
904    fn decide_matches_the_shared_fixture() {
905        let fixture: serde_json::Value =
906            serde_json::from_str(include_str!("../../../../test/fixtures/agent-state-decide.json")).unwrap();
907        let rows = fixture["rows"].as_array().unwrap();
908        assert!(rows.len() >= 20, "the fixture lost rows");
909        for row in rows {
910            let name = row["name"].as_str().unwrap();
911            let failure = row["failure"].as_object().map(|f| {
912                let code: FailureClass = serde_json::from_value(f["code"].clone()).unwrap();
913                (code, f["resets_at_ms"].as_u64())
914            });
915            let got = decide(&StateInputs {
916                controller_type: row["controller_type"].as_str().unwrap(),
917                turn_active: row["turn_active"].as_bool().unwrap(),
918                process_status: row["process_status"].as_str().unwrap(),
919                exit_code: row["exit_code"].as_i64().unwrap() as i32,
920                awaiting_user: row["awaiting_user"].as_bool().unwrap(),
921                failure,
922                now_ms: row["now_ms"].as_u64().unwrap(),
923            });
924            let expected = row["expected"].as_str().unwrap();
925            assert_eq!(got.map_or("none", AgentState::as_str), expected, "{name}");
926        }
927    }
928}