Skip to main content

agentmux_srv/server/
controller_backstop.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A backstop for agent panes nobody connected to after a restart. A controller is registered when a
5//! window's pane mounts and resyncs its block, so an agent block in a layout that no open window shows
6//! (another workspace, a window that was not reopened) has no process and no controller until someone
7//! looks at it. Some seconds after startup, once the windows that are going to reconnect have asked for
8//! their panes, this registers the controller of each such block through the same resync a pane does.
9//!
10//! It runs after the boot refresh-token single-flight (`identity::token_warmup`) and goes through the
11//! same spawn gate: the controller's spawn takes the account's warm-up slot and the sign-in check, so
12//! panes on one account are started one after the other, not at once. A block whose account is signed out
13//! or out of quota is left alone (its turn would only fail), as is one the user stopped
14//! (`agent:desired` = stopped) and one a terminal view starts.
15
16use std::time::Duration;
17
18use crate::backend::blockcontroller;
19use crate::backend::obj;
20
21use super::AppState;
22
23/// How long after startup the backstop runs: windows reconnect and resync their own panes first (a few
24/// seconds after srv is up), and a pane one of them got to has a controller by now.
25const DELAY: Duration = Duration::from_secs(20);
26/// Between two registrations, so a layout of many agents does not start them in one burst.
27const GAP: Duration = Duration::from_millis(250);
28
29/// Run the backstop once, [`DELAY`] after startup.
30pub(crate) fn install(state: &AppState) {
31    let state = state.clone();
32    tokio::spawn(async move {
33        tokio::time::sleep(DELAY).await;
34        let n = run_once(&state).await;
35        if n > 0 {
36            tracing::info!(registered = n, "startup backstop: registered controllers for agent panes nobody connected to");
37        }
38    });
39}
40
41/// Why the backstop leaves an agent block in a tab alone (it has no controller), `None` when it starts it.
42fn left_alone(block: &obj::Block) -> Option<&'static str> {
43    if super::app_api::agent_attach::desired_of(block).as_deref() == Some(super::app_api::agent_attach::DESIRED_STOPPED) {
44        Some("it is recorded as stopped (agent:desired)")
45    } else if let Some(why) = starts_no_controller(block) {
46        Some(why)
47    } else if failed_on_its_account(block) {
48        Some("its account is signed out or out of quota")
49    } else {
50        None
51    }
52}
53
54/// The agent blocks in a tab that have no controller and should have one: `(block_id, tab_id)`. Each
55/// one it leaves alone is logged with the reason, so an agent a restart did not bring back says why.
56fn candidates(state: &AppState) -> Vec<(String, String)> {
57    let Ok(blocks) = super::app_api::agent_block::blocks_in_tabs_or_parked(&state.mstore) else {
58        return Vec::new();
59    };
60    blocks
61        .into_iter()
62        .filter_map(|(block, tab)| Some((block, tab?)))
63        .filter(|(block, _)| crate::sagas::park_agents::is_parkable(state, &block.oid) && blockcontroller::get_controller(&block.oid).is_none())
64        .filter(|(block, _)| match left_alone(block) {
65            Some(why) => {
66                tracing::info!(block_id = %block.oid, "startup backstop: not started: {why}");
67                false
68            }
69            None => true,
70        })
71        .map(|(block, tab)| (block.oid, tab))
72        .collect()
73}
74
75/// The pane's last turn failed because its account is signed out, or out of quota until a reset not yet
76/// reached: starting it would only fail again. (`agent_state::unavailable_of_block` reads this only from a
77/// pane with a controller, which these have not.)
78pub(super) fn failed_on_its_account(block: &obj::Block) -> bool {
79    use crate::agents::failure::FailureClass;
80    match crate::backend::agent_state::failure_of_block(block) {
81        Some(f) if f.code == FailureClass::Auth => true,
82        Some(f) if f.code == FailureClass::UsageLimit => f.resets_at_ms.is_none_or(|at| at > agentmux_common::time::now_ms_u64()),
83        _ => false,
84    }
85}
86
87/// Why a pane never gets a controller from the backstop or a restart: its harness was removed (its saved command would
88/// launch a CLI AgentMux no longer offers, and the pane says so when opened), or its term view starts it once attached.
89pub(super) fn starts_no_controller(block: &obj::Block) -> Option<&'static str> {
90    let provider = obj::meta_get_string(&block.meta, "agentProvider", "");
91    if crate::backend::providers::retired_reason(&provider).is_some() {
92        Some("its harness was removed")
93    } else if crate::backend::providers::get_provider(&provider).is_some_and(|p| p.controller_type == crate::backend::providers::ControllerType::Terminal) {
94        Some("a terminal view starts it")
95    } else {
96        None
97    }
98}
99
100/// Register the controllers [`candidates`] names. Returns how many.
101pub(crate) async fn run_once(state: &AppState) -> usize {
102    let mut registered = 0;
103    for (block_id, tab_id) in candidates(state) {
104        let Ok(Some(block)) = state.mstore.get::<obj::Block>(&block_id) else {
105            continue;
106        };
107        // A window may have resynced it while this ran.
108        if blockcontroller::get_controller(&block_id).is_some() {
109            continue;
110        }
111        let registry = state.mstore.shared_agent_registry();
112        match blockcontroller::resync_controller(
113            &block,
114            &tab_id,
115            None,
116            false,
117            true,
118            Some(state.broker.clone()),
119            Some(state.event_bus.clone()),
120            Some(state.mstore.clone()),
121            Some(state.filestore.clone()),
122            Some(state.id_store.clone()),
123            Some(state.identity_store.clone()),
124            registry,
125            state.boot_id.clone(),
126            &state.auth_key,
127            Some(state.config_watcher.clone()),
128        ) {
129            Ok(()) => registered += 1,
130            Err(e) => tracing::warn!(block_id = %block_id, "startup backstop: could not register its controller: {e}"),
131        }
132        tokio::time::sleep(GAP).await;
133    }
134    registered
135}
136
137#[cfg(test)]
138mod tests;