Skip to main content

agentmux_srv/server/
availability_view.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a sender may know before sending: the target's availability and what a routine message
5//! from a host-tier sender would do now (`docs/specs/SPEC_AGENT_AVAILABILITY_ONE_STATE_2026_10_26.md`
6//! ยง3.3). It reads the same fact and asks the same `verdict` the jekt path applies, and delivers,
7//! reserves and logs nothing, so it is safe to call for every agent in a list.
8
9use axum::extract::{Query, State};
10use axum::http::StatusCode;
11use axum::response::{IntoResponse, Response};
12use axum::Json;
13use serde_json::{json, Value};
14
15use crate::backend::agent_availability::{availability, of_unavailable, verdict, Availability, Verdict, WaitReason};
16use crate::backend::agent_status::{decide, AgentStatus, Decision, Intent, Pane, Reach, Wanted};
17use crate::backend::agent_state::{current_state_at, unavailable_of_block, AgentState};
18use crate::backend::reactive::handler::LookupOutcome;
19use crate::backend::storage::store::Store;
20
21use super::AppState;
22
23/// The wire name of a state: `AgentState`'s, with a defined agent that has no process as `stopped`.
24fn state_name(a: &Availability) -> &'static str {
25    match a {
26        Availability::NotRunning { exited_with_error: true } => AgentState::Error.as_str(),
27        Availability::NotRunning { exited_with_error: false } => AgentState::Stopped.as_str(),
28        Availability::Idle { .. } => AgentState::Idle.as_str(),
29        Availability::Running { waiting_on_user: true } => AgentState::Waiting.as_str(),
30        Availability::Running { waiting_on_user: false } => AgentState::Working.as_str(),
31        Availability::Limited { .. } => AgentState::Limited.as_str(),
32        Availability::SignedOut { .. } => AgentState::SignedOut.as_str(),
33        Availability::Unknown => "unknown",
34    }
35}
36
37/// The answer for one agent: its `state`, when it began (`since_ms`) and, for a limit, when it lifts
38/// (`resets_at_ms`); `would`, what a routine message does now (`deliver` or `hold`); and, when the agent
39/// can't work, `reason` and `retry_when`. A limited agent with no known reset still gets `would: deliver`
40/// (a turn is how it finds out), with `reason: usage_limit` so the sender knows it may fail.
41pub(super) fn describe(av: &Availability, v: &Verdict) -> Value {
42    let mut out = json!({ "state": state_name(av), "would": if v.waits() { "hold" } else { "deliver" } });
43    match *av {
44        Availability::Limited { resets_at_ms, since_ms } => {
45            out["since_ms"] = json!(since_ms);
46            out["resets_at_ms"] = json!(resets_at_ms);
47        }
48        Availability::SignedOut { since_ms } => out["since_ms"] = json!(since_ms),
49        Availability::Idle { quiet_for_ms: Some(quiet) } => out["quiet_for_ms"] = json!(quiet),
50        _ => {}
51    }
52    let reason = match (*v, *av) {
53        (Verdict::Wait { reason, .. }, _) => Some(reason),
54        (_, Availability::Limited { .. }) => Some(WaitReason::UsageLimit),
55        _ => None,
56    };
57    if let Some(reason) = reason {
58        out["reason"] = json!(reason.as_str());
59        out["retry_when"] = json!(reason.retry_when());
60    }
61    if let Verdict::Wait { until_ms: Some(until), .. } = *v {
62        out["until_ms"] = json!(until);
63    }
64    out
65}
66
67/// The block the agent with this UID runs in, when it is registered here under that UID.
68pub(super) fn block_of_uid(handler: &crate::backend::reactive::handler::ReactiveHandler, uid: &str) -> Option<String> {
69    match handler.lookup_delivery_target(uid) {
70        LookupOutcome::One(reg) => Some(reg.block_id),
71        LookupOutcome::Ambiguous(_) | LookupOutcome::NotFound => None,
72    }
73}
74
75/// What can be said about the agent on `block_id` now, or about a defined agent with no live pane (`None`).
76pub(super) fn availability_of_block(mstore: &Store, block_id: Option<&str>, now_ms: u64) -> Availability {
77    match block_id {
78        None => Availability::NotRunning { exited_with_error: false },
79        Some(block_id) => match unavailable_of_block(mstore, None, block_id, now_ms)
80            .or_else(|| super::limit_probe::unavailable_while_probing(mstore, block_id, now_ms))
81        {
82            Some(unavailable) => of_unavailable(&unavailable),
83            None => {
84                let state = current_state_at(mstore, block_id, now_ms);
85                let quiet = (state == Some(AgentState::Idle))
86                    .then(|| crate::backend::cold_hold::session_last_output(mstore, block_id))
87                    .flatten()
88                    .map(|at| now_ms.saturating_sub(u64::try_from(at).unwrap_or(0)));
89                availability(state, None, quiet)
90            }
91        },
92    }
93}
94
95/// The model API of a block's agent as a pane reads it: tracked and answering, offline, not checked yet, or not tracked.
96fn reach_of(meta: &std::collections::HashMap<String, Value>, net: &crate::connectivity::ConnectivityStatus, now_ms: u64) -> Reach {
97    use crate::connectivity::Reachability;
98    let Some(id) = super::held_input::service_of(meta) else { return Reach::NotTracked };
99    let Some(service) = net.services.iter().find(|s| s.service == id) else { return Reach::NotTracked };
100    match service.state {
101        Reachability::Online => Reach::Online,
102        Reachability::Degraded => Reach::Degraded,
103        Reachability::Offline => Reach::Offline,
104        Reachability::Unknown => Reach::Unchecked { for_ms: now_ms.saturating_sub(u64::try_from(service.since_ms).unwrap_or(0)) },
105    }
106}
107
108/// Whether an open window shows the workspace whose tab holds this block.
109fn on_screen(mstore: &Store, block_id: &str) -> bool {
110    crate::backend::notify::router::resolve_click_target(mstore, block_id)
111        .and_then(|target| target.workspace_id)
112        .is_some_and(|workspace| super::service::open_workspace_ids(mstore).contains(&workspace))
113}
114
115/// Everything a path needs to know about an agent: its availability (`live`, the block it is registered
116/// in, if any) and, from `block` (its live block, or the one that holds its desired state), whether it
117/// has a pane, whether it is wanted running, and whether its model API answers (`net`: one snapshot of
118/// the connectivity status, so a list of agents takes it once). Writes nothing.
119pub(super) fn status_of(
120    mstore: &Store,
121    live: Option<&str>,
122    block: Option<&crate::backend::obj::Block>,
123    net: &crate::connectivity::ConnectivityStatus,
124    now_ms: u64,
125) -> AgentStatus {
126    let (pane, wanted, api, controller) = match block {
127        None => (Pane::None, Wanted::Unset, Reach::NotTracked, false),
128        Some(block) => {
129            let parked = crate::backend::obj::meta_get_bool(&block.meta, crate::persist_subscriber::parked::PARKED_META_KEY, false);
130            let wanted = match super::app_api::agent_attach::desired_of(block).as_deref() {
131                Some(super::app_api::agent_attach::DESIRED_RUNNING) => Wanted::Running,
132                Some(super::app_api::agent_attach::DESIRED_STOPPED) => Wanted::Stopped,
133                _ => Wanted::Unset,
134            };
135            let controller = crate::backend::blockcontroller::get_controller(&block.oid).is_some();
136            let pane = if parked {
137                Pane::Parked
138            } else if on_screen(mstore, &block.oid) {
139                Pane::Shown
140            } else {
141                Pane::NotInWindow
142            };
143            (pane, wanted, reach_of(&block.meta, net, now_ms), controller)
144        }
145    };
146    let read = state_block(live, block.map(|b| b.oid.as_str()), controller);
147    let availability = stop_is_not_an_error(availability_of_block(mstore, read, now_ms), wanted);
148    AgentStatus { availability, pane, wanted, api, controller }
149}
150
151/// An agent whose block records a stop (the idle lifecycle, `Agents stop`, a person's shut down) is `stopped`
152/// even when its process ended with a non-zero exit code: the stop is a forced kill, which exits that way. `error`
153/// is for a process that ended when nothing asked it to.
154fn stop_is_not_an_error(availability: Availability, wanted: Wanted) -> Availability {
155    match (availability, wanted) {
156        (Availability::NotRunning { exited_with_error: true }, Wanted::Stopped) => Availability::NotRunning { exited_with_error: false },
157        _ => availability,
158    }
159}
160
161/// The block whose controller says what the agent is doing: the registered one, else the agent's own block
162/// when a controller holds it. A pane in a closed workspace can run with no registration; reading it as
163/// absent made `Agents list` say `stopped` for an agent whose runtime state was `idle`.
164fn state_block<'a>(live: Option<&'a str>, block: Option<&'a str>, controller: bool) -> Option<&'a str> {
165    live.or(block.filter(|_| controller))
166}
167
168/// [`describe`] for a status: what a routine message does now is `decide`'s answer (so an offline model
169/// API reads as a hold), and the status's `pane`, `wanted` and `api` are named, so a sender sees "parked,
170/// running" or "shut down" before it sends.
171pub(super) fn describe_status(status: &AgentStatus, cold_after_ms: Option<u64>) -> Value {
172    let message = Intent::Message { urgent: false, routine: true, cold_after_ms };
173    let verdict = match decide(status, message, || false) {
174        Decision::Wait { reason, until_ms } => Verdict::Wait { reason, until_ms },
175        _ => Verdict::Deliver,
176    };
177    let mut out = describe(&status.availability, &verdict);
178    out["pane"] = json!(status.pane.as_str());
179    out["wanted"] = json!(status.wanted.as_str());
180    out["api"] = json!(status.api.as_str());
181    out
182}
183
184/// [`describe_status`] for the agent registered in `live` (`None` for a defined agent with no live pane).
185/// `state_block` is the block that holds its pane and desired state when that is not `live`: the parked
186/// block of an agent with no process.
187pub(super) fn describe_block(
188    mstore: &Store,
189    live: Option<&str>,
190    state_block: Option<&str>,
191    net: &crate::connectivity::ConnectivityStatus,
192    cold_after_ms: Option<u64>,
193    now_ms: u64,
194) -> Value {
195    let block = live.or(state_block).and_then(|id| mstore.get::<crate::backend::obj::Block>(id).ok().flatten());
196    let mut out = describe_status(&status_of(mstore, live, block.as_ref(), net, now_ms), cold_after_ms);
197    if out["state"] == AgentState::Error.as_str() {
198        // An error that was classified says what: `rate_limited` and `network` are worth another message.
199        if let Some(why) = crate::backend::worker_failure_note::code_name(&block.as_ref().map(|b| b.meta.clone()).unwrap_or_default()) {
200            out["failure"] = json!(why);
201        }
202    }
203    if let Some(usage) = usage_of(block.as_ref(), now_ms) {
204        out["usage"] = usage;
205    }
206    out
207}
208
209/// How much of each usage window of the account the agent's run launched on is used, by window
210/// (`five_hour`, `seven_day`): `used_percent`, `resets_at_ms` and the reading's `age_ms`. `None` when
211/// the account has no reading that has not reset (a provider that reports none, or nothing has run
212/// on it yet): `Identity accounts` says which.
213fn usage_of(block: Option<&crate::backend::obj::Block>, now_ms: u64) -> Option<Value> {
214    let account = block?.meta.get(crate::backend::agent_state::RUN_ACCOUNT_META_KEY)?.as_str()?;
215    let windows = crate::backend::account_usage::of_account(account, now_ms);
216    (!windows.is_empty()).then(|| json!(windows))
217}
218
219#[derive(serde::Deserialize)]
220pub(super) struct AvailabilityQuery {
221    agent: Option<String>,
222}
223
224/// `GET /agentmux/reactive/availability?agent=<name|uid>`: [`describe_block`] for one agent of this
225/// instance. 400 without `agent`, 404 for a name no agent here has, 409 for one that names several.
226pub(super) async fn handle_availability(State(state): State<AppState>, Query(q): Query<AvailabilityQuery>) -> Response {
227    let Some(agent) = q.agent.as_deref().map(str::trim).filter(|a| !a.is_empty()) else {
228        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "missing agent param" }))).into_response();
229    };
230    match view_of_agent(&state, agent).await {
231        Known::Live(view) => Json(view).into_response(),
232        Known::Ambiguous => (StatusCode::CONFLICT, Json(json!({ "error": format!("{agent} names more than one agent here") }))).into_response(),
233        Known::Unknown => (StatusCode::NOT_FOUND, Json(json!({ "error": format!("no agent named {agent} here") }))).into_response(),
234    }
235}
236
237/// [`describe_block`] for the agent `agent` (a name or a UID) names on this instance.
238pub(crate) async fn view_of_agent(state: &AppState, agent: &str) -> Known {
239    let route = crate::backend::reactive::sanitize::route_name(agent).unwrap_or_else(|| agent.to_string());
240    let block_id = match state.reactive_handler.lookup_delivery_target(&route) {
241        LookupOutcome::One(reg) => Some(reg.block_id),
242        LookupOutcome::Ambiguous(_) => return Known::Ambiguous,
243        LookupOutcome::NotFound => None,
244    };
245    let (mstore, agent_owned) = (state.mstore.clone(), agent.to_string());
246    let after_ms = crate::backend::cold_hold::cold_after_ms(&state.config_watcher.get_full_config().settings.extra)
247        .and_then(|ms| u64::try_from(ms).ok());
248    let now_ms = agentmux_common::time::now_ms_u64();
249    let net = crate::connectivity::status();
250    tokio::task::spawn_blocking(move || {
251        if block_id.is_some() {
252            return Known::Live(describe_block(&mstore, block_id.as_deref(), None, &net, after_ms, now_ms));
253        }
254        let defined = super::reactive::defined_here(&mstore, &agent_owned);
255        let matches = mstore.agents_matching_name(&agent_owned).map_or(0, |rows| rows.len());
256        match classify_stopped(defined.is_some(), matches) {
257            // Its retained block (shown in a tab, or parked) holds its pane and desired state.
258            Stopped::Defined => {
259                let retained = defined.and_then(|(uid, _)| super::agent_runtime::pane_blocks_by_agent(&mstore).remove(&uid));
260                Known::Live(describe_block(&mstore, None, retained.as_deref(), &net, after_ms, now_ms))
261            }
262            Stopped::Ambiguous => Known::Ambiguous,
263            Stopped::Unknown => Known::Unknown,
264        }
265    })
266    .await
267    .unwrap_or(Known::Unknown)
268}
269
270/// What to tell a sender who filed a task for the agent `lookup` (a name or a UID) that the agent can't
271/// take up now: its availability (`target`) and a `note` saying the task waits, naming the agent `name`
272/// as the sender typed it (`lookup` when that is empty). `None` for an agent that can work, a group or
273/// unaddressed task, or a name no agent here has, so the answer stays as it was.
274pub(super) async fn enqueue_note(state: &AppState, lookup: &str, name: &str) -> Option<Value> {
275    let lookup = lookup.trim();
276    if lookup.is_empty() {
277        return None;
278    }
279    let Known::Live(view) = view_of_agent(state, lookup).await else {
280        return None;
281    };
282    let name = Some(name.trim()).filter(|n| !n.is_empty()).unwrap_or(lookup);
283    let note = wait_note(&view, name)?;
284    Some(json!({ "target": view, "note": note }))
285}
286
287/// `body` with the fields of [`enqueue_note`], if there is one.
288pub(super) fn with_note(mut body: Value, note: Option<Value>) -> Value {
289    if let (Some(fields), Some(map)) = (note, body.as_object_mut()) {
290        if let Some(extra) = fields.as_object() {
291            map.extend(extra.clone());
292        }
293    }
294    body
295}
296
297/// The sentence for an agent in `view` that can't work: `limited` or `signed_out`. It says the task is
298/// filed and waits for the agent, and when that is expected.
299fn wait_note(view: &Value, agent: &str) -> Option<String> {
300    let when = match view["state"].as_str()? {
301        "limited" => match view["resets_at_ms"].as_u64() {
302            Some(at) => format!("at the limit, which lifts at {}", super::jekt_hold::local_time_label(at).unwrap_or_default()),
303            None => "at its usage limit (no reset time known)".to_string(),
304        },
305        "signed_out" => "signed out".to_string(),
306        _ => return None,
307    };
308    Some(format!(
309        "{agent} is {when}. The task is filed and stays in its queue; {agent} can take it only once it can work again, \
310         so do not expect it sooner."
311    ))
312}
313
314/// How a name that no live pane answers to stands in the directory.
315#[derive(Debug, PartialEq, Eq)]
316enum Stopped {
317    /// Exactly one defined agent: it has no process.
318    Defined,
319    /// Several defined agents answer to it.
320    Ambiguous,
321    Unknown,
322}
323
324fn classify_stopped(defined_here: bool, matching: usize) -> Stopped {
325    match (defined_here, matching) {
326        (true, _) => Stopped::Defined,
327        (false, 0) => Stopped::Unknown,
328        (false, _) => Stopped::Ambiguous,
329    }
330}
331
332pub(crate) enum Known {
333    Live(Value),
334    Ambiguous,
335    Unknown,
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    const AFTER: u64 = 55 * 60_000;
343
344    fn view(av: Availability) -> Value {
345        describe(&av, &verdict(&av, false, true, Some(AFTER), || false))
346    }
347
348    /// A pane in a tab of a workspace no open window shows is not shown (the Masty/Maop panes in a closed
349    /// "Upgrade check" workspace read `shown`); a parked block stays parked.
350    #[test]
351    fn a_pane_in_a_workspace_no_open_window_shows_is_not_shown() {
352        use crate::backend::obj::{Block, Client};
353        let store = Store::open_in_memory().unwrap();
354        crate::backend::wcore::ensure_initial_data(&store).unwrap();
355        let mut block = store.get_all::<Block>().unwrap().into_iter().next().expect("seeded block");
356        let net = crate::connectivity::status();
357        let pane = |block: &Block| status_of(&store, None, Some(block), &net, 1).pane;
358        assert_eq!(pane(&block), Pane::Shown, "the seeded window shows its workspace");
359        let mut client = store.get_all::<Client>().unwrap().into_iter().next().expect("seeded client");
360        client.windowids.clear();
361        store.update(&mut client).unwrap();
362        assert_eq!(pane(&block), Pane::NotInWindow, "no open window has the workspace");
363        assert_eq!(Pane::NotInWindow.as_str(), "not_in_window");
364        block.meta.insert(crate::persist_subscriber::parked::PARKED_META_KEY.into(), json!(true));
365        assert_eq!(pane(&block), Pane::Parked, "a parked block has no tab at all");
366        assert!(!on_screen(&store, "gone"), "a block that is gone is not on screen");
367    }
368
369    #[test]
370    fn a_task_for_an_agent_that_cannot_work_says_it_waits_and_for_one_that_can_says_nothing() {
371        let limited = view(Availability::Limited { resets_at_ms: Some(9_000), since_ms: 7 });
372        let note = wait_note(&limited, "ann").unwrap();
373        assert!(note.starts_with("ann is at the limit, which lifts at "), "{note}");
374        assert!(note.contains("stays in its queue"), "{note}");
375        let no_reset = view(Availability::Limited { resets_at_ms: None, since_ms: 7 });
376        assert!(wait_note(&no_reset, "ann").unwrap().contains("no reset time known"));
377        let out = view(Availability::SignedOut { since_ms: 7 });
378        assert!(wait_note(&out, "ann").unwrap().starts_with("ann is signed out."));
379        for av in [Availability::Idle { quiet_for_ms: None }, Availability::Running { waiting_on_user: false }, Availability::NotRunning { exited_with_error: false }] {
380            assert_eq!(wait_note(&view(av), "ann"), None);
381        }
382    }
383
384    #[test]
385    fn the_note_joins_the_enqueue_answer_only_when_there_is_one() {
386        let body = json!({ "id": "w1", "num": 4 });
387        assert_eq!(with_note(body.clone(), None), body);
388        let joined = with_note(body, Some(json!({ "target": { "state": "limited" }, "note": "n" })));
389        assert_eq!((joined["num"].clone(), joined["note"].clone(), joined["target"]["state"].clone()), (json!(4), json!("n"), json!("limited")));
390    }
391
392    #[test]
393    fn an_agent_that_can_work_is_delivered_to_with_no_reason() {
394        let v = view(Availability::Running { waiting_on_user: false });
395        assert_eq!(v, json!({ "state": "working", "would": "deliver" }));
396        let v = view(Availability::Idle { quiet_for_ms: Some(60_000) });
397        assert_eq!(v, json!({ "state": "idle", "would": "deliver", "quiet_for_ms": 60_000 }));
398    }
399
400    #[test]
401    fn a_limit_with_a_reset_holds_and_says_until_when() {
402        let v = view(Availability::Limited { resets_at_ms: Some(9_000), since_ms: 7 });
403        assert_eq!(v["state"], "limited");
404        assert_eq!(v["would"], "hold");
405        assert_eq!(v["reason"], "usage_limit");
406        assert_eq!(v["retry_when"], "reset_or_account_move");
407        assert_eq!((v["until_ms"].as_u64(), v["resets_at_ms"].as_u64(), v["since_ms"].as_u64()), (Some(9_000), Some(9_000), Some(7)));
408    }
409
410    #[test]
411    fn a_limit_with_no_known_reset_delivers_but_says_it_may_fail() {
412        let v = view(Availability::Limited { resets_at_ms: None, since_ms: 7 });
413        assert_eq!(v["would"], "deliver");
414        assert_eq!(v["reason"], "usage_limit");
415        assert!(v["resets_at_ms"].is_null() && v.get("until_ms").is_none());
416    }
417
418    #[test]
419    fn signed_out_and_not_running_hold_with_their_own_advice() {
420        let v = view(Availability::SignedOut { since_ms: 3 });
421        assert_eq!((v["would"].as_str(), v["reason"].as_str(), v["retry_when"].as_str()), (Some("hold"), Some("needs_login"), Some("sign_in")));
422        let v = view(Availability::NotRunning { exited_with_error: true });
423        assert_eq!((v["state"].as_str(), v["reason"].as_str(), v["retry_when"].as_str()), (Some("error"), Some("not_running"), Some("start")));
424    }
425
426    #[test]
427    fn a_cold_session_holds_a_routine_message_and_is_still_idle_on_the_wire() {
428        let v = view(Availability::Idle { quiet_for_ms: Some(AFTER + 1) });
429        assert_eq!((v["state"].as_str(), v["would"].as_str(), v["reason"].as_str()), (Some("idle"), Some("hold"), Some("idle")));
430        assert_eq!(v["retry_when"], "session_active");
431    }
432
433    /// Two agents with one display name are told apart by UID, which is what discovery asks.
434    #[test]
435    fn agents_sharing_a_display_name_resolve_to_their_own_blocks_by_uid() {
436        use crate::backend::reactive::handler::ReactiveHandler;
437        let h = ReactiveHandler::new();
438        h.register_agent_full("Twin", "block-a", None, 0, None, Some("uid-a"), "test").unwrap();
439        h.register_agent_full("Twin", "block-b", None, 0, None, Some("uid-b"), "test").unwrap();
440        assert_eq!((block_of_uid(&h, "uid-a").as_deref(), block_of_uid(&h, "uid-b").as_deref()), (Some("block-a"), Some("block-b")));
441        assert_eq!(block_of_uid(&h, "uid-none"), None);
442    }
443
444    #[test]
445    fn a_name_no_pane_answers_to_is_defined_ambiguous_or_unknown() {
446        assert_eq!(classify_stopped(true, 1), Stopped::Defined);
447        assert_eq!(classify_stopped(false, 2), Stopped::Ambiguous);
448        assert_eq!(classify_stopped(false, 0), Stopped::Unknown);
449    }
450
451    #[test]
452    fn a_defined_agent_with_no_pane_is_stopped_and_holds() {
453        let store = Store::open_in_memory().unwrap();
454        let v = describe_block(&store, None, None, &crate::connectivity::ConnectivityStatus { revision: 0, services: vec![] }, Some(AFTER), 1_000);
455        assert_eq!((v["state"].as_str(), v["would"].as_str(), v["reason"].as_str()), (Some("stopped"), Some("hold"), Some("not_running")));
456        assert_eq!((v["pane"].as_str(), v["wanted"].as_str(), v["api"].as_str()), (Some("none"), Some("unset"), Some("not_tracked")));
457    }
458
459    /// A stopped agent keeps its block, which records whether it is shown or parked and whether it should
460    /// run: the view reads them from it, not as `none` and `unset`.
461    #[test]
462    fn a_stopped_agent_with_a_retained_block_shows_its_pane_and_wanted_state() {
463        let store = Store::open_in_memory().unwrap();
464        let mut block = crate::backend::obj::Block::default();
465        block.oid = uuid::Uuid::new_v4().to_string();
466        block.meta.insert(crate::persist_subscriber::parked::PARKED_META_KEY.into(), json!(true));
467        block.meta.insert("agent:desired".into(), json!("stopped"));
468        store.insert(&mut block).unwrap();
469        let none = crate::connectivity::ConnectivityStatus { revision: 0, services: vec![] };
470        let v = describe_block(&store, None, Some(&block.oid), &none, Some(AFTER), 1_000);
471        assert_eq!((v["state"].as_str(), v["pane"].as_str(), v["wanted"].as_str()), (Some("stopped"), Some("parked"), Some("stopped")));
472    }
473
474    /// An agent's availability carries how much of each usage window of its account is used, with the
475    /// reading's age, and nothing when the account has no reading that is still current.
476    #[test]
477    fn the_availability_of_an_agent_carries_its_accounts_usage_when_there_is_a_reading() {
478        use crate::backend::account_usage::{observe, windows_of_frame};
479        let store = Store::open_in_memory().unwrap();
480        let account = format!("acct-{}", uuid::Uuid::new_v4());
481        let mut block = crate::backend::obj::Block::default();
482        block.oid = uuid::Uuid::new_v4().to_string();
483        block.meta.insert(crate::backend::agent_state::RUN_ACCOUNT_META_KEY.into(), json!(account));
484        store.insert(&mut block).unwrap();
485        let none = crate::connectivity::ConnectivityStatus { revision: 0, services: vec![] };
486        let view = |now_ms: u64| describe_block(&store, None, Some(&block.oid), &none, Some(AFTER), now_ms);
487        assert!(view(1_000_000).get("usage").is_none(), "no reading yet: no field");
488        let frame = json!({"type": "rate_limit_event", "rate_limit_info": {"unifiedWindows": {"five_hour": {"utilization": 0.6, "resetsAt": 2_000}}}});
489        observe(&account, &windows_of_frame(&frame), 1_000_000);
490        let v = view(1_030_000);
491        assert_eq!(v["usage"]["five_hour"]["used_percent"], 60.0);
492        assert_eq!((v["usage"]["five_hour"]["resets_at_ms"].as_u64(), v["usage"]["five_hour"]["age_ms"].as_u64()), (Some(2_000_000), Some(30_000)));
493        assert!(view(2_000_000).get("usage").is_none(), "the window reset: the reading is gone");
494    }
495
496    #[test]
497    fn a_controller_held_block_with_no_registration_is_read_for_its_state() {
498        assert_eq!(state_block(Some("reg"), Some("own"), true), Some("reg"), "the registered block wins");
499        assert_eq!(state_block(None, Some("own"), true), Some("own"), "a running pane in a closed workspace is read, not called stopped");
500        assert_eq!(state_block(None, Some("own"), false), None, "no controller: nothing runs");
501        assert_eq!(state_block(None, None, true), None);
502    }
503
504    fn status(availability: Availability, pane: Pane, wanted: Wanted, api: Reach) -> AgentStatus {
505        AgentStatus { availability, pane, wanted, api, controller: true }
506    }
507
508    #[test]
509    fn the_view_names_the_pane_the_wanted_state_and_the_api_and_holds_for_an_offline_api() {
510        let idle = Availability::Idle { quiet_for_ms: Some(5) };
511        let v = describe_status(&status(idle, Pane::Parked, Wanted::Running, Reach::Online), Some(AFTER));
512        assert_eq!((v["pane"].as_str(), v["wanted"].as_str(), v["api"].as_str(), v["would"].as_str()), (Some("parked"), Some("running"), Some("online"), Some("deliver")));
513        let v = describe_status(&status(idle, Pane::Shown, Wanted::Running, Reach::Offline), Some(AFTER));
514        assert_eq!((v["api"].as_str(), v["would"].as_str(), v["reason"].as_str(), v["retry_when"].as_str()), (Some("offline"), Some("hold"), Some("api_offline"), Some("api_online")));
515        let working = Availability::Running { waiting_on_user: false };
516        let v = describe_status(&status(working, Pane::Shown, Wanted::Running, Reach::Offline), Some(AFTER));
517        assert_eq!(v["would"].as_str(), Some("deliver"), "a message that joins a turn goes");
518    }
519
520    #[test]
521    fn a_stop_that_was_asked_for_is_not_an_error_even_when_the_kill_exits_non_zero() {
522        let crashed = Availability::NotRunning { exited_with_error: true };
523        let stopped = Availability::NotRunning { exited_with_error: false };
524        assert_eq!(stop_is_not_an_error(crashed, Wanted::Stopped), stopped, "the idle lifecycle's forced kill is a stop");
525        assert_eq!(stop_is_not_an_error(crashed, Wanted::Running), crashed, "an exit nobody asked for stays an error");
526        assert_eq!(stop_is_not_an_error(crashed, Wanted::Unset), crashed);
527        assert_eq!(stop_is_not_an_error(stopped, Wanted::Stopped), stopped);
528        let idle = Availability::Idle { quiet_for_ms: None };
529        assert_eq!(stop_is_not_an_error(idle, Wanted::Stopped), idle, "only the error exit is rewritten");
530    }
531
532    #[test]
533    fn agents_list_and_the_availability_view_both_call_an_asked_for_stop_stopped() {
534        let av = stop_is_not_an_error(Availability::NotRunning { exited_with_error: true }, Wanted::Stopped);
535        let v = describe_status(&status(av, Pane::NotInWindow, Wanted::Stopped, Reach::NotTracked), Some(AFTER));
536        assert_eq!(v["state"].as_str(), Some("stopped"));
537        let (state, _, _, desired) = crate::server::agent_runtime::runtime_of(&status(av, Pane::NotInWindow, Wanted::Stopped, Reach::NotTracked));
538        assert_eq!((state, desired), (crate::backend::agent_runtime_state::AgentRuntimeState::Stopped, crate::backend::agent_runtime_state::AgentDesiredState::Stopped));
539    }
540}