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> = OnceLock::new(); + +/// Notes what the system holds now, so later changes can be told apart from +/// how things were. Call it as the app starts, before any child. +pub fn capture_baseline() { + let _ = BASELINE.get_or_init(system_variables); +} + +/// The environment for a child: the app's own, with the system's variables +/// applied as the module describes. +pub fn for_child() -> Vars { + let own: Vars = std::env::vars_os().collect(); + let Some(baseline) = BASELINE.get_or_init(system_variables) else { + return own; + }; + match system_variables() { + Some(now) => apply_changes(own, baseline, &now), + None => own, + } +} + +/// Names are compared as Windows compares them, without regard to case. +fn key(name: &OsStr) -> String { + name.to_string_lossy().to_uppercase() +} + +/// Applies what the system holds `now` to the app's own environment. A +/// variable missing from `own` is added. One present in `own` is replaced +/// only when the system's value has changed since `baseline`. One that was +/// in `baseline` and is gone now is removed, when `own` still has the value +/// it had then. +fn apply_changes(mut own: Vars, baseline: &Vars, now: &Vars) -> Vars { + let before: HashMap = baseline + .iter() + .map(|(name, value)| (key(name), value)) + .collect(); + let mut present = std::collections::HashSet::new(); + for (name, value) in now { + let k = key(name); + present.insert(k.clone()); + let changed = before.get(&k).is_none_or(|old| *old != value); + match own.iter().position(|(n, _)| key(n) == k) { + None => own.push((name.clone(), value.clone())), + Some(at) if changed => own[at].1 = value.clone(), + Some(_) => {} + } + } + for (k, old) in &before { + if present.contains(k) { + continue; + } + if let Some(at) = own.iter().position(|(n, v)| key(n) == *k && v == *old) { + own.remove(at); + } + } + own +} + +/// Splits an environment block: strings of `name=value`, each ended by a +/// NUL, with an empty string after the last. Entries whose name starts with +/// `=` are the hidden per-drive folders of a console and are left out. +#[cfg_attr(not(windows), allow(dead_code))] +fn split_block(block: &[u16]) -> Vars { + #[cfg(windows)] + use std::os::windows::ffi::OsStringExt; + #[cfg(windows)] + let text = |units: &[u16]| OsString::from_wide(units); + #[cfg(not(windows))] + let text = |units: &[u16]| OsString::from(String::from_utf16_lossy(units)); + + block + .split(|&unit| unit == 0) + .take_while(|entry| !entry.is_empty()) + .filter(|entry| entry.first() != Some(&u16::from(b'='))) + .filter_map(|entry| { + let eq = entry.iter().position(|&unit| unit == u16::from(b'='))?; + Some((text(&entry[..eq]), text(&entry[eq + 1..]))) + }) + .collect() +} + +/// The variables a process of this user started now would get: the +/// machine's and the user's, as the registry holds them at this moment, +/// expanded and with the two PATHs joined, as Windows builds them. +#[cfg(windows)] +fn system_variables() -> Option { + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; + use windows_sys::Win32::Security::{TOKEN_DUPLICATE, TOKEN_QUERY}; + use windows_sys::Win32::System::Environment::{ + CreateEnvironmentBlock, DestroyEnvironmentBlock, + }; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + + let mut token: HANDLE = std::ptr::null_mut(); + // SAFETY: GetCurrentProcess returns a pseudo handle that needs no + // closing, and `token` is a valid place for the handle to go. + let opened = unsafe { + OpenProcessToken( + GetCurrentProcess(), + TOKEN_QUERY | TOKEN_DUPLICATE, + &mut token, + ) + }; + if opened == 0 { + return None; + } + let mut block: *mut core::ffi::c_void = std::ptr::null_mut(); + // SAFETY: `token` was opened above with the access a primary token needs + // here, and `block` is a valid place for the pointer to go. With FALSE + // the block holds the system's variables, not this process's. + let made = unsafe { CreateEnvironmentBlock(&mut block, token, 0) }; + // SAFETY: `token` is a handle this function opened and closes once. + unsafe { CloseHandle(token) }; + if made == 0 || block.is_null() { + return None; + } + let units = block.cast::().cast_const(); + let mut len = 0; + // SAFETY: the block is UTF-16 strings, each ended by a NUL, with one more + // NUL after the last. The scan stops at that pair and reads nothing past + // it. + unsafe { + while !(*units.add(len) == 0 && (len == 0 || *units.add(len - 1) == 0)) { + len += 1; + } + } + // SAFETY: `len + 1` units were read above, all inside the block. + let vars = split_block(unsafe { std::slice::from_raw_parts(units, len + 1) }); + // SAFETY: the block came from CreateEnvironmentBlock and is freed once. + unsafe { DestroyEnvironmentBlock(block) }; + Some(vars) +} + +#[cfg(not(windows))] +fn system_variables() -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + fn vars(pairs: &[(&str, &str)]) -> Vars { + pairs + .iter() + .map(|(n, v)| (OsString::from(n), OsString::from(v))) + .collect() + } + + fn get<'a>(env: &'a Vars, name: &str) -> Option<&'a str> { + env.iter() + .find(|(n, _)| key(n) == key(OsStr::new(name))) + .and_then(|(_, v)| v.to_str()) + } + + #[test] + fn a_variable_set_after_the_app_started_reaches_the_child() { + let own = vars(&[("PATH", "C:\\bin")]); + let baseline = vars(&[("PATH", "C:\\bin")]); + let now = vars(&[("PATH", "C:\\bin"), ("CLOUDFLARE_API_TOKEN", "new")]); + let env = apply_changes(own, &baseline, &now); + assert_eq!(get(&env, "CLOUDFLARE_API_TOKEN"), Some("new")); + assert_eq!(get(&env, "PATH"), Some("C:\\bin")); + } + + #[test] + fn a_variable_changed_after_the_app_started_takes_its_new_value() { + let own = vars(&[("TOKEN", "old")]); + let baseline = vars(&[("TOKEN", "old")]); + let now = vars(&[("TOKEN", "new")]); + assert_eq!( + get(&apply_changes(own, &baseline, &now), "TOKEN"), + Some("new") + ); + } + + #[test] + fn a_variable_removed_after_the_app_started_is_removed() { + let own = vars(&[("TOKEN", "old"), ("KEEP", "1")]); + let baseline = vars(&[("TOKEN", "old"), ("KEEP", "1")]); + let now = vars(&[("KEEP", "1")]); + let env = apply_changes(own, &baseline, &now); + assert_eq!(get(&env, "TOKEN"), None); + assert_eq!(get(&env, "KEEP"), Some("1")); + } + + #[test] + fn a_value_the_app_was_started_with_wins_until_the_system_changes() { + // Set in a terminal for this launch, over the stored value. + let own = vars(&[("AWS_PROFILE", "dev"), ("ONLY_HERE", "x")]); + let baseline = vars(&[("AWS_PROFILE", "prod")]); + let unchanged = apply_changes(own.clone(), &baseline, &baseline); + assert_eq!(get(&unchanged, "AWS_PROFILE"), Some("dev")); + assert_eq!(get(&unchanged, "ONLY_HERE"), Some("x")); + // A variable the system never held is not removed. + let removed = apply_changes(own.clone(), &baseline, &vars(&[])); + assert_eq!(get(&removed, "AWS_PROFILE"), Some("dev")); + assert_eq!(get(&removed, "ONLY_HERE"), Some("x")); + // Changed in the system's settings since: that is the newer word. + let changed = apply_changes(own, &baseline, &vars(&[("AWS_PROFILE", "staging")])); + assert_eq!(get(&changed, "AWS_PROFILE"), Some("staging")); + } + + #[test] + fn names_match_without_regard_to_case() { + let own = vars(&[("Path", "C:\\old")]); + let baseline = vars(&[("Path", "C:\\old")]); + let now = vars(&[("PATH", "C:\\new")]); + let env = apply_changes(own, &baseline, &now); + assert_eq!(env.len(), 1, "{env:?}"); + assert_eq!(get(&env, "path"), Some("C:\\new")); + } + + #[test] + fn a_block_is_split_into_names_and_values() { + let text = "=C:=C:\\work\0A=1\0B=x=y\0EMPTY=\0\0"; + let units: Vec = text.encode_utf16().collect(); + let env = split_block(&units); + assert_eq!(env, vars(&[("A", "1"), ("B", "x=y"), ("EMPTY", "")])); + assert!(split_block(&[0, 0]).is_empty()); + } + + /// Sets a throwaway user variable in the real registry, the way `setx` + /// stores one, and checks the next read sees it while this process's + /// own environment does not. The variable is removed again after. + #[cfg(windows)] + #[test] + fn a_user_variable_stored_now_is_seen_without_restarting() { + use std::process::Command; + + struct Remove(String); + impl Drop for Remove { + fn drop(&mut self) { + let _ = Command::new("reg") + .args(["delete", "HKCU\\Environment", "/v", &self.0, "/f"]) + .output(); + } + } + + capture_baseline(); + let name = format!("STACKQL_WORKBENCH_PROBE_{}", std::process::id()); + let added = Command::new("reg") + .args([ + "add", + "HKCU\\Environment", + "/v", + &name, + "/t", + "REG_SZ", + "/d", + "probe-value", + "/f", + ]) + .output() + .unwrap(); + assert!(added.status.success(), "{added:?}"); + let _cleanup = Remove(name.clone()); + + assert!(std::env::var_os(&name).is_none()); + let env = for_child(); + assert_eq!(get(&env, &name), Some("probe-value")); + // What the process had is still there. + assert!(get(&env, "SystemRoot").is_some()); + } +} diff --git a/src-tauri/src/engine/mod.rs b/src-tauri/src/engine/mod.rs index 1a37303..b904219 100644 --- a/src-tauri/src/engine/mod.rs +++ b/src-tauri/src/engine/mod.rs @@ -5,6 +5,7 @@ pub mod approot; pub mod discovery; +pub mod environment; pub mod logbuf; pub mod port; pub mod supervisor; diff --git a/src-tauri/src/engine/supervisor.rs b/src-tauri/src/engine/supervisor.rs index 840b1d9..38e7f3f 100644 --- a/src-tauri/src/engine/supervisor.rs +++ b/src-tauri/src/engine/supervisor.rs @@ -50,9 +50,11 @@ pub enum StdioMode { /// never left to chance. #[derive(Debug, Clone, Default)] pub struct EnvSpec { - /// Start from the app's own environment. On macOS an app launched from - /// Finder has almost nothing in it, so this must not be relied on for - /// credentials. + /// Start from the app's own environment, with the user's and the + /// machine's variables as Windows holds them now applied, so one set + /// after the app started is passed on. See `environment`. On macOS an + /// app launched from Finder has almost nothing in it, so this must not + /// be relied on for credentials there. pub inherit: bool, /// Variables set on top. Values are never logged. pub vars: Vec<(String, String)>, @@ -106,8 +108,9 @@ impl Supervisor { cmd.stdin(Stdio::piped()).stdout(Stdio::piped()); } } - if !spec.env.inherit { - cmd.env_clear(); + cmd.env_clear(); + if spec.env.inherit { + cmd.envs(super::environment::for_child()); } cmd.envs(spec.env.vars.iter().map(|(k, v)| (k, v))); super::hide_console_window(&mut cmd); 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..66b3b81 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -165,9 +165,12 @@ pub fn run() { // window to say anything in, so say it in a dialog of the system's and // stop. This returns at once where a renderer is found. webview_runtime::require(); + // Note the user's and the machine's variables as they are now, so one + // set later is passed to the engine when it is restarted. + engine::environment::capture_baseline(); let built = tauri::Builder::default() - // The save dialog, used from the host only. The webview has no access to it. + // The save and open dialogs, used from the host only. The webview has no access to them. .plugin(tauri_plugin_dialog::init()) // Opens the Help menu's links in the browser, from the host only. .plugin(tauri_plugin_opener::init()) @@ -197,8 +200,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-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 9db665c..4f378dd 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "StackQL Workbench", "mainBinaryName": "stackql-workbench", - "version": "0.1.0", + "version": "0.2.0", "identifier": "io.stackql.workbench", "build": { "beforeDevCommand": "npm run dev", diff --git a/src-tauri/tests/agent_integration.rs b/src-tauri/tests/agent_integration.rs index f80cc67..a9b36e6 100644 --- a/src-tauri/tests/agent_integration.rs +++ b/src-tauri/tests/agent_integration.rs @@ -791,6 +791,43 @@ async fn changing_the_safety_mode_opens_a_new_engine_session() { teardown(fx).await; } +/// Reload Credentials restarts the engine. The agent's MCP server keeps the +/// environment it was started with, so the next turn must open a new one. +#[tokio::test] +async fn restarting_the_engine_opens_a_new_engine_session() { + if !engine_available() { + return; + } + let fx = fixture("restart").await; + let model = Scripted::new(vec![says("one"), says("two"), says("three")]); + + let mut sessions = Vec::new(); + for restart_first in [false, false, true] { + if restart_first { + let status = fx.connection.restart().await; + assert_eq!(status.state, EngineState::Running, "{:?}", status.error); + } + let (emit, events) = collector(); + fx.runtime + .send(model.clone(), SafetyMode::Safe, "hi".into(), emit) + .await + .unwrap(); + let started = events + .lock() + .unwrap() + .iter() + .filter(|e| matches!(e, AgentEvent::SessionStarted { .. })) + .count(); + sessions.push(started); + } + // Opened once, reused, and opened again after the restart. + assert_eq!(sessions, vec![1, 0, 1]); + // The conversation carried over to the new session. + assert_eq!(model.seen()[2].messages.len(), 5); + + teardown(fx).await; +} + #[tokio::test] async fn without_a_running_engine_the_turn_fails_plainly() { let approot = std::env::temp_dir().join(format!("wb-agent-it-{}-noengine", std::process::id())); 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); + }} + /> +