diff --git a/CLAUDE.md b/CLAUDE.md
index cf26d3b..655dcf6 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,8 @@ 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.
+- Credentials set while the app is open were checked on Windows in a debug build, through the editor. The app was started from a process whose environment lacked `CLOUDFLARE_API_TOKEN`, which was stored for the user before, and a Cloudflare query returned its row. With `DIGITALOCEAN_TOKEN` stored nowhere a query failed with "credentialsenvvar references empty string". A made-up token was then stored for the user in the registry while the app ran, and after Reload Credentials the same query came back with DigitalOcean's 401, so the engine had sent it. Deleted again, and after another Reload Credentials, the query failed as at first. The app was not closed in between. A unit test stores a throwaway user variable in the real registry and sees it reach a child's environment. An integration test checks that the next turn opens a new engine session after a restart. The Copilot CLI's restart after an engine restart was not run.
- 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 +91,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 +119,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 +128,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
@@ -329,7 +332,9 @@ Provider credentials are environment variables read by the engine. The app never
- Apps launched from Finder or the Dock on macOS do not inherit shell profile exports. Do not rely on the app's own environment.
- The host builds the child environment explicitly. Values come from the OS keychain and are injected at spawn, or from an operator-supplied dotenv file passed with `--env.file`.
-- Until the keychain store for provider credentials exists, the engine starts with the app's own environment as the base, plus the `--env.file` from settings. That works on Windows, where the app sees the user's environment variables. On macOS the env file is the dependable route.
+- Until the keychain store for provider credentials exists, the engine starts with the app's own environment as the base, plus the `--env.file` from settings. On macOS the env file is the dependable route.
+- On Windows a process keeps the environment it was started with, so a variable set with `setx` or in the system settings while the app was open used to reach the engine only after the app itself was restarted. Now every child the supervisor starts gets the app's own environment with the user's and the machine's variables, as the registry holds them at that moment, applied on top: a variable the app's environment lacks is added, and one changed or removed in the registry since the app started is changed or removed. Reload Credentials, which restarts the engine, is then enough. A value the app was started with, for example one set in a terminal for that launch, keeps winning until the registry's value changes. The registry is read with `CreateEnvironmentBlock`, which builds what a newly started process of the user would get. See `engine/environment.rs`.
+- The agent's engine session and a delegated agent keep the environment they started with, so after an engine restart the next turn opens new ones. On the API key path the conversation carries over. The Copilot CLI starts a new session and says that it does not remember the earlier messages.
- The MCP `reload_credentials` tool re-sources `--env.file`. `stackql srv` needs a restart to pick up changes.
- The UI shows variable names and whether they are set. Never log or display environment contents.
@@ -358,6 +363,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 +407,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..3772efd 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
@@ -258,14 +258,14 @@ When that folder is there the app uses it and does not look at what the system h
An installed app keeps the engine's provider cache in `.stackql` in your home folder. That is where the `stackql` command keeps it when it is started there, as the command shell the MSI installs does, so providers you pulled with the command are there in the app, and the other way round. A build from this repository keeps a `.stackql` folder beside its executable instead, so a first run of one lists no providers. Run `REGISTRY PULL github;` in the editor to install one. To use another folder, set it under Settings.
-Provider credentials are environment variables the engine reads. On Windows the engine sees the variables of your user account. To use a dotenv file, set it under Settings.
+Provider credentials are environment variables the engine reads. On Windows the engine sees the variables of your user account and of the machine. One set while the app is open, with `setx` or in the system settings, is used after Providers > Reload Credentials, which restarts the engine. The app does not need to be closed. To use a dotenv file, set it under Settings.
The app opens in chat. The side menu leads to the explorer, which holds the provider tree, the query editor and the results grid, to the query library, and to the activity list. The File, Edit, View, Query, Providers and Help menus repeat those.
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/package-lock.json b/package-lock.json
index 5998efd..2767958 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "stackql-workbench",
- "version": "0.1.0",
+ "version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "stackql-workbench",
- "version": "0.1.0",
+ "version": "0.2.0",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.20.4",
diff --git a/package.json b/package.json
index 219dfdc..d1c9e6f 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "stackql-workbench",
"private": true,
- "version": "0.1.0",
+ "version": "0.2.0",
"description": "Desktop query IDE and chat interface for StackQL",
"license": "MIT",
"type": "module",
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 76cfbd4..e750891 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -3874,7 +3874,7 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "stackql-workbench"
-version = "0.1.0"
+version = "0.2.0"
dependencies = [
"apple-native-keyring-store",
"arboard",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index a18d007..a02ca3c 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "stackql-workbench"
-version = "0.1.0"
+version = "0.2.0"
description = "Desktop query IDE and chat interface for StackQL"
edition = "2024"
rust-version = "1.90"
@@ -62,6 +62,10 @@ windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Security",
"Win32_System_JobObjects",
+ # A child's environment: the user's and the machine's variables as the
+ # registry holds them when the child starts, read with the app's token.
+ "Win32_System_Environment",
+ "Win32_System_Threading",
# The dialog shown when no WebView2 runtime is found. The second is needed
# for the first to define it.
"Win32_UI_Controls",
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/agent/runtime.rs b/src-tauri/src/agent/runtime.rs
index c987615..5f081f9 100644
--- a/src-tauri/src/agent/runtime.rs
+++ b/src-tauri/src/agent/runtime.rs
@@ -183,16 +183,30 @@ pub struct DelegateInfo {
/// What a delegated session was started with. A change in any of it needs
/// a new session, because the safety mode is fixed on the agent's command
-/// line.
+/// line, and the agent and its engine keep the environment they started
+/// with.
#[derive(PartialEq, Eq)]
struct DelegateKey {
mode: SafetyMode,
+ /// The engine's start count when the session opened. A restart, for
+ /// example to read credentials again, needs a new session for the same
+ /// reason.
+ engine: u64,
request: DelegateRequest,
}
+/// What an engine session was opened with. The MCP server keeps the safety
+/// mode and the environment it was started with, so a change in either
+/// needs a new one.
+#[derive(Clone, Copy, PartialEq, Eq)]
+struct SessionKey {
+ mode: SafetyMode,
+ engine: u64,
+}
+
#[derive(Default)]
struct State {
- session: Option<(SafetyMode, McpSession)>,
+ session: Option<(SessionKey, McpSession)>,
messages: Vec,
delegate: Option<(DelegateKey, DelegateSession)>,
}
@@ -373,19 +387,25 @@ impl AgentRuntime {
*lock(&self.stop) = Some(stop.clone());
let _guard = TurnGuard { runtime: self };
- let key = DelegateKey { mode, request };
+ let key = DelegateKey {
+ mode,
+ engine: self.connection.generation(),
+ request,
+ };
let reusable = state
.delegate
.as_ref()
.is_some_and(|(current, session)| *current == key && !session.is_closed());
if !reusable {
- let previous = state.delegate.take().map(|(old, _)| old.mode);
+ let previous = state.delegate.take().map(|(old, _)| (old.mode, old.engine));
let (session, tools) = self.open_delegate(&key.request, mode).await?;
- if let Some(old_mode) = previous {
- let cause = if old_mode == mode {
- "The previous session ended"
- } else {
+ if let Some((old_mode, old_engine)) = previous {
+ let cause = if old_mode != mode {
"The safety mode changed"
+ } else if old_engine != key.engine {
+ "The engine was restarted"
+ } else {
+ "The previous session ended"
};
emit(AgentEvent::Notice {
message: format!(
@@ -441,10 +461,15 @@ impl AgentRuntime {
session, messages, ..
} = &mut *state;
- // A session is tied to the safety mode it was started with.
+ // A session is tied to the safety mode and the engine start it was
+ // opened under. The conversation itself carries over to a new one.
+ let key = SessionKey {
+ mode,
+ engine: self.connection.generation(),
+ };
let reusable = session
.as_ref()
- .is_some_and(|(current, s)| *current == mode && !s.is_closed());
+ .is_some_and(|(current, s)| *current == key && !s.is_closed());
if !reusable {
if let Some((_, old)) = session.take() {
old.close().await;
@@ -456,7 +481,7 @@ impl AgentRuntime {
protocol_version: fresh.protocol_version().to_string(),
tools: fresh.tools().len(),
});
- *session = Some((mode, fresh));
+ *session = Some((key, fresh));
}
let Some((_, mcp)) = session.as_ref() else {
return Err(HostError::Agent("No engine session.".to_string()));
diff --git a/src-tauri/src/connection/local.rs b/src-tauri/src/connection/local.rs
index a80b5e4..4ae2cfb 100644
--- a/src-tauri/src/connection/local.rs
+++ b/src-tauri/src/connection/local.rs
@@ -500,6 +500,10 @@ impl Connection for LocalConnection {
self.start()
}
+ fn generation(&self) -> u64 {
+ self.shared.generation.load(Ordering::SeqCst)
+ }
+
fn shutdown(&self) -> BoxFuture<'_, ()> {
async move {
let mut child = self.lifecycle.lock().await;
diff --git a/src-tauri/src/connection/mod.rs b/src-tauri/src/connection/mod.rs
index 607dc98..f357e20 100644
--- a/src-tauri/src/connection/mod.rs
+++ b/src-tauri/src/connection/mod.rs
@@ -156,6 +156,11 @@ pub trait Connection: Send + Sync + 'static {
/// statement that is running, since the engine has no cancel.
fn restart(&self) -> BoxFuture<'_, EngineStatus>;
+ /// Counts the times the engine has been started. A channel the agent
+ /// opened under an earlier count was set up with what the engine had
+ /// then, its credentials among them, so the agent opens a new one.
+ fn generation(&self) -> u64;
+
/// Stops the engine. Called when the app exits.
fn shutdown(&self) -> BoxFuture<'_, ()>;
diff --git a/src-tauri/src/engine/environment.rs b/src-tauri/src/engine/environment.rs
new file mode 100644
index 0000000..cfc5865
--- /dev/null
+++ b/src-tauri/src/engine/environment.rs
@@ -0,0 +1,295 @@
+//! The environment a child process starts with.
+//!
+//! A process keeps the environment it was started with. On Windows the
+//! user's and the machine's variables are kept in the registry, and one set
+//! there after the app started, with `setx` or in the system settings, used
+//! to reach no child until the app itself was started again. So each child
+//! now gets the app's own environment with what the system holds applied on
+//! top: a variable the app's environment lacks is added, and one changed or
+//! removed in the system's settings since the app started is changed or
+//! removed. Restarting the engine is then enough to pick up a credential set
+//! that way.
+//!
+//! A variable the app was started with keeps its value unless the system's
+//! settings change it after the app started. A value set in a terminal for
+//! one launch therefore still wins over the stored one.
+//!
+//! On macOS there is no such store. An app started from Finder gets what
+//! launchd gives it and never reads a shell profile, so there the child gets
+//! the app's own environment, and a dotenv file named in Settings is how the
+//! engine is handed credentials.
+
+use std::collections::HashMap;
+use std::ffi::{OsStr, OsString};
+use std::sync::OnceLock;
+
+/// Variables as name and value, in no particular order.
+pub type Vars = Vec<(OsString, OsString)>;
+
+/// What the system held when the app started. `None` inside means it could
+/// not be read, or there is no such store on this platform.
+static BASELINE: OnceLock