Skip to main content

agentmux_srv/server/app_api/
agent_model.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The composer's model panel, srv's half (`docs/specs/SPEC_AGENT_MODEL_ROUTES_ANY_MODEL_SPAWN_AND_SWITCH_2026_11_06.md`
5//! section 7a). `agent.model.panel` says what the panel may offer for a pane's agent and what cannot be picked, with
6//! the reason; `agent.model.switch` is a person's pick: it moves the agent to a model on a route, or back to the
7//! harness's own sign-in, and restarts its panes so the next turn runs there. Both are the operator's window only: the
8//! click is the approval of the spend, which an agent cannot give for itself.
9
10use std::sync::Arc;
11
12use serde::{Deserialize, Serialize};
13
14use crate::backend::model_gateway::catalog::{self, Model, Route};
15use crate::backend::model_gateway::launch::{self, Choice};
16use crate::backend::model_gateway::switch::{self, Target};
17use crate::backend::rpc::engine::WshRpcEngine;
18use crate::backend::rpc_types::{COMMAND_AGENT_MODEL_PANEL, COMMAND_AGENT_MODEL_SWITCH, COMMAND_AGENT_PEER_LABELS};
19use crate::backend::storage::agents::AgentDefinition;
20use crate::backend::vault::route_key;
21use crate::server::AppState;
22
23/// A conversation over this many tokens makes a switch worth a warning: the new model reads all of it again at full
24/// input price, because a prompt cache belongs to one model.
25const REREAD_WARNING_TOKENS: u32 = 50_000;
26
27/// What a conversation is taken to need after `/compact`: the summary, the system prompt and the tool definitions. A
28/// model whose context is smaller than the conversation can still take it compacted when its context is above this.
29const COMPACTED_TOKENS: u32 = 40_000;
30
31#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
32#[ts(export, export_to = "../../../frontend/types/rpc/")]
33pub struct AgentModelPanelReq {
34    /// The agent pane.
35    pub blockid: String,
36    /// How much the conversation holds now, from the harness's last usage report; absent when not known.
37    #[serde(default)]
38    pub conversation_tokens: Option<u32>,
39    /// How many images the conversation holds; absent when not known.
40    #[serde(default)]
41    pub images: Option<u32>,
42}
43
44#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
45#[ts(export, export_to = "../../../frontend/types/rpc/")]
46pub struct AgentModelPanelModel {
47    pub id: String,
48    pub label: String,
49    pub context: u32,
50    /// US dollars per million tokens.
51    pub price_in: f64,
52    pub price_out: f64,
53    pub tools: bool,
54    pub thinking: bool,
55    pub images: bool,
56    /// The route's default model.
57    pub default: bool,
58    /// The agent runs this now.
59    pub current: bool,
60    /// Why it cannot be picked, or absent.
61    pub unavailable: Option<String>,
62    /// Why the conversation has to be compacted before this model can take it (it holds more than the model's context,
63    /// and a compacted one fits), or absent. The row is offered as "Compact, then switch".
64    pub compact_first: Option<String>,
65    /// About what the switch costs in re-reading the conversation at this model's input price, when it is large.
66    pub reread_cost_usd: Option<f64>,
67}
68
69#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
70#[ts(export, export_to = "../../../frontend/types/rpc/")]
71pub struct AgentModelPanelRoute {
72    pub id: String,
73    pub label: String,
74    pub key_present: bool,
75    /// The Vault label of the key, for the "add it in the Vault" row.
76    pub key_label: String,
77    pub models: Vec<AgentModelPanelModel>,
78}
79
80/// A route and model the agent is on or was on. An empty `route` is the harness's own sign-in.
81#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
82#[ts(export, export_to = "../../../frontend/types/rpc/")]
83pub struct AgentModelPlace {
84    pub route: String,
85    pub model: String,
86    pub label: String,
87}
88
89#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
90#[ts(export, export_to = "../../../frontend/types/rpc/")]
91pub struct AgentModelPanel {
92    pub harness: String,
93    /// The route the agent is on, or absent on the harness's own sign-in.
94    pub current: Option<AgentModelPlace>,
95    /// Where it was before its last change.
96    pub previous: Option<AgentModelPlace>,
97    pub routes: Vec<AgentModelPanelRoute>,
98}
99
100#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
101#[ts(export, export_to = "../../../frontend/types/rpc/")]
102pub struct AgentModelSwitchReq {
103    pub blockid: String,
104    /// The route, or empty for the harness's own sign-in.
105    pub route: String,
106    /// The model on the route; empty is the route's default.
107    #[serde(default)]
108    pub model: String,
109    /// Restart the agent's panes (at the end of a turn in progress). The caller that goes on to change the
110    /// harness's own model itself leaves it out, so there is one restart and not two.
111    #[serde(default = "yes")]
112    pub restart: bool,
113    /// Start a new session on the new model instead of resuming the conversation: each pane ends its session when its
114    /// turn ends, and a first message (the move, and `handoff`) starts the new one. A conversation written by another
115    /// model can send a new one into a loop of thinking, which resuming it does not avoid. Wins over `restart`.
116    #[serde(default)]
117    pub fresh: bool,
118    /// With `fresh`: what the next session must know, in its first message. Empty: it reads its task list.
119    #[serde(default)]
120    pub handoff: Option<String>,
121}
122
123fn yes() -> bool {
124    true
125}
126
127#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
128#[ts(export, export_to = "../../../frontend/types/rpc/")]
129pub struct AgentModelSwitchResult {
130    /// False when the agent was already there.
131    pub changed: bool,
132    pub restarted: u32,
133    pub failed: Vec<String>,
134    /// Panes that start a fresh session (a running pane when its turn ends, a stopped one at its next start).
135    #[serde(default)]
136    pub fresh: u32,
137}
138
139/// What `agent.peer-labels` answers.
140#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
141#[ts(export, export_to = "../../../frontend/types/rpc/")]
142pub struct AgentPeerLabels {
143    /// By agent definition id: the model the agent really runs and the route that serves it, such as
144    /// "DeepSeek V4.1 Flash via OpenRouter". An agent on its harness's own sign-in is not listed.
145    pub labels: std::collections::HashMap<String, String>,
146}
147
148/// The model and route an agent with `choice` runs on `harness`, or None when it has no choice or the saved one no longer
149/// validates (the launch falls back to the harness's own sign-in then, so the label must too).
150fn peer_label(harness: &str, choice: Option<&Choice>) -> Option<String> {
151    let choice = choice?;
152    let (route, model) = catalog::validate(harness, &choice.route, &choice.model).ok()?;
153    Some(format!("{} via {}", model.label, route.label))
154}
155
156fn peer_labels(state: &AppState) -> Result<AgentPeerLabels, String> {
157    let defs = state.mstore.agent_def_list().map_err(|e| e.to_string())?;
158    let labels = defs
159        .iter()
160        .filter_map(|def| {
161            let harness = state.id_store.resolve_effective_provider_id(def);
162            peer_label(&harness, launch::choice_of(&state.mstore, &def.id).as_ref()).map(|l| (def.id.clone(), l))
163        })
164        .collect();
165    Ok(AgentPeerLabels { labels })
166}
167
168fn agent_of_block(state: &AppState, block_id: &str) -> Result<AgentDefinition, String> {
169    let instance = state
170        .mstore
171        .instance_get_active_for_block(block_id)
172        .map_err(|e| e.to_string())?
173        .ok_or_else(|| format!("no agent runs in block {block_id}"))?;
174    state.mstore.agent_def_get(&instance.definition_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no agent definition {}", instance.definition_id))
175}
176
177fn place(route: &str, model: &str) -> AgentModelPlace {
178    let label = catalog::route(route).and_then(|r| r.model(model)).map_or_else(|| model.to_string(), |m| m.label.to_string());
179    AgentModelPlace { route: route.to_string(), model: model.to_string(), label }
180}
181
182/// Why the model cannot be picked now, if it cannot.
183fn unavailable(route: &Route, model: &Model, key_present: bool, images: u32) -> Option<String> {
184    if !key_present {
185        return Some(format!("key missing: add \"{}\" in the Vault", route.key_label));
186    }
187    if images > 0 && !model.images {
188        return Some(format!("can't read images ({images} in this conversation)"));
189    }
190    None
191}
192
193/// Whether a conversation of `tokens` fits the model's context: as it is, only once compacted (`Some` with the sizes, to
194/// say so), or not even then.
195#[derive(Debug, PartialEq, Eq)]
196enum Fit {
197    Yes,
198    AfterCompact(String),
199    No(String),
200}
201
202fn kilo(tokens: u32) -> String {
203    if tokens >= 1_000_000 {
204        format!("{:.1}M", f64::from(tokens) / 1_000_000.0).replace(".0M", "M")
205    } else {
206        format!("{}K", tokens.div_ceil(1000))
207    }
208}
209
210fn fit(context: u32, tokens: u32) -> Fit {
211    if tokens <= context {
212        return Fit::Yes;
213    }
214    let sizes = format!("the conversation ({}) is larger than this model's context ({})", kilo(tokens), kilo(context));
215    if context > COMPACTED_TOKENS {
216        Fit::AfterCompact(sizes)
217    } else {
218        Fit::No(format!("{sizes}, even compacted"))
219    }
220}
221
222fn panel_model(route: &Route, model: &Model, current: Option<&Choice>, key_present: bool, req: &AgentModelPanelReq) -> AgentModelPanelModel {
223    let tokens = req.conversation_tokens.unwrap_or(0);
224    let is_current = current.is_some_and(|c| c.route == route.id && c.model == model.id);
225    let mut unavailable = unavailable(route, model, key_present, req.images.unwrap_or(0));
226    // The model the agent runs now is never made unpickable by its own size: it is where the conversation already is.
227    let mut compact_first = None;
228    if unavailable.is_none() && !is_current {
229        match fit(model.context, tokens) {
230            Fit::Yes => {}
231            Fit::AfterCompact(why) => compact_first = Some(why),
232            Fit::No(why) => unavailable = Some(why),
233        }
234    }
235    AgentModelPanelModel {
236        id: model.id.to_string(),
237        label: model.label.to_string(),
238        context: model.context,
239        price_in: model.price_in,
240        price_out: model.price_out,
241        tools: model.tools,
242        thinking: model.thinking,
243        images: model.images,
244        default: model.id == route.default_model,
245        current: is_current,
246        unavailable,
247        compact_first,
248        reread_cost_usd: (tokens >= REREAD_WARNING_TOKENS).then(|| f64::from(tokens) / 1_000_000.0 * model.price_in),
249    }
250}
251
252/// The images in the agent's conversation, as its transcript lists them: the pane's own count only sees the feed it has
253/// loaded, and a text-only model chosen for a conversation that still holds an image fails on it. 0 when it is not known.
254fn images_in_conversation(def: &AgentDefinition) -> u32 {
255    let Some(gfs) = crate::backend::agent_session::global_transcript_store() else { return 0 };
256    let zone = crate::backend::agent_session::agent_current_zone(&def.id);
257    crate::backend::transcript::images::count_in_zone(gfs, &zone).unwrap_or_else(|e| {
258        tracing::warn!(agent = %def.slug, error = %e, "model panel: the images in the conversation were not counted");
259        0
260    })
261}
262
263/// The images in the conversation as far as they are known without reading the transcript, and the count started in the
264/// background for the next time. The first count of a big agent's transcript takes longer than the panel's request has,
265/// and a panel that times out shows the harness's own models alone. 0 when it is not known.
266fn images_known(def: &AgentDefinition) -> u32 {
267    let Some(gfs) = crate::backend::agent_session::global_transcript_store() else { return 0 };
268    let zone = crate::backend::agent_session::agent_current_zone(&def.id);
269    crate::backend::transcript::images::warm(gfs, &zone);
270    crate::backend::transcript::images::counted(&zone).unwrap_or(0)
271}
272
273fn panel(state: &AppState, req: &AgentModelPanelReq) -> Result<AgentModelPanel, String> {
274    let def = agent_of_block(state, &req.blockid)?;
275    let harness = state.id_store.resolve_effective_provider_id(&def);
276    // The pane's count is a hint: the larger of the two is the one to go by. The switch counts exactly before it moves.
277    let req = &AgentModelPanelReq { images: Some(req.images.unwrap_or(0).max(images_known(&def))), ..req.clone() };
278    let current = launch::choice_of(&state.mstore, &def.id);
279    let routes = catalog::ROUTES
280        .iter()
281        .filter(|r| r.harness == harness)
282        .map(|route| {
283            let key_present = route_key::present(&state.identity_store, route.key_label);
284            AgentModelPanelRoute {
285                id: route.id.to_string(),
286                label: route.label.to_string(),
287                key_present,
288                key_label: route.key_label.to_string(),
289                models: route.models.iter().map(|m| panel_model(route, m, current.as_ref(), key_present, req)).collect(),
290            }
291        })
292        .collect();
293    Ok(AgentModelPanel {
294        harness,
295        current: current.map(|c| place(&c.route, &c.model)),
296        previous: switch::previous_of(&state.mstore, &def.id).map(|p| place(&p.route, &p.model)),
297        routes,
298    })
299}
300
301/// A model that cannot read the images in the conversation is refused, with the reason the panel gives for it. A route or
302/// model that does not validate is left to the switch, which says so.
303fn refuse_unreadable(harness: &str, route: &str, model: &str, images: u32) -> Result<(), String> {
304    match catalog::validate(harness, route, model) {
305        Ok((r, m)) => unavailable(r, m, true, images).map_or(Ok(()), Err),
306        Err(_) => Ok(()),
307    }
308}
309
310/// What a fresh session on a model change needs, checked before anything is changed: a handoff within the limit, and every
311/// pane of the agent able to start a fresh session (the test `Agents fresh` applies to its own pane).
312pub(crate) fn check_fresh(state: &AppState, def_id: &str, handoff: &str) -> Result<(), String> {
313    if handoff.chars().count() > super::agent_context::HANDOFF_MAX_CHARS {
314        return Err(format!("the handoff is over {} characters: shorten it, with the next step in it", super::agent_context::HANDOFF_MAX_CHARS));
315    }
316    for block in crate::server::account_episodes::panes_of(state, def_id) {
317        super::agent_context::fresh_refusal(state, &block.oid).map_err(fresh_refused)?;
318    }
319    Ok(())
320}
321
322/// What a refused fresh session says: why, and what to do instead.
323fn fresh_refused(why: &str) -> String {
324    format!("a fresh session is not possible for this agent ({why}), so this model change was not made: change it without fresh to resume the conversation, or compact it first")
325}
326
327/// Starts the fresh sessions of a model change. A running pane ends its session when its turn ends and starts the new one
328/// with `message`, on the model the agent is set to now; a pane with no controller (a stopped agent) forgets the session
329/// it would resume, so its next start begins a new one. Returns how many panes will start fresh, and what could not.
330pub(crate) fn start_fresh_panes(state: &AppState, def_id: &str, message: &str) -> (u32, Vec<String>) {
331    let (mut started, mut failed, mut running) = (0, Vec::new(), 0);
332    for block in crate::server::account_episodes::panes_of(state, def_id) {
333        if crate::backend::blockcontroller::get_controller(&block.oid).is_some() {
334            if super::agent_context::start_fresh_after_switch(state, &block.oid, message.to_string()) {
335                started += 1;
336                running += 1;
337            } else {
338                failed.push("no runtime to start the fresh session on".to_string());
339            }
340        } else {
341            crate::backend::blockcontroller::core::forget_saved_session(&block.oid, &state.mstore, &state.event_bus);
342            started += 1;
343        }
344    }
345    // The route the agent left ends when a launch on the new one follows (`launch.rs`): with no running pane to relaunch, or one that
346    // could not be started, nothing is coming to do it, so it ends now, as `restart_panes` does.
347    if running == 0 || !failed.is_empty() {
348        switch::finish_leaving_after_relaunch(&state.mstore, def_id, "", |b| switch::pane_in_a_turn(&state.mstore, b));
349    }
350    (started, failed)
351}
352
353/// Where the agent is moved to, as its first message says it: the model's name and its route, or the harness's own sign-in.
354pub(crate) fn place_label(harness: &str, route: &str, model: &str) -> String {
355    if route.is_empty() {
356        return "the harness's own sign-in".to_string();
357    }
358    match catalog::validate(harness, route, model) {
359        Ok((r, m)) => format!("{} on {}", m.label, r.label),
360        Err(_) => format!("{route} {model}").trim().to_string(),
361    }
362}
363
364pub(crate) fn switch_model(state: &AppState, req: &AgentModelSwitchReq) -> Result<AgentModelSwitchResult, String> {
365    let def = agent_of_block(state, &req.blockid)?;
366    let harness = state.id_store.resolve_effective_provider_id(&def);
367    let route = req.route.trim();
368    let target = if route.is_empty() { Target::OwnLogin } else { Target::Route { route, model: req.model.trim() } };
369    if let Target::Route { route, model } = target {
370        refuse_unreadable(&harness, route, model, images_in_conversation(&def))?;
371        // One payer: an agent on an API key is not also put on a model route, which would bill the route and leave the key linked.
372        if crate::server::spend_watch::on_a_key(&state.mstore, &state.identity_store, &def.id) {
373            return Err("ACCOUNT_CANT_RUN: this agent is on an API key, which is billed to the key; move it back to a plan account first".to_string());
374        }
375    }
376    let handoff = req.handoff.as_deref().map(str::trim).unwrap_or_default();
377    // Before anything changes: a fresh session that can't be started must not leave the model moved behind it.
378    if req.fresh {
379        check_fresh(state, &def.id, handoff)?;
380    }
381    let moved = switch::move_to(&state.mstore, &def.id, &harness, target, |r| route_key::present(&state.identity_store, r.key_label))?;
382    if !moved.changed() || (!req.restart && !req.fresh) {
383        return Ok(AgentModelSwitchResult { changed: moved.changed(), restarted: 0, failed: Vec::new(), fresh: 0 });
384    }
385    if req.fresh {
386        let message = super::agent_context::switch_message(&place_label(&harness, route, req.model.trim()), handoff);
387        let (fresh, failed) = start_fresh_panes(state, &def.id, &message);
388        return Ok(AgentModelSwitchResult { changed: true, restarted: 0, failed, fresh });
389    }
390    let (restarted, failed) = restart_panes(state, &def.id);
391    Ok(AgentModelSwitchResult { changed: true, restarted, failed, fresh: 0 })
392}
393
394/// Restarts the agent's panes on its new place, and ends the access of a route it left when no relaunch is coming to do it:
395/// the pane restarts at the end of its turn, and its relaunch is what takes the old route's token away.
396pub(crate) fn restart_panes(state: &AppState, def_id: &str) -> (u32, Vec<String>) {
397    let (restarted, next_turn, failed) = crate::server::account_episodes::restart_panes_of(state, def_id);
398    // Nothing is coming to relaunch it, or a pane could not be: end it now, unless a pane is still in a turn on the old route.
399    if (restarted == 0 && next_turn == 0) || !failed.is_empty() {
400        switch::finish_leaving_after_relaunch(&state.mstore, def_id, "", |b| switch::pane_in_a_turn(&state.mstore, b));
401    }
402    (restarted, failed)
403}
404
405/// A request slower than this is worth a line in the log: the panel is waiting for it with its harness models showing.
406const SLOW_REQUEST_MS: u128 = 2_000;
407
408/// What became of a request from the window. Nothing else records it: a refused or failed one reaches only the pane, and
409/// the pane had nothing to say about a panel it could not read.
410fn logged<T>(command: &str, block: &str, started: std::time::Instant, result: Result<T, String>) -> Result<T, String> {
411    let ms = started.elapsed().as_millis();
412    match &result {
413        Err(error) => tracing::warn!(command, block, ms = ms as u64, %error, "model panel: the request failed"),
414        Ok(_) if ms >= SLOW_REQUEST_MS => tracing::warn!(command, block, ms = ms as u64, "model panel: the request was slow"),
415        Ok(_) => {}
416    }
417    result
418}
419
420/// Both commands are the window's: an agent may change its own model through `Agents update`, which stays on its
421/// route and is counted against its hourly limit.
422pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
423    let s = state.clone();
424    engine.register_typed(COMMAND_AGENT_MODEL_PANEL, move |req: AgentModelPanelReq, ctx| {
425        let s = s.clone();
426        async move {
427            let (block, started) = (req.blockid.clone(), std::time::Instant::now());
428            let result = match ctx.operator_only("only the AgentMux window reads the model panel") {
429                Ok(()) => tokio::task::spawn_blocking(move || panel(&s, &req)).await.map_err(|e| format!("the panel request panicked: {e}")).and_then(|r| r),
430                Err(refused) => Err(refused),
431            };
432            logged(COMMAND_AGENT_MODEL_PANEL, &block, started, result)
433        }
434    });
435    let s = state.clone();
436    // No argument: `Value` takes whatever the caller sends. Any caller may read it: it names no key and no price.
437    engine.register_typed(COMMAND_AGENT_PEER_LABELS, move |_data: serde_json::Value, _ctx| {
438        let s = s.clone();
439        async move { tokio::task::spawn_blocking(move || peer_labels(&s)).await.map_err(|e| e.to_string())? }
440    });
441    let s = state.clone();
442    engine.register_typed(COMMAND_AGENT_MODEL_SWITCH, move |req: AgentModelSwitchReq, ctx| {
443        let s = s.clone();
444        async move {
445            let (block, started) = (req.blockid.clone(), std::time::Instant::now());
446            let result = match ctx.operator_only("only a person moves an agent to a model route, because it spends their key") {
447                Ok(()) => tokio::task::spawn_blocking(move || switch_model(&s, &req)).await.map_err(|e| format!("the switch request panicked: {e}")).and_then(|r| r),
448                Err(refused) => Err(refused),
449            };
450            logged(COMMAND_AGENT_MODEL_SWITCH, &block, started, result)
451        }
452    });
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458
459    fn req(tokens: Option<u32>, images: Option<u32>) -> AgentModelPanelReq {
460        AgentModelPanelReq { blockid: "b".into(), conversation_tokens: tokens, images }
461    }
462
463    #[test]
464    fn a_logged_request_answers_as_it_did() {
465        let now = std::time::Instant::now();
466        assert_eq!(logged("c", "b", now, Ok::<_, String>(3)), Ok(3));
467        assert_eq!(logged::<u8>("c", "b", now, Err("no agent runs in block b".into())), Err("no agent runs in block b".to_string()));
468    }
469
470    #[test]
471    fn a_route_agent_is_labelled_with_its_model_and_route() {
472        let on_route = Choice { route: "openrouter".into(), model: "deepseek/deepseek-v4.1-flash-1017".into() };
473        assert_eq!(peer_label("claude", Some(&on_route)).as_deref(), Some("DeepSeek V4.1 Flash via OpenRouter"));
474        // No choice, or a saved one that no longer validates (another harness, an unknown model): the harness's own sign-in.
475        assert_eq!(peer_label("claude", None), None);
476        assert_eq!(peer_label("codex", Some(&on_route)), None);
477        let gone = Choice { route: "openrouter".into(), model: "nobody/retired".into() };
478        assert_eq!(peer_label("claude", Some(&gone)), None);
479    }
480
481    #[test]
482    fn a_model_that_cannot_be_picked_says_why() {
483        let route = catalog::route("openrouter").unwrap();
484        let pro = route.model("deepseek/deepseek-v4-pro-0813").unwrap();
485        let no_key = unavailable(route, pro, false, 0).unwrap();
486        assert!(no_key.starts_with("key missing") && no_key.contains("OpenRouter API key"), "{no_key}");
487        assert!(unavailable(route, pro, true, 0).is_none());
488        assert_eq!(unavailable(route, pro, true, 3).unwrap(), "can't read images (3 in this conversation)");
489        let flash = route.model("deepseek/deepseek-v4.1-flash-1017").unwrap();
490        assert!(unavailable(route, flash, true, 3).is_none(), "this one reads images");
491    }
492
493    #[test]
494    fn a_switch_to_a_model_that_cannot_read_the_conversations_images_is_refused_with_the_panels_reason() {
495        let pro = "deepseek/deepseek-v4-pro-0813";
496        assert_eq!(refuse_unreadable("claude", "openrouter", pro, 2).unwrap_err(), "can't read images (2 in this conversation)");
497        assert!(refuse_unreadable("claude", "openrouter", pro, 0).is_ok(), "no image, no refusal");
498        assert!(refuse_unreadable("claude", "openrouter", "deepseek/deepseek-v4.1-flash-1017", 2).is_ok(), "this one reads images");
499        assert!(refuse_unreadable("claude", "openrouter", "nobody/retired", 2).is_ok(), "the switch says what is wrong with it");
500    }
501
502    #[test]
503    fn a_big_conversation_shows_what_re_reading_it_costs() {
504        let route = catalog::route("openrouter").unwrap();
505        let flash = route.model("deepseek/deepseek-v4.1-flash-1017").unwrap();
506        let big = panel_model(route, flash, None, true, &req(Some(200_000), None));
507        assert!((big.reread_cost_usd.unwrap() - 0.03).abs() < 1e-9, "{:?}", big.reread_cost_usd);
508        assert!(panel_model(route, flash, None, true, &req(Some(10_000), None)).reread_cost_usd.is_none());
509        assert!(panel_model(route, flash, None, true, &req(None, None)).reread_cost_usd.is_none());
510    }
511
512    #[test]
513    fn the_model_the_agent_runs_is_marked_current() {
514        let route = catalog::route("openrouter").unwrap();
515        let flash = route.model("deepseek/deepseek-v4.1-flash-1017").unwrap();
516        let on = Choice { route: "openrouter".into(), model: flash.id.into() };
517        assert!(panel_model(route, flash, Some(&on), true, &req(None, None)).current);
518        assert!(!panel_model(route, flash, None, true, &req(None, None)).current);
519    }
520
521    #[test]
522    fn sizes_read_in_thousands_and_in_millions_to_one_decimal() {
523        assert_eq!(kilo(40_000), "40K");
524        assert_eq!(kilo(1_000_000), "1M");
525        assert_eq!(kilo(1_048_576), "1M");
526        assert_eq!(kilo(1_500_000), "1.5M");
527    }
528
529    #[test]
530    fn a_conversation_larger_than_a_models_context_is_offered_compacted_when_that_would_fit() {
531        assert_eq!(fit(1_000_000, 200_000), Fit::Yes);
532        assert_eq!(fit(128_000, 128_000), Fit::Yes, "exactly the size");
533        assert_eq!(fit(128_000, 200_000), Fit::AfterCompact("the conversation (200K) is larger than this model's context (128K)".into()));
534        assert_eq!(fit(32_000, 100_000), Fit::No("the conversation (100K) is larger than this model's context (32K), even compacted".into()));
535        assert_eq!(fit(40_000, 100_000), Fit::No("the conversation (100K) is larger than this model's context (40K), even compacted".into()), "no room left over for the work");
536    }
537
538    #[test]
539    fn a_model_too_small_for_the_conversation_is_offered_compacted_and_the_current_one_is_left_alone() {
540        let route = catalog::route("openrouter").unwrap();
541        let flash = route.model("deepseek/deepseek-v4.1-flash-1017").unwrap();
542        let over = req(Some(flash.context + 1), None);
543        let offered = panel_model(route, flash, None, true, &over);
544        assert!(offered.unavailable.is_none() && offered.compact_first.is_some(), "{offered:?}");
545        let on = Choice { route: "openrouter".into(), model: flash.id.into() };
546        let running = panel_model(route, flash, Some(&on), true, &over);
547        assert!(running.current && running.unavailable.is_none() && running.compact_first.is_none(), "{running:?}");
548        assert!(panel_model(route, flash, None, true, &req(Some(10_000), None)).compact_first.is_none());
549    }
550
551    #[test]
552    fn the_fresh_sessions_first_message_names_the_move_and_carries_the_handoff() {
553        let said = super::super::agent_context::switch_message("DeepSeek V4.1 Flash on OpenRouter", "Task 31427 is yours; the next step is the card.");
554        assert!(said.starts_with("[AgentMux] You were moved to DeepSeek V4.1 Flash on OpenRouter and this is a fresh session"), "{said}");
555        assert!(said.contains("Agents search_history"), "it says where the earlier conversation is: {said}");
556        assert!(said.ends_with("Task 31427 is yours; the next step is the card."), "{said}");
557        let none = super::super::agent_context::switch_message("x", "  ");
558        assert!(none.contains("Tasks list"), "with no handoff it says where to look: {none}");
559    }
560
561    #[test]
562    fn a_place_is_named_by_its_model_and_route_or_as_the_harness_own_sign_in() {
563        assert_eq!(place_label("claude", "", ""), "the harness's own sign-in");
564        let flash = place_label("claude", "openrouter", "deepseek/deepseek-v4.1-flash-1017");
565        assert!(flash.contains("Flash") && flash.contains(" on "), "{flash}");
566        assert_eq!(place_label("claude", "nowhere", "m"), "nowhere m", "a place that does not validate is named as given");
567    }
568}