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): preview harness settings for Codex, Claude Code, and Pi (#1104)

Elyas Mehtabuddina64bacc9501d
diff --git a/crates/switchyard-desktop/src/accounts.rs b/crates/switchyard-desktop/src/accounts.rs
index e5e14c950..0b34bb7f9 100644
--- a/crates/switchyard-desktop/src/accounts.rs
+++ b/crates/switchyard-desktop/src/accounts.rs
@@ -26,6 +26,19 @@ fn root(tool: Harness) -> Result<PathBuf, String> {
Ok(path)
}
+pub fn validate(tool: Harness, path: &Path) -> Result<(), String> {
+ let root = root(tool)?;
+ if path.parent() != Some(root.as_path())
+ || !std::fs::symlink_metadata(path).is_ok_and(|m| m.is_dir() && !m.file_type().is_symlink())
+ {
+ return Err(format!(
+ "{} is not a saved account folder. Choose an account folder that exists and is not a symlink.",
+ path.display()
+ ));
+ }
+ Ok(())
+}
+
pub fn discover(tool: Harness) -> Result<Vec<(String, PathBuf)>, String> {
if !matches!(tool, Harness::CodexCli | Harness::Claude) {
return Ok(Vec::new());
@@ -61,6 +74,10 @@ pub fn discover(tool: Harness) -> Result<Vec<(String, PathBuf)>, String> {
Ok(accounts)
}
+pub fn list(tool: Harness) -> Vec<(String, PathBuf)> {
+ discover(tool).unwrap_or_default()
+}
+
pub fn config_paths(tool: Harness, account: Option<&Path>) -> Result<Vec<PathBuf>, String> {
let Some(account) = account else {
return harness::paths(tool);
diff --git a/crates/switchyard-desktop/src/controller.rs b/crates/switchyard-desktop/src/controller.rs
index 6d5523c9b..70228b75c 100644
--- a/crates/switchyard-desktop/src/controller.rs
+++ b/crates/switchyard-desktop/src/controller.rs
@@ -71,6 +71,13 @@ pub enum Action {
/// controller refuses `key` unless the endpoint still has this URL.
base_url: Option<String>,
},
+ PreviewInstall {
+ tool: Harness,
+ account: Option<String>,
+ route: String,
+ id: String,
+ settings_file: Option<String>,
+ },
Restart {},
PreviewUpdate {},
Update {
@@ -168,6 +175,9 @@ pub struct RouteInfo {
/// This field holds the marker of the generated block that contains the route. The tool
/// that wrote the block replaces the route the next time it runs.
pub generated: Option<String>,
+ /// This field maps each harness to the reason it cannot use the route, or to `None`
+ /// when it can.
+ pub compatibility: BTreeMap<Harness, Option<String>>,
}
/// ToolInfo describes one harness whose settings the apps can change.
@@ -360,6 +370,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>,
+ tool_review: Option<Review>,
route_change: Option<Review>,
update_review: Option<(String, Value)>,
@@ -373,6 +384,7 @@ impl Controller {
reader: rollup::Reader::default(),
generation: 0,
route_reviews: Default::default(),
+ tool_review: None,
route_change: None,
update_review: None,
@@ -383,7 +395,7 @@ impl Controller {
if config.config_file != self.config.config_file {
self.generation += 1;
self.route_reviews.clear();
-
+ self.tool_review = None;
self.route_change = None;
}
self.config = config;
@@ -505,6 +517,10 @@ impl Controller {
.map(|r| r.tier.map(|t| format!("{t:?}")))
.collect()
}),
+ compatibility: harness::HARNESSES
+ .iter()
+ .map(|&(tool, _)| (tool, login_mode(tool, &config, &route.name).err()))
+ .collect(),
editable: algorithm.is_some(),
generated: config
.generated_by("routes", &route.name)
@@ -928,6 +944,36 @@ impl Controller {
data: json!({"notes":edited.notes,"revision":revision,"file":self.config.config_file}),
})
}
+ Action::PreviewInstall {
+ tool,
+ account,
+ route,
+ id,
+ settings_file,
+ } => {
+ let files = install_paths(tool, account.as_deref(), settings_file.as_deref())?;
+ let inputs = json!({"tool":tool,"account":account,"route":route,"id":id,"settings_file":settings_file,"server_url":self.config.server_url});
+ let mut paths = harness::review_files(&files);
+ paths.push(self.config.config_file.clone());
+ let review = Review::capture(inputs, paths)?;
+ let config = self.routes()?;
+ let selected = current_route(&config, &route, Some(&id))?;
+ let mut data = harness::preview(
+ tool,
+ &files,
+ &self.config.server_url,
+ &selected.id,
+ config.context_window(&selected.key),
+ login_mode(tool, &config, &selected.key)?,
+ )?;
+ review.check(Some(&review.token), &review.inputs)?;
+ data["preview_token"] = json!(review.token);
+ self.tool_review = Some(review);
+ Ok(Reply {
+ message: String::new(),
+ data,
+ })
+ }
Action::Restart {} => server::restart_checked(&self.config).map(Reply::message),
Action::CheckConfig {} => server::check_config(&self.config)
.map(|()| Reply::message("Server config check passed.".into())),
@@ -1064,6 +1110,85 @@ 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())
}
+// A custom file selects one settings location; saved accounts select their own folders.
+fn install_paths(
+ tool: Harness,
+ account: Option<&str>,
+ file: Option<&str>,
+) -> Result<Vec<PathBuf>, String> {
+ if let Some(file) = file {
+ if account.is_some() {
+ return Err("Choose a saved account or a custom settings file, not both.".into());
+ }
+ let path = PathBuf::from(file);
+ if !path.is_absolute() || file.trim().is_empty() || file.contains(['\n', '\r']) {
+ return Err("Enter an absolute settings file path without line breaks.".into());
+ }
+ if path.is_dir() {
+ return Err("Choose a settings file, not a folder.".into());
+ }
+ if tool == Harness::Pi {
+ if path.file_name().is_none_or(|name| name != "models.json") {
+ return Err("Choose Pi’s models.json; settings.json is read beside it.".into());
+ }
+ return Ok(vec![path.clone(), path.with_file_name("settings.json")]);
+ }
+ return Ok(vec![path]);
+ }
+ let account = account_path(tool, account)?;
+ accounts::config_paths(tool, account.as_deref())
+}
+
+fn account_path(tool: Harness, name: Option<&str>) -> Result<Option<PathBuf>, String> {
+ let Some(name) = name else {
+ return Ok(None);
+ };
+ let path = accounts::list(tool)
+ .into_iter()
+ .find(|(n, _)| n == name)
+ .map(|(_, p)| p)
+ .ok_or("Unknown account. Refresh and choose an existing account.")?;
+ accounts::validate(tool, &path)?;
+ Ok(Some(path))
+}
+fn login_mode(tool: Harness, config: &ServerConfig, route: &str) -> Result<bool, String> {
+ let clients = config.clients();
+ let choices = config.choices(route);
+ if choices.is_empty() {
+ return Err(
+ "This route cannot be installed by the app. Choose a route with models.".into(),
+ );
+ }
+ let mut login = false;
+ for choice in choices {
+ let client = clients
+ .iter()
+ .find(|c| c.name == choice.client)
+ .ok_or("The route has an unknown endpoint.")?;
+ if client.forward_auth {
+ let url = url::Url::parse(&client.base_url)
+ .map_err(|_| "The route has an invalid endpoint URL.")?;
+ let host = url
+ .host_str()
+ .ok_or("The route has an invalid endpoint URL.")?;
+ let supported = url.scheme() == "https"
+ && url.port().is_none_or(|port| port == 443)
+ && match tool {
+ Harness::CodexCli | Harness::CodexApp => host == "chatgpt.com",
+ Harness::Claude => host == "api.anthropic.com",
+ Harness::Pi => false,
+ };
+ if !supported {
+ return Err(format!(
+ "This route forwards the caller's login to {host}. \
+ Pick a matching harness or a route with server API credentials."
+ ));
+ }
+ login = true;
+ }
+ }
+ Ok(login)
+}
fn install_metadata(settings: &std::path::Path) -> Result<PathBuf, String> {
let executable = std::env::current_exe().map_err(|e| e.to_string())?;
diff --git a/crates/switchyard-desktop/src/harness.rs b/crates/switchyard-desktop/src/harness.rs
index dc05670fa..aca2579c2 100644
--- a/crates/switchyard-desktop/src/harness.rs
+++ b/crates/switchyard-desktop/src/harness.rs
@@ -5,7 +5,7 @@
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
-use toml_edit::DocumentMut;
+use toml_edit::{DocumentMut, value};
pub type ReviewedFile = (PathBuf, Option<std::sync::Arc<[u8]>>);
@@ -175,6 +175,393 @@ fn object(text: &str) -> Result<Value, String> {
Ok(doc)
}
+fn map<'a>(doc: &'a mut Value, key: &str) -> Result<&'a mut Value, String> {
+ if doc.get(key).is_none() {
+ doc[key] = json!({});
+ }
+ if !doc[key].is_object() {
+ return Err(format!("{key} must be a JSON object."));
+ }
+ Ok(&mut doc[key])
+}
+
+pub fn validate(tool: Harness, root: &str, model: &str, login: bool) -> Result<String, String> {
+ let url = url::Url::parse(root).map_err(|e| e.to_string())?;
+ if url.scheme() != "http"
+ || !matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
+ || !url.username().is_empty()
+ || url.password().is_some()
+ || url.query().is_some()
+ || url.fragment().is_some()
+ || url.path() != "/"
+ {
+ return Err(
+ "Install requires a local HTTP server URL, such as http://127.0.0.1:4123.".into(),
+ );
+ }
+ if model.trim().is_empty() {
+ return Err("Pick a route first.".into());
+ }
+ if tool == Harness::Pi && login {
+ return Err(
+ "Pi's custom provider needs a route with server API credentials. \
+ Use Codex or Claude for subscription login forwarding."
+ .into(),
+ );
+ }
+ // validate returns the parsed URL without a trailing slash so callers can append API paths.
+ Ok(url.to_string().trim_end_matches('/').to_owned())
+}
+
+fn codex_settings(
+ text: &str,
+ root: &str,
+ model: &str,
+ context_window: Option<u64>,
+ login: bool,
+) -> Result<String, String> {
+ let mut doc = text
+ .parse::<DocumentMut>()
+ .map_err(|e| e.message().to_owned())?;
+ if doc
+ .get("model_providers")
+ .is_some_and(|item| item.as_table_like().is_none())
+ {
+ return Err("model_providers must be a TOML table.".into());
+ }
+ if doc
+ .get("model_providers")
+ .and_then(|v| v.get("sy"))
+ .is_some_and(|item| item.as_table_like().is_none())
+ {
+ return Err("sy must be a TOML provider table.".into());
+ }
+ doc["model"] = value(model);
+ doc["model_provider"] = value("sy");
+ // Codex does not know a route ID, so it compacts only when the settings name the
+ // route's window. A window kept from another route would compact at the wrong size.
+ match context_window.and_then(|window| i64::try_from(window).ok()) {
+ Some(window) => doc["model_context_window"] = value(window),
+ None => {
+ doc.remove("model_context_window");
+ }
+ }
+ doc["model_providers"]["sy"]["name"] = value("Switchyard");
+ doc["model_providers"]["sy"]["base_url"] = value(format!("{root}/v1"));
+ doc["model_providers"]["sy"]["wire_api"] = value("responses");
+ doc["model_providers"]["sy"]["requires_openai_auth"] = value(login);
+ // A stale env_key would make Codex require a local API key even when the
+ // server owns the credentials or forwards the harness’s subscription login.
+ doc["model_providers"]["sy"]
+ .as_table_like_mut()
+ .ok_or("sy must be a provider table")?
+ .remove("env_key");
+ Ok(doc.to_string())
+}
+
+fn claude_settings(text: &str, root: &str, model: &str, login: bool) -> Result<String, String> {
+ let mut doc = object(text)?;
+ let env = map(&mut doc, "env")?;
+ let role_models = [
+ "ANTHROPIC_DEFAULT_OPUS_MODEL",
+ "ANTHROPIC_DEFAULT_SONNET_MODEL",
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
+ ];
+ // The complete installation signature distinguishes our placeholder from a user credential.
+ let prior_switchyard = env["ANTHROPIC_BASE_URL"].as_str() == Some(root)
+ && env["ANTHROPIC_AUTH_TOKEN"].as_str() == Some("switchyard-local")
+ && env["ANTHROPIC_API_KEY"].as_str() == Some("")
+ && env["ANTHROPIC_MODEL"]
+ .as_str()
+ .is_some_and(|model| !model.is_empty())
+ && role_models
+ .iter()
+ .all(|key| env[*key] == env["ANTHROPIC_MODEL"]);
+ env["ANTHROPIC_BASE_URL"] = json!(root);
+ env["ANTHROPIC_MODEL"] = json!(model);
+ // All model roles use the selected public route, including subagents.
+ for key in role_models {
+ env[key] = json!(model);
+ }
+ if login {
+ if prior_switchyard {
+ let values = env.as_object_mut().ok_or("env must be a JSON object.")?;
+ values.remove("ANTHROPIC_AUTH_TOKEN");
+ values.remove("ANTHROPIC_API_KEY");
+ }
+ for key in ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"] {
+ if env.get(key).is_some_and(|value| value.as_str() != Some("")) {
+ return Err(format!(
+ "{key} overrides subscription login. \
+ Remove it from Claude settings before installing this route."
+ ));
+ }
+ }
+ } else {
+ env["ANTHROPIC_AUTH_TOKEN"] = json!("switchyard-local");
+ env["ANTHROPIC_API_KEY"] = json!("");
+ }
+ Ok(serde_json::to_string_pretty(&doc).map_err(|e| e.to_string())? + "\n")
+}
+
+// The preview uses the installation transformations without creating files or backups.
+pub fn preview(
+ tool: Harness,
+ files: &[PathBuf],
+ root: &str,
+ model: &str,
+ context_window: Option<u64>,
+ login: bool,
+) -> Result<Value, String> {
+ let root = validate(tool, root, model, login)?;
+ for path in files {
+ if read_file(&restore_pending_path(path))?.is_some() {
+ return Err("A previous restore still needs backup cleanup. \
+ Retry Restore before connecting another route."
+ .into());
+ }
+ }
+ let originals = files
+ .iter()
+ .map(|path| read_file(path))
+ .collect::<Result<Vec<_>, _>>()?;
+ let incoming = configured(tool, &originals, &root, model, context_window, login)?;
+ let current = originals
+ .iter()
+ .map(|text| text.clone().unwrap_or_default())
+ .collect::<Vec<_>>();
+ Ok(json!({
+ "changes": settings_changes(tool, files, &current, &incoming)?,
+ "current": inspect_settings(tool, files, &current)?,
+ "proposed": inspect_settings(tool, files, &incoming)?,
+ "authentication": if login {
+ "This route uses the harness’s subscription login."
+ } else {
+ "This route uses the API credentials configured on the Switchyard server."
+ },
+ "files": files.iter().map(|path| path.display().to_string()).collect::<Vec<_>>(),
+ "file_actions": files.iter().zip(originals.iter().zip(&incoming)).map(|(path,(before,after))|json!({"file":path,"action":if before.as_deref()==Some(after.as_str()) {"preserve"} else if before.is_none() {"create"} else {"update"}})).collect::<Vec<_>>()
+ }))
+}
+
+// PreviewModel and its nested types omit unknown fields that could contain credentials.
+#[derive(serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PreviewModel {
+ id: Option<String>,
+ name: Option<String>,
+ reasoning: Option<bool>,
+ input: Option<Vec<PreviewInput>>,
+ context_window: Option<u64>,
+ max_tokens: Option<u64>,
+ cost: Option<PreviewCosts>,
+}
+#[derive(serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "lowercase")]
+enum PreviewInput {
+ Text,
+ Image,
+}
+#[derive(serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PreviewCosts {
+ input: Option<f64>,
+ output: Option<f64>,
+ cache_read: Option<f64>,
+ cache_write: Option<f64>,
+}
+
+// settings_changes compares supported routing fields and hides credential values before display.
+fn settings_changes(
+ tool: Harness,
+ files: &[PathBuf],
+ before: &[String],
+ after: &[String],
+) -> Result<Vec<Value>, String> {
+ let mut changes = Vec::new();
+ for (index, file) in files.iter().enumerate() {
+ let decode = |text: &str| -> Result<Value, String> {
+ if matches!(tool, Harness::CodexCli | Harness::CodexApp) {
+ let doc: toml::Value = toml::from_str(text).map_err(|e| e.to_string())?;
+ serde_json::to_value(doc).map_err(|e| e.to_string())
+ } else {
+ object(text)
+ }
+ };
+ let old = decode(&before[index])?;
+ let new = decode(&after[index])?;
+ let keys: &[&str] = match tool {
+ Harness::CodexCli | Harness::CodexApp => &[
+ "/model",
+ "/model_provider",
+ "/model_context_window",
+ "/model_providers/sy/name",
+ "/model_providers/sy/env_key",
+ "/model_providers/sy/base_url",
+ "/model_providers/sy/requires_openai_auth",
+ "/model_providers/sy/wire_api",
+ ],
+ Harness::Claude => &[
+ "/model",
+ "/env/ANTHROPIC_MODEL",
+ "/env/ANTHROPIC_DEFAULT_OPUS_MODEL",
+ "/env/ANTHROPIC_DEFAULT_SONNET_MODEL",
+ "/env/ANTHROPIC_DEFAULT_HAIKU_MODEL",
+ "/env/ANTHROPIC_BASE_URL",
+ "/env/ANTHROPIC_AUTH_TOKEN",
+ "/env/ANTHROPIC_API_KEY",
+ ],
+ Harness::Pi if index == 0 => &[
+ "/providers/switchyard/baseUrl",
+ "/providers/switchyard/api",
+ "/providers/switchyard/apiKey",
+ "/providers/switchyard/headers",
+ "/providers/switchyard/models",
+ ],
+ Harness::Pi => &["/defaultModel", "/defaultProvider"],
+ };
+ for key in keys {
+ let left = old.pointer(key);
+ let right = new.pointer(key);
+ if left == right {
+ continue;
+ }
+ let display = |value: Option<&Value>| -> String {
+ let Some(value) = value else {
+ return "(unset)".into();
+ };
+ match *key {
+ "/env/ANTHROPIC_AUTH_TOKEN"
+ | "/env/ANTHROPIC_API_KEY"
+ | "/providers/switchyard/apiKey" => if value.as_str() == Some("") {
+ "(empty)"
+ } else {
+ "(set; hidden)"
+ }
+ .into(),
+ "/providers/switchyard/headers" => value
+ .as_object()
+ .map(|headers| {
+ headers
+ .keys()
+ .map(|name| format!("{name}: (set; hidden)"))
+ .collect::<Vec<_>>()
+ .join(", ")
+ })
+ .unwrap_or_else(|| "(configured headers; values hidden)".into()),
+ "/providers/switchyard/models" => value
+ .as_array()
+ .map(|models| {
+ models
+ .iter()
+ .map(|model| {
+ serde_json::from_value::<PreviewModel>(model.clone())
+ .and_then(serde_json::to_value)
+ .unwrap_or_else(|_| {
+ json!("(unsupported model metadata; hidden)")
+ })
+ })
+ .collect::<Vec<_>>()
+ })
+ .map(|models| Value::Array(models).to_string())
+ .unwrap_or_default(),
+ "/env/ANTHROPIC_BASE_URL"
+ | "/model_providers/sy/base_url"
+ | "/providers/switchyard/baseUrl" => value
+ .as_str()
+ .and_then(|v| url::Url::parse(v).ok())
+ .map(|mut url| {
+ let _ = url.set_username("");
+ let _ = url.set_password(None);
+ url.set_query(None);
+ url.set_fragment(None);
+ url.to_string()
+ })
+ .unwrap_or_else(|| "(configured endpoint)".into()),
+ _ => match value {
+ Value::String(value) => value.clone(),
+ Value::Bool(value) => value.to_string(),
+ Value::Number(value) => value.to_string(),
+ _ => "(set; hidden)".into(),
+ },
+ }
+ };
+ changes.push(json!({"file":file.display().to_string(),"key":key.trim_start_matches('/').replace('/',"."),"before":display(left),"after":display(right)}));
+ }
+ }
+ Ok(changes)
+}
+
+// Both preview and installation use these transformations so the proposed settings match the saved settings.
+fn configured(
+ tool: Harness,
+ originals: &[Option<String>],
+ root: &str,
+ model: &str,
+ context_window: Option<u64>,
+ login: bool,
+) -> Result<Vec<String>, String> {
+ let mut incoming = Vec::new();
+ match tool {
+ Harness::CodexCli | Harness::CodexApp => incoming.push(codex_settings(
+ originals[0].as_deref().unwrap_or_default(),
+ root,
+ model,
+ context_window,
+ login,
+ )?),
+ Harness::Claude => incoming.push(claude_settings(
+ originals[0].as_deref().unwrap_or_default(),
+ root,
+ model,
+ login,
+ )?),
+ Harness::Pi => {
+ let mut doc = object(originals[0].as_deref().unwrap_or_default())?;
+ let providers = map(&mut doc, "providers")?;
+ providers["switchyard"] = json!({"baseUrl":format!("{root}/v1"), "api":"openai-completions", "apiKey":"switchyard-local", "headers":{"x-switchyard-origin":"pi"}, "models":[{"id":model,"name":model,"reasoning":true,"input":["text"],"contextWindow":context_window.unwrap_or(128000),"maxTokens":16384,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0}}]});
+ incoming.push(serde_json::to_string_pretty(&doc).map_err(|e| e.to_string())? + "\n");
+ let mut settings = object(originals[1].as_deref().unwrap_or_default())?;
+ settings["defaultProvider"] = json!("switchyard");
+ settings["defaultModel"] = json!(model);
+ incoming
+ .push(serde_json::to_string_pretty(&settings).map_err(|e| e.to_string())? + "\n");
+ }
+ }
+ Ok(incoming)
+}
+
+fn backup_path(path: &Path) -> PathBuf {
+ path.with_file_name(format!(
+ "{}.switchyard-original",
+ path.file_name().unwrap_or_default().to_string_lossy()
+ ))
+}
+
+// The marker distinguishes an originally missing file from an empty file.
+// Restore removes installed settings only when the original file was missing.
+fn absent_path(path: &Path) -> PathBuf {
+ backup_path(path).with_extension("switchyard-original-missing")
+}
+
+fn restore_pending_path(path: &Path) -> PathBuf {
+ backup_path(path).with_extension("switchyard-restore-pending")
+}
+
+pub fn review_files(files: &[PathBuf]) -> Vec<PathBuf> {
+ files
+ .iter()
+ .flat_map(|path| {
+ [
+ path.clone(),
+ backup_path(path),
+ absent_path(path),
+ restore_pending_path(path),
+ ]
+ })
+ .collect()
+}
+
pub fn binary(tool: Harness) -> Option<PathBuf> {
if tool == Harness::CodexApp {
#[cfg(windows)]
diff --git a/crates/switchyard-desktop/src/server_config.rs b/crates/switchyard-desktop/src/server_config.rs
index 94285b8ec..04dba4b04 100644
--- a/crates/switchyard-desktop/src/server_config.rs
+++ b/crates/switchyard-desktop/src/server_config.rs
@@ -607,6 +607,15 @@ impl ServerConfig {
ALGORITHMS.iter().find(|algorithm| algorithm.kind == kind)
}
+ /// This function returns the route's `context_window`, the largest request in tokens
+ /// that the route accepts, or `None` when the route does not set it.
+ pub fn context_window(&self, route: &str) -> Option<u64> {
+ self.route(route)?
+ .get("context_window")?
+ .as_integer()
+ .and_then(|window| u64::try_from(window).ok())
+ }
+
/// This function returns the roles that `algorithm` needs on `route`. A random route
/// keeps its number of targets, and has at least two.
pub fn roles(&self, route: &str, algorithm: &Algorithm) -> Vec<Role> {
diff --git a/crates/switchyard-desktop/src/tui.rs b/crates/switchyard-desktop/src/tui.rs
index 9713d3a9d..fb24b3c6d 100644
--- a/crates/switchyard-desktop/src/tui.rs
+++ b/crates/switchyard-desktop/src/tui.rs
@@ -227,6 +227,14 @@ const ACTIONS: &[ActionRow] = &[
"Saves an API key that lets the app load an endpoint's model IDs, then loads them.",
&[ActionKind::Models],
),
+ (
+ Tab::Harnesses,
+ 'p',
+ "preview",
+ "Shows the settings diff that installing the selected route would make. Nothing is \
+ saved.",
+ &[ActionKind::PreviewInstall],
+ ),
(
Tab::Settings,
'o',
@@ -1123,6 +1131,10 @@ struct App {
/// This field indexes `data.tools`, which lists every harness in a fixed order.
harness: usize,
destination: Destination,
+ /// This field holds the last install preview, the action that produced it, and the route
+ /// revision it was built from. The Harnesses page shows it only while that action matches
+ /// the selection and the route is unchanged.
+ install_preview: Option<(Action, String, Value)>,
/// 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>,
@@ -1158,7 +1170,7 @@ impl App {
route_offset: 0,
harness: 0,
destination: Destination::Harness,
-
+ install_preview: None,
server_keys: None,
popup: None,
popup_generation: 0,
@@ -1248,6 +1260,15 @@ impl App {
.ok_or_else(|| "No harness is listed. Fix the app settings, then press r.".into())
}
+ /// This function returns the selected account's name, or `None` when the harness's own
+ /// settings or a custom settings file is the destination.
+ fn account(&self) -> Option<String> {
+ match &self.destination {
+ Destination::Account(name) => Some(name.clone()),
+ Destination::Harness | Destination::File(_) => None,
+ }
+ }
+
fn custom_file(&self) -> Option<String> {
match &self.destination {
Destination::File(path) => Some(path.clone()),
@@ -1255,6 +1276,51 @@ impl App {
}
}
+ /// This function builds the install preview of the selected route for the selected
+ /// harness and destination.
+ fn install_action(&self) -> Result<Action, String> {
+ let tool = self.harness()?.tool;
+ let route = self.selected_route()?;
+ Ok(Action::PreviewInstall {
+ tool,
+ account: self.account(),
+ route: route.key.clone(),
+ id: route.id.clone(),
+ settings_file: self.custom_file(),
+ })
+ }
+
+ /// This function returns the last install preview while it still describes the selection.
+ fn install_preview(&self) -> Option<&Value> {
+ let (
+ Action::PreviewInstall {
+ tool,
+ account,
+ route,
+ id,
+ settings_file,
+ },
+ revision,
+ preview,
+ ) = self.install_preview.as_ref()?
+ else {
+ return None;
+ };
+ let selected = self.selected_route().ok()?;
+ let destination = match (&self.destination, account, settings_file) {
+ (Destination::Harness, None, None) => true,
+ (Destination::Account(name), Some(previewed), None) => name == previewed,
+ (Destination::File(path), None, Some(previewed)) => path == previewed,
+ _ => false,
+ };
+ let current = destination
+ && self.harness().is_ok_and(|harness| harness.tool == *tool)
+ && selected.key == *route
+ && selected.id == *id
+ && selected.revision == *revision;
+ current.then_some(preview)
+ }
+
// 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;
@@ -1356,6 +1422,12 @@ impl App {
.map(|busy| (busy.action, busy.key))
.unwrap_or((None, None));
let reply = reply?;
+ if matches!(
+ (&action, reply.is_ok()),
+ (Some(Action::PreviewInstall { .. }), false)
+ ) {
+ self.install_preview = None;
+ }
match (kind, reply) {
(Some(ActionKind::ServerKeys), Err(error)) => {
self.server_keys = None;
@@ -1388,6 +1460,29 @@ impl App {
"Type UPDATE to start",
)));
}
+ // The Harnesses page shows the diff while the selection still matches it.
+ (Some(ActionKind::PreviewInstall), Ok(reply)) => {
+ let previewed = action?;
+ let changed = reply.data["changes"]
+ .as_array()
+ .is_some_and(|changes| !changes.is_empty());
+ if !changed {
+ self.report(
+ "The settings already match this route.".into(),
+ Tone::Done,
+ popup_matches,
+ );
+ }
+ // The revision comes from the last snapshot. An older snapshot only hides the
+ // preview early; edits made outside the app are caught by the install recheck.
+ let revision = self
+ .data
+ .routes
+ .iter()
+ .find(|route| matches!(&previewed, Action::PreviewInstall { route: key, .. } if *key == route.key))
+ .map(|route| route.revision.clone())?;
+ self.install_preview = Some((previewed, revision, reply.data));
+ }
(Some(ActionKind::Editor), Ok(reply)) if popup_matches => {
if let Some(Action::Editor {
route: key,
@@ -1942,6 +2037,13 @@ impl App {
};
self.open(form)
}
+ ActionKind::PreviewInstall => {
+ let label = match key {
+ 'p' => "Previewing the settings",
+ _ => return Err(format!("The {key} key does not preview harness settings.")),
+ };
+ request(self.install_action()?, label)
+ }
ActionKind::OpenConfig => request(Action::OpenConfig {}, "Opening the server config"),
ActionKind::CheckConfig => {
@@ -3214,6 +3316,7 @@ fn route_lines(theme: Theme, data: &Snapshot, route: &RouteInfo) -> Vec<Line<'st
tiers: _, // route_models_form keeps each role's model by tier
editable,
generated,
+ compatibility: _, // harness_lines explains it for the selected harness
} = route;
let field = |name: &str, value: String| labeled(theme, name, WIDTH, value);
let algorithm = data.algorithms.iter().find(|known| known.kind == *kind);
@@ -3323,7 +3426,21 @@ fn draw_harnesses(frame: &mut Frame, app: &App, area: Rect) {
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);
+ let Some(preview) = app.install_preview() else {
+ frame.render_widget(detail, rest);
+ return;
+ };
+ let diff = Paragraph::new(install_lines(theme, preview))
+ .wrap(Wrap { trim: false })
+ .block(block(theme, "Settings diff").padding(Padding::horizontal(1)));
+ // Wide terminals put the diff beside the details; others put it below them.
+ let [details_area, diff_area] = if rest.width >= SIDE_DETAIL_WIDTH {
+ Layout::horizontal([Constraint::Fill(1); 2]).areas(rest)
+ } else {
+ Layout::vertical([Constraint::Fill(1); 2]).areas(rest)
+ };
+ frame.render_widget(detail, details_area);
+ frame.render_widget(diff, diff_area);
}
fn draw_harness_table(frame: &mut Frame, app: &App, area: Rect) {
@@ -3393,7 +3510,7 @@ fn harness_lines(app: &App, harness: &ToolInfo) -> Vec<Line<'static>> {
// This destructuring has no `..`, so adding a harness field breaks the build until this
// page shows it.
let ToolInfo {
- tool: _,
+ tool,
label: _, // draw_harnesses titles these details with it
available,
files,
@@ -3406,6 +3523,11 @@ fn harness_lines(app: &App, harness: &ToolInfo) -> Vec<Line<'static>> {
match app.selected_route() {
Ok(route) => {
lines.push(field("Route", route.label.clone()));
+ match route.compatibility.get(tool) {
+ Some(Some(reason)) => lines.push(Line::styled(reason.clone(), theme.warn)),
+ Some(None) => lines.push(Line::styled("This harness can use the route.", theme.ok)),
+ None => {}
+ }
}
Err(error) => lines.push(Line::from(vec![
Span::styled(format!("{:<WIDTH$}", "Route"), theme.muted),
@@ -4028,6 +4150,50 @@ fn remove_lines(
lines
}
+/// This function returns a text field of a controller reply, or nothing when it is missing.
+fn text(value: &Value, key: &str) -> String {
+ value[key].as_str().unwrap_or_default().to_string()
+}
+
+/// This function lists each setting that a harness preview changes: the file and setting, the
+/// current value, and the value afterward.
+fn diff_lines(theme: Theme, preview: &Value, after: &str) -> Vec<Line<'static>> {
+ let mut lines = vec![Line::styled(
+ format!("SETTINGS DIFF · − current / + {after}"),
+ theme.muted.bold(),
+ )];
+ for change in preview["changes"].as_array().into_iter().flatten() {
+ lines.extend([
+ Line::default(),
+ Line::styled(
+ format!("{} · {}", text(change, "file"), text(change, "key")),
+ theme.muted,
+ ),
+ Line::styled(format!("− {}", text(change, "before")), theme.error),
+ Line::styled(format!("+ {}", text(change, "after")), theme.ok),
+ ]);
+ }
+ lines
+}
+
+/// This function shows an install preview: the settings afterward, each changed setting, what
+/// happens to each file, and how the harness signs in.
+fn install_lines(theme: Theme, preview: &Value) -> Vec<Line<'static>> {
+ let mut lines = vec![Line::styled("AFTER APPLYING ROUTING", theme.muted.bold())];
+ let proposed = text(preview, "proposed");
+ lines.extend(proposed.lines().map(|line| Line::from(line.to_string())));
+ lines.push(Line::default());
+ lines.extend(diff_lines(theme, preview, "proposed"));
+ lines.push(Line::default());
+ for file in preview["file_actions"].as_array().into_iter().flatten() {
+ let (action, file) = (text(file, "action"), text(file, "file"));
+ lines.push(Line::from(format!("Will {action}: {file}")));
+ }
+ lines.push(Line::default());
+ lines.push(Line::from(text(preview, "authentication")));
+ lines
+}
+
fn update_lines(theme: Theme, preview: &Value) -> Vec<Line<'static>> {
// `git status --short` starts some lines with a space, so only trailing space is removed.
let field = |name: &str| {