1use 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
48const LOOK_EVERY: std::time::Duration = std::time::Duration::from_secs(2);
50
51pub use crate::backend::agent_runtime_state::{AgentDesiredState, AgentRuntime, AgentRuntimeState};
52
53#[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#[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
68pub const STARTS_ON_FIRST_MESSAGE: &str = "starts_on_first_message";
70
71pub 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
88pub const BROWSER_REQUEST: &str = "browser_request";
90
91pub const META_AWAITING_BROWSER: &str = "term:awaiting_browser";
93
94pub 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
108fn 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
118fn 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
124pub 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 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
142pub fn desired_of(state: AgentRuntimeState) -> AgentDesiredState {
144 match state {
145 AgentRuntimeState::Stopped | AgentRuntimeState::Error => AgentDesiredState::Stopped,
146 _ => AgentDesiredState::Running,
147 }
148}
149
150pub 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
160pub 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
175fn 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
181pub(crate) fn list(state: &AppState, now_ms: u64) -> Vec<AgentRuntime> {
183 let mstore = &state.mstore;
184 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 let live = block_of_uid(state.reactive_handler, &d.id);
198 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
251pub 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
257fn 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
263fn agent_of_block(block: &Block) -> Option<String> {
265 if crate::backend::obj::is_history_reader(&block.meta) {
266 return None; }
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
274pub(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
293fn 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
299pub 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
314fn 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
324fn 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
333fn 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
341fn 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
352fn 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
365async 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
379pub(crate) fn spawn(state: AppState) {
381 super::registry_reconcile::spawn(state.clone()); 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 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 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 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 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 #[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 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 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 #[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 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 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 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 #[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 #[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 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 assert_eq!(wanted_running_is_idle(S::Stopped, None, AgentDesiredState::Stopped, true), (S::Stopped, None));
709 assert_eq!(wanted_running_is_idle(S::Stopped, None, AgentDesiredState::Running, false), (S::Stopped, None));
711 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 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 #[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}