Skip to content

Switchyard lets LLM applications route traffic across models and providers while preserving native OpenAI and Anthropic API compatibility - enabling flexible model selection, benchmarking, and cost/performance optimization.

Rust

feat(desktop): inspect harness settings and add the Harnesses page (#1103)

Elyas Mehtabuddineb193a5e5057
diff --git a/crates/switchyard-desktop/src/accounts.rs b/crates/switchyard-desktop/src/accounts.rs
new file mode 100644
index 000000000..e5e14c950
--- /dev/null
+++ b/crates/switchyard-desktop/src/accounts.rs
@@ -0,0 +1,73 @@
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+//! Named login directories use the harness's own authentication commands.
+
+use crate::harness::{self, Harness};
+use std::path::{Path, PathBuf};
+
+fn root(tool: Harness) -> Result<PathBuf, String> {
+ let name = match tool {
+ Harness::CodexCli => "codex",
+ Harness::Claude => "claude",
+ _ => return Err("Named accounts are available for Codex CLI and Claude Code.".into()),
+ };
+ let home = crate::config::expand_home(Path::new("~"))?;
+ let mut path = home;
+ for component in [".switchyard", "accounts", name] {
+ path.push(component);
+ if std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) {
+ return Err(format!(
+ "{} is a symlink. Edit its target yourself.",
+ path.display()
+ ));
+ }
+ }
+ Ok(path)
+}
+
+pub fn discover(tool: Harness) -> Result<Vec<(String, PathBuf)>, String> {
+ if !matches!(tool, Harness::CodexCli | Harness::Claude) {
+ return Ok(Vec::new());
+ }
+ let root = root(tool)?;
+ let entries = match std::fs::read_dir(&root) {
+ Ok(entries) => entries,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
+ Err(error) => {
+ return Err(format!(
+ "Could not list accounts in {}: {error}",
+ root.display()
+ ));
+ }
+ };
+ let mut accounts = Vec::new();
+ for entry in entries {
+ let entry = entry.map_err(|error| error.to_string())?;
+ if !entry
+ .file_name()
+ .to_string_lossy()
+ .starts_with(".archived-")
+ && entry
+ .file_type()
+ .map_err(|error| error.to_string())?
+ .is_dir()
+ && let Ok(name) = entry.file_name().into_string()
+ {
+ accounts.push((name, entry.path()));
+ }
+ }
+ accounts.sort_by(|a, b| a.0.cmp(&b.0));
+ Ok(accounts)
+}
+
+pub fn config_paths(tool: Harness, account: Option<&Path>) -> Result<Vec<PathBuf>, String> {
+ let Some(account) = account else {
+ return harness::paths(tool);
+ };
+ match tool {
+ Harness::CodexCli => Ok(vec![account.join("sy.config.toml")]),
+ Harness::Claude => Ok(vec![account.join("settings.json")]),
+ _ => harness::paths(tool),
+ }
+}
diff --git a/crates/switchyard-desktop/src/controller.rs b/crates/switchyard-desktop/src/controller.rs
index f948ea70a..6d5523c9b 100644
--- a/crates/switchyard-desktop/src/controller.rs
+++ b/crates/switchyard-desktop/src/controller.rs
@@ -5,7 +5,9 @@
//! It retains the log reader and health probe across refreshes.
use crate::{
+ accounts,
config::Config,
+ harness::{self, Harness},
history, models, pricing, rollup, server,
server_config::{ALGORITHMS, Choice, Route, ServerConfig},
};
@@ -109,6 +111,7 @@ pub struct Snapshot {
pub generation: u64,
pub routes: Vec<RouteInfo>,
pub clients: Vec<ClientInfo>,
+ pub tools: Vec<ToolInfo>,
pub algorithms: Vec<AlgorithmInfo>,
pub metrics: Metrics,
pub today: chrono::NaiveDate,
@@ -167,6 +170,32 @@ pub struct RouteInfo {
pub generated: Option<String>,
}
+/// ToolInfo describes one harness whose settings the apps can change.
+#[derive(Clone, Serialize)]
+pub struct ToolInfo {
+ pub tool: Harness,
+ pub label: &'static str,
+ /// This field is true when the settings files resolve and the harness program is installed.
+ pub available: bool,
+ pub files: Vec<PathBuf>,
+ /// This field summarizes the current settings, or holds the error that stopped the read.
+ pub status: String,
+ pub accounts: Vec<String>,
+ pub account_details: Vec<AccountInfo>,
+ pub discovery_error: Option<String>,
+}
+
+/// AccountInfo describes one saved account folder of a harness.
+#[derive(Clone, Serialize)]
+pub struct AccountInfo {
+ pub name: String,
+ pub path: PathBuf,
+ /// The apps cannot ask a harness whether a login finished, so this field is `unknown`.
+ pub login_status: &'static str,
+ /// This field summarizes the account's settings, or holds the error that stopped the read.
+ pub status: String,
+}
+
/// ClientInfo describes one endpoint under `[llm_clients]` in the server config.
#[derive(Clone, Default, Serialize)]
pub struct ClientInfo {
@@ -265,7 +294,7 @@ impl Reply {
struct Review {
token: String,
inputs: Value,
- files: Vec<(PathBuf, Option<std::sync::Arc<[u8]>>)>,
+ files: Vec<harness::ReviewedFile>,
}
impl Review {
fn capture(inputs: Value, paths: Vec<PathBuf>) -> Result<Self, String> {
@@ -331,6 +360,7 @@ pub struct Controller {
// The generation ties a draft to the server config file selected by the settings.
generation: u64,
route_reviews: std::collections::HashMap<String, Review>,
+
route_change: Option<Review>,
update_review: Option<(String, Value)>,
}
@@ -343,6 +373,7 @@ impl Controller {
reader: rollup::Reader::default(),
generation: 0,
route_reviews: Default::default(),
+
route_change: None,
update_review: None,
}
@@ -352,6 +383,7 @@ impl Controller {
if config.config_file != self.config.config_file {
self.generation += 1;
self.route_reviews.clear();
+
self.route_change = None;
}
self.config = config;
@@ -536,6 +568,42 @@ impl Controller {
history::History::default()
});
let activity = history::hourly_calls(&history.entries, chrono::Utc::now());
+ let tools = harness::HARNESSES
+ .iter()
+ .map(|&(tool, label)| {
+ let discovered = accounts::discover(tool);
+ let discovery_error = discovered.as_ref().err().cloned();
+ let discovered = discovered.unwrap_or_default();
+ let account_details = discovered
+ .iter()
+ .map(|(name, path)| AccountInfo {
+ name: name.clone(),
+ path: path.clone(),
+ login_status: "unknown",
+ status: accounts::config_paths(tool, Some(path))
+ .and_then(|files| harness::inspect(tool, &files))
+ .unwrap_or_else(|error| error),
+ })
+ .collect();
+ // A path error stays in status; files remains an array and the tool is unavailable.
+ let files = harness::paths(tool);
+ let status = files
+ .as_ref()
+ .map_err(Clone::clone)
+ .and_then(|files| harness::inspect(tool, files))
+ .unwrap_or_else(|error| error);
+ ToolInfo {
+ tool,
+ label,
+ available: files.is_ok() && harness::binary(tool).is_some(),
+ files: files.unwrap_or_default(),
+ status,
+ accounts: discovered.into_iter().map(|(name, _)| name).collect(),
+ account_details,
+ discovery_error,
+ }
+ })
+ .collect();
let Config {
server_url,
routing_log,
@@ -577,6 +645,7 @@ impl Controller {
generation: self.generation,
routes,
clients,
+ tools,
algorithms: ALGORITHMS
.iter()
.map(|a| AlgorithmInfo {
@@ -611,7 +680,7 @@ impl Controller {
refresh_seconds: refresh_seconds.max(1),
})
}
- /// The TUI uses these file paths to run an editor in the foreground.
+ /// The TUI uses these file and folder paths to run an editor in the foreground.
pub fn editor_target(&mut self, action: &Action) -> Result<Option<PathBuf>, String> {
match action {
Action::OpenSettings {} => Ok(Some(self.settings.clone())),
@@ -627,6 +696,7 @@ impl Controller {
}
Action::OpenUpdateLog {} => self.update_log().map(Some),
Action::OpenLogs {} => logs_dir().map(Some),
+
_ => Ok(None),
}
}
@@ -994,6 +1064,7 @@ fn current_route(config: &ServerConfig, key: &str, id: Option<&str>) -> Result<R
.find(|r| r.key == key && id.is_none_or(|id| id == r.id))
.ok_or_else(|| "The route changed or was removed. Refresh and choose it again.".into())
}
+
fn install_metadata(settings: &std::path::Path) -> Result<PathBuf, String> {
let executable = std::env::current_exe().map_err(|e| e.to_string())?;
let bundle = switchyard_desktop::install::bundle_metadata(&executable);
@@ -1020,7 +1091,7 @@ fn update(settings: &std::path::Path) -> Result<String, String> {
#[cfg(test)]
mod tests {
- use super::{Action, Config, Controller};
+ use super::*;
#[test]
fn recent_call_read_errors_name_the_source_and_keep_the_io_details() {
@@ -1201,4 +1272,332 @@ policy = { type = "target_selector", selector = "/target" }
assert!(error.starts_with("The URL for primary changed"), "{error}");
}
}
+
+ #[test]
+ // An algorithm switch must not give stale choices a revision for externally edited bytes.
+ fn algorithm_switches_keep_the_first_revision_and_external_edits_reject_it() {
+ let dir = tempfile::tempdir().expect("fixture");
+ let settings = dir.path().join("desktop.toml");
+ let config = dir.path().join("server.toml");
+ let text = "schema_version = 1\n\
+ [llm_clients.c]\n\
+ base_url='http://localhost:1234'\n\
+ format='openai_chat'\n\
+ [targets.m]\n\
+ id='actual'\n\
+ llm_client='c'\n\
+ [routes.r]\n\
+ id='public'\n\
+ type='passthrough'\n\
+ target='m'\n";
+ std::fs::write(&config, text).expect("config");
+ std::fs::write(
+ &settings,
+ format!(
+ "config_file={config:?}\nrouting_log={:?}",
+ dir.path().join("log")
+ ),
+ )
+ .expect("settings");
+ let mut controller = Controller::new(Config::load(&settings).expect("load"), settings);
+ let first = controller
+ .dispatch(Action::Editor {
+ generation: 0,
+ route: "r".into(),
+ algorithm: "passthrough".into(),
+ })
+ .expect("editor");
+ let second = controller
+ .dispatch(Action::Editor {
+ generation: 0,
+ route: "r".into(),
+ algorithm: "random".into(),
+ })
+ .expect("switch roles");
+ assert_eq!(first.data["revision"], second.data["revision"]);
+ assert_eq!(
+ controller.snapshot().expect("snapshot").routes[0].revision,
+ first.data["revision"]
+ );
+ std::fs::write(&config, format!("{text}# external edit\n")).expect("external edit");
+ let latest = controller
+ .dispatch(Action::Editor {
+ generation: 0,
+ route: "r".into(),
+ algorithm: "passthrough".into(),
+ })
+ .expect("new editor");
+ assert_ne!(latest.data["revision"], first.data["revision"]);
+ let rejected = controller.dispatch(Action::PreviewRoute {
+ generation: 0,
+ route: "r".into(),
+ algorithm: "passthrough".into(),
+ choices: vec![Choice {
+ client: "c".into(),
+ model: "replacement".into(),
+ }],
+ revision: first.data["revision"].as_str().map(str::to_string),
+ });
+ assert!(rejected.is_err());
+ assert_eq!(
+ std::fs::read_to_string(&config).expect("config"),
+ format!("{text}# external edit\n")
+ );
+ assert_eq!(std::fs::read_dir(dir.path()).expect("files").count(), 2);
+ }
+
+ #[cfg(any(target_os = "macos", windows))]
+ #[test]
+ // A cached list must not let an untested key reach Keychain.
+ fn submitting_a_key_checks_upstream_even_when_refresh_is_false() {
+ use std::io::{Read, Write};
+ let dir = tempfile::tempdir().expect("directory");
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("listener");
+ listener.set_nonblocking(true).expect("nonblocking");
+ let url = format!("http://{}/v1", listener.local_addr().expect("address"));
+ #[cfg(windows)]
+ assert_eq!(
+ switchyard_desktop::install::windows::saved_key(&url).expect("no saved key"),
+ None
+ );
+ let worker = std::thread::spawn(move || {
+ for _ in 0..200 {
+ if let Ok((mut stream, _)) = listener.accept() {
+ stream.set_nonblocking(false).expect("blocking request");
+ stream
+ .set_read_timeout(Some(std::time::Duration::from_secs(1)))
+ .expect("timeout");
+ let mut request = Vec::new();
+ let mut chunk = [0; 1024];
+ for _ in 0..4 {
+ let n = stream.read(&mut chunk).expect("request");
+ request.extend_from_slice(&chunk[..n]);
+ if n == 0 || request.windows(4).any(|bytes| bytes == b"\r\n\r\n") {
+ break;
+ }
+ }
+ stream
+ .write_all(
+ b"HTTP/1.1 401 Unauthorized\r\n\
+ Content-Length: 0\r\n\
+ Connection: close\r\n\
+ \r\n",
+ )
+ .expect("response");
+ return String::from_utf8_lossy(&request).into_owned();
+ }
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ String::new()
+ });
+ let settings = dir.path().join("settings.toml");
+ let routes = dir.path().join("routes.toml");
+ std::fs::write(
+ &routes,
+ format!(
+ "[llm_clients.c]\n\
+ base_url={url:?}\n\
+ format='openai_responses'\n\
+ forward_auth=true\n\
+ [targets.m]\n\
+ id='actual'\n\
+ llm_client='c'\n\
+ [routes.r]\n\
+ id='public'\n\
+ type='passthrough'\n\
+ target='m'\n"
+ ),
+ )
+ .expect("routes");
+ std::fs::write(
+ &settings,
+ format!(
+ "config_file={routes:?}\nrouting_log={:?}",
+ dir.path().join("log")
+ ),
+ )
+ .expect("settings");
+ let cached =
+ json!({format!("{url}/models"): {"models":["cached"],"fetched_at":models::now()}})
+ .to_string();
+ let cache = dir.path().join(models::CACHE_FILE);
+ std::fs::write(&cache, &cached).expect("cache");
+ let mut controller = Controller::new(Config::load(&settings).expect("settings"), settings);
+ let cached_reply = controller
+ .dispatch(Action::Models {
+ client: "c".into(),
+ refresh: false,
+ key: None,
+ base_url: None,
+ })
+ .expect("cached list");
+ assert_eq!(cached_reply.data["warning"], false);
+ assert_eq!(cached_reply.data["source"], "cache");
+ // A failed refresh must not report the cached list as a successful upstream fetch.
+ let failed_refresh = controller
+ .dispatch(Action::Models {
+ client: "c".into(),
+ refresh: true,
+ key: None,
+ base_url: None,
+ })
+ .expect("cached fallback");
+ assert_eq!(failed_refresh.data["warning"], true);
+ assert_eq!(failed_refresh.data["source"], "cache");
+ assert_eq!(failed_refresh.data["models"], json!(["cached"]));
+ let result = controller.dispatch(Action::Models {
+ client: "c".into(),
+ refresh: false,
+ key: Some("rejected-fixture-key".into()),
+ base_url: Some(url.clone()),
+ });
+ let request = worker.join().expect("worker");
+ assert!(result.err().expect("rejected key").contains("401"));
+ assert!(request.starts_with("GET /v1/models "));
+ assert!(request.contains("Authorization: Bearer rejected-fixture-key"));
+ assert_eq!(std::fs::read_to_string(cache).expect("cache"), cached);
+ #[cfg(windows)]
+ assert_eq!(
+ switchyard_desktop::install::windows::saved_key(&url).expect("rejected key not saved"),
+ None
+ );
+ std::fs::write(
+ &routes,
+ "[llm_clients.c]\n\
+ base_url='http://127.0.0.1:9/v1'\n\
+ format='openai_responses'\n\
+ [targets.m]\n\
+ id='actual'\n\
+ llm_client='c'\n\
+ [routes.r]\n\
+ id='public'\n\
+ type='passthrough'\n\
+ target='m'\n",
+ )
+ .expect("routes");
+ let result = controller.dispatch(Action::Models {
+ client: "c".into(),
+ refresh: false,
+ key: Some("unused-fixture-key".into()),
+ base_url: Some("http://127.0.0.1:9/v1".into()),
+ });
+ assert!(
+ result
+ .err()
+ .expect("unused key")
+ .contains("does not accept a model-list key")
+ );
+ }
+ #[test]
+ // Matching route names in two files must not let an old draft edit the newly selected file.
+ fn stale_editor_rejects_after_settings_change_without_writes() {
+ let dir = tempfile::tempdir().expect("directory");
+ let settings = dir.path().join("settings.toml");
+ let first = dir.path().join("first.toml");
+ let second = dir.path().join("second.toml");
+ let text = "schema_version = 1\n\
+ [llm_clients.c]\n\
+ base_url='https://example.com/v1'\n\
+ format='openai_responses'\n\
+ [targets.m]\n\
+ id='actual'\n\
+ llm_client='c'\n\
+ [routes.r]\n\
+ id='public'\n\
+ type='passthrough'\n\
+ target='m'\n";
+ std::fs::write(&first, text).expect("first");
+ std::fs::write(&second, text).expect("second");
+ let write_settings = |path: &std::path::Path| {
+ std::fs::write(
+ &settings,
+ format!(
+ "config_file={path:?}\nrouting_log={:?}",
+ dir.path().join("log")
+ ),
+ )
+ .expect("settings");
+ };
+ write_settings(&first);
+ let mut controller =
+ Controller::new(Config::load(&settings).expect("settings"), settings.clone());
+ let snapshot = controller.snapshot().expect("snapshot");
+ assert_eq!(
+ snapshot.routes[0].tiers,
+ Some(vec![Some("Capable".to_string())])
+ );
+ let generation = snapshot.generation;
+ write_settings(&second);
+ for action in [
+ Action::Editor {
+ generation,
+ route: "r".into(),
+ algorithm: "passthrough".into(),
+ },
+ Action::Apply {
+ generation,
+ route: "r".into(),
+ algorithm: "passthrough".into(),
+ choices: vec![Choice {
+ client: "c".into(),
+ model: "changed".into(),
+ }],
+ revision: None,
+ },
+ ] {
+ assert!(controller.dispatch(action).is_err());
+ }
+ assert_eq!(std::fs::read_to_string(&second).expect("second"), text);
+ assert_eq!(std::fs::read_dir(dir.path()).expect("files").count(), 3);
+ assert_eq!(
+ controller.snapshot().expect("snapshot").generation,
+ generation + 1
+ );
+ }
+
+ #[test]
+ fn unsupported_routes_are_read_only_before_any_write() {
+ let dir = tempfile::tempdir().expect("directory");
+ let config = dir.path().join("server.toml");
+ let settings = dir.path().join("app.toml");
+ std::fs::write(
+ &settings,
+ format!("config_file={config:?}\nserver_url='http://127.0.0.1:0'"),
+ )
+ .expect("settings");
+ let mut controller = Controller::new(Config::load(&settings).expect("settings"), settings);
+ // These fixtures use valid server algorithms that the app cannot edit.
+ for fields in [
+ "type='noop'",
+ "type='prefill_router'\ntargets=['answer']\ncheckpoint='router.pt'",
+ "type='llm_classifier'\n\
+ mode='custom'\n\
+ models={judge=['judge'],any=['answer']}\n\
+ default_target='any'\n\
+ prompt='Select a target.'\n\
+ response_schema='{\"type\":\"object\"}'\n\
+ policy={type='target_selector',selector='/target'}",
+ ] {
+ let _: switchyard_runner::AlgorithmSpec =
+ toml::from_str(fields).expect("server route schema");
+ let original =
+ format!("schema_version = 1\ntargets = {{}}\n[routes.r]\nid='public'\n{fields}\n");
+ std::fs::write(&config, &original).expect("config");
+ assert!(!controller.snapshot().expect("snapshot").routes[0].editable);
+ for kind in ["editor", "apply"] {
+ let mut raw =
+ json!({"kind":kind,"generation":0,"route":"r","algorithm":"passthrough"});
+ if kind == "apply" {
+ raw["choices"] = json!([]);
+ }
+ let action = serde_json::from_value(raw).expect("action");
+ assert_eq!(
+ controller.dispatch(action).err().expect("read only"),
+ "This route must be edited in the server config file."
+ );
+ }
+ assert_eq!(std::fs::read_to_string(&config).expect("config"), original);
+ assert_eq!(std::fs::read_dir(dir.path()).expect("files").count(), 2);
+ }
+ }
}
diff --git a/crates/switchyard-desktop/src/harness.rs b/crates/switchyard-desktop/src/harness.rs
new file mode 100644
index 000000000..dc05670fa
--- /dev/null
+++ b/crates/switchyard-desktop/src/harness.rs
@@ -0,0 +1,242 @@
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+//! This module installs and restores user settings for the supported harnesses.
+
+use serde_json::{Value, json};
+use std::path::{Path, PathBuf};
+use toml_edit::DocumentMut;
+
+pub type ReviewedFile = (PathBuf, Option<std::sync::Arc<[u8]>>);
+
+#[derive(
+ Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Deserialize, serde::Serialize,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum Harness {
+ CodexCli,
+ CodexApp,
+ Claude,
+ Pi,
+}
+
+pub const HARNESSES: &[(Harness, &str)] = &[
+ (Harness::CodexCli, "Codex CLI profile"),
+ (Harness::CodexApp, "Codex app and CLI defaults"),
+ (Harness::Claude, "Claude Code"),
+ (Harness::Pi, "Pi"),
+];
+
+/// This function uses the selected harness's environment variable when it is present.
+/// This function resolves the home directory only when that variable is absent.
+pub fn paths(tool: Harness) -> Result<Vec<PathBuf>, String> {
+ let (variable, default, files): (&str, &str, &[&str]) = match tool {
+ Harness::CodexCli => ("CODEX_HOME", "~/.codex", &["sy.config.toml"]),
+ Harness::CodexApp => ("CODEX_HOME", "~/.codex", &["config.toml"]),
+ Harness::Claude => ("CLAUDE_CONFIG_DIR", "~/.claude", &["settings.json"]),
+ Harness::Pi => (
+ "PI_CODING_AGENT_DIR",
+ "~/.pi/agent",
+ &["models.json", "settings.json"],
+ ),
+ };
+ let directory = match std::env::var_os(variable) {
+ Some(path) => PathBuf::from(path),
+ None => crate::config::expand_home(Path::new(default))?,
+ };
+ Ok(files.iter().map(|file| directory.join(file)).collect())
+}
+
+pub fn inspect(tool: Harness, files: &[PathBuf]) -> Result<String, String> {
+ let texts = files
+ .iter()
+ .map(|path| read(path))
+ .collect::<Result<Vec<_>, _>>()?;
+ inspect_settings(tool, files, &texts)
+}
+
+fn inspect_settings(tool: Harness, files: &[PathBuf], texts: &[String]) -> Result<String, String> {
+ let text = &texts[0];
+ let model;
+ let endpoint;
+ let default_endpoint;
+ match tool {
+ Harness::CodexCli | Harness::CodexApp => {
+ let doc = text
+ .parse::<DocumentMut>()
+ .map_err(|e| e.message().to_owned())?;
+ model = doc
+ .get("model")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Default")
+ .to_string();
+ let provider = doc
+ .get("model_provider")
+ .and_then(|v| v.as_str())
+ .unwrap_or("openai");
+ endpoint = doc
+ .get("model_providers")
+ .and_then(|v| v.get(provider))
+ .and_then(|v| v.get("base_url"))
+ .and_then(|v| v.as_str())
+ .map(str::to_owned);
+ default_endpoint = "Provider default";
+ }
+ Harness::Claude => {
+ let doc = object(text)?;
+ model = doc
+ .pointer("/env/ANTHROPIC_MODEL")
+ .and_then(Value::as_str)
+ .or_else(|| doc.get("model").and_then(Value::as_str))
+ .unwrap_or("Default")
+ .to_string();
+ endpoint = doc
+ .pointer("/env/ANTHROPIC_BASE_URL")
+ .and_then(Value::as_str)
+ .map(str::to_owned);
+ default_endpoint = "Anthropic default";
+ }
+ Harness::Pi => {
+ let doc = object(&texts[1])?;
+ model = doc
+ .get("defaultModel")
+ .and_then(Value::as_str)
+ .unwrap_or("Default")
+ .to_string();
+ let provider = doc
+ .get("defaultProvider")
+ .and_then(Value::as_str)
+ .unwrap_or("Default");
+ let models = object(text)?;
+ endpoint = models
+ .get("providers")
+ .and_then(|v| v.get(provider))
+ .and_then(|v| v.get("baseUrl"))
+ .and_then(Value::as_str)
+ .map(str::to_owned);
+ default_endpoint = "Provider default";
+ }
+ }
+ // The display keeps the URL scheme, host, and port to omit credentials and queries.
+ let endpoint = match endpoint {
+ None => default_endpoint.to_owned(),
+ Some(raw) => url::Url::parse(&raw)
+ .ok()
+ .and_then(|u| {
+ let host = u.host_str()?;
+ Some(format!(
+ "{}://{host}{}",
+ u.scheme(),
+ u.port().map(|p| format!(":{p}")).unwrap_or_default()
+ ))
+ })
+ .unwrap_or_else(|| "Not a valid URL".into()),
+ };
+ Ok(format!(
+ "Model: {model}\nEndpoint: {endpoint}\nSettings: {}",
+ files
+ .iter()
+ .map(|file| file.display().to_string())
+ .collect::<Vec<_>>()
+ .join("\n ")
+ ))
+}
+
+fn read_file(path: &Path) -> Result<Option<String>, String> {
+ match std::fs::symlink_metadata(path) {
+ Ok(meta) if meta.file_type().is_symlink() => {
+ return Err(format!(
+ "{} is a symlink. Edit its target yourself.",
+ path.display()
+ ));
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(e) => return Err(e.to_string()),
+ _ => {}
+ }
+ std::fs::read_to_string(path)
+ .map(Some)
+ .map_err(|e| format!("Read {}: {e}", path.display()))
+}
+
+fn read(path: &Path) -> Result<String, String> {
+ Ok(read_file(path)?.unwrap_or_default())
+}
+
+fn object(text: &str) -> Result<Value, String> {
+ let doc: Value = if text.is_empty() {
+ json!({})
+ } else {
+ serde_json::from_str(text).map_err(|e| e.to_string())?
+ };
+ if !doc.is_object() {
+ return Err("Settings must be a JSON object.".into());
+ }
+ Ok(doc)
+}
+
+pub fn binary(tool: Harness) -> Option<PathBuf> {
+ if tool == Harness::CodexApp {
+ #[cfg(windows)]
+ return crate::windows::codex_app();
+ #[cfg(not(windows))]
+ {
+ #[cfg(target_os = "macos")]
+ if let Some(path) = objc2_app_kit::NSWorkspace::sharedWorkspace()
+ .URLForApplicationWithBundleIdentifier(&objc2_foundation::NSString::from_str(
+ "com.openai.codex",
+ ))
+ .and_then(|url| url.path())
+ .map(|path| PathBuf::from(path.to_string()))
+ .filter(|path| path.is_dir())
+ {
+ return Some(path);
+ }
+ return [
+ Some(PathBuf::from("/Applications/Codex.app")),
+ crate::config::expand_home(Path::new("~/Applications/Codex.app")).ok(),
+ ]
+ .into_iter()
+ .flatten()
+ .find(|p| p.exists());
+ }
+ }
+ let name = match tool {
+ Harness::CodexCli => "codex",
+ Harness::Claude => "claude",
+ Harness::Pi => "pi",
+ Harness::CodexApp => return None,
+ };
+ let mut dirs: Vec<_> = std::env::var_os("PATH")
+ .map(|s| std::env::split_paths(&s).collect())
+ .unwrap_or_default();
+ dirs.extend([
+ PathBuf::from("/opt/homebrew/bin"),
+ PathBuf::from("/usr/local/bin"),
+ ]);
+ dirs.extend(
+ [
+ crate::config::expand_home(Path::new("~/.local/bin")).ok(),
+ crate::config::expand_home(Path::new("~/.npm-global/bin")).ok(),
+ ]
+ .into_iter()
+ .flatten(),
+ );
+ #[cfg(windows)]
+ {
+ dirs.extend(
+ [
+ crate::config::expand_home(Path::new("~/AppData/Roaming/npm")).ok(),
+ crate::config::expand_home(Path::new("~/.cargo/bin")).ok(),
+ crate::config::expand_home(Path::new("~/.local/bin")).ok(),
+ ]
+ .into_iter()
+ .flatten(),
+ );
+ dirs.into_iter()
+ .flat_map(|p| [p.join(format!("{name}.exe")), p.join(format!("{name}.cmd"))])
+ .find(|p| p.is_file())
+ }
+ #[cfg(not(windows))]
+ dirs.into_iter().map(|p| p.join(name)).find(|p| p.is_file())
+}
diff --git a/crates/switchyard-desktop/src/main.rs b/crates/switchyard-desktop/src/main.rs
index e0a9adeaa..df0985779 100644
--- a/crates/switchyard-desktop/src/main.rs
+++ b/crates/switchyard-desktop/src/main.rs
@@ -8,9 +8,11 @@
#![cfg_attr(windows, windows_subsystem = "windows")]
use switchyard_desktop::{config, health, history, rollup};
+mod accounts;
mod controller;
#[cfg(any(target_os = "macos", windows))]
mod gui;
+mod harness;
mod models;
mod pricing;
mod server;
diff --git a/crates/switchyard-desktop/src/tui.rs b/crates/switchyard-desktop/src/tui.rs
index 7b7ddb32b..9713d3a9d 100644
--- a/crates/switchyard-desktop/src/tui.rs
+++ b/crates/switchyard-desktop/src/tui.rs
@@ -1,13 +1,15 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
-//! The terminal app shows recorded usage, recent calls, and server status.
+//! The terminal app shows usage, recent calls, routes, and harness settings from controller
+//! snapshots, and it runs server, route, harness, and account actions.
//!
//! One worker thread owns the controller and refreshes its snapshots while the UI thread
//! draws and reads input.
use crate::controller::{
- Action, ActionKind, AppSettings, Availability, Controller, Reply, RouteInfo, Snapshot,
+ AccountInfo, Action, ActionKind, AppSettings, Availability, Controller, Reply, RouteInfo,
+ Snapshot, ToolInfo,
};
use crate::history::Entry;
use crate::pricing::Estimate;
@@ -50,7 +52,7 @@ const SPINNER: [char; 8] = ['⣷', '⣯', '⣟', '⡿', '⢿', '⣻', '⣽', '
type Key = (&'static str, &'static str, &'static str);
const GLOBAL_KEYS: &[Key] = &[
(
- "1-5",
+ "1-6",
"page",
"Switch pages. Tab, Shift-Tab, ← and → also switch pages.",
),
@@ -106,6 +108,27 @@ const ROUTES_KEYS: &[Key] = &[
),
("esc", "clear", "Clear the filter."),
];
+const HARNESSES_KEYS: &[Key] = &[
+ (
+ "↑↓",
+ "route",
+ "Choose the route to install. j, k, PgUp, PgDn, g, and G also move it. The Routes page \
+ selects the same route, and its filter limits the choices.",
+ ),
+ ("t", "harness", "Select the next harness."),
+ (
+ "a",
+ "account",
+ "Select the next saved account, then the harness's own settings again. Install, \
+ restore, and the account keys use the selection.",
+ ),
+ (
+ "x",
+ "custom file",
+ "Install to or restore a custom settings file instead. Leave it empty to use the \
+ detected settings again.",
+ ),
+];
const SETTINGS_KEYS: &[Key] = &[
("↑↓", "select", "Select an action. j, g, and G also move."),
(
@@ -324,6 +347,14 @@ const ROUTE_COLUMNS: [(Column, bool); 3] = [
(("ALGORITHM", Constraint::Length(24), false), false),
(("MODELS", Constraint::Fill(2), false), true),
];
+/// The harnesses table drops the columns marked `true` below 80 columns; the details still
+/// show the current settings.
+const HARNESS_COLUMNS: [(Column, bool); 4] = [
+ (("HARNESS", Constraint::Fill(2), false), false),
+ (("STATE", Constraint::Length(13), false), false),
+ (("CURRENT SETTINGS", Constraint::Fill(3), false), true),
+ (("ACCOUNTS", Constraint::Length(8), true), false),
+];
/// Theme maps each kind of text to one style. NO_COLOR keeps the text modifiers.
#[derive(Clone, Copy)]
@@ -377,13 +408,15 @@ enum Tab {
Calls,
Models,
Routes,
+ Harnesses,
Settings,
}
-const TABS: [Tab; 5] = [
+const TABS: [Tab; 6] = [
Tab::Overview,
Tab::Calls,
Tab::Models,
Tab::Routes,
+ Tab::Harnesses,
Tab::Settings,
];
impl Tab {
@@ -393,6 +426,7 @@ impl Tab {
Tab::Calls => "Calls",
Tab::Models => "Models",
Tab::Routes => "Routes",
+ Tab::Harnesses => "Harnesses",
Tab::Settings => "Settings",
}
}
@@ -479,8 +513,9 @@ enum FormKind {
operation: &'static str,
route: String,
},
- /// The action is the one that the user reviewed. Typing SAVE submits it unchanged.
- Save(Box<Action>),
+ /// The fields hold the word that the user must type and the reviewed action, which the
+ /// form submits unchanged.
+ Confirm(Cow<'static, str>, Box<Action>),
Remove {
generation: u64,
route: String,
@@ -491,17 +526,20 @@ enum FormKind {
/// This map holds each endpoint's base URL when the form opened. The controller refuses
/// the key if the chosen endpoint's URL no longer matches.
ModelKey(BTreeMap<String, String>),
+ SettingsFile,
}
/// Choices names the list that ↑ and ↓ cycle through in a form field.
enum Choices {
Algorithms,
Endpoints,
}
-/// Submit is what a form sends: a controller action, or the next form of a flow that needs
-/// more input before the controller can review it.
+/// Submit is what a form sends: a controller action, the next form of a flow that needs more
+/// input before the controller can review it, or a custom settings file, which changes only
+/// where the Harnesses page installs.
enum Submit {
Run(Action),
Next(Form),
+ SettingsFile(String),
}
/// Form holds the text fields for an action that needs input.
struct Form {
@@ -746,8 +784,8 @@ impl Form {
choices: Vec::new(),
}
}
- FormKind::Save(action) => {
- confirm("SAVE", "Type SAVE to apply the reviewed changes.")?;
+ FormKind::Confirm(word, action) => {
+ confirm(word, &format!("Type {word} to apply the reviewed changes."))?;
(**action).clone()
}
FormKind::Remove {
@@ -779,6 +817,13 @@ impl Form {
key: Some(self.value(1)),
base_url: urls.get(&self.value(0)).cloned(),
},
+ FormKind::SettingsFile => {
+ let path = self.value(0);
+ if !path.is_empty() && !std::path::Path::new(&path).is_absolute() {
+ return Err("Enter an absolute file path, or leave the field empty.".into());
+ }
+ return Ok(Submit::SettingsFile(path));
+ }
}))
}
fn label(&self) -> &'static str {
@@ -793,10 +838,12 @@ impl Form {
FormKind::NewRoute { .. }
| FormKind::NewRouteModels { .. }
| FormKind::RouteIdentity { .. } => "Reviewing the route change",
- FormKind::Save(_) => "Saving the route",
+ FormKind::Confirm(_, _action) => "Saving the route",
FormKind::Remove { .. } => "Deleting the route",
FormKind::Models => "Loading models",
FormKind::ModelKey(_) => "Saving the key and loading models",
+
+ FormKind::SettingsFile => "Choosing the settings file",
}
}
}
@@ -866,8 +913,10 @@ fn route_models_form(
}
/// This function returns the action that a preview's review window submits after the user
-/// types SAVE: the previewed inputs, plus the token for a route change.
+/// types the confirmation word: the previewed inputs, plus the preview's token for every flow
+/// except a route edit, which sends its revision instead.
fn reviewed(previewed: Action, preview: &Value) -> Option<Action> {
+ let preview_token = preview["preview_token"].as_str().map(str::to_owned);
Some(match previewed {
Action::PreviewRoute {
generation,
@@ -898,8 +947,9 @@ fn reviewed(previewed: Action, preview: &Value) -> Option<Action> {
id,
algorithm,
choices,
- preview_token: preview["preview_token"].as_str().map(str::to_owned),
+ preview_token,
},
+
_ => return None,
})
}
@@ -980,6 +1030,9 @@ struct Request {
job: Job,
label: &'static str,
automatic: bool,
+ /// This field holds the `ACTIONS` key that started the job. Keys that share a first action
+ /// continue differently when the reply arrives, such as `p` and `i` on the Harnesses page.
+ key: Option<char>,
}
impl Request {
fn run(action: Action, label: &'static str) -> Self {
@@ -987,6 +1040,7 @@ impl Request {
job: Job::Run(action),
label,
automatic: false,
+ key: None,
}
}
fn refresh(automatic: bool) -> Self {
@@ -994,6 +1048,7 @@ impl Request {
job: Job::Refresh,
label: "Refreshing",
automatic,
+ key: None,
}
}
}
@@ -1004,6 +1059,7 @@ struct Busy {
action: Option<Action>,
/// This field records the popup generation when the action starts.
popup_generation: u64,
+ key: Option<char>,
started: Instant,
/// Automatic refreshes report errors in the status bar, and automatic key checks update
/// Settings without opening a popup.
@@ -1034,6 +1090,18 @@ impl Tone {
}
}
+/// Destination is where the Harnesses page installs and restores settings.
+enum Destination {
+ /// The harness's own settings files.
+ Harness,
+ /// A saved account, by name. The name stays after a refresh stops listing the account, so
+ /// its actions still send it and the controller rejects them instead of changing other
+ /// settings.
+ Account(String),
+ /// A custom settings file path.
+ File(String),
+}
+
struct App {
theme: Theme,
data: Snapshot,
@@ -1052,6 +1120,9 @@ struct App {
route_visible: Vec<usize>,
route_selected: usize,
route_offset: usize,
+ /// This field indexes `data.tools`, which lists every harness in a fixed order.
+ harness: usize,
+ destination: Destination,
/// This field holds the last `ServerKeys` reply. It is `None` until the user checks the keys,
/// and a failed check clears it so the page never shows outdated key states.
server_keys: Option<Value>,
@@ -1085,6 +1156,9 @@ impl App {
route_visible: Vec::new(),
route_selected: 0,
route_offset: 0,
+ harness: 0,
+ destination: Destination::Harness,
+
server_keys: None,
popup: None,
popup_generation: 0,
@@ -1167,6 +1241,20 @@ impl App {
}
}
+ fn harness(&self) -> Result<&ToolInfo, String> {
+ self.data
+ .tools
+ .get(self.harness)
+ .ok_or_else(|| "No harness is listed. Fix the app settings, then press r.".into())
+ }
+
+ fn custom_file(&self) -> Option<String> {
+ match &self.destination {
+ Destination::File(path) => Some(path.clone()),
+ Destination::Harness | Destination::Account(_) => None,
+ }
+ }
+
// Every replacement or dismissal changes the generation, even when the same form reopens.
fn set_popup(&mut self, popup: Option<Popup>) {
self.popup_generation += 1;
@@ -1264,7 +1352,9 @@ impl App {
}
}
}
- let action = busy.and_then(|busy| busy.action);
+ let (action, _key) = busy
+ .map(|busy| (busy.action, busy.key))
+ .unwrap_or((None, None));
let reply = reply?;
match (kind, reply) {
(Some(ActionKind::ServerKeys), Err(error)) => {
@@ -1298,8 +1388,6 @@ impl App {
"Type UPDATE to start",
)));
}
- // The reply lists the roles of the chosen algorithm. The models form replaces the
- // algorithm form only while that form is still open for the same route.
(Some(ActionKind::Editor), Ok(reply)) if popup_matches => {
if let Some(Action::Editor {
route: key,
@@ -1336,7 +1424,7 @@ impl App {
self.set_popup(Some(Popup::review(
change_lines(self.theme, &reply.data),
"Save",
- FormKind::Save(Box::new(reviewed)),
+ FormKind::Confirm("SAVE".into(), Box::new(reviewed)),
"Review route changes",
"Type SAVE to apply",
)));
@@ -1484,6 +1572,7 @@ impl App {
self.busy = Some(Busy {
label: request.label,
action,
+ key: request.key,
started: Instant::now(),
automatic: request.automatic,
popup_generation: self.popup_generation,
@@ -1503,6 +1592,7 @@ impl App {
(None, false, Tab::Calls) => CALLS_KEYS,
(None, false, Tab::Models) => MODELS_KEYS,
(None, false, Tab::Routes) => ROUTES_KEYS,
+ (None, false, Tab::Harnesses) => HARNESSES_KEYS,
(None, false, Tab::Settings) => SETTINGS_KEYS,
}
}
@@ -1552,7 +1642,7 @@ impl App {
match key.code {
KeyCode::Char('q') => self.quit = true,
KeyCode::Char('?') => self.set_popup(Some(Popup::Help { scroll: 0 })),
- KeyCode::Char(digit @ '1'..='5') => {
+ KeyCode::Char(digit @ '1'..='6') => {
self.tab = TABS[digit as usize - '1' as usize];
}
KeyCode::Tab | KeyCode::Right => self.tab = TABS[(self.tab.index() + 1) % TABS.len()],
@@ -1572,7 +1662,7 @@ impl App {
self.route_filter.clear();
self.refilter();
}
- Tab::Overview | Tab::Models | Tab::Settings => {}
+ Tab::Overview | Tab::Models | Tab::Harnesses | Tab::Settings => {}
}
}
code => {
@@ -1596,6 +1686,7 @@ impl App {
_ => {}
},
Tab::Routes => self.routes_key(code),
+ Tab::Harnesses => self.harnesses_key(code),
Tab::Settings => return self.settings_key(code),
}
}
@@ -1644,6 +1735,44 @@ impl App {
}
}
+ /// The arrows choose the route, which is the longer list; `t` cycles through the few
+ /// harnesses. A new harness starts at its own settings, because accounts belong to one
+ /// harness.
+ fn harnesses_key(&mut self, code: KeyCode) {
+ let last = self.route_visible.len().saturating_sub(1);
+ if let Some(selected) = step(code, self.route_selected, last) {
+ self.route_selected = selected;
+ return;
+ }
+ match code {
+ KeyCode::Char('t') => {
+ self.harness = (self.harness + 1) % self.data.tools.len().max(1);
+ self.destination = Destination::Harness;
+ }
+ // The cycle runs through the harness's own settings and then each saved account.
+ KeyCode::Char('a') => {
+ let names = self.harness().map_or(&[][..], |tool| &tool.accounts);
+ let current = match &self.destination {
+ Destination::Account(name) => names.iter().position(|known| known == name),
+ Destination::Harness | Destination::File(_) => None,
+ };
+ let next = names.get(current.map_or(0, |index| index + 1)).cloned();
+ self.destination = next.map_or(Destination::Harness, Destination::Account);
+ }
+ KeyCode::Char('x') => {
+ self.set_popup(Some(Popup::Form(Form::new(
+ FormKind::SettingsFile,
+ "Custom settings file · leave empty to use the detected settings",
+ vec![(
+ "Absolute file path (Pi: models.json)",
+ self.custom_file().unwrap_or_default(),
+ )],
+ ))));
+ }
+ _ => {}
+ }
+ }
+
fn filter_key(&mut self, key: KeyEvent) {
let control = key.modifiers.contains(KeyModifiers::CONTROL);
match key.code {
@@ -1682,11 +1811,19 @@ impl App {
None
}
+ /// This function runs a row's flow and records its key on the request, so the reply can
+ /// continue that key's flow.
fn run_row(&mut self, kind: ActionKind, key: char) -> Option<Request> {
- self.start_action(kind, key).unwrap_or_else(|error| {
- self.notify(error, Tone::Error);
- None
- })
+ match self.start_action(kind, key) {
+ Ok(request) => request.map(|request| Request {
+ key: Some(key),
+ ..request
+ }),
+ Err(error) => {
+ self.notify(error, Tone::Error);
+ None
+ }
+ }
}
fn open(&mut self, form: Form) -> Result<Option<Request>, String> {
@@ -1805,6 +1942,7 @@ impl App {
};
self.open(form)
}
+
ActionKind::OpenConfig => request(Action::OpenConfig {}, "Opening the server config"),
ActionKind::CheckConfig => {
request(Action::CheckConfig {}, "Checking the server config")
@@ -1882,6 +2020,16 @@ impl App {
KeyCode::Enter => match form.action(&self.data) {
Ok(Submit::Run(action)) => return Some(Request::run(action, form.label())),
Ok(Submit::Next(next)) => self.set_popup(Some(Popup::Form(next))),
+ Ok(Submit::SettingsFile(path)) => {
+ self.set_popup(None);
+ self.destination = if path.is_empty() {
+ Destination::Harness
+ } else {
+ Destination::File(path)
+ };
+ let text = "Press p to preview or i to install.";
+ self.notify(text.into(), Tone::Done);
+ }
Err(error) => form.error = error,
},
// A field with choices cycles through them. Otherwise only the review
@@ -2119,6 +2267,7 @@ fn block(theme: Theme, title: &str) -> Block<'static> {
fn draw(frame: &mut Frame, app: &mut App) {
// This exhaustive destructuring requires an update when Snapshot gains a field.
let Snapshot {
+ tools: _, // draw_harnesses and harness_lines show these tools.
generation: _, // Each route form returns this value with its action.
clients: _, // draw_endpoints and the endpoint forms show these clients.
algorithms: _, // draw_routes and the algorithm fields show these algorithms.
@@ -2157,6 +2306,7 @@ fn draw(frame: &mut Frame, app: &mut App) {
Tab::Calls => draw_calls(frame, app, body),
Tab::Models => draw_models(frame, app, body),
Tab::Routes => draw_routes(frame, app, body),
+ Tab::Harnesses => draw_harnesses(frame, app, body),
Tab::Settings => draw_settings(frame, app, body),
}
draw_status(frame, app, status);
@@ -2190,14 +2340,27 @@ fn draw_too_small(frame: &mut Frame, theme: Theme, area: Rect) {
fn draw_header(frame: &mut Frame, app: &App, area: Rect) {
let theme = app.theme;
- let titles = TABS.map(|tab| {
- Line::from(vec![
- Span::styled(format!("{} ", tab.index() + 1), theme.key),
- Span::raw(tab.name()),
- ])
- });
+ // Each title is the tab's digit and at most `letters` letters of its name.
+ let titles = |letters: usize| {
+ TABS.map(|tab| {
+ let name = tab.name().get(..letters).unwrap_or(tab.name());
+ Line::from(vec![
+ Span::styled((tab.index() + 1).to_string(), theme.key),
+ Span::raw(if name.is_empty() { "" } else { " " }),
+ Span::raw(name),
+ ])
+ })
+ };
// Tabs pads each title by one space on both sides and puts a divider between titles.
- let tabs_width: usize = titles.iter().map(|title| title.width() + 3).sum();
+ let width = |titles: &[Line]| titles.iter().map(|title| title.width() + 3).sum::<usize>();
+ // Narrow terminals shorten the names to three letters, then show the digits alone, so no
+ // tab is cut off.
+ let titles = [usize::MAX, 3]
+ .into_iter()
+ .map(titles)
+ .find(|titles| width(titles) <= usize::from(area.width))
+ .unwrap_or_else(|| titles(0));
+ let tabs_width = width(&titles);
let running = app.data.metrics.running;
let mut status = server_state(theme, running).to_vec();
let updated = match app.refreshed {
@@ -3037,41 +3200,43 @@ fn draw_route_table(frame: &mut Frame, app: &mut App, area: Rect) {
/// short terminal still shows them, then the notes that limit editing it here.
fn route_lines(theme: Theme, data: &Snapshot, route: &RouteInfo) -> Vec<Line<'static>> {
const WIDTH: usize = 11;
+ // This destructuring has no `..`, so adding a route field breaks the build until the
+ // terminal app shows it. Each comment names the place that shows the field.
+ let RouteInfo {
+ key,
+ id: _, // draw_routes titles these details with it
+ kind,
+ revision: _, // the edit and delete flows send it back
+ label: _, // harness_lines names the route with it, and the filter reads it
+ choices: _, // the edit flow starts from these choices
+ models,
+ judges,
+ tiers: _, // route_models_form keeps each role's model by tier
+ editable,
+ generated,
+ } = route;
let field = |name: &str, value: String| labeled(theme, name, WIDTH, value);
- let algorithm = data
- .algorithms
- .iter()
- .find(|known| known.kind == route.kind);
+ let algorithm = data.algorithms.iter().find(|known| known.kind == *kind);
let mut lines = vec![
- field("Config", format!("[routes.{}]", route.key)),
+ field("Config", format!("[routes.{key}]")),
field(
"Algorithm",
algorithm.map_or_else(
- || route.kind.clone(),
+ || kind.clone(),
|known| format!("{} ({})", known.title, known.kind),
),
),
];
- lines.extend(
- route
- .models
- .iter()
- .map(|model| field("Model", model.clone())),
- );
- lines.extend(
- route
- .judges
- .iter()
- .map(|judge| field("Judge", judge.clone())),
- );
- if !route.editable {
+ lines.extend(models.iter().map(|model| field("Model", model.clone())));
+ lines.extend(judges.iter().map(|judge| field("Judge", judge.clone())));
+ if !editable {
lines.push(Line::default());
lines.push(Line::styled(
"This routing method has no editor here. Edit its fields in the server config.",
theme.warn,
));
}
- if let Some(generated) = &route.generated {
+ if let Some(generated) = generated {
lines.push(Line::default());
lines.push(Line::styled(
format!("Generated by {generated}. That tool can replace edits made here."),
@@ -3142,6 +3307,198 @@ fn draw_endpoints(frame: &mut Frame, app: &App, notes: Vec<Line<'static>>, area:
frame.render_widget(Paragraph::new(notes).wrap(Wrap { trim: false }), notes_area);
}
+fn draw_harnesses(frame: &mut Frame, app: &App, area: Rect) {
+ let theme = app.theme;
+ // The borders and the header row take three rows.
+ let rows = app.data.tools.len().max(1) as u16 + 3;
+ let [list, rest] = Layout::vertical([
+ Constraint::Length(rows.min(area.height / 2)),
+ Constraint::Fill(1),
+ ])
+ .areas(area);
+ draw_harness_table(frame, app, list);
+ let Ok(harness) = app.harness() else {
+ return;
+ };
+ let detail = Paragraph::new(harness_lines(app, harness))
+ .wrap(Wrap { trim: false })
+ .block(block(theme, harness.label).padding(Padding::horizontal(1)));
+ frame.render_widget(detail, rest);
+}
+
+fn draw_harness_table(frame: &mut Frame, app: &App, area: Rect) {
+ let theme = app.theme;
+ let tools = &app.data.tools;
+ let outer = block(theme, &format!("Harnesses [{}]", tools.len()));
+ if tools.is_empty() {
+ let text = "No harness is listed. Fix the app settings, then press r.";
+ frame.render_widget(
+ Paragraph::new(Line::styled(text, theme.muted))
+ .centered()
+ .block(outer),
+ area,
+ );
+ return;
+ }
+ let wide = area.width >= 80;
+ let shown = |column: &(Column, bool)| wide || !column.1;
+ let rows: Vec<Row> = tools
+ .iter()
+ .map(|tool| {
+ let state = if tool.available {
+ Span::styled("Detected", theme.ok)
+ } else {
+ Span::styled("Not detected", theme.warn)
+ };
+ // The first two lines name the model and the endpoint, or hold the read error.
+ let settings: Vec<&str> = tool.status.lines().take(2).collect();
+ let cells = [
+ Cell::from(tool.label),
+ Cell::from(state),
+ Cell::from(settings.join(" · ")),
+ right(count(tool.accounts.len() as u64)),
+ ];
+ Row::new(
+ cells
+ .into_iter()
+ .zip(&HARNESS_COLUMNS)
+ .filter(|(_, column)| shown(column))
+ .map(|(cell, _)| cell),
+ )
+ })
+ .collect();
+ let columns: Vec<Column> = HARNESS_COLUMNS
+ .iter()
+ .filter(|column| shown(column))
+ .map(|column| column.0)
+ .collect();
+ let mut state = TableState::default().with_selected(Some(app.harness));
+ frame.render_stateful_widget(
+ table(theme, &columns, rows)
+ .row_highlight_style(theme.selected)
+ .highlight_symbol("› ")
+ .block(outer),
+ area,
+ &mut state,
+ );
+}
+
+/// This function shows the route to install and whether the harness can use it, then where
+/// the settings go and what they hold now, then the saved accounts.
+fn harness_lines(app: &App, harness: &ToolInfo) -> Vec<Line<'static>> {
+ const WIDTH: usize = 12;
+ let theme = app.theme;
+ let field = |name: &str, value: String| labeled(theme, name, WIDTH, value);
+ let heading = |text: &'static str| Line::styled(text, theme.muted.bold());
+ // This destructuring has no `..`, so adding a harness field breaks the build until this
+ // page shows it.
+ let ToolInfo {
+ tool: _,
+ label: _, // draw_harnesses titles these details with it
+ available,
+ files,
+ status,
+ accounts: _, // the a key cycles through them, and account_details has the same names
+ account_details,
+ discovery_error,
+ } = harness;
+ let mut lines = Vec::new();
+ match app.selected_route() {
+ Ok(route) => {
+ lines.push(field("Route", route.label.clone()));
+ }
+ Err(error) => lines.push(Line::from(vec![
+ Span::styled(format!("{:<WIDTH$}", "Route"), theme.muted),
+ Span::styled(error, theme.warn),
+ ])),
+ }
+ if !available {
+ lines.push(Line::styled(
+ "Not detected. You can prepare settings and install the harness later.",
+ theme.warn,
+ ));
+ }
+ // The current settings summary of the destination, or why there is none, and its style.
+ let (current, style) = match &app.destination {
+ Destination::Harness => {
+ let files: Vec<String> = files.iter().map(|f| f.display().to_string()).collect();
+ lines.push(field("Install to", "The harness's own settings".into()));
+ lines.push(field("Files", files.join(", ")));
+ (status.clone(), Style::new())
+ }
+ Destination::Account(name) => {
+ match account_details.iter().find(|account| account.name == *name) {
+ Some(account) => {
+ lines.push(field("Install to", format!("Account {name}")));
+ lines.push(field("Folder", account.path.display().to_string()));
+ (account.status.clone(), Style::new())
+ }
+ None => (
+ format!(
+ "Account {name} is no longer listed. Press a to choose another \
+ destination."
+ ),
+ theme.warn,
+ ),
+ }
+ }
+ Destination::File(path) => {
+ lines.push(field("Install to", "Custom file".into()));
+ lines.push(field("File", path.clone()));
+ ("Press p to read it.".into(), theme.muted)
+ }
+ };
+ lines.extend([Line::default(), heading("CURRENT SETTINGS")]);
+ // A summary spans several lines, and Paragraph does not start a new line at '\n'.
+ lines.extend(
+ current
+ .lines()
+ .map(|line| Line::styled(line.to_string(), style)),
+ );
+ lines.extend([
+ Line::default(),
+ heading("SAVED ACCOUNTS · a folder does not confirm a completed login"),
+ ]);
+ if let Some(error) = discovery_error {
+ lines.push(Line::styled(error.clone(), theme.error));
+ }
+ for account in account_details {
+ // This destructuring has no `..`, so adding an account field breaks the build until
+ // this page shows it.
+ let AccountInfo {
+ name,
+ path,
+ login_status,
+ status: _, // CURRENT SETTINGS shows it for the selected account
+ } = account;
+ let selected = matches!(&app.destination, Destination::Account(chosen) if chosen == name);
+ lines.push(Line::from(vec![
+ Span::styled(if selected { "› " } else { " " }, theme.key),
+ Span::raw(name.clone()),
+ Span::styled(
+ format!(" · login status {login_status} · {}", path.display()),
+ theme.muted,
+ ),
+ ]));
+ }
+ if account_details.is_empty() {
+ lines.push(Line::styled(
+ "None. Press n to sign in to another account.",
+ theme.muted,
+ ));
+ }
+ lines.extend([
+ Line::default(),
+ Line::styled(
+ "Login opens in a new terminal window, and account folders open in $VISUAL or \
+ $EDITOR. Native account limits still apply. Switchyard does not rotate login \
+ tokens.",
+ theme.muted,
+ ),
+ ]);
+ lines
+}
+
/// This function lists the server key variables from the last `ServerKeys` reply.
fn key_lines(theme: Theme, keys: Option<&Value>) -> Vec<Line<'static>> {
let Some(data) = keys else {
@@ -3607,9 +3964,16 @@ fn form_notes(app: &App, form: &Form) -> Vec<Line<'static>> {
lines.push(Line::default());
lines
}
+ FormKind::SettingsFile => vec![
+ Line::from(
+ "The harness must load a custom file itself. Pi reads settings.json from the \
+ folder of models.json.",
+ ),
+ Line::default(),
+ ],
FormKind::Preferences
| FormKind::Update(_)
- | FormKind::Save(_)
+ | FormKind::Confirm(..)
| FormKind::Remove { .. } => Vec::new(),
}
}
@@ -3715,6 +4079,7 @@ fn help_lines(theme: Theme, width: usize) -> Vec<Line<'static>> {
("While filtering calls or routes", FILTER_KEYS, None),
("Models", MODELS_KEYS, Some(Tab::Models)),
("Routes", ROUTES_KEYS, Some(Tab::Routes)),
+ ("Harnesses", HARNESSES_KEYS, Some(Tab::Harnesses)),
("Settings", SETTINGS_KEYS, Some(Tab::Settings)),
] {
if !lines.is_empty() {
@@ -3922,19 +4287,37 @@ pub fn run(mut controller: Controller) -> Result<(), String> {
#[cfg(test)]
mod tests {
- use super::{
- ACTIONS, Action, ActionKind, App, Availability, BTreeMap, Done, Estimate, KeyCode,
- KeyEvent, KeyModifiers, ModelTokens, Popup, Request, Snapshot, TABS, Tab, Theme, Tone,
- Totals, Usage, draw, mpsc,
- };
+ use super::*;
+ use crate::config::Config;
use crate::history::Entry;
use ratatui::{Terminal, backend::TestBackend};
use serde_json::json;
use strum::IntoEnumIterator;
+ fn press(app: &mut App, code: KeyCode) -> Option<Request> {
+ app.key(KeyEvent::from(code))
+ }
+
+ /// This function runs one request the way the worker thread does.
+ fn work(app: &mut App, controller: &mut Controller, request: Option<Request>) {
+ let (jobs, inbox) = mpsc::channel();
+ app.start(&jobs, request.expect("a request"))
+ .expect("start");
+ let Ok(Job::Run(action)) = inbox.try_recv() else {
+ panic!("the request runs no action");
+ };
+ let reply = controller.dispatch(action);
+ let next = app.finish(Some(reply), controller.snapshot().map(Box::new));
+ assert!(next.is_none());
+ }
+
fn screen(app: &mut App, tab: Tab) -> String {
+ screen_sized(app, tab, 140, 40)
+ }
+
+ fn screen_sized(app: &mut App, tab: Tab, width: u16, height: u16) -> String {
app.tab = tab;
- let mut terminal = Terminal::new(TestBackend::new(140, 40)).expect("terminal");
+ let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("terminal");
terminal.draw(|frame| draw(frame, app)).expect("draw");
let buffer = terminal.backend().buffer();
buffer
@@ -4586,6 +4969,7 @@ mod tests {
Tab::Calls => &['/', 's'],
Tab::Models => &['p', '[', ']'],
Tab::Routes => &['/'],
+ Tab::Harnesses => &['t', 'a', 'x'],
Tab::Overview | Tab::Settings => &[],
}
};
@@ -4606,4 +4990,55 @@ mod tests {
.collect();
assert!(missing.is_empty(), "No key runs {missing:?}");
}
+
+ #[test]
+ // The models form must keep the revision from when the editor opened, so a server config
+ // that changed since then fails the review and keeps the draft instead of saving old
+ // choices into the new file.
+ fn externally_changed_routes_cannot_bless_snapshot_choices() {
+ let dir = tempfile::tempdir().expect("fixture");
+ let settings = dir.path().join("desktop.toml");
+ let routes = dir.path().join("server.toml");
+ let original = "schema_version = 1\n\
+ [llm_clients.c]\n\
+ base_url='http://localhost:1'\n\
+ format='openai_responses'\n\
+ [targets.m]\n\
+ id='original'\n\
+ llm_client='c'\n\
+ [routes.r]\n\
+ id='public'\n\
+ type='passthrough'\n\
+ target='m'\n";
+ std::fs::write(&routes, original).expect("routes");
+ std::fs::write(
+ &settings,
+ format!(
+ "config_file={routes:?}\nrouting_log={:?}\nserver_url='http://127.0.0.1:0'",
+ dir.path().join("log")
+ ),
+ )
+ .expect("settings");
+ let mut controller = Controller::new(Config::load(&settings).expect("config"), settings);
+ let mut app = App::new(Theme::new(false));
+ app.finish(None, Ok(Box::new(controller.snapshot().expect("snapshot"))));
+ app.tab = Tab::Routes;
+ assert!(press(&mut app, KeyCode::Char('e')).is_none());
+ let external = original.replace("id='original'", "id='external'");
+ std::fs::write(&routes, &external).expect("external edit");
+ let editor = press(&mut app, KeyCode::Enter);
+ work(&mut app, &mut controller, editor);
+ let preview = press(&mut app, KeyCode::Enter);
+ work(&mut app, &mut controller, preview);
+ let Some(Popup::Form(draft)) = &app.popup else {
+ panic!("the draft closed");
+ };
+ assert!(matches!(draft.kind, FormKind::RouteModels { .. }));
+ assert!(draft.error.contains("Review"), "{}", draft.error);
+ assert_eq!(
+ std::fs::read_to_string(&routes).expect("preserved"),
+ external
+ );
+ assert_eq!(std::fs::read_dir(dir.path()).expect("files").count(), 2);
+ }
}
diff --git a/crates/switchyard-desktop/src/windows.rs b/crates/switchyard-desktop/src/windows.rs
index f939f3a16..d36a5e7f7 100644
--- a/crates/switchyard-desktop/src/windows.rs
+++ b/crates/switchyard-desktop/src/windows.rs
@@ -1,6 +1,27 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
+use std::path::PathBuf;
+
+/// This function reads current-user MSIX registrations without launching or changing the Codex app.
+pub fn codex_app() -> Option<PathBuf> {
+ use windows::{Management::Deployment::PackageManager, core::HSTRING};
+ // An empty SID restricts discovery to packages registered for the current user.
+ let packages = PackageManager::new()
+ .ok()?
+ .FindPackagesByUserSecurityId(&HSTRING::new())
+ .ok()?;
+ for package in packages {
+ let Some(name) = package.Id().ok().and_then(|id| id.Name().ok()) else {
+ continue;
+ };
+ if name == "OpenAI.Codex" {
+ return Some(PathBuf::from(package.InstalledPath().ok()?.to_os_string()));
+ }
+ }
+ None
+}
+
pub fn attach_console() {
unsafe {
windows_console(false);