From c7f2afa696d69ebcbf34d0f653d7c660c943323d Mon Sep 17 00:00:00 2001 From: Jeffrey Aven Date: Mon, 23 Nov 2026 16:01:27 +1100 Subject: [PATCH 1/3] feat(settings): model lists, why Save is unavailable, and Browse on paths Save model backend was disabled with the reason only in a hover tooltip. In the case reported, Remove model backend had also deleted the stored Gemini key, so Gemini asked for a key again and an OpenAI-compatible server asked for a model, and neither said so on screen. - The reason a backend cannot be saved yet is said beside the button. - Whether a key is stored is reported for each backend, not only for the configured one, so switching back to a backend does not ask for its key again. Remove model backend says on hover that it deletes the key. - The model of an API key backend is chosen from the list its provider gives: Gemini's models that take generateContent, Anthropic's models without retired ones, and everything an OpenAI-compatible server lists. The list is read when the pane opens on a backend whose key is stored, or a local server with an address, and otherwise on List models. A key typed and not saved yet is sent with that request and kept nowhere. When the list cannot be read the model stays a text field. - Every path in Settings has a Browse button: the engine, the data folder, the credentials file and the Copilot CLI. The host opens the system's file or folder dialog through tauri-plugin-dialog, which was already used for exports. The webview names what the path is for. - The address field now comes before the key and the model, since the list depends on both. No new dependencies. The model list uses reqwest as the backends do, with the query string built through its Url type. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 14 +- README.md | 4 +- src-tauri/src/agent/backends/anthropic.rs | 4 +- src-tauri/src/agent/backends/gemini.rs | 4 +- src-tauri/src/agent/backends/mod.rs | 49 ++- src-tauri/src/agent/backends/models.rs | 441 ++++++++++++++++++++++ src-tauri/src/agent/backends/openai.rs | 2 +- src-tauri/src/ipc/mod.rs | 45 ++- src-tauri/src/ipc/pick.rs | 193 ++++++++++ src-tauri/src/lib.rs | 2 + src/host/index.ts | 19 + src/host/types.ts | 14 +- src/lib/models.test.ts | 78 ++++ src/lib/models.ts | 50 +++ src/panes/settings/ChatSettings.tsx | 205 +++++++--- src/panes/settings/PathInput.tsx | 78 ++++ src/panes/settings/SettingsDialog.tsx | 37 +- src/panes/settings/settings.test.tsx | 275 ++++++++++++++ 18 files changed, 1423 insertions(+), 91 deletions(-) create mode 100644 src-tauri/src/agent/backends/models.rs create mode 100644 src-tauri/src/ipc/pick.rs create mode 100644 src/lib/models.test.ts create mode 100644 src/lib/models.ts create mode 100644 src/panes/settings/PathInput.tsx create mode 100644 src/panes/settings/settings.test.tsx diff --git a/CLAUDE.md b/CLAUDE.md index cf26d3b..10d50e8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,6 +17,7 @@ Pre-alpha. This much has landed on Windows. - Most of M1, the query IDE: editor tabs, completion from provider metadata, the JSON cell viewer, statement history, export as CSV and JSON, and a `stackql exec` command for a statement. - A query library view: the entries of the published query library, for the operator, with no chat backend needed. - A conversation that shows a turn as its answer: the calls the assistant made are a list of steps that folds away, a call that failed is written to the app's log and not listed, the result set is a table that sorts and downloads, and a model can ask for a chart with a chart block. +- Version 0.2.0, the settings: the model of an API key backend is chosen from the list its provider gives, each backend keeps its own key, the reason a backend cannot be saved yet is said beside the button, and every path has a Browse button that opens the system's dialog. Not started: the rest of M1 (saved `.iql` files, cancel, a streaming grid), M2 (packaging), plan sign-in and any delegated agent other than the Copilot CLI. Replies from the API key backends are not streamed yet. Replies from the Copilot CLI are. @@ -47,6 +48,7 @@ What has and has not been run: - The data folder of an installed app was checked on Windows with the app and a copy of `stackql.exe` in a folder the account could read and run from but not write to, which is what `Program Files` is to an ordinary account. The app was started with that folder as its working folder. It started the engine beside it, the engine's data folder was `/engine`, and nothing was added to the folder of the app. The real `Program Files` was not used, since that needs an administrator, and the note in the settings pane was not looked at in that run. - That run was before an installed app used the home folder. After the change the same layout was run again: the engine beside the app was started on `.stackql` in the home folder, the app listed the providers the operator's own `stackql` command had pulled there, and nothing was added to the folder of the app. The app alone in a folder it could write to, which is what a build is, kept a `.stackql` folder beside itself and listed no providers. The fallback to the local app data directory has run only in tests, and the macOS rule only as unit tests. - The token counts were seen in the built app with a scripted model, and for real through the Copilot CLI: one prompt to a probe to see what the CLI sends, and one turn through the app, which showed the count on the steps line and in the log. The counts of Gemini, Anthropic and an OpenAI-compatible server are read as their documentation describes and tested against stubs, not against the real services. +- The settings of 0.2.0 were driven in a debug build on Windows, in both themes. Opened on an OpenAI-compatible backend with the address of a stand-in server, the pane asked it for its models once, with no key, and showed them as a list with the saved model chosen. Switched to Gemini with no key stored, it said "Enter an API key to save." beside a Save button that was not available. Browse opened the system's folder dialog for the data folder and its file dialog for the credentials file and for the engine, each under its own title, and the path chosen went into the field. Cancel left the field as it was. The model lists of Gemini, Anthropic and OpenAI themselves have not been read: each is tested against a stub that checks what goes on the wire. The dialogs have not been opened on macOS. - The supervisor's tests see a child end by waiting on a handle to it on Windows, and with `kill -0` on Unix. They used to ask `tasklist`, which on a busy machine could use up the time a test allowed. They passed 30 runs in a row with every core busy. With twice as many busy loops as cores a different test, `an_unexpected_exit_is_reported_with_its_code`, missed its 10 second limit twice in 30 runs. Update this section when a milestone lands. The roadmap is in `README.md`. @@ -88,7 +90,7 @@ These are the chosen defaults. Check the current stable version and API of each | Lint and format | ESLint with typescript-eslint, Prettier, rustfmt, clippy | | Process supervision | `windows-sys` job object on Windows, process group plus a pipe watchdog on Unix | | Clipboard | `arboard`, write only, through a host command | -| Save dialog | `tauri-plugin-dialog`, called from host commands only. The webview has no access to it | +| Save and open dialogs | `tauri-plugin-dialog`, called from host commands only: saving an export and choosing a path in Settings. The webview has no access to it | | Links | `tauri-plugin-opener`, called from one host command that holds a fixed list of the app's own links, and from the dialog shown when no WebView2 runtime is found | | Completion | `@codemirror/autocomplete`, with a source written in this repository | | HTTPS client | `reqwest` with the OS TLS stack (`native-tls`) | @@ -116,7 +118,7 @@ The layout is below. Keep it current as the code lands. stackql-workbench/ src/ webview (React) host/ typed wrappers over IPC, the only Tauri imports - lib/ pure logic with tests: results, cells, sorting, export formats, explorer tree, statement templates, completion, tabs, history, the CLI command, chat, the conversation layout, the chart block and its layout, activity, the query library, menu, theme, markdown + lib/ pure logic with tests: results, cells, sorting, export formats, explorer tree, statement templates, completion, tabs, history, the CLI command, chat, the conversation layout, the chart block and its layout, activity, the query library, menu, theme, markdown, the model choice state/ hooks that connect the host to the panes panes/ shell (menu bar, side menu), chat, explorer, editor, results, library, activity, settings, statusbar ui/ small shared components @@ -125,13 +127,13 @@ stackql-workbench/ engine/ discovery, data folder, port selection, supervisor, job object, watchdog connection/ Connection trait, LocalConnection, safety mode, agent channel query/ pg wire session, statement splitting, results, explorer statements - agent/ MCP client, approvals, InferenceBackend trait, backends, loop, ACP client, delegated agent, what a model is told about presentation, the turn log + agent/ MCP client, approvals, InferenceBackend trait, backends and the models they list, loop, ACP client, delegated agent, what a model is told about presentation, the turn log secrets/ keychain access activity/ operator history, engine audit log reader icons/ provider icon lookup, fetch and cache library/ the query library's index and documents, fetch and cache config/ settings - ipc/ command and event definitions, saving an export, the app's own links + ipc/ command and event definitions, saving an export, choosing a path, the app's own links applog.rs the app's own log webview_runtime.rs the page renderer on Windows: using one shipped beside the app, and the dialog shown when there is none .cargo/ build flags: the C runtime linked in on Windows @@ -358,6 +360,8 @@ How they are built: - The tool calls of one reply run at the same time when the engine marks the tool as not destructive, with `destructiveHint: false`. That covers its query and discovery tools. A tool the engine marks as destructive, or one that carries no hint, runs alone and in the model's order, so what follows a change sees the change. The host takes the engine's word for this and reads nothing into the statement. Results go back to the model in the order it asked. - More than one approval prompt can be open at once. A prompt is shown on the tool call that sent the statement. - The API key is read from the keychain when a turn starts. Settings hold the backend, the model and the address, never the key. +- Each backend keeps its own key in the keychain, so switching back to a backend does not ask for its key again. Removing the model backend deletes the key of the backend it removes. +- The settings pane offers the models a backend's provider lists, from `agent/backends/models.rs`: Gemini's model list narrowed to the models that take `generateContent`, Anthropic's without retired models, and everything an OpenAI-compatible server lists. It is asked when the pane opens on a backend whose key is stored, or on a server of the operator's own that needs no key, and otherwise on List models. A key typed and not saved yet is sent with that request and kept nowhere. When the list cannot be read, the model stays a field to type in, with the provider's message under it. - Every backend reports what a call used in the same three counts: the whole input, the part of it read from the provider's cache, and the output, with the model's thinking where the provider counts it. The host adds them up over the calls of a turn. A count a provider does not send stays unknown and is not turned into zero. - A model is told how its work is shown, and how to ask for a chart, by one text in `agent/guidance.rs`. The host's loop puts it in the system prompt ahead of the engine's guidance. A delegated agent gets it with the first message. It is about presentation only, which is this app's to say because drawing is this app's capability. It says nothing about how a result is to be read. A test holds it to that. @@ -400,6 +404,8 @@ A few fixed points for the interface. - Entries are grouped by use case, which is the first of the entry's own tags that names one. By default only entries whose providers are all installed are listed. - Under an empty conversation one suggestion asks about metadata and the others come from library entries that can run here: stable, not a mutation, and for installed providers. With none, the earlier fixed suggestions are shown. - Saved queries are plain `.iql` files on disk, not an app database. +- Every path in Settings can be typed or chosen with Browse, which opens the system's own file or folder dialog through a host command. The webview names what the path is for, and the host decides the kind of dialog, its title and the file types it offers first. A chosen path goes into the field like typed text and is saved with the rest. +- A save button that is not available says why beside it, for example that an API key is needed. A reason given only on hover was missed. - Layout: a menu bar with File, Edit, View, Query, Providers and Help, a side menu, one main view at a time, and the status bar. The views are chat, the explorer with the editor and results, the query library, and activity. Settings is a dialog. Chat is the view the app opens in. - The menus are drawn in the webview, not by the OS, so they are the same on both platforms and can be tested like the rest of the page. They repeat what the side menu and the panes offer. - Every view stays mounted while another is shown, so the editor keeps its text and history and a running turn keeps its place. diff --git a/README.md b/README.md index d783516..1703883 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ The planned capabilities are listed below. - Chat: the view the app opens in. It needs a model backend, and asks for one the first time a message is sent - Answers with results: a turn is shown as its answer, with the result set as a table that sorts and downloads, and as a chart when one is asked for - Approvals and activity: mutations proposed by a model wait for the operator, and every agent action is logged -- Settings: engine path, credentials profile, safety mode, inference backend +- Settings: engine path, credentials profile, safety mode, inference backend. Every path can be typed or chosen in the system's file dialog ## Architecture @@ -265,7 +265,7 @@ The app opens in chat. The side menu leads to the explorer, which holds the prov Chat needs a model backend. The first time you send a message without one, the model backend settings open. There are two kinds. - GitHub Copilot: uses the Copilot CLI installed on this machine and the sign-in it already has. Install the CLI, run `copilot login` once, then choose GitHub Copilot. Requests count against your Copilot plan, and the settings list each model with what it costs. There is an experimental setting that lets the agent hand the parts of a request that spans several providers to subagents. It is off by default. -- An API key for Gemini, Anthropic, or an OpenAI-compatible server, which covers local inference. The key goes to the operating system keychain. +- An API key for Gemini, Anthropic, or an OpenAI-compatible server, which covers local inference. The key goes to the operating system keychain, and each backend keeps its own. List models asks the provider which models the key can use, and the model is then chosen from that list. With a key already stored the list is read when the settings open. With an API key backend, independent queries the model asks for in one step run at the same time. diff --git a/src-tauri/src/agent/backends/anthropic.rs b/src-tauri/src/agent/backends/anthropic.rs index c1dfe07..d14a767 100644 --- a/src-tauri/src/agent/backends/anthropic.rs +++ b/src-tauri/src/agent/backends/anthropic.rs @@ -30,7 +30,7 @@ use crate::agent::backend::{ pub const DEFAULT_BASE_URL: &str = "https://api.anthropic.com"; pub const DEFAULT_MODEL: &str = "claude-opus-5-5"; -const API_VERSION: &str = "2026-10-21"; +pub(super) const API_VERSION: &str = "2026-10-21"; /// Kept below the size at which a non-streaming request risks a timeout. const MAX_TOKENS: u32 = 16_000; @@ -96,7 +96,7 @@ fn uses_fallback(model: &str) -> bool { MODELS_WITH_FALLBACK.contains(&model) } -fn error_message(body: &Value) -> Option { +pub(super) fn error_message(body: &Value) -> Option { let error = body.get("error")?; let message = error.get("message")?.as_str()?; let kind = error.get("type").and_then(Value::as_str).unwrap_or(""); diff --git a/src-tauri/src/agent/backends/gemini.rs b/src-tauri/src/agent/backends/gemini.rs index d8ba45f..f50e194 100644 --- a/src-tauri/src/agent/backends/gemini.rs +++ b/src-tauri/src/agent/backends/gemini.rs @@ -82,7 +82,7 @@ impl InferenceBackend for Gemini { } } -fn error_message(body: &Value) -> Option { +pub(super) fn error_message(body: &Value) -> Option { let error = body.get("error")?; let message = error.get("message")?.as_str()?; let status = error.get("status").and_then(Value::as_str).unwrap_or(""); @@ -90,7 +90,7 @@ fn error_message(body: &Value) -> Option { } /// A bad key comes back as 400 INVALID_ARGUMENT, not as 401. -fn reclassify_key_error(err: InferenceError) -> InferenceError { +pub(super) fn reclassify_key_error(err: InferenceError) -> InferenceError { match err { InferenceError::InvalidRequest(message) if message.contains("API key") => { InferenceError::Auth(message) diff --git a/src-tauri/src/agent/backends/mod.rs b/src-tauri/src/agent/backends/mod.rs index 265e087..8eaef1b 100644 --- a/src-tauri/src/agent/backends/mod.rs +++ b/src-tauri/src/agent/backends/mod.rs @@ -7,6 +7,7 @@ pub mod anthropic; pub mod gemini; +pub mod models; pub mod openai; use std::sync::Arc; @@ -47,6 +48,17 @@ pub fn default_base_url(kind: BackendKind) -> &'static str { } } +/// The operator's address, or the provider's own when none is set, without +/// a trailing slash. +pub(crate) fn resolve_base_url(kind: BackendKind, base_url: Option<&str>) -> String { + base_url + .map(str::trim) + .filter(|url| !url.is_empty()) + .unwrap_or_else(|| default_base_url(kind)) + .trim_end_matches('/') + .to_string() +} + /// Builds the backend the settings describe. pub fn build( settings: &InferenceSettings, @@ -68,14 +80,7 @@ pub fn build( "No model is set. Choose one in Settings.".to_string(), )); } - let base_url = settings - .base_url - .as_deref() - .map(str::trim) - .filter(|url| !url.is_empty()) - .unwrap_or_else(|| default_base_url(settings.kind)) - .trim_end_matches('/') - .to_string(); + let base_url = resolve_base_url(settings.kind, settings.base_url.as_deref()); let api_key = api_key.filter(|key| !key.trim().is_empty()); if api_key.is_none() && !settings.kind.key_optional() { return Err(InferenceError::Auth( @@ -129,6 +134,34 @@ async fn post_json( for (name, value) in headers { request = request.header(*name, *value); } + read_json(request, error_message).await +} + +/// Sends a GET and returns the parsed reply, the same way `post_json` does. +async fn get_json( + http: &reqwest::Client, + url: &str, + query: &[(&str, &str)], + headers: &[(&str, &str)], + error_message: fn(&Value) -> Option, +) -> Result { + let mut url = reqwest::Url::parse(url).map_err(|err| { + InferenceError::InvalidRequest(format!("the address is not valid: {err}")) + })?; + if !query.is_empty() { + url.query_pairs_mut().extend_pairs(query); + } + let mut request = http.get(url); + for (name, value) in headers { + request = request.header(*name, *value); + } + read_json(request, error_message).await +} + +async fn read_json( + request: reqwest::RequestBuilder, + error_message: fn(&Value) -> Option, +) -> Result { let response = request .send() .await diff --git a/src-tauri/src/agent/backends/models.rs b/src-tauri/src/agent/backends/models.rs new file mode 100644 index 0000000..2a48c1f --- /dev/null +++ b/src-tauri/src/agent/backends/models.rs @@ -0,0 +1,441 @@ +//! The models a backend offers, read from the provider, so the settings pane +//! can offer a list instead of a blank field. +//! +//! Wire format notes, from each provider's API reference as read in +//! November 2026: +//! +//! - Gemini: `GET {base}/v1beta/models` with `x-goog-api-key`. Up to 1000 +//! models a page with `pageSize`. A reply with `nextPageToken` has another +//! page, asked for with `pageToken`. `name` is `models/{id}`. A model that +//! can hold a conversation lists `generateContent` in +//! `supportedGenerationMethods`, which is the call the backend makes. +//! - Anthropic: `GET {base}/v1/models` with `x-api-key` and +//! `anthropic-version`. Up to 1000 models a page with `limit`. A reply with +//! `has_more` has another page, asked for with `after_id` set to `last_id`. +//! Each model has `id`, `display_name` and `lifecycle`. +//! - OpenAI and compatible servers: `GET {base}/models`, with a bearer key +//! when there is one. One page, `data[].id`. There is no display name and +//! no capability field, so every model the server lists is offered. +//! +//! Listing models is free with all three and counts against no quota. + +use serde::Serialize; +use serde_json::Value; + +use super::{anthropic, gemini, get_json, http_client, openai, resolve_base_url}; +use crate::agent::backend::{BackendKind, InferenceError}; + +/// Stops a provider that keeps sending a next page from looping forever. +const MAX_PAGES: usize = 20; + +/// One model a backend offers. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ModelOption { + /// What goes in the settings and on the wire. + pub id: String, + /// What the provider calls it. The id when the provider gives no name. + pub name: String, +} + +/// Asks the provider which models the key can use. `base_url` is the +/// operator's address, or `None` for the provider's own. +pub async fn list( + kind: BackendKind, + base_url: Option<&str>, + api_key: Option, +) -> Result, InferenceError> { + let api_key = api_key.filter(|key| !key.trim().is_empty()); + if kind.is_delegated() { + return Err(InferenceError::InvalidRequest( + "This backend is an agent, not a model API.".to_string(), + )); + } + if api_key.is_none() && !kind.key_optional() { + return Err(InferenceError::Auth( + "Enter an API key to list the models".to_string(), + )); + } + let base = resolve_base_url(kind, base_url); + let key = api_key.unwrap_or_default(); + let http = http_client()?; + let models = match kind { + BackendKind::Gemini => list_gemini(&http, &base, &key).await?, + BackendKind::Anthropic => list_anthropic(&http, &base, &key).await?, + BackendKind::OpenaiCompatible => list_openai(&http, &base, &key).await?, + BackendKind::GithubCopilot => Vec::new(), + }; + Ok(dedupe(models)) +} + +async fn list_gemini( + http: &reqwest::Client, + base: &str, + key: &str, +) -> Result, InferenceError> { + let url = format!("{base}/v1beta/models"); + let headers = [("x-goog-api-key", key)]; + let mut models = Vec::new(); + let mut token: Option = None; + for _ in 0..MAX_PAGES { + let mut query = vec![("pageSize", "1000")]; + if let Some(token) = token.as_deref() { + query.push(("pageToken", token)); + } + let reply = get_json(http, &url, &query, &headers, gemini::error_message) + .await + .map_err(gemini::reclassify_key_error)?; + let (page, next) = gemini_page(&reply); + models.extend(page); + match next { + Some(next) => token = Some(next), + None => break, + } + } + Ok(models) +} + +async fn list_anthropic( + http: &reqwest::Client, + base: &str, + key: &str, +) -> Result, InferenceError> { + let url = format!("{base}/v1/models"); + let headers = [ + ("x-api-key", key), + ("anthropic-version", anthropic::API_VERSION), + ]; + let mut models = Vec::new(); + let mut after: Option = None; + for _ in 0..MAX_PAGES { + let mut query = vec![("limit", "1000")]; + if let Some(after) = after.as_deref() { + query.push(("after_id", after)); + } + let reply = get_json(http, &url, &query, &headers, anthropic::error_message).await?; + let (page, next) = anthropic_page(&reply); + models.extend(page); + match next { + Some(next) => after = Some(next), + None => break, + } + } + Ok(models) +} + +async fn list_openai( + http: &reqwest::Client, + base: &str, + key: &str, +) -> Result, InferenceError> { + let bearer = format!("Bearer {key}"); + let headers: Vec<(&str, &str)> = if key.is_empty() { + Vec::new() + } else { + vec![("authorization", bearer.as_str())] + }; + let reply = get_json( + http, + &format!("{base}/models"), + &[], + &headers, + openai::error_message, + ) + .await?; + Ok(openai_models(&reply)) +} + +fn text<'a>(value: &'a Value, name: &str) -> Option<&'a str> { + value + .get(name) + .and_then(Value::as_str) + .map(str::trim) + .filter(|text| !text.is_empty()) +} + +/// One page from Gemini: the models that take `generateContent`, and the +/// token for the next page. +fn gemini_page(reply: &Value) -> (Vec, Option) { + let models = reply + .get("models") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|model| { + model + .get("supportedGenerationMethods") + .and_then(Value::as_array) + .is_some_and(|methods| { + methods + .iter() + .any(|m| m.as_str() == Some("generateContent")) + }) + }) + .filter_map(|model| { + let name = text(model, "name")?; + let id = name.strip_prefix("models/").unwrap_or(name); + Some(ModelOption { + id: id.to_string(), + name: text(model, "displayName").unwrap_or(id).to_string(), + }) + }) + .collect(); + let next = text(reply, "nextPageToken").map(str::to_string); + (models, next) +} + +/// One page from Anthropic: the models that can still be called, and the id +/// to start the next page after. +fn anthropic_page(reply: &Value) -> (Vec, Option) { + let models = reply + .get("data") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|model| text(model, "lifecycle") != Some("retired")) + .filter_map(|model| { + let id = text(model, "id")?; + let name = text(model, "display_name").unwrap_or(id); + let name = if text(model, "lifecycle") == Some("deprecated") { + format!("{name} (deprecated)") + } else { + name.to_string() + }; + Some(ModelOption { + id: id.to_string(), + name, + }) + }) + .collect(); + let more = reply + .get("has_more") + .and_then(Value::as_bool) + .unwrap_or(false); + let next = if more { + text(reply, "last_id").map(str::to_string) + } else { + None + }; + (models, next) +} + +/// The models of an OpenAI-compatible server, by id. The order a server +/// sends them in means nothing, so they are sorted. +fn openai_models(reply: &Value) -> Vec { + let mut models: Vec = reply + .get("data") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|model| { + let id = text(model, "id")?; + Some(ModelOption { + id: id.to_string(), + name: id.to_string(), + }) + }) + .collect(); + models.sort_by(|a, b| a.id.cmp(&b.id)); + models +} + +/// Keeps the first of each id. +fn dedupe(models: Vec) -> Vec { + let mut seen = std::collections::HashSet::new(); + models + .into_iter() + .filter(|model| seen.insert(model.id.clone())) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::agent::backends::testing::serve_once; + use serde_json::json; + + #[test] + fn gemini_offers_only_models_that_take_generate_content() { + let reply = json!({ + "models": [ + { + "name": "models/gemini-test-flash", + "displayName": "Gemini Test Flash", + "supportedGenerationMethods": ["generateContent", "countTokens"] + }, + { + "name": "models/text-embedding-test", + "displayName": "Embedding", + "supportedGenerationMethods": ["embedContent"] + }, + { + "name": "models/gemini-no-name", + "supportedGenerationMethods": ["generateContent"] + }, + { "name": "models/no-methods" } + ], + "nextPageToken": "page-2" + }); + let (models, next) = gemini_page(&reply); + assert_eq!( + models, + vec![ + ModelOption { + id: "gemini-test-flash".into(), + name: "Gemini Test Flash".into() + }, + ModelOption { + id: "gemini-no-name".into(), + name: "gemini-no-name".into() + }, + ] + ); + assert_eq!(next.as_deref(), Some("page-2")); + let (_, last) = gemini_page(&json!({ "models": [], "nextPageToken": "" })); + assert_eq!(last, None); + } + + #[test] + fn anthropic_leaves_out_retired_models_and_marks_deprecated_ones() { + let reply = json!({ + "data": [ + { "id": "claude-new", "display_name": "Claude New", "lifecycle": "active" }, + { "id": "claude-old", "display_name": "Claude Old", "lifecycle": "deprecated" }, + { "id": "claude-gone", "display_name": "Claude Gone", "lifecycle": "retired" }, + { "id": "claude-plain" } + ], + "has_more": true, + "last_id": "claude-plain" + }); + let (models, next) = anthropic_page(&reply); + let names: Vec<&str> = models.iter().map(|m| m.name.as_str()).collect(); + assert_eq!( + names, + ["Claude New", "Claude Old (deprecated)", "claude-plain"] + ); + assert_eq!(next.as_deref(), Some("claude-plain")); + let (_, last) = anthropic_page(&json!({ "data": [], "has_more": false, "last_id": "x" })); + assert_eq!(last, None); + } + + #[test] + fn a_compatible_server_lists_every_model_sorted_once() { + let reply = json!({ + "object": "list", + "data": [ + { "id": "zeta", "object": "model" }, + { "id": "alpha", "object": "model" }, + { "object": "model" } + ] + }); + let ids: Vec = dedupe(openai_models(&reply)) + .into_iter() + .map(|m| m.id) + .collect(); + assert_eq!(ids, ["alpha", "zeta"]); + let twice = vec![ + ModelOption { + id: "a".into(), + name: "first".into(), + }, + ModelOption { + id: "a".into(), + name: "second".into(), + }, + ]; + assert_eq!(dedupe(twice)[0].name, "first"); + } + + #[tokio::test] + async fn a_backend_that_needs_a_key_asks_for_one_before_calling() { + for kind in [BackendKind::Gemini, BackendKind::Anthropic] { + let err = list(kind, None, Some(" ".into())).await.unwrap_err(); + assert!(matches!(err, InferenceError::Auth(_)), "{kind:?}"); + } + let err = list(BackendKind::GithubCopilot, None, None) + .await + .unwrap_err(); + assert!(matches!(err, InferenceError::InvalidRequest(_))); + } + + #[tokio::test] + async fn gemini_is_asked_with_the_key_in_a_header() { + let reply = json!({ "models": [{ + "name": "models/gemini-test", + "displayName": "Gemini Test", + "supportedGenerationMethods": ["generateContent"] + }] }); + let (base, request) = serve_once(200, reply).await; + let models = list(BackendKind::Gemini, Some(&base), Some("key-123".into())) + .await + .unwrap(); + assert_eq!(models[0].id, "gemini-test"); + let request = request.await.unwrap(); + assert_eq!(request.method, "GET"); + assert_eq!(request.path, "/v1beta/models?pageSize=1000"); + assert_eq!(request.header("x-goog-api-key"), Some("key-123")); + assert!(!request.path.contains("key-123")); + } + + #[tokio::test] + async fn anthropic_is_asked_with_its_key_and_version_headers() { + let reply = json!({ + "data": [{ "id": "claude-test", "display_name": "Claude Test" }], + "has_more": false + }); + let (base, request) = serve_once(200, reply).await; + let models = list(BackendKind::Anthropic, Some(&base), Some("sk-test".into())) + .await + .unwrap(); + assert_eq!(models[0].name, "Claude Test"); + let request = request.await.unwrap(); + assert_eq!(request.path, "/v1/models?limit=1000"); + assert_eq!(request.header("x-api-key"), Some("sk-test")); + assert_eq!( + request.header("anthropic-version"), + Some(anthropic::API_VERSION) + ); + } + + #[tokio::test] + async fn a_compatible_server_is_asked_with_a_bearer_key_only_when_there_is_one() { + let reply = json!({ "data": [{ "id": "local-model" }] }); + let (base, request) = serve_once(200, reply.clone()).await; + let models = list( + BackendKind::OpenaiCompatible, + Some(&format!("{base}/v1/")), + None, + ) + .await + .unwrap(); + assert_eq!(models[0].id, "local-model"); + let request = request.await.unwrap(); + assert_eq!(request.path, "/v1/models"); + assert_eq!(request.header("authorization"), None); + + let (base, request) = serve_once(200, reply).await; + list( + BackendKind::OpenaiCompatible, + Some(&format!("{base}/v1")), + Some("sk-local".into()), + ) + .await + .unwrap(); + let request = request.await.unwrap(); + assert_eq!(request.header("authorization"), Some("Bearer sk-local")); + } + + #[tokio::test] + async fn a_rejected_key_is_reported_as_one() { + let reply = json!({ "error": { + "code": 400, + "message": "API key not valid. Please pass a valid API key.", + "status": "INVALID_ARGUMENT" + } }); + let (base, _request) = serve_once(400, reply).await; + let err = list(BackendKind::Gemini, Some(&base), Some("bad".into())) + .await + .unwrap_err(); + assert!(matches!(err, InferenceError::Auth(_)), "{err:?}"); + } +} diff --git a/src-tauri/src/agent/backends/openai.rs b/src-tauri/src/agent/backends/openai.rs index fa14254..7b245cf 100644 --- a/src-tauri/src/agent/backends/openai.rs +++ b/src-tauri/src/agent/backends/openai.rs @@ -81,7 +81,7 @@ impl InferenceBackend for OpenAiCompatible { } } -fn error_message(body: &Value) -> Option { +pub(super) fn error_message(body: &Value) -> Option { let error = body.get("error")?; // Some compatible servers send the error as a bare string. if let Some(text) = error.as_str() { diff --git a/src-tauri/src/ipc/mod.rs b/src-tauri/src/ipc/mod.rs index 0ffe786..058587f 100644 --- a/src-tauri/src/ipc/mod.rs +++ b/src-tauri/src/ipc/mod.rs @@ -4,6 +4,7 @@ //! side is `src/host/`, the only place in the webview that touches Tauri. pub mod links; +pub mod pick; pub mod save; use std::collections::HashMap; @@ -16,6 +17,7 @@ use crate::activity::{Activity, History, HistoryEntry, read_audit}; use crate::agent::approvals::ApprovalDecision; use crate::agent::backend::BackendKind; use crate::agent::backends; +use crate::agent::backends::models::{self, ModelOption}; use crate::agent::runtime::{ AgentEvent, AgentRuntime, DelegateInfo, DelegateRequest, Emit, TurnSummary, }; @@ -315,7 +317,6 @@ pub async fn explorer_method_fields( pub struct AgentConfigView { /// `None` means chat is not configured and the chat pane stays hidden. pub inference: Option, - pub has_key: bool, pub safety_mode: SafetyMode, pub backends: Vec, /// False when keys cannot be kept in the OS keychain on this machine. @@ -330,19 +331,24 @@ pub struct BackendOption { pub default_model: String, pub default_base_url: String, pub key_optional: bool, + /// Whether a key for this backend is in the keychain. Each backend keeps + /// its own, so switching back to one does not ask for its key again. + pub key_stored: bool, /// An agent the operator installed runs the model. There is no key and /// no address to enter, and no approval prompt. pub delegated: bool, } +/// The key stored for a backend, if there is one. +fn stored_key(state: &AppState, kind: BackendKind) -> HostResult> { + match kind.secret_name() { + Some(name) => state.secrets.get(name), + None => Ok(None), + } +} + fn agent_config_view(state: &AppState) -> AgentConfigView { let settings = state.settings.get(); - let has_key = settings.inference.as_ref().is_some_and(|inference| { - inference - .kind - .secret_name() - .is_some_and(|name| state.secrets.get(name).is_ok_and(|key| key.is_some())) - }); let backends = BackendKind::ALL .into_iter() .map(|kind| BackendOption { @@ -350,12 +356,12 @@ fn agent_config_view(state: &AppState) -> AgentConfigView { default_model: backends::default_model(kind).to_string(), default_base_url: backends::default_base_url(kind).to_string(), key_optional: kind.key_optional(), + key_stored: stored_key(state, kind).is_ok_and(|key| key.is_some()), delegated: kind.is_delegated(), }) .collect(); AgentConfigView { inference: settings.inference, - has_key, safety_mode: settings.safety_mode, backends, keychain_available: state.keychain_available, @@ -390,6 +396,29 @@ pub async fn agent_config_save( Ok(agent_config_view(&state)) } +/// The models a backend offers, as its provider lists them. `api_key` is a +/// key the operator has typed and not saved yet. Without one, the key stored +/// for that backend is used. The key is sent to the provider and nowhere +/// else. +#[tauri::command] +pub async fn agent_list_models( + state: State<'_, AppState>, + kind: BackendKind, + base_url: Option, + api_key: Option, +) -> HostResult> { + let typed = api_key + .map(|key| key.trim().to_string()) + .filter(|key| !key.is_empty()); + let key = match typed { + Some(key) => Some(key), + None => stored_key(&state, kind)?, + }; + models::list(kind, base_url.as_deref(), key) + .await + .map_err(|err| HostError::Agent(err.to_string())) +} + /// Removes the chat backend and its stored key. The chat pane goes away and /// the rest of the app carries on as before. #[tauri::command] diff --git a/src-tauri/src/ipc/pick.rs b/src-tauri/src/ipc/pick.rs new file mode 100644 index 0000000..4fbc0ff --- /dev/null +++ b/src-tauri/src/ipc/pick.rs @@ -0,0 +1,193 @@ +//! Choosing a file or a folder for a setting, in the system's own dialog. +//! +//! The webview says what the path is for. The host decides whether that is +//! a file or a folder, what the dialog is titled and which files it offers. +//! The webview gets back the path the operator chose and nothing else. + +use std::path::{Path, PathBuf}; + +use serde::Deserialize; +use tauri_plugin_dialog::DialogExt; + +use crate::error::{HostError, HostResult}; + +/// What a path in the settings is for. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum PathPurpose { + /// The `stackql` binary. + Engine, + /// The folder the engine keeps its providers in. + DataFolder, + /// A dotenv file the engine reads. + EnvFile, + /// The program of a delegated agent, the Copilot CLI. + Agent, +} + +/// How the dialog for one purpose is set up. +#[derive(Debug, PartialEq, Eq)] +struct Picker { + folder: bool, + title: &'static str, + /// The file types offered first on Windows, where programs have one. + /// Every file can still be chosen. A Mac program has no extension, so + /// there no filter is set. + programs: &'static [&'static str], +} + +impl PathPurpose { + fn picker(self) -> Picker { + match self { + Self::Engine => Picker { + folder: false, + title: "Choose the stackql program", + programs: &["exe"], + }, + Self::DataFolder => Picker { + folder: true, + title: "Choose the engine data folder", + programs: &[], + }, + Self::EnvFile => Picker { + folder: false, + title: "Choose a credentials file", + programs: &[], + }, + Self::Agent => Picker { + folder: false, + title: "Choose the GitHub Copilot CLI", + // The npm install is a .cmd shim. Other installs are an .exe. + programs: &["exe", "cmd"], + }, + } + } +} + +/// Where the dialog opens: the folder the field names, or the folder of +/// the file it names, when that folder exists. +fn start_folder(current: Option<&str>) -> Option { + let current = current?.trim().trim_matches('"'); + if current.is_empty() { + return None; + } + let path = Path::new(current); + if path.is_dir() { + return Some(path.to_path_buf()); + } + path.parent() + .filter(|parent| parent.is_dir()) + .map(Path::to_path_buf) +} + +/// Opens the system's dialog for a setting. `current` is what the field +/// holds now, or the path in use, and only decides where the dialog opens. +/// Returns the chosen path, or `None` when the dialog was dismissed. +#[tauri::command] +pub async fn pick_path( + window: tauri::WebviewWindow, + purpose: PathPurpose, + current: Option, +) -> HostResult> { + let picker = purpose.picker(); + let mut dialog = window + .dialog() + .file() + .set_parent(&window) + .set_title(picker.title); + if let Some(folder) = start_folder(current.as_deref()) { + dialog = dialog.set_directory(folder); + } + if cfg!(windows) && !picker.programs.is_empty() { + dialog = dialog + .add_filter("Programs", picker.programs) + .add_filter("All files", &["*"]); + } + let (sender, receiver) = tokio::sync::oneshot::channel(); + if picker.folder { + dialog + .set_can_create_directories(true) + .pick_folder(move |picked| { + let _ = sender.send(picked); + }); + } else { + dialog.pick_file(move |picked| { + let _ = sender.send(picked); + }); + } + let picked = receiver + .await + .map_err(|_| HostError::Internal("The dialog closed unexpectedly.".into()))?; + let Some(picked) = picked else { + return Ok(None); + }; + let path = picked + .into_path() + .map_err(|err| HostError::Internal(format!("That location cannot be used: {err}")))?; + Ok(Some(path.display().to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_data_folder_is_a_folder() { + for purpose in [ + PathPurpose::Engine, + PathPurpose::EnvFile, + PathPurpose::Agent, + ] { + assert!(!purpose.picker().folder, "{purpose:?}"); + } + assert!(PathPurpose::DataFolder.picker().folder); + } + + #[test] + fn programs_are_offered_first_and_a_credentials_file_has_no_filter() { + assert_eq!(PathPurpose::Engine.picker().programs, ["exe"]); + assert_eq!(PathPurpose::Agent.picker().programs, ["exe", "cmd"]); + // A dotenv file is usually called .env, which has no extension. + assert!(PathPurpose::EnvFile.picker().programs.is_empty()); + } + + #[test] + fn the_webview_names_a_purpose_in_camel_case() { + let purpose: PathPurpose = serde_json::from_str("\"dataFolder\"").unwrap(); + assert_eq!(purpose, PathPurpose::DataFolder); + let purpose: PathPurpose = serde_json::from_str("\"envFile\"").unwrap(); + assert_eq!(purpose, PathPurpose::EnvFile); + assert!(serde_json::from_str::("\"anything\"").is_err()); + } + + #[test] + fn the_dialog_opens_where_the_field_points_when_that_exists() { + let dir = std::env::temp_dir().join(format!("wb-pick-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("stackql.exe"); + std::fs::write(&file, "").unwrap(); + let shown = dir.display().to_string(); + + assert_eq!(start_folder(Some(&shown)), Some(dir.clone())); + assert_eq!( + start_folder(Some(&file.display().to_string())), + Some(dir.clone()) + ); + // A file that is not there yet still opens in its folder. + assert_eq!( + start_folder(Some(&dir.join("new.env").display().to_string())), + Some(dir.clone()) + ); + assert_eq!( + start_folder(Some(&format!("\"{shown}\""))), + Some(dir.clone()) + ); + assert_eq!( + start_folder(Some(&dir.join("gone").join("x").display().to_string())), + None + ); + assert_eq!(start_folder(Some(" ")), None); + assert_eq!(start_folder(None), None); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 05b46ce..2288af9 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -197,8 +197,10 @@ pub fn run() { ipc::agent_stop, ipc::agent_reset, ipc::agent_delegate_info, + ipc::agent_list_models, ipc::activity_list, ipc::save::save_text_file, + ipc::pick::pick_path, ipc::links::open_link, ipc::links::reveal_log, ipc::library_index, diff --git a/src/host/index.ts b/src/host/index.ts index 6816970..cac93bf 100644 --- a/src/host/index.ts +++ b/src/host/index.ts @@ -11,6 +11,7 @@ import type { AgentEvent, AppLink, ApprovalDecision, + BackendKind, DelegateInfo, EngineStatus, Field, @@ -20,6 +21,8 @@ import type { LibraryIndex, Method, MethodField, + ModelOption, + PathPurpose, Provider, ProviderIcon, QueryEvent, @@ -130,8 +133,24 @@ export const host = { */ delegateInfo: (program: string | null) => invoke('agent_delegate_info', { program }), + + /** + * The models an API key backend offers, as its provider lists them. + * `apiKey` is a key typed and not saved yet. With null, the key stored + * for that backend is used. Null `baseUrl` means the provider's own. + */ + listModels: (kind: BackendKind, baseUrl: string | null, apiKey: string | null) => + invoke('agent_list_models', { kind, baseUrl, apiKey }), }, + /** + * Asks the operator for a file or a folder in the system's dialog. The + * host decides which, from `purpose`. `current` only decides where the + * dialog opens. Resolves to the path, or to null when it was dismissed. + */ + pickPath: (purpose: PathPurpose, current: string | null) => + invoke('pick_path', { purpose, current }), + /** Closes the window, which ends the app and stops the engine. */ closeWindow: () => getCurrentWindow().close(), diff --git a/src/host/types.ts b/src/host/types.ts index d1ecc12..d448225 100644 --- a/src/host/types.ts +++ b/src/host/types.ts @@ -193,6 +193,8 @@ export interface BackendOption { defaultBaseUrl: string; /** A local server usually needs no key. */ keyOptional: boolean; + /** Whether a key for this backend is in the keychain. Each backend keeps its own. */ + keyStored: boolean; /** * An agent the operator installed runs the model. There is no key and no * address to enter, and no approval prompt. @@ -200,6 +202,17 @@ export interface BackendOption { delegated: boolean; } +/** A model an API key backend offers, as its provider lists it. */ +export interface ModelOption { + /** What goes in the settings and on the wire. */ + id: string; + /** What the provider calls it. The id when it gives no name. */ + name: string; +} + +/** What a path in the settings is for. The host picks the dialog to match. */ +export type PathPurpose = 'engine' | 'dataFolder' | 'envFile' | 'agent'; + /** A model a delegated agent offers. */ export interface AgentModel { id: string; @@ -220,7 +233,6 @@ export interface DelegateInfo { export interface AgentConfig { /** Null means no model backend is set up yet. */ inference: InferenceSettings | null; - hasKey: boolean; safetyMode: SafetyMode; backends: BackendOption[]; /** False when keys cannot be kept in the OS keychain on this machine. */ diff --git a/src/lib/models.test.ts b/src/lib/models.test.ts new file mode 100644 index 0000000..6f20ec9 --- /dev/null +++ b/src/lib/models.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from 'vitest'; +import type { BackendOption } from '../host/types'; +import { canListModels, listsOnOpen, modelLabel, saveBlocker } from './models'; + +function option(overrides: Partial): BackendOption { + return { + kind: 'gemini', + defaultModel: 'gemini-default', + defaultBaseUrl: 'https://generativelanguage.googleapis.com', + keyOptional: false, + keyStored: false, + delegated: false, + ...overrides, + }; +} + +const copilot = option({ + kind: 'github_copilot', + defaultModel: '', + defaultBaseUrl: '', + keyOptional: true, + delegated: true, +}); +const compatible = option({ + kind: 'openai_compatible', + defaultModel: '', + defaultBaseUrl: 'https://api.openai.com/v1', + keyOptional: true, +}); + +describe('modelLabel', () => { + it('shows the provider name with the id, and the id alone when they match', () => { + expect(modelLabel({ id: 'gemini-x', name: 'Gemini X' })).toBe('Gemini X (gemini-x)'); + expect(modelLabel({ id: 'llama3', name: 'llama3' })).toBe('llama3'); + }); +}); + +describe('listsOnOpen', () => { + it('asks a provider straight away only when it needs nothing more', () => { + expect(listsOnOpen(option({ keyStored: true }), '')).toBe(true); + expect(listsOnOpen(option({ keyStored: false }), '')).toBe(false); + // A server of the operator's own, which needs no key. + expect(listsOnOpen(compatible, 'http://127.0.0.1:11434/v1')).toBe(true); + // The default address of a compatible backend is a hosted one that needs a key. + expect(listsOnOpen(compatible, ' ')).toBe(false); + expect(listsOnOpen(copilot, '')).toBe(false); + expect(listsOnOpen(undefined, '')).toBe(false); + }); +}); + +describe('canListModels', () => { + it('needs a key where the backend needs one, typed or stored', () => { + expect(canListModels(option({}), '')).toBe(false); + expect(canListModels(option({}), 'typed-key')).toBe(true); + expect(canListModels(option({ keyStored: true }), '')).toBe(true); + expect(canListModels(compatible, '')).toBe(true); + expect(canListModels(copilot, '')).toBe(false); + }); +}); + +describe('saveBlocker', () => { + it('says a key is missing when the backend needs one and none is stored', () => { + expect(saveBlocker(option({}), 'gemini-x', '')).toBe('Enter an API key to save.'); + expect(saveBlocker(option({}), '', 'typed-key')).toBeNull(); + expect(saveBlocker(option({ keyStored: true }), '', '')).toBeNull(); + }); + + it('says a model is missing only where there is no default', () => { + expect(saveBlocker(compatible, '', '')).toBe('Choose a model to save.'); + expect(saveBlocker(compatible, ' ', '')).toBe('Choose a model to save.'); + expect(saveBlocker(compatible, 'local-model', '')).toBeNull(); + }); + + it('never stops a delegated agent or an empty choice', () => { + expect(saveBlocker(copilot, '', '')).toBeNull(); + expect(saveBlocker(undefined, '', '')).toBeNull(); + }); +}); diff --git a/src/lib/models.ts b/src/lib/models.ts new file mode 100644 index 0000000..77d7065 --- /dev/null +++ b/src/lib/models.ts @@ -0,0 +1,50 @@ +// Choosing a model in the settings: when the provider can be asked for its +// list, how a listed model is named, and what still stops a save. + +import type { BackendOption, ModelOption } from '../host/types'; + +/** How a listed model is named in the dropdown. */ +export function modelLabel(model: ModelOption): string { + return model.name === model.id ? model.id : `${model.name} (${model.id})`; +} + +/** + * Whether to ask for the models as soon as the backend is shown: when the + * provider can be asked with nothing more from the operator. That is a + * stored key, or a server of the operator's own that needs none. + */ +export function listsOnOpen(option: BackendOption | undefined, baseUrl: string): boolean { + if (!option || option.delegated) { + return false; + } + return option.keyStored || (option.keyOptional && baseUrl.trim() !== ''); +} + +/** Whether the provider can be asked for its models now. */ +export function canListModels(option: BackendOption | undefined, apiKey: string): boolean { + if (!option || option.delegated) { + return false; + } + return option.keyOptional || option.keyStored || apiKey.trim() !== ''; +} + +/** + * Why an API key backend cannot be saved yet, said next to the button, or + * null when it can. A delegated agent needs neither a key nor a model. + */ +export function saveBlocker( + option: BackendOption | undefined, + model: string, + apiKey: string, +): string | null { + if (!option || option.delegated) { + return null; + } + if (!option.keyOptional && !option.keyStored && apiKey.trim() === '') { + return 'Enter an API key to save.'; + } + if (option.defaultModel === '' && model.trim() === '') { + return 'Choose a model to save.'; + } + return null; +} diff --git a/src/panes/settings/ChatSettings.tsx b/src/panes/settings/ChatSettings.tsx index b163184..56d0455 100644 --- a/src/panes/settings/ChatSettings.tsx +++ b/src/panes/settings/ChatSettings.tsx @@ -1,4 +1,4 @@ -import { useId, useState } from 'react'; +import { useCallback, useEffect, useId, useRef, useState } from 'react'; import { host, toHostError, @@ -6,7 +6,10 @@ import { type BackendKind, type BackendOption, type DelegateInfo, + type ModelOption, } from '../../host'; +import { canListModels, listsOnOpen, modelLabel, saveBlocker } from '../../lib/models'; +import { PathInput } from './PathInput'; const LABELS: Record = { github_copilot: 'GitHub Copilot (the Copilot CLI and its sign-in)', @@ -49,6 +52,18 @@ export function ChatSettings({ config, onChanged }: ChatSettingsProps) { // What the agent said about itself, once asked. const [info, setInfo] = useState(null); const [asking, setAsking] = useState(false); + // The models an API key backend's provider listed, once asked. + const [initial] = useState(() => { + const opening = config.backends.find((b) => b.kind === config.inference?.kind); + const url = config.inference?.baseUrl ?? ''; + return { option: opening, baseUrl: url, list: listsOnOpen(opening, url) }; + }); + const [models, setModels] = useState(null); + const [listing, setListing] = useState(initial.list); + const [listError, setListError] = useState(null); + // Only the answer to the latest request is used, so an answer for a + // backend the operator has moved away from is dropped. + const latest = useRef(0); const kindId = useId(); const modelId = useId(); const urlId = useId(); @@ -57,12 +72,51 @@ export function ChatSettings({ config, onChanged }: ChatSettingsProps) { const option: BackendOption | undefined = config.backends.find((b) => b.kind === kind); const delegated = option?.delegated ?? false; - const sameBackend = config.inference?.kind === kind; - const keyStored = sameBackend && config.hasKey; - const needsKey = - option !== undefined && !option.keyOptional && !keyStored && apiKey.trim() === ''; - const needsModel = - option !== undefined && !delegated && option.defaultModel === '' && model.trim() === ''; + const keyStored = option?.keyStored ?? false; + const blocker = saveBlocker(option, model, apiKey); + + const fetchModels = useCallback((forKind: BackendKind, url: string, key: string) => { + latest.current += 1; + const request = latest.current; + host.agent.listModels(forKind, url.trim() || null, key.trim() || null).then( + (list) => { + if (latest.current === request) { + setModels(list); + setListError(null); + setListing(false); + } + }, + (reason: unknown) => { + if (latest.current === request) { + setModels(null); + setListError(toHostError(reason).message); + setListing(false); + } + }, + ); + }, []); + + // Opened on a backend whose provider can be asked straight away. + useEffect(() => { + if (initial.list && initial.option) { + fetchModels(initial.option.kind, initial.baseUrl, ''); + } + }, [initial, fetchModels]); + + const startListing = (forKind: BackendKind, url: string, key: string) => { + setListing(true); + setListError(null); + fetchModels(forKind, url, key); + }; + + // Drops a list, and any answer still on its way, when what it was asked + // for has changed. + const forgetModels = () => { + latest.current += 1; + setModels(null); + setListing(false); + setListError(null); + }; const finish = (work: Promise) => { setBusy(true); @@ -106,6 +160,7 @@ export function ChatSettings({ config, onChanged }: ChatSettingsProps) { setBaseUrl(''); setProgram(''); setInfo(null); + forgetModels(); finish(host.agent.clearConfig()); }; @@ -156,7 +211,8 @@ export function ChatSettings({ config, onChanged }: ChatSettingsProps) { className="mb-1 h-7 w-full rounded border border-line bg-surface px-1" value={kind} onChange={(event) => { - setKind(event.target.value as BackendKind | ''); + const next = event.target.value as BackendKind | ''; + setKind(next); setModel(''); setBaseUrl(''); setProgram(''); @@ -164,6 +220,11 @@ export function ChatSettings({ config, onChanged }: ChatSettingsProps) { setInfo(null); setError(null); setSaved(false); + forgetModels(); + const nextOption = config.backends.find((b) => b.kind === next); + if (nextOption && listsOnOpen(nextOption, '')) { + startListing(nextOption.kind, '', ''); + } }} > @@ -187,18 +248,19 @@ export function ChatSettings({ config, onChanged }: ChatSettingsProps) { Optional. Leave empty to find copilot on PATH. If it is not signed in, run copilot login in a terminal first.

- { - setProgram(event.target.value); - setInfo(null); - }} - /> +
+ { + setProgram(value); + setInfo(null); + }} + /> +