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