Skip to main content

agentmux_srv/server/
spend_watch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What srv does as an agent's spend on a model route reaches its caps (`docs/specs/SPEC_ROUTE_AGENT_BRAKES_2026_11_10.md`
5//! section 3.3). The gateway counts each response and refuses a request once a cap is used
6//! (`model_gateway::cap`); it tells this watcher of both, and the watcher, off the stream's task:
7//!
8//! - **50%** of the agent's cap: one non-urgent note to its leader.
9//! - **80%:** the agent's pane gets a warning line (block meta `agent:spend_warning`).
10//! - **100%** (or the route's cap): the pane carries `agent:spend_stopped`, its turn in flight is interrupted, and the
11//!   leader is told. The gateway has refused (or will refuse) the agent's next request.
12//!
13//! Each level is acted on once per agent per UTC day; the level already sent is kept with the day's spend, so a restart
14//! does not send it again. A raised or reset cap, or the first response of a new day, takes the stop off.
15
16use std::sync::OnceLock;
17
18use serde_json::{json, Value};
19use tokio::sync::mpsc::{unbounded_channel, UnboundedSender};
20
21use crate::backend::blockcontroller::{self, BlockInputUnion};
22use crate::backend::model_gateway::cap::{self, Hit, Scope};
23use crate::backend::model_gateway::token::Grant;
24use crate::backend::model_gateway::{catalog, launch, spend};
25use crate::backend::{obj, worker_notes};
26use crate::server::AppState;
27
28/// Block meta the pane's stop card reads; absent when the agent is not stopped.
29pub const STOPPED_META_KEY: &str = "agent:spend_stopped";
30/// Block meta the pane's warning line reads, from 80% of the cap.
31pub const WARNING_META_KEY: &str = "agent:spend_warning";
32/// Block meta the chips read: what the agent has used today and its cap (`day` is days since the epoch, UTC).
33pub const TODAY_META_KEY: &str = "agent:spend_today";
34/// The least time between two writes of [`TODAY_META_KEY`] for an agent, unless its level or cap changed.
35const TODAY_EVERY_MS: i64 = 15_000;
36/// How often every active agent's figure is written again, so a skipped one and a new pane catch up.
37const REFRESH_EVERY: std::time::Duration = std::time::Duration::from_secs(60);
38
39enum Event {
40    Settled(Grant),
41    Refused(Grant, Hit),
42}
43
44fn inbox() -> &'static OnceLock<UnboundedSender<Event>> {
45    static INBOX: OnceLock<UnboundedSender<Event>> = OnceLock::new();
46    &INBOX
47}
48
49/// A response of `grant`'s agent has been counted.
50pub(crate) fn settled(grant: &Grant) {
51    if let Some(tx) = inbox().get() {
52        let _ = tx.send(Event::Settled(grant.clone()));
53    }
54}
55
56/// The gateway refused `grant`'s agent a request because `hit` is used.
57pub(crate) fn refused(grant: &Grant, hit: Hit) {
58    if let Some(tx) = inbox().get() {
59        let _ = tx.send(Event::Refused(grant.clone(), hit));
60    }
61}
62
63/// Starts the watcher.
64pub(crate) fn start(state: AppState) {
65    let (tx, mut rx) = unbounded_channel();
66    if inbox().set(tx).is_err() {
67        return;
68    }
69    // A route out of credits stops every agent on it; its first success ends that (`on_settled`).
70    crate::backend::route_credits::install(state.broker.clone(), state.mstore.clone(), state.event_bus.clone());
71    tokio::spawn(async move {
72        let mut refresh = tokio::time::interval(REFRESH_EVERY);
73        refresh.tick().await;
74        loop {
75            let state = state.clone();
76            tokio::select! {
77                event = rx.recv() => {
78                    let Some(event) = event else { break };
79                    // Store reads, block-meta writes and a note to the leader: not on the async worker.
80                    let _ = tokio::task::spawn_blocking(move || handle(&state, event)).await;
81                }
82                // The chips catch up: a figure skipped inside the throttle window, and a pane opened since the last write.
83                _ = refresh.tick() => {
84                    let _ = tokio::task::spawn_blocking(move || refresh_chips(&state)).await;
85                }
86            }
87        }
88    });
89}
90
91const DAY_MS: i64 = 86_400_000;
92
93/// Brings every agent's panes up to date once a minute: the figure of an agent on a route that has spent today, and the
94/// removal of what no longer holds (see [`stale_keys`]).
95fn refresh_chips(state: &AppState) {
96    let now = agentmux_common::time::now_ms();
97    let Ok(defs) = state.mstore.agent_def_list() else { return };
98    let spending = spend::agents_today(now);
99    let settings = state.config_watcher.get_settings().extra;
100    for def in &defs {
101        let on_route = spends_through_gateway(state, &def.id);
102        drop_stale(state, &def.id, on_route, now);
103        forget_alert_off_route(&def.slug, on_route, now);
104        if on_route && spending.contains(&def.slug) {
105            let spent = spend::today(&def.slug, now).cost_usd;
106            publish_today(state, &def.id, &def.slug, cap::agent_cap(&state.mstore, &settings, &def.id), spent, now, true);
107        }
108    }
109}
110
111/// Whether the agent's requests go through the gateway and are counted there: it is on a model route, or on an API key.
112pub(super) fn spends_through_gateway(state: &AppState, def_id: &str) -> bool {
113    on_a_key(&state.mstore, &state.identity_store, def_id) || launch::choice_of(&state.mstore, def_id).is_some()
114}
115
116/// A Claude agent linked to an Anthropic key: the gateway carries its requests. An agent of another provider that holds
117/// such a link sends its own requests to the vendor, where nothing is counted or capped.
118pub(crate) fn on_a_key(mstore: &crate::backend::storage::store::Store, identity_store: &crate::backend::storage::store::Store, def_id: &str) -> bool {
119    let claude = mstore.agent_def_get(def_id).ok().flatten().is_some_and(|d| crate::backend::providers::resolve_provider_alias(&mstore.resolve_effective_provider_id(&d)) == "claude");
120    claude && identity_store.agent_identity_list_for_agent(def_id).is_ok_and(|links| links.iter().any(|l| l.provider.eq_ignore_ascii_case(catalog::KEY_ROUTE_ID)))
121}
122
123/// The spend keys on a pane's `meta` that no longer hold. An agent that is not on a model route has no cap and no day of
124/// spend to show, so it carries none of them; on a route, a stop or warning written on an earlier UTC day belongs to a
125/// day the gateway has since reset, and nothing else would take it off an agent that stays idle through midnight.
126fn stale_keys(meta: &obj::MetaMapType, on_route: bool, now: i64) -> Vec<&'static str> {
127    let earlier_day = |card: &Value| card.get("at").and_then(Value::as_i64).is_some_and(|at| at.div_euclid(DAY_MS) < now.div_euclid(DAY_MS));
128    [TODAY_META_KEY, STOPPED_META_KEY, WARNING_META_KEY]
129        .into_iter()
130        .filter(|key| match meta.get(*key) {
131            None | Some(Value::Null) => false,
132            Some(card) => !on_route || (*key != TODAY_META_KEY && earlier_day(card)),
133        })
134        .collect()
135}
136
137/// An agent off a model route has had its stop and warning taken off its panes, so the alert level the gateway's refusals
138/// check goes back to zero with them. Left at 100, an agent stopped at its cap that returns to a route the same UTC day
139/// is refused on its first request and gets no stop card, because the stop was already counted as sent.
140fn forget_alert_off_route(slug: &str, on_route: bool, now: i64) {
141    if !on_route && spend::alerted(slug, now) > 0 {
142        spend::set_alerted(slug, 0, now);
143    }
144}
145
146fn drop_stale(state: &AppState, def_id: &str, on_route: bool, now: i64) {
147    for block_id in worker_notes::live_panes_of(&state.mstore, def_id) {
148        let Some(block) = state.mstore.get::<obj::Block>(&block_id).ok().flatten() else { continue };
149        for key in stale_keys(&block.meta, on_route, now) {
150            set_meta(state, &block_id, key, Value::Null);
151        }
152    }
153}
154
155fn handle(state: &AppState, event: Event) {
156    let now = agentmux_common::time::now_ms();
157    match event {
158        Event::Settled(grant) => {
159            on_settled(state, &grant, now);
160            crate::server::compact_backstop::after_settled(state, &grant);
161        }
162        Event::Refused(grant, hit) => {
163            if spend::alerted(&grant.agent, now) < 100 {
164                spend::set_alerted(&grant.agent, 100, now);
165                stop(state, &grant, &hit, now);
166            }
167        }
168    }
169}
170
171/// Writes the figure the chips show to the agent's open panes: at most every [`TODAY_EVERY_MS`] unless `force`.
172fn publish_today(state: &AppState, def_id: &str, agent: &str, cap: Option<f64>, spent: f64, now: i64, force: bool) {
173    static LAST: OnceLock<std::sync::Mutex<std::collections::HashMap<String, i64>>> = OnceLock::new();
174    {
175        let mut last = LAST.get_or_init(Default::default).lock().unwrap();
176        if !force && last.get(agent).is_some_and(|at| now - at < TODAY_EVERY_MS) {
177            return;
178        }
179        last.insert(agent.to_string(), now);
180    }
181    let value = json!({ "day": now.div_euclid(86_400_000), "spent": spent, "cap": cap });
182    for block_id in worker_notes::live_panes_of(&state.mstore, def_id) {
183        let same = state.mstore.get::<obj::Block>(&block_id).ok().flatten().is_some_and(|b| b.meta.get(TODAY_META_KEY) == Some(&value));
184        if !same {
185            set_meta(state, &block_id, TODAY_META_KEY, value.clone());
186        }
187    }
188}
189
190fn on_settled(state: &AppState, grant: &Grant, now: i64) {
191    // A response that worked: a route that was out of credits is not.
192    crate::backend::route_credits::cleared(&state.mstore, &state.event_bus, &state.broker, &grant.route);
193    let settings = state.config_watcher.get_settings().extra;
194    let (level, cap, spent) = cap::agent_level(&state.mstore, &settings, grant, now);
195    let sent = spend::alerted(&grant.agent, now);
196    publish_today(state, &grant.def_id, &grant.agent, cap, spent, now, level > sent);
197    // The first response of a day, or one after a cap was lifted in Settings: the stop is over.
198    if spend::today(&grant.agent, now).requests == 1 || (sent >= 100 && level < 100 && cap::reached(&state.mstore, &settings, grant, now).is_none()) {
199        clear(state, &grant.def_id, STOPPED_META_KEY);
200        if sent >= 100 {
201            spend::set_alerted(&grant.agent, level, now);
202        }
203    }
204    let (Some(cap), true) = (cap, level > sent) else { return };
205    spend::set_alerted(&grant.agent, level, now);
206    let hit = Hit { scope: Scope::Agent, cap, spent };
207    match level {
208        100 => stop(state, grant, &hit, now),
209        80 => warn(state, grant, &hit, now),
210        _ => {
211            let note = format!("{} has used ${spent:.2} of its ${cap:.2} for today on {}.", name_of(state, &grant.def_id), place_of(state, grant));
212            // Nothing for the leader to act on yet: it reads this with its next turn, and is not woken for it.
213            worker_notes::tell_leader_held(&state.mstore, &grant.def_id, &note, &format!("spend-{}", grant.agent));
214        }
215    }
216}
217
218/// "OpenRouter (DeepSeek V4.1 Flash)": where the agent's spend goes.
219fn place_of(state: &AppState, grant: &Grant) -> String {
220    let Some(route) = catalog::gateway_route(&grant.route) else { return grant.route.clone() };
221    match launch::model_on_route(&state.mstore, &grant.def_id, route) {
222        Some(model) => format!("{} ({})", route.label, model.label),
223        None => route.label.to_string(),
224    }
225}
226
227fn name_of(state: &AppState, def_id: &str) -> String {
228    state.mstore.agent_def_get(def_id).ok().flatten().map_or_else(|| def_id.to_string(), |d| d.name)
229}
230
231fn card(state: &AppState, grant: &Grant, hit: &Hit, now: i64) -> Value {
232    let scope = if hit.scope == Scope::Agent { "agent" } else { "route" };
233    json!({ "at": now, "scope": scope, "cap": hit.cap, "spent": hit.spent, "route": grant.route, "place": place_of(state, grant) })
234}
235
236pub(crate) fn set_meta(state: &AppState, block_id: &str, key: &str, value: Value) {
237    let mut update = obj::MetaMapType::new();
238    update.insert(key.to_string(), value);
239    match crate::server::service::update_object_meta(&state.mstore, &format!("block:{block_id}"), &update) {
240        Ok(()) => blockcontroller::core::broadcast_block_update(&state.mstore, &state.event_bus, block_id),
241        Err(e) => tracing::warn!(block_id, key, error = %e, "spend cap: the pane was not told"),
242    }
243}
244
245/// Takes `key` off every open pane of the agent that carries it.
246pub(crate) fn clear(state: &AppState, def_id: &str, key: &str) {
247    for block_id in worker_notes::live_panes_of(&state.mstore, def_id) {
248        let carries = state.mstore.get::<obj::Block>(&block_id).ok().flatten().is_some_and(|b| b.meta.get(key).is_some_and(|v| !v.is_null()));
249        if carries {
250            set_meta(state, &block_id, key, Value::Null);
251        }
252    }
253}
254
255fn warn(state: &AppState, grant: &Grant, hit: &Hit, now: i64) {
256    let card = card(state, grant, hit, now);
257    for block_id in worker_notes::live_panes_of(&state.mstore, &grant.def_id) {
258        set_meta(state, &block_id, WARNING_META_KEY, card.clone());
259    }
260}
261
262fn stop(state: &AppState, grant: &Grant, hit: &Hit, now: i64) {
263    let card = card(state, grant, hit, now);
264    for block_id in worker_notes::live_panes_of(&state.mstore, &grant.def_id) {
265        set_meta(state, &block_id, STOPPED_META_KEY, card.clone());
266        set_meta(state, &block_id, WARNING_META_KEY, Value::Null);
267        // The turn in flight ends now rather than retrying against the refusal.
268        if let Some(ctrl) = blockcontroller::get_controller(&block_id) {
269            if let Err(e) = ctrl.interrupt_turn() {
270                tracing::warn!(block_id, error = %e, "spend cap: the turn was not interrupted");
271            }
272        }
273    }
274    let name = name_of(state, &grant.def_id);
275    let note = match hit.scope {
276        Scope::Agent => format!(
277            "{name} is stopped: it has used ${:.2} of its ${:.2} for today on {}. The gateway refuses its requests until its cap is raised (Agents update spend_cap_usd) or the UTC day ends.",
278            hit.spent, hit.cap, place_of(state, grant)
279        ),
280        Scope::Route => format!(
281            "{name} is stopped: the daily cap of ${:.2} for its model route or API key is used by all agents together (${:.2}). It can go on when the cap is raised in Settings (Advanced) or the UTC day ends.",
282            hit.cap, hit.spent
283        ),
284    };
285    tracing::warn!(agent = %grant.agent, route = %grant.route, spent = hit.spent, cap = hit.cap, "spend cap: the agent is stopped");
286    worker_notes::tell_leader(&state.mstore, &grant.def_id, &note);
287}
288
289/// What `Agents list` shows for an agent on a model route: what it has used today and its cap. For an agent on the
290/// DeepSeek Harness, which uses its own key and reports no spend, that nothing is measured. `None` for any other.
291pub(crate) fn view(mstore: &crate::backend::storage::store::Store, identity_store: &crate::backend::storage::store::Store, settings: &std::collections::HashMap<String, Value>, defs: &[crate::backend::storage::AgentDefinition], def_id: &str) -> Option<Value> {
292    if defs.iter().any(|d| d.id == def_id && d.provider == "dsh") {
293        return Some(json!({ "measured": false, "why": "this harness bills the vendor account directly and reports no cost or tokens per call, so AgentMux counts nothing and a daily cap cannot apply; its ceiling is the account's balance" }));
294    }
295    if launch::choice_of(mstore, def_id).is_none() && !on_a_key(mstore, identity_store, def_id) {
296        return None;
297    }
298    let slug = &defs.iter().find(|d| d.id == def_id)?.slug;
299    let spent = spend::today(slug, agentmux_common::time::now_ms()).cost_usd;
300    let cap = cap::agent_cap(mstore, settings, def_id);
301    Some(json!({ "spent_usd": spent, "cap_usd": cap, "stopped": cap.is_some_and(|c| spent >= c) }))
302}
303
304/// The cap before and after a change.
305pub(crate) struct CapChange {
306    pub from: Option<f64>,
307    pub to: Option<f64>,
308}
309
310/// A cap, and a day of spend, belong to an agent on a model route or an API key: a login agent has plan limits instead.
311pub(crate) fn on_a_route(state: &AppState, def_id: &str) -> Result<(), String> {
312    if spends_through_gateway(state, def_id) { Ok(()) } else { Err("the agent is not on a model route or an API key, so it has no spend cap".to_string()) }
313}
314
315/// Sets the agent's daily cap (`None`: no cap). The alert level goes back to where the day now stands, and a stop the
316/// new cap no longer reaches is taken off the agent's panes. The caller has checked who may do this and records it.
317pub(crate) fn change_cap(state: &AppState, def_id: &str, to: Option<f64>) -> Result<CapChange, String> {
318    write_cap(state, def_id, CapWrite::Set(to))
319}
320
321/// Takes the agent's own cap away, so it has the default again, and does what [`change_cap`] does for the cap that gives.
322pub(crate) fn clear_cap(state: &AppState, def_id: &str) -> Result<CapChange, String> {
323    write_cap(state, def_id, CapWrite::Default)
324}
325
326enum CapWrite {
327    Set(Option<f64>),
328    Default,
329}
330
331fn write_cap(state: &AppState, def_id: &str, write: CapWrite) -> Result<CapChange, String> {
332    on_a_route(state, def_id)?;
333    let settings = state.config_watcher.get_settings().extra;
334    let from = cap::agent_cap(&state.mstore, &settings, def_id);
335    let to = match write {
336        CapWrite::Set(to) => {
337            cap::set_agent_cap(&state.mstore, def_id, to)?;
338            to
339        }
340        CapWrite::Default => {
341            cap::clear_agent_cap(&state.mstore, def_id)?;
342            cap::default_agent_cap(&settings)
343        }
344    };
345    let Some(def) = state.mstore.agent_def_get(def_id).map_err(|e| e.to_string())?.filter(|d| !d.slug.is_empty()) else {
346        return Ok(CapChange { from, to });
347    };
348    let now = agentmux_common::time::now_ms();
349    let spent = spend::today(&def.slug, now).cost_usd;
350    let level = to.map_or(0, |c| cap::level(spent, c));
351    // A raised cap takes the level down. A lowered one leaves it where it was: the next response, or the next request the
352    // gateway refuses, finds the level above it and sends the warning or the stop, which setting it here would skip.
353    if level < spend::alerted(&def.slug, now) {
354        spend::set_alerted(&def.slug, level, now);
355    }
356    publish_today(state, def_id, &def.slug, to, spent, now, true);
357    if level < 100 {
358        clear(state, def_id, STOPPED_META_KEY);
359    }
360    if level < 80 {
361        clear(state, def_id, WARNING_META_KEY);
362    }
363    Ok(CapChange { from, to })
364}
365
366/// Zeroes the agent's spend for today and takes its stop and warning off. Returns the dollars that were counted.
367pub(crate) fn reset_today(state: &AppState, def_id: &str) -> Result<f64, String> {
368    on_a_route(state, def_id)?;
369    let def = state.mstore.agent_def_get(def_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no agent {def_id}"))?;
370    let now = agentmux_common::time::now_ms();
371    let removed = spend::reset_today(&def.slug, now);
372    publish_today(state, def_id, &def.slug, cap::agent_cap(&state.mstore, &state.config_watcher.get_settings().extra, def_id), 0.0, now, true);
373    clear(state, def_id, STOPPED_META_KEY);
374    clear(state, def_id, WARNING_META_KEY);
375    Ok(removed)
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381    use crate::agents::types::TokenCounts;
382    use crate::backend::storage::store::Store;
383
384    #[test]
385    fn an_agent_on_the_deepseek_harness_is_listed_as_not_measured() {
386        let store = Store::open_in_memory().unwrap();
387        let mut def = crate::backend::storage::agents::test_agent_def("dsh-def", "dsh-agent", "dsh", "host", 1, "");
388        def.slug = "dsh-agent".to_string();
389        store.agent_def_insert(&mut def).unwrap();
390        let defs = store.agent_def_list().unwrap();
391        let shown = view(&store, &store, &Default::default(), &defs, "dsh-def").expect("a line saying so");
392        assert_eq!(shown["measured"], json!(false));
393        assert!(shown.get("spent_usd").is_none() && shown.get("cap_usd").is_none(), "no figure is made up");
394    }
395
396    #[test]
397    fn an_agent_stopped_at_its_cap_that_leaves_a_route_and_returns_gets_its_stop_again() {
398        let model = crate::backend::model_gateway::catalog::route("openrouter").unwrap().model("deepseek/deepseek-v4.1-flash-1017").unwrap();
399        let used = TokenCounts { input: 1_000_000, ..Default::default() };
400        let now = 5_000;
401        spend::record("stop-return", "openrouter", model, &used, Some(1.0), now);
402        spend::set_alerted("stop-return", 100, now);
403        forget_alert_off_route("stop-return", true, now);
404        assert_eq!(spend::alerted("stop-return", now), 100, "on its route the stop stays counted as sent");
405        forget_alert_off_route("stop-return", false, now);
406        assert_eq!(spend::alerted("stop-return", now), 0, "off the route it is forgotten, so the next refusal sends the stop");
407    }
408
409    fn meta_of(entries: &[(&str, Value)]) -> obj::MetaMapType {
410        entries.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
411    }
412
413    #[test]
414    fn an_agent_off_its_route_carries_no_spend_keys() {
415        let now = 20_000 * DAY_MS + 5_000;
416        let meta = meta_of(&[
417            (TODAY_META_KEY, json!({ "day": 20_000, "spent": 4.2, "cap": 20.0 })),
418            (STOPPED_META_KEY, json!({ "at": now - 1, "cap": 20.0, "spent": 20.0 })),
419            (WARNING_META_KEY, Value::Null),
420            ("agent:other", json!(1)),
421        ]);
422        assert_eq!(stale_keys(&meta, false, now), vec![TODAY_META_KEY, STOPPED_META_KEY], "a null key is already gone");
423        assert!(stale_keys(&meta_of(&[]), false, now).is_empty());
424    }
425
426    #[test]
427    fn on_a_route_only_a_stop_or_warning_from_an_earlier_utc_day_goes() {
428        let now = 20_000 * DAY_MS + 5_000;
429        let yesterday = 20_000 * DAY_MS - 1;
430        let meta = meta_of(&[
431            (TODAY_META_KEY, json!({ "day": 19_999, "spent": 20.0, "cap": 20.0 })),
432            (STOPPED_META_KEY, json!({ "at": yesterday, "cap": 20.0, "spent": 20.0 })),
433            (WARNING_META_KEY, json!({ "at": yesterday, "cap": 20.0, "spent": 16.0 })),
434        ]);
435        assert_eq!(stale_keys(&meta, true, now), vec![STOPPED_META_KEY, WARNING_META_KEY], "the chip's figure is day-gated by its reader");
436        let today = meta_of(&[(STOPPED_META_KEY, json!({ "at": 20_000 * DAY_MS, "cap": 20.0, "spent": 20.0 })), (WARNING_META_KEY, json!({ "cap": 20.0 }))]);
437        assert!(stale_keys(&today, true, now).is_empty(), "this UTC day's stop stays, and a card with no time is left alone");
438    }
439
440    #[test]
441    fn agents_list_shows_spend_for_an_agent_on_a_route_and_nothing_for_any_other() {
442        let store = Store::open_in_memory().unwrap();
443        for (id, slug) in [("view-def", "view-agent"), ("plain-def", "plain-agent")] {
444            let mut def = crate::backend::storage::agents::test_agent_def(id, slug, "claude", "host", 1, "");
445            def.slug = slug.to_string();
446            store.agent_def_insert(&mut def).unwrap();
447        }
448        launch::set_choice(&store, "view-def", "claude", "openrouter", "").unwrap();
449        let model = catalog::route("openrouter").unwrap().model("deepseek/deepseek-v4.1-flash-1017").unwrap();
450        let used = TokenCounts { input: 1, ..Default::default() };
451        let now = agentmux_common::time::now_ms();
452        spend::record("view-agent", "openrouter", model, &used, Some(4.5), now);
453        let defs = store.agent_def_list().unwrap();
454        let shown = view(&store, &store, &Default::default(), &defs, "view-def").expect("an agent on a route");
455        assert_eq!((shown["spent_usd"].as_f64(), shown["cap_usd"].as_f64(), shown["stopped"].as_bool()), (Some(4.5), Some(cap::DEFAULT_AGENT_CAP_USD), Some(false)));
456        assert!(view(&store, &store, &Default::default(), &defs, "plain-def").is_none(), "a login agent has no spend line");
457        spend::record("view-agent", "openrouter", model, &used, Some(cap::DEFAULT_AGENT_CAP_USD - 4.5), now);
458        assert_eq!(view(&store, &store, &Default::default(), &defs, "view-def").unwrap()["stopped"], json!(true));
459    }
460}