From 0f7cd2eb83f57cc796aa3abbf671cd18852b33a4 Mon Sep 17 00:00:00 2001 From: Tryanks Date: Sat, 5 Dec 2026 06:54:47 +0800 Subject: [PATCH] Models: a harness's models are listed when something that decides them changes, and taken from running sessions OpenCode answers /api/model with whatever has loaded so far until its plugins are in: nothing, then a partial list (2.4.4). The listing read it the moment the server answered and kept what it got, an empty catalog included. It now subscribes to the event stream first and reads once the plugin list has filled, as OpenCode's own one-shot clients wait, and a running session reads again on each model.updated. Every codex app-server fetches Codex's model catalog over the network as it starts (0.174.0). The process started for the models now reads the account's usage too, and a Codex session reports the list it already fetches for reasoning efforts, so neither starts another. The host listed all seven harnesses on every profile edit, a display name or a colour included, stopping the listing under way each time. It now lists a harness again only when what its listing is started with changes (binary, home, environment, whether any account is enabled), when its account signs in or out, when a secret of its is saved, when Tcode updates its CLI, or when the user asks from the harness dialog. A disabled harness is not listed. A change that the settings do not show waits for the listing under way and lists once more instead of stopping it. Sessions report models as AgentEvent::ProviderModels: Codex at start, OpenCode on model.updated, a registry ACP agent whenever its model option changes, which is how an agent that fills its models in after session/new reaches the catalog. A native catalog takes them from sessions of the harness's own account; an ACP catalog keeps the default its probe saw. --- crates/agent/examples/probe.rs | 10 +- crates/agent/src/acp_session.rs | 86 +++-- crates/agent/src/acp_session/tests.rs | 44 +++ crates/agent/src/claude.rs | 1 + crates/agent/src/codex.rs | 88 +++-- crates/agent/src/codex/tests.rs | 1 + crates/agent/src/lib.rs | 39 ++- crates/agent/src/opencode.rs | 68 +++- crates/core/src/session.rs | 1 + crates/core/src/session/boundaries.rs | 1 + crates/protocol/src/command.rs | 5 + crates/protocol/src/lib.rs | 3 +- crates/runtime/src/app/acp.rs | 31 ++ crates/runtime/src/app/authorization.rs | 1 + crates/runtime/src/app/events.rs | 5 + crates/runtime/src/app/providers.rs | 335 +++++++++++++++----- crates/runtime/src/app/sessions.rs | 1 + crates/runtime/src/app/tests/acp_catalog.rs | 44 +++ crates/runtime/src/app/tests/providers.rs | 58 ++++ crates/runtime/src/pipe.rs | 1 + crates/ui/src/harness_dialog.rs | 5 +- crates/ui/src/store/intents.rs | 3 + 22 files changed, 685 insertions(+), 146 deletions(-) diff --git a/crates/agent/examples/probe.rs b/crates/agent/examples/probe.rs index 523b51c02..538297f70 100644 --- a/crates/agent/examples/probe.rs +++ b/crates/agent/examples/probe.rs @@ -251,13 +251,21 @@ fn main() { provider, binary, Default::default(), - Default::default(), + agent::CatalogRefresh { + account_usage: true, + ..Default::default() + }, &Default::default(), ) .await { Ok(listing) => { println!("{}", serde_json::to_string_pretty(&listing.models).unwrap()); + match listing.account_usage { + Some(Ok(usage)) => eprintln!("account usage: {usage}"), + Some(Err(error)) => eprintln!("account usage failed: {error}"), + None => {} + } for problem in listing.problems { eprintln!("{problem}"); } diff --git a/crates/agent/src/acp_session.rs b/crates/agent/src/acp_session.rs index 6fdf3e130..6fd21070f 100644 --- a/crates/agent/src/acp_session.rs +++ b/crates/agent/src/acp_session.rs @@ -2241,7 +2241,13 @@ async fn emit_provider_options( events: &Sender, emit_empty: bool, ) { - let event = state.lock_recover().provider_options(); + let (event, models) = { + let mut state = state.lock_recover(); + (state.provider_options(), state.changed_models()) + }; + if let Some(models) = models { + let _ = events.send(AgentEvent::ProviderModels { models }).await; + } if matches!( &event, AgentEvent::ProviderOptions { descriptors, .. } if descriptors.is_empty() @@ -2528,6 +2534,32 @@ impl OptionRegistry { .find(|record| record.selection.id == MODEL_OPTION_ID) .and_then(|record| record.selection.value.as_str().map(str::to_string)) } + + /// The choices of the agent's model option, the one it is set to marked + /// as the default. + fn models(&self) -> Vec { + self.records + .iter() + .find_map(|record| match &record.descriptor { + OptionDescriptor::Select { + options, + default_value, + .. + } if record.selection.id == MODEL_OPTION_ID => Some( + options + .iter() + .map(|option| crate::ModelSpec { + is_default: default_value.as_deref() == Some(option.value.as_str()), + id: option.value.clone(), + display_name: option.label.clone(), + options: Vec::new(), + }) + .collect(), + ), + _ => None, + }) + .unwrap_or_default() + } } /// What `session/new` offered an ACP agent's sessions on `provider`: the @@ -2539,28 +2571,17 @@ pub(crate) fn catalog( ) -> crate::AcpCatalog { let mut registry = OptionRegistry::new(provider); registry.ingest(modes, config_options); - let mut catalog = crate::AcpCatalog::default(); - for record in registry.records { - match record.descriptor { - OptionDescriptor::Select { - options, - default_value, - .. - } if record.selection.id == MODEL_OPTION_ID => { - catalog.models = options - .into_iter() - .map(|option| crate::ModelSpec { - is_default: default_value.as_deref() == Some(option.value.as_str()), - id: option.value, - display_name: option.label, - options: Vec::new(), - }) - .collect(); - } - descriptor => catalog.options.push(descriptor), - } + crate::AcpCatalog { + models: registry.models(), + options: registry + .records + .into_iter() + .map(|record| record.descriptor) + .filter(|descriptor| { + !matches!(descriptor, OptionDescriptor::Select { id, .. } if id == MODEL_OPTION_ID) + }) + .collect(), } - catalog } fn descriptor_id(descriptor: &OptionDescriptor) -> &str { @@ -2630,6 +2651,8 @@ pub(crate) struct State { terminals: HashMap>, usage: Option, options: OptionRegistry, + /// The models last sent as [`AgentEvent::ProviderModels`]. + reported_models: Vec, /// [`Dialect::owned_config_options`]. owned_options: &'static [&'static str], /// A turn the agent started while another was still open. @@ -2664,6 +2687,7 @@ impl State { terminals: HashMap::new(), usage: None, options: OptionRegistry::new(provider), + reported_models: Vec::new(), owned_options: &[], next_turn: None, modes: None, @@ -2854,6 +2878,21 @@ impl State { self.options.select(id, Value::String(mode.0.to_string())); } + /// The agent's models when they are not the ones last reported. Only an + /// agent from the registry lists its models in its model option alone; + /// the native ACP harnesses each have a catalog of their own. + fn changed_models(&mut self) -> Option> { + if self.options.provider != ProviderKind::Acp { + return None; + } + let models = self.options.models(); + if models == self.reported_models { + return None; + } + self.reported_models.clone_from(&models); + Some(models) + } + fn provider_options(&self) -> AgentEvent { let surfaced = || { self.options.records.iter().filter(|record| { @@ -3076,6 +3115,9 @@ impl State { let previous_model = self.options.current_model(); self.options.ingest(None, Some(&update.config_options)); let mut events = vec![self.provider_options()]; + if let Some(models) = self.changed_models() { + events.push(AgentEvent::ProviderModels { models }); + } if let Some(model) = self.options.current_model() && Some(model.as_str()) != previous_model.as_deref() { diff --git a/crates/agent/src/acp_session/tests.rs b/crates/agent/src/acp_session/tests.rs index accea0ef8..6743e1a4a 100644 --- a/crates/agent/src/acp_session/tests.rs +++ b/crates/agent/src/acp_session/tests.rs @@ -692,6 +692,50 @@ fn modes_and_categorized_config_become_provider_options() { } } +/// A registry agent may answer `session/new` before it knows its models and +/// push them in a `config_option_update` (ACP schema: `SessionConfigOption` +/// of category `model`). The session reports them when they arrive, and not +/// again while they stay the same. +#[test] +fn an_agents_models_are_reported_when_its_model_option_brings_them() { + let mut state = State::new(ProviderKind::Acp, PathBuf::from("/workspace")); + let pushed = || { + update(json!({ + "sessionUpdate": "config_option_update", + "configOptions": [{ + "id": "model", + "name": "Model", + "category": "model", + "type": "select", + "currentValue": "sonnet", + "options": [ + { "value": "sonnet", "name": "Sonnet" }, + { "value": "opus", "name": "Opus" } + ] + }] + })) + }; + let reported = |events: Vec| { + events.into_iter().find_map(|event| match event { + AgentEvent::ProviderModels { models } => Some( + models + .into_iter() + .map(|model| (model.id, model.display_name, model.is_default)) + .collect::>(), + ), + _ => None, + }) + }; + assert_eq!( + reported(state.apply_update(pushed())), + Some(vec![ + ("sonnet".into(), "Sonnet".into(), true), + ("opus".into(), "Opus".into(), false), + ]) + ); + assert_eq!(reported(state.apply_update(pushed())), None); +} + /// An ACP agent's mode, from `modes` or a config option of category `mode`, /// says what runs without asking, so the composer's permission control /// carries it. Cursor and Grok have a permission control of their own, diff --git a/crates/agent/src/claude.rs b/crates/agent/src/claude.rs index 9149d6e54..6ba0bca9e 100644 --- a/crates/agent/src/claude.rs +++ b/crates/agent/src/claude.rs @@ -3254,6 +3254,7 @@ pub async fn list_models( Ok(crate::ModelListing { models: crate::claude_manifest::current().models_for_version(version), problems: crate::claude_manifest::problems(), + account_usage: None, }) } diff --git a/crates/agent/src/codex.rs b/crates/agent/src/codex.rs index 96c92474c..0aac5060d 100644 --- a/crates/agent/src/codex.rs +++ b/crates/agent/src/codex.rs @@ -235,19 +235,32 @@ pub async fn start(opts: SessionOptions) -> Result { } /// Spawn `codex app-server`, page through `model/list` (initial `{}`, then -/// `{cursor}` until `nextCursor` is empty), and tear the process down. +/// `{cursor}` until `nextCursor` is empty), read the account's rate limits +/// when `read_usage`, and tear the process down. Every `codex app-server` +/// fetches Codex's model catalog over the network as it starts (0.174.0), +/// whatever it is then asked, so the one started for the models answers for +/// the usage too. pub async fn list_models( binary_path: Option, launch_env: LaunchEnv, + read_usage: bool, processes: &crate::SessionProcesses, -) -> Result, AgentError> { +) -> Result<(Vec, Option>), AgentError> { let (child, mut stdin, lines, mut stderr_tail) = spawn_server(binary_path.as_deref(), &[], &launch_env)?; let child = processes.hold(child); - let windows = home_dir(&launch_env) - .map(|home| model_windows::read(&home)) - .unwrap_or_default(); - let result = collect_models(&mut stdin, &lines, &windows).await; + let result = async { + initialize(&mut stdin, &lines).await?; + let mut next_id = 2; + let entries = + list_models_raw(&mut stdin, &lines, &mut next_id, false, &mut Vec::new()).await?; + let usage = match read_usage { + true => Some(request_rate_limits(&mut stdin, &lines, next_id).await), + false => None, + }; + Ok((map_models(&entries, &launch_env), usage)) + } + .await; finish_one_shot(child, stdin, &mut stderr_tail, result).await } @@ -261,16 +274,24 @@ pub async fn read_rate_limits( spawn_server(binary_path.as_deref(), &[], &launch_env)?; let result = async { initialize(&mut stdin, &lines).await?; - send_json( - &mut stdin, - &json!({ "id": 2, "method": "account/rateLimits/read", "params": {} }), - )?; - wait_for_response(&lines, 2).await + request_rate_limits(&mut stdin, &lines, 2).await } .await; finish_one_shot(child, stdin, &mut stderr_tail, result).await } +async fn request_rate_limits( + stdin: &mut BufWriter, + lines: &Receiver, + id: i64, +) -> Result { + send_json( + stdin, + &json!({ "id": id, "method": "account/rateLimits/read", "params": {} }), + )?; + wait_for_response(lines, id).await +} + /// Stop a server started for one request, and fold its death into the /// request's error. async fn finish_one_shot( @@ -336,20 +357,19 @@ pub fn home_dir(launch_env: &LaunchEnv) -> Option { }) } -async fn collect_models( - stdin: &mut BufWriter, - lines: &Receiver, - windows: &HashMap, -) -> Result, AgentError> { - initialize(stdin, lines).await?; - let entries = list_models_raw(stdin, lines, &mut 2, false, &mut Vec::new()).await?; - Ok(entries +/// The `model/list` entries the picker shows, each with the context windows +/// Codex caches under the home `launch_env` gives it. +fn map_models(entries: &[Value], launch_env: &LaunchEnv) -> Vec { + let windows = home_dir(launch_env) + .map(|home| model_windows::read(&home)) + .unwrap_or_default(); + entries .iter() .filter_map(|model| { let slug = model.get("model").and_then(Value::as_str); map_model(model, slug.and_then(|slug| windows.get(slug))) }) - .collect()) + .collect() } /// Every `model/list` entry, page after page (initial `{}`, then `{cursor}` @@ -911,6 +931,7 @@ async fn run_actor( config_effort, service_tier: reported_tier, model_efforts, + models, next_id, provider_commands, permission_descriptor, @@ -1007,6 +1028,12 @@ async fn run_actor( commands: provider_commands, }) .await; + if let Some(models) = models { + actor + .events + .emit(AgentEvent::ProviderModels { models }) + .await; + } for message in warnings { actor.events.emit(AgentEvent::Warning { message }).await; } @@ -1594,6 +1621,8 @@ struct OpenedThread { /// `serviceTier` as the answer gave it: the tier in effect, `None` for none. service_tier: Option, model_efforts: ModelEfforts, + /// The models `model/list` offers the picker; `None` when it failed. + models: Option>, next_id: i64, provider_commands: Vec, permission_descriptor: OptionDescriptor, @@ -1692,13 +1721,17 @@ async fn initialize_and_open_thread( Vec::new() }); next_id += 1; - let model_efforts = list_models_raw(stdin, lines, &mut next_id, true, &mut said) - .await - .map(|entries| ModelEfforts::from_list(&entries)) - .unwrap_or_else(|err| { - warnings.push(format!("Codex model/list failed: {err}")); - ModelEfforts::default() - }); + let (model_efforts, models) = + match list_models_raw(stdin, lines, &mut next_id, true, &mut said).await { + Ok(entries) => ( + ModelEfforts::from_list(&entries), + Some(map_models(&entries, &opts.launch_env)), + ), + Err(err) => { + warnings.push(format!("Codex model/list failed: {err}")); + (ModelEfforts::default(), None) + } + }; // Without a chosen model Codex ran the configured one or its default; a // chosen one hides which, and the list's default stands in. let default_model = match &opts.model { @@ -1716,6 +1749,7 @@ async fn initialize_and_open_thread( config_effort, service_tier, model_efforts, + models, next_id, provider_commands, permission_descriptor, diff --git a/crates/agent/src/codex/tests.rs b/crates/agent/src/codex/tests.rs index cb54ed4c8..432d6d234 100644 --- a/crates/agent/src/codex/tests.rs +++ b/crates/agent/src/codex/tests.rs @@ -1647,6 +1647,7 @@ fn startup_failure_reports_exit_status_and_stderr_tail() { env: vec![("LC_ALL".into(), "C".into())], home: None, }, + false, &Default::default(), )) .unwrap_err() diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs index be1ca34ad..0fd30794e 100644 --- a/crates/agent/src/lib.rs +++ b/crates/agent/src/lib.rs @@ -2510,15 +2510,19 @@ pub struct TurnOptions { pub effort: Option, } -/// Where a static model catalog may refresh its data from. Claude's catalog is -/// the t3code model manifest (see `claude_manifest`); the other providers -/// discover their models from the CLI and ignore this. +/// What a listing of a provider's models may do besides asking its CLI. +/// Claude's catalog is the t3code model manifest (see `claude_manifest`), +/// which `cache_dir` and `network` are for; the other providers discover +/// their models from the CLI and ignore those. #[derive(Debug, Clone, Default)] pub struct CatalogRefresh { /// Directory holding the last good remote manifest (the tcode data dir). pub cache_dir: Option, /// Whether a network fetch is allowed (the provider update-check setting). pub network: bool, + /// Whether to read the account's usage too, where the process started + /// for the models can ([`listing_reads_account_usage`]). + pub account_usage: bool, } /// List the provider's models (spawn, query, teardown). `launch_env` carries the @@ -2536,7 +2540,16 @@ pub async fn list_models( processes: &SessionProcesses, ) -> Result { let models = match provider { - ProviderKind::Codex => codex::list_models(binary_path, launch_env, processes).await, + ProviderKind::Codex => { + let (models, usage) = + codex::list_models(binary_path, launch_env, refresh.account_usage, processes) + .await?; + return Ok(ModelListing { + models, + problems: Vec::new(), + account_usage: usage.map(|usage| usage.map_err(|error| error.to_string())), + }); + } ProviderKind::ClaudeCode => { return claude::list_models(binary_path, launch_env, refresh, processes).await; } @@ -2553,9 +2566,17 @@ pub async fn list_models( Ok(ModelListing { models, problems: Vec::new(), + account_usage: None, }) } +/// Whether listing `provider`'s models reads its account's usage in the same +/// process ([`ModelListing::account_usage`]), which then needs no process of +/// its own. +pub fn listing_reads_account_usage(provider: ProviderKind) -> bool { + provider == ProviderKind::Codex +} + /// A provider's models, and what of the catalog they came from could not be /// read and was left out, in Tcode's words. #[cfg(feature = "process")] @@ -2563,6 +2584,9 @@ pub async fn list_models( pub struct ModelListing { pub models: Vec, pub problems: Vec, + /// The account's usage in the harness's own shape, or why it could not + /// be read, when [`CatalogRefresh::account_usage`] asked for it. + pub account_usage: Option>, } #[derive(Debug)] @@ -3137,6 +3161,13 @@ pub enum AgentEvent { ProviderCommands { commands: Vec, }, + /// The models the harness offers, as a running session learned them: at + /// its start, or when the harness announced that its list changed. + /// Session metadata like [`Self::ProviderCommands`], and what the next + /// thread's model picker shows. + ProviderModels { + models: Vec, + }, /// The provider compacted its context window (Claude `system/compact_boundary`; /// Codex `contextCompaction` item). Rendered as a "Context compacted" work-log row. ContextCompacted(Compaction), diff --git a/crates/agent/src/opencode.rs b/crates/agent/src/opencode.rs index 4c5e2fccf..53ba3319b 100644 --- a/crates/agent/src/opencode.rs +++ b/crates/agent/src/opencode.rs @@ -81,9 +81,9 @@ pub async fn list_models( &processes, )?; let result = (|| { - let models = server.http.get("/api/model")?; - let default = server.http.get("/api/model/default")?; - Ok(map_models(&models["data"], &default["data"])) + let (events, _) = server.subscribe()?; + wait_for_plugins(&server.http, &events)?; + read_models(&server.http) })(); server.stop(); result @@ -489,6 +489,47 @@ fn discover_commands(http: &Http) -> Result, AgentError> { Ok(commands) } +/// OpenCode loads its plugins after the server answers, and until they are +/// loaded `/api/model` lists whatever has registered so far: nothing, then a +/// partial list (2.4.4). A one-shot read waits for the plugin list to fill, +/// as OpenCode's own do (`packages/cli/src/acp/catalog.ts`); `plugin.updated` +/// announces each load, so the wait is on the event stream, subscribed to +/// before the first read. +fn wait_for_plugins(http: &Http, events: &Receiver) -> Result<(), AgentError> { + loop { + let plugins = http.get("/api/plugin")?; + if plugins["data"] + .as_array() + .is_some_and(|loaded| !loaded.is_empty()) + { + return Ok(()); + } + loop { + match events.recv_blocking() { + Ok(Transport::Event(event)) if event["type"] == "plugin.updated" => break, + Ok( + Transport::Event(_) + | Transport::ShellOutput { .. } + | Transport::ShellPollEnded { .. }, + ) => {} + Ok(Transport::Error(error)) => return Err(AgentError::Protocol(error)), + Ok(Transport::Eof) | Err(_) => { + return Err(AgentError::Protocol( + "OpenCode event stream closed before its plugins loaded".into(), + )); + } + } + } + } +} + +/// The models the location `http` addresses offers, and which is its default. +fn read_models(http: &Http) -> Result, AgentError> { + let models = http.get("/api/model")?; + let default = http.get("/api/model/default")?; + Ok(map_models(&models["data"], &default["data"])) +} + fn map_models(models: &Value, default: &Value) -> Vec { let default = ModelRef::from_wire(default); models @@ -1280,6 +1321,7 @@ impl OpenCodeActor { // Plugins register commands, skills and agents after the server // is ready; these announce each change. "command.updated" | "skill.updated" => self.refresh_commands().await, + "model.updated" => self.refresh_models().await, "mcp.status.changed" => self.refresh_mcp_servers().await, "agent.updated" => self.refresh_agents().await, // Moved by `MoveTo` or by the model's own `session_move`: requests @@ -1454,6 +1496,26 @@ impl OpenCodeActor { } } + /// The model list changed: plugins register models after the server is + /// ready, and a provider signed in to or out of changes them later. + async fn refresh_models(&mut self) { + match self.http.get("/api/model") { + Ok(models) => { + self.mapper.context_windows = context_windows(&models["data"]); + match self.http.get("/api/model/default") { + Ok(default) => { + let models = map_models(&models["data"], &default["data"]); + self.events + .emit(AgentEvent::ProviderModels { models }) + .await; + } + Err(err) => self.read_failed("default model", &err).await, + } + } + Err(err) => self.read_failed("models", &err).await, + } + } + async fn refresh_agents(&mut self) { match self.http.get("/api/agent") { Ok(agents) => { diff --git a/crates/core/src/session.rs b/crates/core/src/session.rs index 60edb4dc0..16e200551 100644 --- a/crates/core/src/session.rs +++ b/crates/core/src/session.rs @@ -2023,6 +2023,7 @@ impl Timeline { } // Composer metadata belongs to the runtime, not the timeline. AgentEvent::ProviderCommands { .. } + | AgentEvent::ProviderModels { .. } | AgentEvent::ProviderOptions { .. } | AgentEvent::SessionModel { .. } => {} } diff --git a/crates/core/src/session/boundaries.rs b/crates/core/src/session/boundaries.rs index 242496119..dc0159ffc 100644 --- a/crates/core/src/session/boundaries.rs +++ b/crates/core/src/session/boundaries.rs @@ -404,6 +404,7 @@ impl TurnBoundaries { | AgentEvent::UsageLimitReached { .. } | AgentEvent::SessionModel { .. } | AgentEvent::ProviderCommands { .. } + | AgentEvent::ProviderModels { .. } | AgentEvent::ProviderOptions { .. } => false, } } diff --git a/crates/protocol/src/command.rs b/crates/protocol/src/command.rs index 3349e523c..2cd8d3495 100644 --- a/crates/protocol/src/command.rs +++ b/crates/protocol/src/command.rs @@ -266,6 +266,10 @@ pub enum Command { #[serde(default, skip_serializing_if = "Option::is_none")] model: Option, }, + /// List native harness `provider`'s models again. + RefreshModels { + provider: ProviderKind, + }, /// List installed ACP agent `id`'s models and options again. RefreshAcpCatalog { id: String, @@ -946,6 +950,7 @@ impl Command { | Self::CheckProviderVersions | Self::MeasureDiskUsage | Self::RefreshAcpRegistry + | Self::RefreshModels { .. } | Self::RefreshAcpCatalog { .. } | Self::RefreshProviderPlugins { .. } | Self::LoadBranches { .. } diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs index 748fb0317..338c56eb4 100644 --- a/crates/protocol/src/lib.rs +++ b/crates/protocol/src/lib.rs @@ -445,7 +445,8 @@ pub use wire::{ // return the remaining threads as a SessionPage. // // Unreleased: ItemContent gains PlanModeEntered (`plan_mode_entered`) with an -// optional `reason` for harnesses entering plan mode. +// optional `reason` for harnesses entering plan mode. The RefreshModels +// command lists one native harness's models again. pub const PROTOCOL_VERSION: u32 = 35; #[cfg(test)] diff --git a/crates/runtime/src/app/acp.rs b/crates/runtime/src/app/acp.rs index 0cb492b0d..f2a5b0d61 100644 --- a/crates/runtime/src/app/acp.rs +++ b/crates/runtime/src/app/acp.rs @@ -377,6 +377,37 @@ impl AppState { }); } + /// A running session of ACP agent `id` reported the models it offers + /// ([`AgentEvent::ProviderModels`]), which an agent may fill in after its + /// `session/new` answered. A session marks the model it is set to; the + /// one a new session starts on is only the listing's to say, and stays + /// while the agent still offers it. + pub(super) fn adopt_acp_session_models(&mut self, id: &str, models: &[ModelSpec]) { + let Some(catalog) = self.providers.acp_catalogs.get_mut(id) else { + return; + }; + let default = catalog + .default_model() + .filter(|default| models.iter().any(|model| model.id == *default)) + .map(str::to_owned); + let models: Vec = models + .iter() + .cloned() + .map(|mut model| { + model.is_default = default.as_deref() == Some(model.id.as_str()); + model + }) + .collect(); + if catalog.models == models { + return; + } + catalog.models = models; + if let Err(error) = self.store.save_acp_catalog(id, catalog) { + log::warn!("could not save the catalog of ACP agent {id}: {error}"); + } + self.seed_acp_drafts(id); + } + /// List the catalog of every enabled ACP agent that has none yet, as the /// host starts. pub(crate) fn refresh_missing_acp_catalogs(&mut self, cx: &mut HostCx) { diff --git a/crates/runtime/src/app/authorization.rs b/crates/runtime/src/app/authorization.rs index 9d56f9afa..1173e1860 100644 --- a/crates/runtime/src/app/authorization.rs +++ b/crates/runtime/src/app/authorization.rs @@ -547,6 +547,7 @@ impl AppState { | Command::UpdateProviders { .. } | Command::CancelProviderUpdate | Command::RefreshAcpRegistry + | Command::RefreshModels { .. } | Command::RefreshAcpCatalog { .. } | Command::InstallAcpAgent { .. } | Command::CancelAcpInstall { .. } diff --git a/crates/runtime/src/app/events.rs b/crates/runtime/src/app/events.rs index aafdae89b..8efc48a9d 100644 --- a/crates/runtime/src/app/events.rs +++ b/crates/runtime/src/app/events.rs @@ -213,6 +213,11 @@ impl AppState { return; } + AgentEvent::ProviderModels { models } => { + self.adopt_session_models(session_id, models); + return; + } + AgentEvent::ProviderOptions { descriptors, selections, diff --git a/crates/runtime/src/app/providers.rs b/crates/runtime/src/app/providers.rs index 7c0bbb8e1..df0264a28 100644 --- a/crates/runtime/src/app/providers.rs +++ b/crates/runtime/src/app/providers.rs @@ -17,6 +17,20 @@ struct UpdateRun { running: Option>, } +/// What a listing of a harness's models is started with. The models are +/// listed again when these change, and for no other edit to the harness. +#[derive(Clone, PartialEq)] +struct ListingInputs { + /// Whether any account of the harness takes new threads. + enabled: bool, + binary_path: Option, + home_path: Option, + env: Vec, + shared_env: Vec, + /// Whether Claude's manifest may be fetched. + network: bool, +} + #[derive(Default)] struct ModelRefresh { generation: u64, @@ -26,20 +40,35 @@ struct ModelRefresh { /// The harness processes the latest listing started, which the next one /// stops. processes: agent::SessionProcesses, + /// What the latest listing of a native harness was started with; `None` + /// until this host lists its models. + inputs: Option, + /// The harness's account, secrets or version changed while the listing + /// ran, so its answer may be the old one's: it is not taken, and the + /// models are listed once more when it ends. + again: bool, } impl ModelRefresh { /// A new listing, which replaces one still running: that one's harness /// is stopped, and its answer is not taken. fn begin(&mut self) -> (u64, agent::SessionProcesses) { + self.stop(); + self.loading = true; + (self.generation, self.processes.clone()) + } + + /// Stops the listing still running, whose answer is not taken. + fn stop(&mut self) { self.processes.stop(); *self = ModelRefresh { generation: self.generation + 1, - loading: true, + loading: false, failure: None, processes: agent::SessionProcesses::default(), + inputs: self.inputs.take(), + again: false, }; - (self.generation, self.processes.clone()) } /// Ends the listing of `generation` with why it failed, if it did; @@ -150,22 +179,6 @@ impl ProviderCatalog { } /// [`ModelRefresh::begin`] for `provider`'s models. - fn begin_model_refresh(&mut self, provider: ProviderKind) -> (u64, agent::SessionProcesses) { - self.model_refreshes.entry(provider).or_default().begin() - } - - /// [`ModelRefresh::finish`] for `provider`'s models. - fn finish_model_refresh( - &mut self, - provider: ProviderKind, - generation: u64, - failure: Option, - ) -> bool { - self.model_refreshes - .get_mut(&provider) - .is_some_and(|refresh| refresh.finish(generation, failure)) - } - /// [`ModelRefresh::begin`] for installed ACP agent `id`'s catalog. pub(super) fn begin_acp_refresh(&mut self, id: &str) -> (u64, agent::SessionProcesses) { self.acp_refreshes.entry(id.to_owned()).or_default().begin() @@ -391,82 +404,215 @@ impl AppState { self.providers.login_shell_unread = error; } - /// Kick off a background refresh of every provider's model catalog (called - /// at app start and after a binary-path change). Results update - /// `model_catalogs` and are persisted so the next launch is instant. + /// List every harness's models, as the host starts. From then on they + /// are listed again only when something that decides them changes + /// ([`Self::relist_changed_models`], [`Self::relist_models`]), when a + /// session reports them ([`Self::adopt_session_models`]), or when the + /// user asks ([`Self::refresh_models`]); never on a timer. pub fn refresh_model_catalogs(&mut self, cx: &mut HostCx) { for provider in ProviderKind::NATIVE { - let profile_id = Settings::builtin_profile_id(provider).to_string(); - let configuration = self.settings.provider(provider); - let profile_revision = self + self.start_model_listing(provider, cx); + } + } + + fn listing_inputs(&self, provider: ProviderKind) -> ListingInputs { + let settings = self.settings.provider(provider); + ListingInputs { + enabled: self + .settings + .profiles_for_kind(provider) + .iter() + .any(|profile| profile.settings.enabled), + binary_path: settings.binary_path, + home_path: settings.home_path, + env: settings.env, + shared_env: settings.shared_env, + network: provider == ProviderKind::ClaudeCode && self.provider_update_checks_enabled(), + } + } + + /// The settings changed: the harnesses whose listing they change are + /// listed again. A name, a colour or a hidden model changes no listing. + pub(super) fn relist_changed_models(&mut self, cx: &mut HostCx) { + for provider in ProviderKind::NATIVE { + let listed = self .providers - .profile_revisions - .get(&profile_id) - .copied() - .unwrap_or(0); - let network = self.provider_update_checks_enabled(); - let (generation, processes) = self.providers.begin_model_refresh(provider); - let binary = configuration.binary_path.clone(); - let launch_env = self.prepare_profile_env(&profile_id, cx); - let store = self.store.clone(); - // Claude's manifest cache lives next to the persisted catalogs and - // phones home only under the same switch as CLI update checks. - let refresh = CatalogRefresh { - cache_dir: Some(store.root().clone()), - network, + .model_refreshes + .get(&provider) + .and_then(|refresh| refresh.inputs.as_ref()); + if listed.is_some_and(|listed| *listed != self.listing_inputs(provider)) { + self.start_model_listing(provider, cx); + } + } + } + + /// `provider`'s account, secrets or CLI version changed, which its + /// settings do not show: its models are listed again, after the listing + /// still running, whose answer may be from before the change. + pub(super) fn relist_models(&mut self, provider: ProviderKind, cx: &mut HostCx) { + let Some(refresh) = self + .providers + .model_refreshes + .get_mut(&provider) + .filter(|refresh| refresh.inputs.is_some()) + else { + return; + }; + if refresh.loading { + refresh.again = true; + } else { + self.start_model_listing(provider, cx); + } + } + + /// The user asked for `provider`'s models again, in place of a listing + /// still running: asking again is how one that does not end is stopped. + pub fn refresh_models(&mut self, provider: ProviderKind, cx: &mut HostCx) { + if provider != ProviderKind::Acp { + self.start_model_listing(provider, cx); + } + } + + /// Whether a listing of the models of profile `id`'s harness, which runs + /// as its built-in profile, reads that profile's usage too. + fn listing_reads_usage(&self, id: &str) -> bool { + self.settings.resolved_profile(id).is_some_and(|profile| { + id == Settings::builtin_profile_id(profile.kind) + && agent::listing_reads_account_usage(profile.kind) + && profile.supports_account_usage() + }) + } + + /// The profile `id` names, or the harness whose shared secrets it names, + /// when the listing of that harness's models runs as it. + fn listed_as(id: &str) -> Option { + ProviderKind::NATIVE.into_iter().find(|kind| { + Settings::builtin_profile_id(*kind) == id || Settings::harness_secret_id(*kind) == id + }) + } + + fn start_model_listing(&mut self, provider: ProviderKind, cx: &mut HostCx) { + let inputs = self.listing_inputs(provider); + let refresh = self.providers.model_refreshes.entry(provider).or_default(); + refresh.inputs = Some(inputs.clone()); + if !inputs.enabled { + return refresh.stop(); + } + let (generation, processes) = refresh.begin(); + let profile_id = Settings::builtin_profile_id(provider); + let reads_usage = self.listing_reads_usage(profile_id); + let binary = inputs.binary_path.clone(); + let launch_env = self.prepare_profile_env(profile_id, cx); + let store = self.store.clone(); + // Claude's manifest cache lives next to the persisted catalogs and + // phones home only under the same switch as CLI update checks. + let catalog = CatalogRefresh { + cache_dir: Some(store.root().clone()), + network: inputs.network, + account_usage: reads_usage, + }; + let host_cx = cx.clone(); + HostCx::spawn_detached(cx, async move { + let result = match launch_env.await { + Ok(launch_env) => list_models(provider, binary, launch_env, catalog, &processes) + .await + .map_err(|error| error.to_string()), + Err(error) => Err(error), }; - let host_cx = cx.clone(); - HostCx::spawn_detached(cx, async move { - let result = match launch_env.await { - Ok(launch_env) => { - list_models(provider, binary, launch_env, refresh, &processes) - .await - .map_err(|error| error.to_string()) - } - Err(error) => Err(error), + host_cx.enqueue(move |state, cx| { + let Some(refresh) = state + .providers + .model_refreshes + .get_mut(&provider) + .filter(|refresh| refresh.generation == generation) + else { + return; }; - host_cx.enqueue(move |state, _cx| { - let failure = result.as_ref().err().cloned(); - if !state + if refresh.again { + return state.start_model_listing(provider, cx); + } + refresh.loading = false; + refresh.failure = result.as_ref().err().cloned(); + if let Some(usage) = result + .as_ref() + .ok() + .and_then(|listing| listing.account_usage.clone()) + { + let revision = state .providers - .finish_model_refresh(provider, generation, failure) - { - return; - } - if state.settings.provider(provider) != configuration - || state - .providers - .profile_revisions - .get(&profile_id) - .copied() - .unwrap_or(0) - != profile_revision - || state.provider_update_checks_enabled() != network - { - return; - } - match result { - Ok(listing) => { - if let Err(err) = store.save_models(provider, &listing.models) { - log::warn!("failed to persist {provider:?} model catalog: {err}"); - } + .profile_revisions + .get(profile_id) + .copied() + .unwrap_or(0); + state.providers.complete_usage( + profile_id.to_owned(), + revision, + tcode_services::provider_usage::usage_from_payload(provider, usage), + ); + } + match result { + Ok(listing) => { + state.adopt_models(provider, listing.models); + if listing.problems.is_empty() { + state.providers.model_problems.remove(&provider); + } else { state .providers - .model_catalogs - .insert(provider, listing.models); - if listing.problems.is_empty() { - state.providers.model_problems.remove(&provider); - } else { - state - .providers - .model_problems - .insert(provider, listing.problems); - } + .model_problems + .insert(provider, listing.problems); } - Err(err) => log::warn!("failed to list {provider:?} models: {err}"), } - }); + Err(err) => { + log::warn!("failed to list {provider:?} models: {err}"); + // The usage the listing was to read is read on its own. + if reads_usage + && let Some(profile) = state.settings.resolved_profile(profile_id) + { + state.refresh_profile_usage(profile, false, None, cx); + } + } + } }); + }); + } + + /// `provider`'s models as its harness last gave them, kept for the next + /// start. + fn adopt_models(&mut self, provider: ProviderKind, models: Vec) { + if self.providers.model_catalogs.get(&provider) == Some(&models) { + return; + } + if let Err(err) = self.store.save_models(provider, &models) { + log::warn!("failed to persist {provider:?} model catalog: {err}"); + } + self.providers.model_catalogs.insert(provider, models); + } + + /// A running session reported its harness's models + /// ([`AgentEvent::ProviderModels`]): they are the harness's own answer, + /// had without starting it again. A native harness's catalog is the one + /// its own account sees, so a session of another account leaves it be. + pub(super) fn adopt_session_models(&mut self, session_id: &str, models: &[ModelSpec]) { + let Some(session) = self.resident(session_id) else { + return; + }; + let provider = session.meta.provider; + if let Some(id) = session.meta.acp_agent_id.clone() { + return self.adopt_acp_session_models(&id, models); + } + let own_account = session + .live_profile_id + .as_deref() + .is_none_or(|id| id == Settings::builtin_profile_id(provider)); + if provider == ProviderKind::Acp || !own_account { + return; + } + self.adopt_models(provider, models.to_vec()); + // The listing that failed is answered now. + if let Some(refresh) = self.providers.model_refreshes.get_mut(&provider) + && !refresh.loading + { + refresh.failure = None; } } @@ -503,10 +649,11 @@ impl AppState { .or_else(|| agent::find_on_path(profile.kind.harness().binary_name)) } - /// Re-run everything that depends on *how* a provider's CLI is launched - /// (binary path, home, environment): its model catalog and its status probe. + /// Probe every profile's status again after an edit to how a provider's + /// CLI is launched (binary path, home, environment). The models such an + /// edit changes are listed again as the edit is applied + /// ([`Self::relist_changed_models`]). pub fn reload_provider(&mut self, cx: &mut HostCx) { - self.refresh_model_catalogs(cx); self.refresh_provider_status(cx); if self.provider_update_checks_enabled() { self.check_provider_versions(cx); @@ -653,6 +800,9 @@ impl AppState { } else { names.remove(name); } + if let Some(provider) = Self::listed_as(id) { + self.relist_models(provider, cx); + } self.resume_provider_queues(cx); } @@ -1173,6 +1323,9 @@ impl AppState { /// dropped and read again. fn provider_account_changed(&mut self, profile_id: &str, cx: &mut HostCx) { self.providers.invalidate_profile_reads(profile_id); + if let Some(provider) = Self::listed_as(profile_id) { + self.relist_models(provider, cx); + } if let Some(profile) = self.settings.resolved_profile(profile_id) { self.refresh_profile_status(profile.clone(), cx); self.refresh_profile_usage(profile, true, None, cx); @@ -1234,6 +1387,13 @@ impl AppState { .get(&profile_id) .is_some_and(|snapshot| !snapshot.installed && !snapshot.checking) || self.providers.usage_checking.contains(&profile_id) + // The listing of its models answers for its usage when it ends. + || self.listing_reads_usage(&profile_id) + && self + .providers + .model_refreshes + .get(&provider) + .is_some_and(|refresh| refresh.loading) || stale_only && self .providers @@ -1480,6 +1640,9 @@ impl AppState { status.update_available = false; } } + if ok { + self.relist_models(provider, cx); + } let Some(run) = self.providers.update_run.as_mut() else { return; }; diff --git a/crates/runtime/src/app/sessions.rs b/crates/runtime/src/app/sessions.rs index a4e66bc88..f263935bf 100644 --- a/crates/runtime/src/app/sessions.rs +++ b/crates/runtime/src/app/sessions.rs @@ -1217,6 +1217,7 @@ impl AppState { let control_changed = self.settings.control != settings.control; self.settings = settings; self.executions.settings_changed(&self.settings); + self.relist_changed_models(cx); self.refresh_collaboration_briefs(); self.resume_provider_queues(cx); if control_changed { diff --git a/crates/runtime/src/app/tests/acp_catalog.rs b/crates/runtime/src/app/tests/acp_catalog.rs index 9f8e0d2cf..9f52ed330 100644 --- a/crates/runtime/src/app/tests/acp_catalog.rs +++ b/crates/runtime/src/app/tests/acp_catalog.rs @@ -260,6 +260,50 @@ fn a_mode_a_thread_runs_in_reaches_neither_the_catalog_nor_a_new_draft() { assert_eq!(cx.seen().providers().acp_models[AGENT], catalog().models); } +/// An agent may fill its models in after `session/new` answered, which is +/// all its probe read. What a running session reports becomes the agent's +/// models for the next thread. The session marks the model it runs; the one +/// a new thread starts on stays the probe's. +#[test] +fn the_models_a_session_reports_become_its_agents() { + let cx = &mut TestAppContext::default(); + let (store, project) = acp_store("tcode-acp-session-models"); + stored_thread(&store, "thread", ProviderKind::Acp, &project.root, |meta| { + meta.project_id = Some(project.id.clone()); + meta.acp_agent_id = Some(AGENT.into()); + meta.model = Some("model-b".into()); + }); + let (state, providers) = played_host(cx, &store); + state.subscribe(cx, Topic::Providers); + let provider = first_turn(&state, cx, &providers, "thread", 0); + let model = |id: &str, is_default| agent::ModelSpec { + id: id.into(), + display_name: id.to_uppercase(), + is_default, + options: Vec::new(), + }; + provider.play([AgentEvent::ProviderModels { + models: vec![ + model("model-a", false), + model("model-b", true), + model("model-c", false), + ], + }]); + let offered = vec![ + model("model-a", true), + model("model-b", false), + model("model-c", false), + ]; + cx.run_until_seen(|view| view.providers().acp_models[AGENT] == offered); + assert_eq!( + store.load_acp_catalog(AGENT), + Some(agent::AcpCatalog { + models: offered, + options: catalog().options, + }) + ); +} + /// The model a space lets its members run is checked against the model the /// thread would run, the agent's default included when none is named. #[test] diff --git a/crates/runtime/src/app/tests/providers.rs b/crates/runtime/src/app/tests/providers.rs index 4b27b3a19..cdf31c5b6 100644 --- a/crates/runtime/src/app/tests/providers.rs +++ b/crates/runtime/src/app/tests/providers.rs @@ -1050,3 +1050,61 @@ fn antigravity_draft_shows_per_model_thought_level_and_passes_it_on_start() { played.fence(cx, &draft); assert!(!has_effort(cx.seen().status(&draft))); } + +/// A harness's models are the ones its own account sees. A running session +/// of that account reports them and the next thread's picker has them, kept +/// for the next start, with no harness started to ask. A session of another +/// account of the harness says nothing about them. +#[test] +fn the_models_a_session_reports_become_its_harnesss() { + let cx = &mut TestAppContext::default(); + let store = TestStore::new("tcode-session-models"); + let mut settings = Settings::default(); + settings.profiles.insert( + "work".into(), + ProviderProfile { + kind: ProviderKind::Codex, + settings: ProviderSettings::default(), + }, + ); + tcode_services::settings::SettingsStore::new(store.root().clone()) + .save(&settings) + .unwrap(); + let cwd = store.root().join("thread"); + stored_thread(&store, "theirs", ProviderKind::Codex, &cwd, |meta| { + meta.profile_id = Some("work".into()); + }); + stored_thread(&store, "ours", ProviderKind::Codex, &cwd, |_| {}); + let (state, providers) = played_host(cx, &store); + state.subscribe(cx, Topic::Providers); + let models = |id: &str| { + vec![ModelSpec { + id: id.into(), + display_name: id.into(), + is_default: true, + options: Vec::new(), + }] + }; + + let theirs = first_turn(&state, cx, &providers, "theirs", 0); + theirs.play([AgentEvent::ProviderModels { + models: models("their-model"), + }]); + theirs.fence(cx, "theirs"); + assert_eq!( + cx.seen() + .providers() + .model_catalogs + .get(&ProviderKind::Codex), + None + ); + + let ours = first_turn(&state, cx, &providers, "ours", 1); + ours.play([AgentEvent::ProviderModels { + models: models("our-model"), + }]); + cx.run_until_seen(|view| { + view.providers().model_catalogs.get(&ProviderKind::Codex) == Some(&models("our-model")) + }); + assert_eq!(store.load_models(ProviderKind::Codex), models("our-model")); +} diff --git a/crates/runtime/src/pipe.rs b/crates/runtime/src/pipe.rs index 5ade82470..5a6f81711 100644 --- a/crates/runtime/src/pipe.rs +++ b/crates/runtime/src/pipe.rs @@ -795,6 +795,7 @@ fn dispatch_command(app: &mut AppState, cx: &mut HostCx, command: Command) -> Co app.set_active_acp_agent(&session_id, &id, model, cx); app.release_policy_holds(&session_id, cx); } + Command::RefreshModels { provider } => app.refresh_models(provider, cx), Command::RefreshAcpCatalog { id } => app.refresh_acp_catalog(&id, cx), Command::RefreshProviderPlugins { profile_id, cwd } => { app.refresh_provider_plugins(&profile_id, cwd, cx) diff --git a/crates/ui/src/harness_dialog.rs b/crates/ui/src/harness_dialog.rs index 537ff4ce1..5488c7f61 100644 --- a/crates/ui/src/harness_dialog.rs +++ b/crates/ui/src/harness_dialog.rs @@ -826,8 +826,9 @@ impl HarnessDialog { store.refresh_provider_status(); store.check_provider_versions(); store.refresh_acp_registry(); - if let HarnessId::Acp(id) = &self.harness { - store.refresh_acp_catalog(id.clone()); + match &self.harness { + HarnessId::Native(kind) => store.refresh_models(*kind), + HarnessId::Acp(id) => store.refresh_acp_catalog(id.clone()), } }); } diff --git a/crates/ui/src/store/intents.rs b/crates/ui/src/store/intents.rs index 8377d5259..b2c4fa497 100644 --- a/crates/ui/src/store/intents.rs +++ b/crates/ui/src/store/intents.rs @@ -1517,6 +1517,9 @@ impl WorkspaceStore { model, }); } + pub fn refresh_models(&mut self, provider: agent::ProviderKind) { + self.dispatch(Command::RefreshModels { provider }); + } pub fn refresh_acp_catalog(&mut self, id: String) { self.dispatch(Command::RefreshAcpCatalog { id }); }