Skip to main content

agentmux_srv/server/
agent_runtime.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What state every created agent is in, with or without a pane: `agentruntime.list`, the
5//! `agentruntime:changed:<agent id>` event that carries a change, and `agent.start`
6//! (the always-available agents spec, §3.4 and §5).
7//!
8//! One source: the availability view (`availability_view`, which is what a message to the agent
9//! asks), mapped onto the states a viewer sees. An agent with no live pane is `stopped`; its row
10//! comes from its definition. A viewer (the Swarm) lists the rows once, then follows the event.
11//!
12//! A pane whose process ended keeps its `block_id` (found by the block's agent id) and reads `stopped`.
13//!
14//! Two things a viewer must not wait for until the always-available agents build lands: `starting`
15//! is never produced (a controller just created, with no process yet, reads as `idle`), and no event
16//! says an agent was deleted (`changed_rows` only forgets it), so a viewer relists on `agents:changed`.
17//!
18//! An agent wanted running with no process reads `idle`, not `stopped`: a persistent agent with no
19//! session on file starts on its first message, and an agent that has only ended its process is
20//! started by the next one. The failure states (limited, signed out, waiting) keep their place.
21//!
22//! An agent between turns whose Browser request is still open reads `waiting_on_user` (`browser_request`,
23//! with the pane the request waits in): its call answered "waiting" and it ended its turn, so nothing else
24//! says the person is asked. Only what a viewer sees: the availability a message asks is unchanged, so a
25//! message still starts a turn. The same fact is kept in the block's `term:awaiting_browser` for the rows
26//! that read block meta (the Swarm's).
27//!
28//! `desired` is the agent's own desired state when its block records one (`agent:desired`, set by an
29//! open, a start and a stop), and otherwise `running` while a process is alive and `stopped` if not.
30
31use std::collections::HashMap;
32use std::sync::Arc;
33
34use serde::{Deserialize, Serialize};
35
36use crate::backend::agent_availability::{Availability, WaitReason};
37use crate::backend::agent_status::{AgentStatus, Wanted};
38use crate::backend::obj::Block;
39use crate::server::app_api::agent_attach::{self, DESIRED_RUNNING, DESIRED_STOPPED};
40use crate::backend::rpc::engine::WshRpcEngine;
41use crate::backend::rpc_types::{COMMAND_AGENTRUNTIME_LIST, COMMAND_AGENT_START};
42use crate::backend::runtime_adapter::RuntimeKind;
43use crate::backend::storage::store::Store;
44
45use super::availability_view::{block_of_uid, status_of};
46use super::AppState;
47
48/// How often the runtime states are looked at for a change.
49const LOOK_EVERY: std::time::Duration = std::time::Duration::from_secs(2);
50
51pub use crate::backend::agent_runtime_state::{AgentDesiredState, AgentRuntime, AgentRuntimeState};
52
53/// `agent.start`.
54#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
55#[ts(export, export_to = "../../../frontend/types/rpc/")]
56pub struct CommandAgentStartData {
57    pub agent_id: String,
58}
59
60/// What a start gave: the block the agent runs in (the parked block, for an agent never opened).
61#[derive(Debug, Clone, Serialize, ts_rs::TS)]
62#[ts(export, export_to = "../../../frontend/types/rpc/")]
63pub struct AgentStartResult {
64    pub agent_id: String,
65    pub block_id: String,
66}
67
68/// Why an agent wanted running with no process reads `idle` (`state_of`'s reasons are codes too).
69pub const STARTS_ON_FIRST_MESSAGE: &str = "starts_on_first_message";
70
71/// What a viewer sees of an agent that the availability view calls stopped but its block says should
72/// run and a controller holds: it is waiting for a message to start it, which is `idle`. With no
73/// controller (the server restarted and nothing resumed it yet) it stays `stopped`: the Swarm lists
74/// only controller-backed agents as live, so an idle row there would be listed nowhere, with no Start.
75pub fn wanted_running_is_idle(
76    state: AgentRuntimeState,
77    detail: Option<String>,
78    desired: AgentDesiredState,
79    has_controller: bool,
80) -> (AgentRuntimeState, Option<String>) {
81    if state == AgentRuntimeState::Stopped && desired == AgentDesiredState::Running && has_controller {
82        (AgentRuntimeState::Idle, Some(STARTS_ON_FIRST_MESSAGE.to_string()))
83    } else {
84        (state, detail)
85    }
86}
87
88/// Why an agent between turns reads `waiting_on_user`: a Browser request of its is still open.
89pub const BROWSER_REQUEST: &str = "browser_request";
90
91/// Block meta, true while the agent's row waits on a Browser request (the Swarm row reads block meta).
92pub const META_AWAITING_BROWSER: &str = "term:awaiting_browser";
93
94/// An idle agent with an open Browser request is waiting for the person. Only an idle one: an agent that
95/// works is working (a message started another turn), and one that cannot work says that first.
96pub fn waiting_on_browser_request(
97    state: AgentRuntimeState,
98    detail: Option<String>,
99    request_open: bool,
100) -> (AgentRuntimeState, Option<String>) {
101    if request_open && state == AgentRuntimeState::Idle {
102        (AgentRuntimeState::WaitingOnUser, Some(BROWSER_REQUEST.to_string()))
103    } else {
104        (state, detail)
105    }
106}
107
108/// The pane where the open Browser request of the agent bound under `names` waits. A request carries the
109/// name its call used, which is one of the names the agent's block is bound under.
110fn request_pane(names: &[String]) -> Option<String> {
111    names.iter().find_map(|n| super::browser_waiting::pending_for(n))
112}
113
114fn waits_on_browser_request(row: &AgentRuntime) -> bool {
115    row.state == AgentRuntimeState::WaitingOnUser && row.detail.as_deref() == Some(BROWSER_REQUEST)
116}
117
118/// What to write to the block's [`META_AWAITING_BROWSER`] so it says what the row says, if it does not.
119fn browser_flag_fix(row: &AgentRuntime, flag_now: bool) -> Option<bool> {
120    let wanted = waits_on_browser_request(row);
121    (wanted != flag_now).then_some(wanted)
122}
123
124/// The state, its reason and its reset, from what the availability view says.
125pub fn state_of(av: &Availability) -> (AgentRuntimeState, Option<String>, Option<u64>) {
126    match *av {
127        Availability::NotRunning { exited_with_error: true } => (AgentRuntimeState::Error, None, None),
128        Availability::NotRunning { exited_with_error: false } => (AgentRuntimeState::Stopped, None, None),
129        // Nothing tracks the turns of a pane with no agent session in it: alive, and idle for a viewer.
130        Availability::Idle { .. } | Availability::Unknown => (AgentRuntimeState::Idle, None, None),
131        Availability::Running { waiting_on_user: true } => (AgentRuntimeState::WaitingOnUser, None, None),
132        Availability::Running { waiting_on_user: false } => (AgentRuntimeState::Working, None, None),
133        Availability::Limited { resets_at_ms, .. } => {
134            (AgentRuntimeState::Limited, Some(WaitReason::UsageLimit.as_str().to_string()), resets_at_ms)
135        }
136        Availability::SignedOut { .. } => {
137            (AgentRuntimeState::SignedOut, Some(WaitReason::NeedsLogin.as_str().to_string()), None)
138        }
139    }
140}
141
142/// A process is alive in every state but these two.
143pub fn desired_of(state: AgentRuntimeState) -> AgentDesiredState {
144    match state {
145        AgentRuntimeState::Stopped | AgentRuntimeState::Error => AgentDesiredState::Stopped,
146        _ => AgentDesiredState::Running,
147    }
148}
149
150/// What the agent's block says it should be doing, when it says: a stop sets `stopped`, an open or a
151/// start `running`. An agent whose block records nothing is wanted as its state says.
152pub fn desired_from(recorded: Option<&str>, state: AgentRuntimeState) -> AgentDesiredState {
153    match recorded {
154        Some(DESIRED_RUNNING) => AgentDesiredState::Running,
155        Some(DESIRED_STOPPED) => AgentDesiredState::Stopped,
156        _ => desired_of(state),
157    }
158}
159
160/// What a viewer sees of an agent from its status: the state, why, when a limit lifts and what is
161/// wanted. The one place the availability, the wanted state and the controller meet (`state_of`,
162/// `desired_from` and `wanted_running_is_idle` are its steps).
163pub fn runtime_of(status: &AgentStatus) -> (AgentRuntimeState, Option<String>, Option<u64>, AgentDesiredState) {
164    let (state, detail, resets_at) = state_of(&status.availability);
165    let recorded = match status.wanted {
166        Wanted::Running => Some(DESIRED_RUNNING),
167        Wanted::Stopped => Some(DESIRED_STOPPED),
168        Wanted::Unset => None,
169    };
170    let desired = desired_from(recorded, state);
171    let (state, detail) = wanted_running_is_idle(state, detail, desired, status.controller);
172    (state, detail, resets_at, desired)
173}
174
175/// Why a start would be refused, for an agent that is stopped and wanted running: its block says running,
176/// or a message waits for it. `why` is asked only then, because it reads every live agent.
177fn blocked_start(state: AgentRuntimeState, desired: AgentDesiredState, message_waits: bool, why: impl FnOnce() -> Option<String>) -> Option<String> {
178    (state == AgentRuntimeState::Stopped && (desired == AgentDesiredState::Running || message_waits)).then(why).flatten()
179}
180
181/// The runtime state of every created agent, as of `now_ms`. Blocking: reads the store.
182pub(crate) fn list(state: &AppState, now_ms: u64) -> Vec<AgentRuntime> {
183    let mstore = &state.mstore;
184    // The definitions, not the local instance rows: an agent defined on another channel of this
185    // host is in the shared registry before it has a row here, and `listagents` shows it too.
186    // A template is not an agent.
187    let defs = mstore.agent_def_list().unwrap_or_default();
188    let panes = pane_blocks_by_agent(mstore);
189    let net = crate::connectivity::status();
190    let waiting_for: std::collections::HashSet<String> = mstore.jekt_held_targets().unwrap_or_default().into_iter().collect();
191    let requests_open = super::browser_waiting::any_open();
192    let facts = super::live_facts::Ctx::new(state, now_ms, &super::live_facts::Select::default(), false);
193    defs.into_iter()
194        .filter(|d| d.is_seeded != 1 && d.user_hidden == 0)
195        .map(|d| {
196            // By the agent's UID, not its name: two agents can share a display name.
197            let live = block_of_uid(state.reactive_handler, &d.id);
198            // A pane whose process ended is no longer registered, and a headless agent's block is in no
199            // tab, but each is still the agent's block: a viewer needs its id to open or stop it, and
200            // it holds the desired state. The state is `stopped`.
201            let block_id = live.clone().or_else(|| panes.get(&d.id).cloned());
202            let block = block_id.as_deref().and_then(|b| mstore.get::<Block>(b).ok().flatten());
203            let color = block.as_ref().and_then(block_color);
204            let (runtime_state, detail, resets_at, desired) = runtime_of(&status_of(mstore, live.as_deref(), block.as_ref(), &net, now_ms));
205            let detail = detail.or_else(|| error_reason(runtime_state, block.as_ref()));
206            let blocked = blocked_start(runtime_state, desired, waiting_for.contains(&d.id), || super::agent_lifecycle::start_blocked(state, &d.id));
207            let waiting_in = (requests_open && runtime_state == AgentRuntimeState::Idle)
208                .then(|| live.as_deref().and_then(|b| request_pane(&state.reactive_handler.names_for_block(b))))
209                .flatten();
210            let (runtime_state, detail) = waiting_on_browser_request(runtime_state, detail, waiting_in.is_some());
211            let runtime = runtime_of_agent(block.as_ref(), &d.agent_type);
212            let model = super::live_facts::model_of(
213                &facts,
214                &super::live_facts::Agent {
215                    uid: &d.id,
216                    name: &d.name,
217                    provider: &d.provider,
218                    block_id: block_id.as_deref(),
219                    state: if matches!(runtime_state, AgentRuntimeState::Stopped | AgentRuntimeState::Error) { "stopped" } else { "idle" },
220                    container: runtime == RuntimeKind::Container,
221                },
222                block.as_ref(),
223            );
224            AgentRuntime {
225                runtime,
226                model_id: model.id,
227                model_label: model.label,
228                model_source: serde_json::to_value(model.source).ok().and_then(|v| v.as_str().map(str::to_string)),
229                effort: model.effort,
230                pending_switch: model.pending_label,
231                definition_model_label: model.definition_label,
232                quiet_since_ms: crate::backend::quiet_watch::quiet_view(&d.id).map(|q| q.since_ms),
233                handover: crate::backend::agent_runtime_state::handover_summary(mstore, &d.id),
234                blocked,
235                color,
236                agent_id: d.id,
237                state: runtime_state,
238                detail,
239                resets_at,
240                block_id,
241                waiting_in,
242                desired,
243                name: d.name,
244                provider: d.provider,
245                icon: d.icon,
246            }
247        })
248        .collect()
249}
250
251/// Why an agent in `error` is, when its last run's failure was classified (`rate_limited`, `network`...):
252/// whether it is worth another try is not in `error` itself (#2617).
253pub fn error_reason(state: AgentRuntimeState, block: Option<&Block>) -> Option<String> {
254    (state == AgentRuntimeState::Error).then(|| block.and_then(|b| crate::backend::worker_failure_note::code_name(&b.meta))).flatten()
255}
256
257/// Where an agent runs: its pane's mode is the current truth; a definition with no pane says it by its
258/// type, so a stopped agent has an answer too.
259fn runtime_of_agent(block: Option<&Block>, agent_type: &str) -> RuntimeKind {
260    block.map_or_else(|| RuntimeKind::of_agent_type(agent_type), |b| RuntimeKind::of_block_meta(&b.meta))
261}
262
263/// The agent a block belongs to, by the id its meta carries.
264fn agent_of_block(block: &Block) -> Option<String> {
265    if crate::backend::obj::is_history_reader(&block.meta) {
266        return None; // the reader of its transcript, not its pane
267    }
268    ["agentId", "agent:id"]
269        .iter()
270        .map(|k| crate::backend::obj::meta_get_string(&block.meta, k, ""))
271        .find(|v| !v.is_empty())
272}
273
274/// The block of each agent that has one, by agent id: the one in a pane (the first by id when it has
275/// several), else the one parked in no tab, which holds the agent's desired state while it has no
276/// process. One pass over the blocks for the whole list.
277pub(super) fn pane_blocks_by_agent(mstore: &Store) -> HashMap<String, String> {
278    let blocks = mstore.get_all::<Block>().unwrap_or_default();
279    let agent_blocks: Vec<String> = blocks.iter().filter(|b| agent_of_block(b).is_some()).map(|b| b.oid.clone()).collect();
280    let mut by_agent: HashMap<String, String> = HashMap::new();
281    for pane in super::app_api::agent_io::open_agent_panes(mstore, &agent_blocks) {
282        by_agent.entry(pane.agent_id).or_insert(pane.block_id);
283    }
284    for block in &blocks {
285        let parked = crate::backend::obj::meta_get_bool(&block.meta, crate::persist_subscriber::parked::PARKED_META_KEY, false);
286        if let (true, Some(agent)) = (parked, agent_of_block(block)) {
287            by_agent.entry(agent).or_insert_with(|| block.oid.clone());
288        }
289    }
290    by_agent
291}
292
293/// The colour the agent's pane shows (its border colour, `frame:activebordercolor`, set when it opens).
294fn block_color(block: &Block) -> Option<String> {
295    let color = crate::backend::obj::meta_get_string(&block.meta, "frame:activebordercolor", "");
296    (!color.is_empty()).then_some(color)
297}
298
299/// The rows that differ from what was last sent, and what to remember now: an agent that is gone
300/// is forgotten.
301pub fn changed_rows(last: &mut HashMap<String, AgentRuntime>, now: Vec<AgentRuntime>) -> Vec<AgentRuntime> {
302    let still: std::collections::HashSet<&str> = now.iter().map(|r| r.agent_id.as_str()).collect();
303    last.retain(|id, _| still.contains(id.as_str()));
304    let mut changed = Vec::new();
305    for row in now {
306        if last.get(&row.agent_id) != Some(&row) {
307            last.insert(row.agent_id.clone(), row.clone());
308            changed.push(row);
309        }
310    }
311    changed
312}
313
314/// Whether `row` just began waiting on the user: it is waiting now and was not at the last look. An
315/// agent with no block has nothing to notify about, and a Browser request was announced by its own
316/// banner, on the Browser pane, under the person's setting for it.
317fn begins_waiting(before: Option<AgentRuntimeState>, row: &AgentRuntime) -> bool {
318    row.state == AgentRuntimeState::WaitingOnUser
319        && row.block_id.is_some()
320        && before != Some(AgentRuntimeState::WaitingOnUser)
321        && !waits_on_browser_request(row)
322}
323
324/// The block an agent was waiting in, when it just stopped waiting (answered, cancelled or ended): the
325/// block of the last look, which the row may no longer name.
326fn ends_waiting(before: Option<&(AgentRuntimeState, Option<String>)>, row: &AgentRuntime) -> Option<String> {
327    match before {
328        Some((AgentRuntimeState::WaitingOnUser, Some(block_id))) if row.state != AgentRuntimeState::WaitingOnUser => Some(block_id.clone()),
329        _ => None,
330    }
331}
332
333/// Take down the notice [`notify_waiting`] raised, so a wait that ended before it showed does not show
334/// a stale question, and the next wait on the block is a new notice and not coalesced into the old.
335fn resolve_waiting(state: &AppState, block_id: &str) {
336    if let Some(router) = crate::backend::notify::router::get(&state.broker) {
337        router.resolve_nonblocking(block_id, crate::backend::notify::policy::Family::Input);
338    }
339}
340
341/// "Waiting on you" as an OS notification, for an agent no pane need show (a headless or parked one):
342/// the router coalesces it with the question's own report for the same block, so it adds nothing
343/// when the question already notified, and covers a wait that had no such report (an App Server
344/// approval).
345fn notify_waiting(state: &AppState, row: &AgentRuntime) {
346    let (Some(block_id), Some(router)) = (row.block_id.as_deref(), crate::backend::notify::router::get(&state.broker)) else {
347        return;
348    };
349    router.input_waiting_nonblocking(block_id, None, 0);
350}
351
352/// The blocks of `rows` whose [`META_AWAITING_BROWSER`] does not say what the row says, with what it
353/// should say. Blocking: reads the store.
354fn browser_flag_fixes(mstore: &Store, rows: &[AgentRuntime]) -> Vec<(String, bool)> {
355    rows.iter()
356        .filter_map(|row| {
357            let block_id = row.block_id.as_deref()?;
358            let block = mstore.get::<Block>(block_id).ok().flatten()?;
359            let flag_now = crate::backend::obj::meta_get_bool(&block.meta, META_AWAITING_BROWSER, false);
360            browser_flag_fix(row, flag_now).map(|on| (block_id.to_string(), on))
361        })
362        .collect()
363}
364
365/// Keep each changed row's block meta saying whether it waits on a Browser request. Every row is a change
366/// at the first look after a start, so a flag a stopped srv left behind is taken down then.
367async fn mirror_browser_wait(state: &AppState, changed: &[AgentRuntime]) {
368    let (looked, rows) = (state.clone(), changed.to_vec());
369    let Ok(fixes) = tokio::task::spawn_blocking(move || browser_flag_fixes(&looked.mstore, &rows)).await else { return };
370    for (block_id, on) in fixes {
371        let flag = if on { serde_json::Value::Bool(true) } else { serde_json::Value::Null };
372        let meta = serde_json::json!({ META_AWAITING_BROWSER: flag });
373        if let Err(e) = super::agent_status_handlers::write_block_meta(state, &block_id, meta).await {
374            tracing::warn!(block_id = %block_id, error = %e, "[agent-runtime] couldn't write the block's Browser-request flag; its Swarm row may be out of date");
375        }
376    }
377}
378
379/// Look at the states on a short interval and publish each change to `agentruntime:changed:<id>`.
380pub(crate) fn spawn(state: AppState) {
381    super::registry_reconcile::spawn(state.clone()); // a running agent missing from the registry is put back
382    tokio::spawn(async move {
383        let mut last: HashMap<String, AgentRuntime> = HashMap::new();
384        loop {
385            let looked = state.clone();
386            if let Ok(rows) = tokio::task::spawn_blocking(move || list(&looked, agentmux_common::time::now_ms_u64())).await {
387                let before: HashMap<String, (AgentRuntimeState, Option<String>)> =
388                    last.iter().map(|(id, r)| (id.clone(), (r.state, r.block_id.clone()))).collect();
389                let changed = changed_rows(&mut last, rows);
390                mirror_browser_wait(&state, &changed).await;
391                for row in changed {
392                    let was = before.get(&row.agent_id);
393                    if begins_waiting(was.map(|w| w.0), &row) {
394                        notify_waiting(&state, &row);
395                    }
396                    if let Some(block_id) = ends_waiting(was, &row) {
397                        resolve_waiting(&state, &block_id);
398                    }
399                    state.broker.publish_event_for::<crate::backend::mps_events::AgentRuntimeChanged>(
400                        &row.agent_id,
401                        &row,
402                        vec![],
403                        0,
404                    );
405                }
406            }
407            tokio::time::sleep(LOOK_EVERY).await;
408        }
409    });
410}
411
412pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
413    // No argument: `Value` takes whatever the caller sends.
414    let list_state = state.clone();
415    engine.register_typed(COMMAND_AGENTRUNTIME_LIST, move |_data: serde_json::Value, _ctx| {
416        let state = list_state.clone();
417        async move {
418            tokio::task::spawn_blocking(move || list(&state, agentmux_common::time::now_ms_u64()))
419                .await
420                .map_err(|e| format!("agentruntime.list: {e}"))
421        }
422    });
423    // Not behind `agents:always_available`: a start is an explicit action and changes nothing for
424    // anyone who does not call it; only closing a pane parking its block depends on the setting.
425    let start_state = state.clone();
426    engine.register_typed(COMMAND_AGENT_START, move |cmd: CommandAgentStartData, _ctx| {
427        let state = start_state.clone();
428        async move {
429            let block_id = agent_attach::start_agent(&state, &cmd.agent_id)
430                .await
431                .map_err(|e| format!("agent.start: {e}"))?;
432            Ok::<AgentStartResult, String>(AgentStartResult { agent_id: cmd.agent_id, block_id })
433        }
434    });
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440
441    #[test]
442    fn a_stopped_agent_something_wants_running_says_why_it_cannot_start_and_no_other_is_asked() {
443        use AgentDesiredState::{Running, Stopped};
444        use AgentRuntimeState::{Idle, Stopped as Down};
445        let why = || Some("capacity: memory commit is at 89%".to_string());
446        assert_eq!(blocked_start(Down, Stopped, true, why).as_deref(), Some("capacity: memory commit is at 89%"), "a message waits for it");
447        assert_eq!(blocked_start(Down, Running, false, why).as_deref(), Some("capacity: memory commit is at 89%"), "its block says running");
448        let asked = std::cell::Cell::new(0);
449        let counted = || {
450            asked.set(asked.get() + 1);
451            Some("x".to_string())
452        };
453        assert_eq!(blocked_start(Down, Stopped, false, counted), None, "stopped on purpose, nothing waits");
454        assert_eq!(blocked_start(Idle, Running, true, counted), None, "it runs");
455        assert_eq!(asked.get(), 0, "the check reads every live agent: only a wanted, stopped one asks");
456        assert_eq!(blocked_start(Down, Running, false, || None), None, "nothing refuses the start");
457    }
458
459    fn row(id: &str, state: AgentRuntimeState) -> AgentRuntime {
460        AgentRuntime {
461            agent_id: id.into(),
462            state,
463            detail: None,
464            resets_at: None,
465            block_id: None,
466            waiting_in: None,
467            desired: desired_of(state),
468            name: id.into(),
469            provider: "claude".into(),
470            icon: String::new(),
471            color: None,
472            blocked: None,
473            runtime: RuntimeKind::Host,
474            model_id: None,
475            model_label: None,
476            model_source: None,
477            effort: None,
478            pending_switch: None,
479            definition_model_label: None,
480            quiet_since_ms: None,
481            handover: None,
482        }
483    }
484
485    #[test]
486    fn an_idle_agent_with_an_open_browser_request_waits_for_the_person() {
487        use AgentRuntimeState as S;
488        assert_eq!(waiting_on_browser_request(S::Idle, None, true), (S::WaitingOnUser, Some(BROWSER_REQUEST.to_string())));
489        assert_eq!(
490            waiting_on_browser_request(S::Idle, Some(STARTS_ON_FIRST_MESSAGE.to_string()), true),
491            (S::WaitingOnUser, Some(BROWSER_REQUEST.to_string())),
492            "an agent whose process ended is still asked for"
493        );
494        assert_eq!(waiting_on_browser_request(S::Idle, None, false), (S::Idle, None), "no request, no change");
495        // A message started another turn: it works. And an agent that cannot work says that first.
496        for state in [S::Working, S::WaitingOnUser, S::Limited, S::SignedOut, S::Stopped, S::Error, S::Starting] {
497            let why = Some("usage_limit".to_string());
498            assert_eq!(waiting_on_browser_request(state, why.clone(), true), (state, why), "{state:?} keeps its place");
499        }
500    }
501
502    #[test]
503    fn the_request_is_found_under_any_name_the_agents_block_is_bound_under() {
504        let id = uuid::Uuid::new_v4().to_string();
505        crate::server::browser_waiting::open(&id, "rt-asker", "pane-rt-asker", "approval", "Click Send", std::time::Duration::from_secs(600));
506        assert!(crate::server::browser_waiting::any_open());
507        // The block is bound under its display name and its slug; the call carried the slug, in another case.
508        let names = ["Rt Asker".to_string(), "RT-ASKER".to_string()];
509        assert_eq!(request_pane(&names).as_deref(), Some("pane-rt-asker"));
510        assert_eq!(request_pane(&["someone-else".to_string()]), None);
511        assert!(crate::server::browser_waiting::finish(&id, crate::server::browser_waiting::State::Declined));
512        assert_eq!(request_pane(&names), None, "an answered request is over");
513    }
514
515    #[test]
516    fn a_browser_request_is_not_announced_a_second_time_and_its_flag_follows_the_row() {
517        use AgentRuntimeState as S;
518        let mut asks = row("a", S::WaitingOnUser);
519        asks.block_id = Some("block-a".into());
520        assert!(begins_waiting(Some(S::Working), &asks), "a question in a turn is announced");
521        asks.detail = Some(BROWSER_REQUEST.into());
522        assert!(!begins_waiting(Some(S::Idle), &asks), "its banner on the Browser pane announced it");
523        assert_eq!(ends_waiting(Some(&(S::WaitingOnUser, Some("block-a".into()))), &row("a", S::Idle)).as_deref(), Some("block-a"));
524        assert_eq!(browser_flag_fix(&asks, false), Some(true));
525        assert_eq!(browser_flag_fix(&asks, true), None, "already says so: nothing is written");
526        assert_eq!(browser_flag_fix(&row("a", S::Idle), true), Some(false), "answered, or left by a stopped srv");
527        assert_eq!(browser_flag_fix(&row("a", S::WaitingOnUser), true), Some(false), "a question in a turn is not a Browser request");
528        assert_eq!(browser_flag_fix(&row("a", S::Working), false), None);
529    }
530
531    #[test]
532    fn an_agent_says_where_it_runs_from_its_pane_else_from_its_definition() {
533        let pane = |mode: &str| {
534            let mut meta = crate::backend::obj::MetaMapType::new();
535            meta.insert("agentMode".to_string(), serde_json::json!(mode));
536            Block { meta, ..Default::default() }
537        };
538        assert_eq!(runtime_of_agent(None, "container"), RuntimeKind::Container, "a stopped agent with no pane says it by its type");
539        assert_eq!(runtime_of_agent(None, "host"), RuntimeKind::Host);
540        assert_eq!(runtime_of_agent(Some(&pane("container")), "host"), RuntimeKind::Container, "the pane wins");
541        assert_eq!(runtime_of_agent(Some(&pane("host")), "container"), RuntimeKind::Host, "the pane wins");
542        assert_eq!(runtime_of_agent(None, "something-new"), RuntimeKind::Host, "unknown is the host");
543        assert_eq!(serde_json::to_value(row("a", AgentRuntimeState::Idle)).unwrap()["runtime"], "host");
544    }
545
546    #[test]
547    fn the_history_reader_is_not_the_agents_pane() {
548        let mut meta = crate::backend::obj::MetaMapType::new();
549        meta.insert("agentId".to_string(), serde_json::json!("ann"));
550        let mut block = Block { meta, ..Default::default() };
551        assert_eq!(agent_of_block(&block).as_deref(), Some("ann"));
552        block.meta.insert(crate::backend::obj::HISTORY_READER_META_KEY.to_string(), serde_json::json!("ann"));
553        assert_eq!(agent_of_block(&block), None, "a reader carries the id but is not the pane");
554    }
555
556    /// An agent in `error` says why when its last failure was classified, so a viewer can tell a rate limit
557    /// from a crash (#2617); any other state, or an unclassified error, adds no reason.
558    #[test]
559    fn an_error_state_carries_the_class_of_its_last_failure() {
560        let mut meta = crate::backend::obj::MetaMapType::new();
561        meta.insert("agent:last_failure".to_string(), serde_json::json!({ "code": "rate_limited", "title": "x", "retryable": true }));
562        let block = Block { meta, ..Default::default() };
563        assert_eq!(error_reason(AgentRuntimeState::Error, Some(&block)).as_deref(), Some("rate_limited"));
564        assert_eq!(error_reason(AgentRuntimeState::Idle, Some(&block)), None, "only `error` takes it");
565        assert_eq!(error_reason(AgentRuntimeState::Error, Some(&Block::default())), None, "nothing classified");
566        assert_eq!(error_reason(AgentRuntimeState::Error, None), None);
567    }
568
569    #[test]
570    fn every_availability_has_a_state_a_viewer_sees() {
571        let s = |av| state_of(&av).0;
572        assert_eq!(s(Availability::NotRunning { exited_with_error: false }), AgentRuntimeState::Stopped);
573        assert_eq!(s(Availability::NotRunning { exited_with_error: true }), AgentRuntimeState::Error);
574        assert_eq!(s(Availability::Idle { quiet_for_ms: None }), AgentRuntimeState::Idle);
575        assert_eq!(s(Availability::Running { waiting_on_user: false }), AgentRuntimeState::Working);
576        assert_eq!(s(Availability::Running { waiting_on_user: true }), AgentRuntimeState::WaitingOnUser);
577        assert_eq!(s(Availability::SignedOut { since_ms: 1 }), AgentRuntimeState::SignedOut);
578        assert_eq!(s(Availability::Unknown), AgentRuntimeState::Idle);
579    }
580
581    #[test]
582    fn the_blocks_own_desired_state_wins_over_the_state_it_is_in() {
583        use AgentRuntimeState as S;
584        // Stopped by the user while the process is still ending, or left wanted after a crash.
585        assert_eq!(desired_from(Some("stopped"), S::Working), AgentDesiredState::Stopped);
586        assert_eq!(desired_from(Some("running"), S::Stopped), AgentDesiredState::Running);
587        assert_eq!(desired_from(Some("running"), S::Error), AgentDesiredState::Running);
588        // Nothing recorded, or something this build does not know: as the state says.
589        assert_eq!(desired_from(None, S::Idle), AgentDesiredState::Running);
590        assert_eq!(desired_from(None, S::Stopped), AgentDesiredState::Stopped);
591        assert_eq!(desired_from(Some("later"), S::Stopped), AgentDesiredState::Stopped);
592    }
593
594    /// The whole path: a registered agent between turns, a request opened under its slug, the row, what
595    /// the block's flag should say, and both back once the request is answered.
596    #[tokio::test]
597    async fn an_open_browser_request_shows_in_the_agents_row_and_its_blocks_flag_until_it_is_answered() {
598        let state = crate::server::tests::test_state();
599        let uid = uuid::Uuid::new_v4().to_string();
600        let slug = format!("rt-web-{}", &uid[..8]);
601        let mut def: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
602            "id": uid, "slug": slug, "name": "Rt Web", "icon": "robot", "provider": "claude",
603            "description": "", "created_at": 1,
604        }))
605        .unwrap();
606        state.mstore.agent_def_insert(&mut def).unwrap();
607        let mut meta = crate::backend::obj::MetaMapType::new();
608        meta.insert("agentId".to_string(), serde_json::json!(uid));
609        let mut block = Block { oid: uuid::Uuid::new_v4().to_string(), meta, ..Default::default() };
610        state.mstore.insert(&mut block).unwrap();
611        state.reactive_handler.register_agent_full(&slug, &block.oid, None, 1, Some(&slug), Some(&uid), "test.runtime").unwrap();
612        let row_now = |state: &AppState| list(state, 10_000).into_iter().find(|r| r.agent_id == uid).expect("the agent is listed");
613        // What `mirror_browser_wait` writes through the object service, here straight to the store.
614        let write = |state: &AppState, fixes: Vec<(String, bool)>| {
615            for (block_id, on) in fixes {
616                let mut b = state.mstore.get::<Block>(&block_id).unwrap().unwrap();
617                if on {
618                    b.meta.insert(META_AWAITING_BROWSER.to_string(), serde_json::json!(true));
619                } else {
620                    b.meta.remove(META_AWAITING_BROWSER);
621                }
622                state.mstore.update(&mut b).unwrap();
623            }
624        };
625
626        let before = row_now(&state);
627        assert_eq!((before.state, before.detail.as_deref(), before.waiting_in.as_deref()), (AgentRuntimeState::Idle, None, None));
628
629        // Its Browser call answered "waiting" and it ended its turn. The call carried its slug.
630        let request = uuid::Uuid::new_v4().to_string();
631        let pane = format!("web-{request}");
632        crate::server::browser_waiting::open(&request, &slug.to_uppercase(), &pane, "approval", "Click Send", std::time::Duration::from_secs(600));
633        let asks = row_now(&state);
634        assert_eq!(asks.state, AgentRuntimeState::WaitingOnUser);
635        assert_eq!((asks.detail.as_deref(), asks.waiting_in.as_deref()), (Some(BROWSER_REQUEST), Some(pane.as_str())));
636        assert_eq!(asks.desired, AgentDesiredState::Running);
637        let fixes = browser_flag_fixes(&state.mstore, std::slice::from_ref(&asks));
638        assert_eq!(fixes, vec![(block.oid.clone(), true)], "the Swarm row reads the block's meta");
639        write(&state, fixes);
640        assert_eq!(browser_flag_fixes(&state.mstore, std::slice::from_ref(&asks)), vec![], "it says so now");
641
642        // Answered: idle again, and the flag comes down with the row.
643        assert!(crate::server::browser_waiting::finish(&request, crate::server::browser_waiting::State::Declined));
644        let after = row_now(&state);
645        assert_eq!((after.state, after.detail.as_deref(), after.waiting_in.as_deref()), (AgentRuntimeState::Idle, None, None));
646        let fixes = browser_flag_fixes(&state.mstore, std::slice::from_ref(&after));
647        assert_eq!(fixes, vec![(block.oid.clone(), false)]);
648        write(&state, fixes);
649        assert_eq!(browser_flag_fixes(&state.mstore, std::slice::from_ref(&after)), vec![]);
650    }
651
652    /// A pane that follows its agent's row shows where the agent went: the row carries the hand-over mark while it stands and
653    /// not after it is cleared.
654    #[tokio::test]
655    async fn the_row_says_where_a_moved_agent_went_until_it_is_brought_back() {
656        let state = crate::server::tests::test_state();
657        let shared = tempfile::tempdir().unwrap();
658        state.mstore.set_def_registry(Arc::new(crate::registry::DefinitionStore::open(shared.path().join("definitions")).unwrap()));
659        let mut def: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
660            "id": "def-rt-moved", "slug": "rt-moved", "name": "Rt Moved", "icon": "robot", "provider": "claude",
661            "description": "", "created_at": 1,
662        }))
663        .unwrap();
664        state.mstore.agent_def_insert(&mut def).unwrap();
665        let handover_of = |state: &AppState| list(state, 10_000).into_iter().find(|r| r.agent_id == "def-rt-moved").expect("the agent is listed").handover;
666        assert_eq!(handover_of(&state), None, "an agent that is here has no mark");
667
668        let mark = crate::registry::Handover { state: crate::registry::Handover::MOVED.into(), to: "Annex".into(), at_ms: 4242, manifest_hash: "h".into() };
669        state.mstore.agent_handover_set("def-rt-moved", Some(&mark)).unwrap();
670        let there = handover_of(&state).expect("the row carries the mark");
671        assert_eq!((there.state.as_str(), there.to.as_str(), there.at_ms), ("moved", "Annex", 4242));
672
673        state.mstore.agent_handover_set("def-rt-moved", None).unwrap();
674        assert_eq!(handover_of(&state), None, "brought back: the row says it is here");
675    }
676
677    /// A headless agent whose process ended without a stop: its parked block is in no tab, still records
678    /// that it should run, and is the block a viewer opens.
679    #[tokio::test]
680    async fn a_parked_block_with_no_controller_keeps_its_agent_wanted_running_but_stopped() {
681        let state = crate::server::tests::test_state();
682        let mut def: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
683            "id": "def-rt-2", "slug": "rt-two", "name": "Rt Two", "icon": "robot", "provider": "claude",
684            "description": "", "created_at": 1,
685        }))
686        .unwrap();
687        state.mstore.agent_def_insert(&mut def).unwrap();
688        let mut meta = crate::backend::obj::MetaMapType::new();
689        meta.insert("agentId".to_string(), serde_json::json!("def-rt-2"));
690        meta.insert(crate::persist_subscriber::parked::PARKED_META_KEY.to_string(), serde_json::json!(true));
691        meta.insert(agent_attach::META_DESIRED.to_string(), serde_json::json!("running"));
692        let mut block = Block { oid: uuid::Uuid::new_v4().to_string(), meta, ..Default::default() };
693        state.mstore.insert(&mut block).unwrap();
694        let rows = list(&state, 10_000);
695        let one = rows.iter().find(|r| r.agent_id == "def-rt-2").expect("the agent is listed");
696        // No controller holds it (a restart): stopped, still wanted running, so the Swarm offers Start.
697        assert_eq!((one.state, one.desired), (AgentRuntimeState::Stopped, AgentDesiredState::Running));
698        assert!(one.detail.is_none());
699        assert_eq!(one.block_id.as_deref(), Some(block.oid.as_str()));
700    }
701
702    #[test]
703    fn an_agent_wanted_running_with_no_process_is_idle_and_says_it_starts_on_its_first_message() {
704        use AgentRuntimeState as S;
705        let (state, detail) = wanted_running_is_idle(S::Stopped, None, AgentDesiredState::Running, true);
706        assert_eq!((state, detail.as_deref()), (S::Idle, Some("starts_on_first_message")));
707        // Stopped on purpose, or with nothing said (a block from before the feature): as it was.
708        assert_eq!(wanted_running_is_idle(S::Stopped, None, AgentDesiredState::Stopped, true), (S::Stopped, None));
709        // Wanted running with no controller (after a restart): still stopped, so the Swarm lists it with Start.
710        assert_eq!(wanted_running_is_idle(S::Stopped, None, AgentDesiredState::Running, false), (S::Stopped, None));
711        // The other states keep their place, and their reason.
712        for kept in [S::Error, S::Limited, S::SignedOut, S::WaitingOnUser, S::Working, S::Idle] {
713            let (state, detail) = wanted_running_is_idle(kept, Some("why".into()), AgentDesiredState::Running, true);
714            assert_eq!((state, detail.as_deref()), (kept, Some("why")));
715        }
716    }
717
718    #[test]
719    fn a_status_gives_the_state_its_reason_its_reset_and_what_is_wanted() {
720        use crate::backend::agent_status::{Pane, Reach};
721        let status = |availability, wanted, controller| AgentStatus { availability, pane: Pane::Parked, wanted, api: Reach::Online, controller };
722        let stopped = Availability::NotRunning { exited_with_error: false };
723        let (off, off_wanted) = (AgentRuntimeState::Stopped, AgentDesiredState::Stopped);
724        assert_eq!(runtime_of(&status(stopped, Wanted::Running, true)), (AgentRuntimeState::Idle, Some(STARTS_ON_FIRST_MESSAGE.into()), None, AgentDesiredState::Running));
725        assert_eq!(runtime_of(&status(stopped, Wanted::Running, false)), (off, None, None, AgentDesiredState::Running), "no controller: stays stopped");
726        assert_eq!(runtime_of(&status(stopped, Wanted::Stopped, true)), (off, None, None, off_wanted), "a shut-down agent stays off");
727        assert_eq!(runtime_of(&status(stopped, Wanted::Unset, true)), (off, None, None, off_wanted));
728        let limited = Availability::Limited { resets_at_ms: Some(9_000), since_ms: 7 };
729        assert_eq!(runtime_of(&status(limited, Wanted::Unset, true)), (AgentRuntimeState::Limited, Some("usage_limit".into()), Some(9_000), AgentDesiredState::Running));
730    }
731
732    #[test]
733    fn a_limit_says_why_and_when_it_lifts() {
734        let (state, detail, resets) = state_of(&Availability::Limited { resets_at_ms: Some(9_000), since_ms: 7 });
735        assert_eq!((state, detail.as_deref(), resets), (AgentRuntimeState::Limited, Some("usage_limit"), Some(9_000)));
736        let (_, detail, resets) = state_of(&Availability::SignedOut { since_ms: 7 });
737        assert_eq!((detail.as_deref(), resets), (Some("needs_login"), None));
738    }
739
740    #[test]
741    fn a_process_is_wanted_running_in_every_state_but_stopped_and_error() {
742        assert_eq!(desired_of(AgentRuntimeState::Stopped), AgentDesiredState::Stopped);
743        assert_eq!(desired_of(AgentRuntimeState::Error), AgentDesiredState::Stopped);
744        for state in [
745            AgentRuntimeState::Starting,
746            AgentRuntimeState::Idle,
747            AgentRuntimeState::Working,
748            AgentRuntimeState::WaitingOnUser,
749            AgentRuntimeState::Limited,
750            AgentRuntimeState::SignedOut,
751        ] {
752            assert_eq!(desired_of(state), AgentDesiredState::Running, "{state:?}");
753        }
754    }
755
756    #[test]
757    fn an_agent_begins_waiting_once_and_only_with_a_block() {
758        let mut waiting = row("a", AgentRuntimeState::WaitingOnUser);
759        waiting.block_id = Some("blk".into());
760        assert!(begins_waiting(Some(AgentRuntimeState::Working), &waiting));
761        assert!(begins_waiting(None, &waiting), "first seen already waiting");
762        assert!(!begins_waiting(Some(AgentRuntimeState::WaitingOnUser), &waiting), "it was already waiting");
763        waiting.block_id = None;
764        assert!(!begins_waiting(Some(AgentRuntimeState::Working), &waiting), "no block, nothing to notify about");
765        assert!(!begins_waiting(None, &row("b", AgentRuntimeState::Working)));
766    }
767
768    #[test]
769    fn a_wait_ends_in_the_block_it_began_in() {
770        let waiting = (AgentRuntimeState::WaitingOnUser, Some("blk".to_string()));
771        let mut now = row("a", AgentRuntimeState::Working);
772        assert_eq!(ends_waiting(Some(&waiting), &now).as_deref(), Some("blk"));
773        now.block_id = Some("other".into());
774        assert_eq!(ends_waiting(Some(&waiting), &now).as_deref(), Some("blk"), "the old block, not the row's");
775        assert_eq!(ends_waiting(Some(&waiting), &row("a", AgentRuntimeState::WaitingOnUser)), None, "still waiting");
776        assert_eq!(ends_waiting(Some(&(AgentRuntimeState::Working, Some("blk".into()))), &now), None, "was not waiting");
777        assert_eq!(ends_waiting(None, &now), None);
778    }
779
780    #[test]
781    fn only_what_changed_is_sent_and_a_gone_agent_is_forgotten() {
782        let mut last = HashMap::new();
783        let first = changed_rows(&mut last, vec![row("a", AgentRuntimeState::Idle), row("b", AgentRuntimeState::Stopped)]);
784        assert_eq!(first.len(), 2);
785        assert!(changed_rows(&mut last, vec![row("a", AgentRuntimeState::Idle), row("b", AgentRuntimeState::Stopped)]).is_empty());
786        let next = changed_rows(&mut last, vec![row("a", AgentRuntimeState::Working), row("b", AgentRuntimeState::Stopped)]);
787        assert_eq!(
788            next.iter().map(|r| (r.agent_id.as_str(), r.state)).collect::<Vec<_>>(),
789            vec![("a", AgentRuntimeState::Working)]
790        );
791        // b is deleted, then created again: it is sent again, as new.
792        assert!(changed_rows(&mut last, vec![row("a", AgentRuntimeState::Working)]).is_empty());
793        let again = changed_rows(&mut last, vec![row("a", AgentRuntimeState::Working), row("b", AgentRuntimeState::Stopped)]);
794        assert_eq!(again.len(), 1);
795    }
796
797    #[test]
798    fn the_wire_names_are_snake_case_and_leave_out_what_is_absent() {
799        let mut r = row("a", AgentRuntimeState::WaitingOnUser);
800        r.block_id = Some("blk".into());
801        let json = serde_json::to_value(&r).unwrap();
802        assert_eq!(json["state"], "waiting_on_user");
803        assert_eq!(json["desired"], "running");
804        assert_eq!(json["block_id"], "blk");
805        assert!(json.get("detail").is_none() && json.get("resets_at").is_none() && json.get("color").is_none());
806    }
807
808    /// A created agent (a definition that is not a template) with no pane is listed from its definition, as stopped and not wanted running;
809    /// no block, no colour.
810    #[tokio::test]
811    async fn an_agent_with_no_pane_is_listed_as_stopped_from_its_definition() {
812        let state = crate::server::tests::test_state();
813        let mut def: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
814            "id": "def-rt-1", "slug": "rt-one", "name": "Rt One", "icon": "robot", "provider": "claude",
815            "description": "", "created_at": 1,
816        }))
817        .unwrap();
818        state.mstore.agent_def_insert(&mut def).unwrap();
819        let rows = list(&state, 10_000);
820        let one = rows.iter().find(|r| r.agent_id == "def-rt-1").expect("the agent is listed");
821        assert_eq!((one.state, one.desired), (AgentRuntimeState::Stopped, AgentDesiredState::Stopped));
822        assert_eq!((one.name.as_str(), one.provider.as_str(), one.icon.as_str()), ("Rt One", "claude", "robot"));
823        assert!(one.block_id.is_none() && one.color.is_none() && one.detail.is_none());
824    }
825}