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

test(desktop): cover named accounts and the Windows terminal launcher (#1108)

Elyas Mehtabuddin78f44c2f3679
diff --git a/crates/switchyard-desktop/src/accounts.rs b/crates/switchyard-desktop/src/accounts.rs
index 58d2a862d..22e0857d1 100644
--- a/crates/switchyard-desktop/src/accounts.rs
+++ b/crates/switchyard-desktop/src/accounts.rs
@@ -192,3 +192,44 @@ pub fn archive(tool: Harness, path: &Path) -> Result<String, String> {
archived.display()
))
}
+
+#[cfg(all(test, unix))]
+mod tests {
+ use super::*;
+
+ // The subprocess isolates HOME so parallel tests keep their own settings.
+ #[cfg(unix)]
+ #[test]
+ fn symlinked_account_roots_are_not_listed_or_used_for_login() {
+ if std::env::var_os("SWITCHYARD_ACCOUNT_FIXTURE").is_some() {
+ assert!(list(Harness::CodexCli).is_empty());
+ assert!(discover(Harness::CodexCli).is_err());
+ assert!(add(Harness::CodexCli, "new").is_err());
+ let path = crate::config::expand_home(Path::new("~/.switchyard/accounts/codex/named"))
+ .expect("home");
+ assert!(validate(Harness::CodexCli, &path).is_err());
+ return;
+ }
+ let dir = tempfile::tempdir().expect("fixture");
+ let home = dir.path().join("home");
+ let target = dir.path().join("target");
+ std::fs::create_dir(&home).expect("home");
+ std::fs::create_dir_all(target.join("accounts/codex/named")).expect("accounts");
+ std::os::unix::fs::symlink(&target, home.join(".switchyard")).expect("symlink");
+ let output = std::process::Command::new(std::env::current_exe().expect("runner"))
+ .args([
+ "--exact",
+ "accounts::tests::symlinked_account_roots_are_not_listed_or_used_for_login",
+ ])
+ .env("SWITCHYARD_ACCOUNT_FIXTURE", "1")
+ .env("HOME", &home)
+ .output()
+ .expect("child");
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stdout)
+ );
+ assert!(!target.join("accounts/codex/new").exists());
+ }
+}
diff --git a/crates/switchyard-desktop/src/controller.rs b/crates/switchyard-desktop/src/controller.rs
index 16ed9f7f5..d3261b31e 100644
--- a/crates/switchyard-desktop/src/controller.rs
+++ b/crates/switchyard-desktop/src/controller.rs
@@ -10,6 +10,7 @@ use crate::{
harness::{self, Harness},
history, models, pricing, rollup, server,
server_config::{ALGORITHMS, Choice, Route, ServerConfig},
+ sessions,
};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -101,6 +102,21 @@ pub enum Action {
tool: Harness,
name: String,
},
+ Launch {
+ preview_token: Option<String>,
+ tool: Harness,
+ account: Option<String>,
+ route: String,
+ id: String,
+ project: String,
+ },
+ PreviewLaunch {
+ tool: Harness,
+ account: Option<String>,
+ route: String,
+ id: String,
+ project: String,
+ },
LoginAccount {
tool: Harness,
name: String,
@@ -151,6 +167,12 @@ pub enum Action {
#[derive(Clone, Default, Serialize)]
pub struct Snapshot {
pub update_status: Value,
+ /// Each value is the `session.json` file that `sessions::launch` wrote for a managed
+ /// worktree session, plus `process_status`. The snapshot passes these files through as JSON.
+ pub session_inventory: Vec<Value>,
+ /// This field holds the error that stopped the inventory read. `session_inventory` is empty
+ /// when this field is set.
+ pub session_inventory_error: Option<String>,
pub settings: Option<AppSettings>,
pub data_state: DataState,
/// The controller increases this number when the app settings select another server
@@ -414,6 +436,17 @@ impl Review {
}
}
+// Each Controller retains one launch review until the next preview or a selected config change.
+// Review keeps raw settings private; Launch uses these values and the reviewed Git commit.
+struct ReviewedLaunch {
+ review: Review,
+ project: Value,
+ model: String,
+ server_url: String,
+ login: bool,
+ account: Option<PathBuf>,
+}
+
pub struct Controller {
health_probe: crate::health::Probe,
settings: PathBuf,
@@ -423,9 +456,11 @@ pub struct Controller {
generation: u64,
route_reviews: std::collections::HashMap<String, Review>,
tool_review: Option<Review>,
+
account_archive: Option<(Harness, String, String)>,
route_change: Option<Review>,
update_review: Option<(String, Value)>,
+ launch_review: Option<ReviewedLaunch>,
}
impl Controller {
pub fn new(config: Config, settings: PathBuf) -> Self {
@@ -437,9 +472,11 @@ impl Controller {
generation: 0,
route_reviews: Default::default(),
tool_review: None,
+
account_archive: None,
route_change: None,
update_review: None,
+ launch_review: None,
}
}
fn reload(&mut self) -> Result<(), String> {
@@ -449,6 +486,7 @@ impl Controller {
self.route_reviews.clear();
self.tool_review = None;
self.route_change = None;
+ self.launch_review = None;
}
self.config = config;
@@ -678,6 +716,10 @@ impl Controller {
}
})
.collect();
+ let (session_inventory, session_inventory_error) = match sessions::inventory() {
+ Ok(inventory) => (inventory, None),
+ Err(error) => (Vec::new(), Some(error)),
+ };
let Config {
server_url,
routing_log,
@@ -703,6 +745,8 @@ impl Controller {
baseline_model: baseline_model.clone(),
prices_file,
}),
+ session_inventory,
+ session_inventory_error,
data_state: DataState {
usage: Source {
state: usage_state,
@@ -770,9 +814,10 @@ impl Controller {
}
Action::OpenUpdateLog {} => self.update_log().map(Some),
Action::OpenLogs {} => logs_dir().map(Some),
- // An account folder opens in the editor too, because a terminal may run over SSH,
- // where `open` would start a file manager on another screen.
+ // Account and session folders open in the editor too, because a terminal may run
+ // over SSH, where `open` would start a file manager on another screen.
Action::OpenAccount { tool, name } => account_path(*tool, Some(name)),
+
_ => Ok(None),
}
}
@@ -1107,6 +1152,104 @@ impl Controller {
Action::AddAccount { tool, name } => {
accounts::add(tool, name.trim()).map(Reply::message)
}
+ Action::Launch {
+ tool,
+ account,
+ route,
+ id,
+ project,
+ preview_token,
+ } => {
+ let inputs =
+ json!({"tool":tool,"account":account,"route":route,"id":id,"project":project});
+ // Each attempt uses up the review, so a repeated request cannot create a second
+ // worktree and terminal from one review.
+ let plan = self
+ .launch_review
+ .take()
+ .ok_or("Review the session before opening Terminal.")?;
+ plan.review.check(preview_token.as_deref(), &inputs)?;
+ let current = sessions::preview(std::path::Path::new(&project))?;
+ if current != plan.project {
+ return Err(
+ "The project changed since review. Review the session again.".into(),
+ );
+ }
+ sessions::launch(
+ tool,
+ std::path::Path::new(
+ plan.project["project"]
+ .as_str()
+ .ok_or("Missing reviewed project.")?,
+ ),
+ &plan.model,
+ &plan.server_url,
+ plan.login,
+ plan.account.as_deref(),
+ plan.project["revision"]
+ .as_str()
+ .ok_or("Missing reviewed commit.")?,
+ )
+ .map(Reply::message)
+ }
+ Action::PreviewLaunch {
+ tool,
+ account,
+ route,
+ id,
+ project,
+ } => {
+ if tool == Harness::CodexApp {
+ return Err("Use Codex app’s workspace controls or choose Codex CLI.".into());
+ }
+ if harness::binary(tool).is_none() {
+ return Err("Install the selected harness first.".into());
+ }
+ let inputs =
+ json!({"tool":tool,"account":account,"route":route,"id":id,"project":project});
+ let review = Review::capture(
+ inputs.clone(),
+ vec![self.config.config_file.clone(), self.settings.clone()],
+ )?;
+ let app_config = Config::load(&self.settings)?;
+ review.check(Some(&review.token), &inputs)?;
+ if app_config.config_file != self.config.config_file {
+ return Err("Review these changes again before applying them.".into());
+ }
+ let config = ServerConfig::parse(review.original()?).map_err(
+ |_| "The server config contains invalid TOML. Open it in Settings to fix it.",
+ )?;
+ let route = current_route(&config, &route, Some(&id))?;
+ let login = login_mode(tool, &config, &route.key)?;
+ let account = account_path(tool, account.as_deref())?;
+ let project_review = sessions::preview(std::path::Path::new(&project))?;
+ let mut data = project_review.clone();
+ data["tool"] = json!(tool);
+ data["route"] = json!(route.id);
+ data["account_directory"] = json!(account);
+ data["server_url"] = json!(app_config.server_url);
+ data["login"] = json!(login);
+ if tool == Harness::Pi {
+ data["settings_notice"] = json!(
+ "Pi uses isolated session settings. \
+ Personal settings and extensions are not copied."
+ );
+ }
+ review.check(Some(&review.token), &inputs)?;
+ data["preview_token"] = json!(review.token);
+ self.launch_review = Some(ReviewedLaunch {
+ review,
+ project: project_review,
+ model: route.id,
+ server_url: app_config.server_url,
+ login,
+ account,
+ });
+ Ok(Reply {
+ message: String::new(),
+ data,
+ })
+ }
Action::LoginAccount { tool, name } => {
let path = account_path(tool, Some(&name))?.ok_or("Choose an account.")?;
accounts::login(tool, &path, &name).map(Reply::message)
@@ -1680,6 +1823,133 @@ policy = { type = "target_selector", selector = "/target" }
assert_eq!(std::fs::read_dir(dir.path()).expect("files").count(), 2);
}
+ #[test]
+ // A custom destination must use the same files for preview, installation, backup, and restore.
+ fn custom_settings_are_validated_and_restored() {
+ let dir = tempfile::tempdir().expect("directory");
+ for (tool, _) in harness::HARNESSES {
+ let file = dir.path().join(if *tool == Harness::Pi {
+ "models.json"
+ } else {
+ "custom-settings"
+ });
+ assert_eq!(
+ install_paths(*tool, None, Some(file.to_str().expect("path"))).expect("custom")[0],
+ file
+ );
+ }
+ for (account, file) in [
+ (None, "relative.json"),
+ (None, ""),
+ (Some("account"), "/tmp/settings.json"),
+ (None, "/tmp/settings\n.json"),
+ ] {
+ assert!(install_paths(Harness::Claude, account, Some(file)).is_err());
+ }
+ assert!(install_paths(Harness::Pi, None, Some("/tmp/settings.json")).is_err());
+ assert!(install_paths(Harness::Claude, None, dir.path().to_str()).is_err());
+ assert_eq!(std::fs::read_dir(dir.path()).expect("files").count(), 0);
+ let settings = dir.path().join("app.toml");
+ let config = dir.path().join("server.toml");
+ std::fs::write(
+ &config,
+ "[llm_clients.c]\n\
+ base_url='https://example.com/v1'\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",
+ )
+ .expect("config");
+ std::fs::write(
+ &settings,
+ format!(
+ "config_file={config:?}\nrouting_log={:?}",
+ dir.path().join("log")
+ ),
+ )
+ .expect("settings");
+ let custom = dir.path().join("custom.json");
+ std::fs::write(&custom, "{\"user\":true}").expect("custom");
+ let mut controller = Controller::new(Config::load(&settings).expect("settings"), settings);
+ let file = Some(custom.display().to_string());
+ let preview = controller
+ .dispatch(Action::PreviewInstall {
+ tool: Harness::Claude,
+ account: None,
+ settings_file: file.clone(),
+ route: "r".into(),
+ id: "public".into(),
+ })
+ .expect("preview");
+ assert!(
+ preview.data["changes"]
+ .as_array()
+ .expect("diff")
+ .iter()
+ .any(|change| change["file"] == custom.display().to_string())
+ );
+ std::fs::write(&custom, "{\"external\":true}").expect("external edit");
+ let rejected = controller.dispatch(Action::Install {
+ tool: Harness::Claude,
+ account: None,
+ settings_file: file.clone(),
+ route: "r".into(),
+ id: "public".into(),
+ preview_token: preview.data["preview_token"].as_str().map(str::to_string),
+ });
+ assert!(rejected.is_err());
+ assert_eq!(
+ std::fs::read_to_string(&custom).expect("custom"),
+ "{\"external\":true}"
+ );
+ assert!(
+ !custom
+ .with_file_name("custom.json.switchyard-original")
+ .exists()
+ );
+ std::fs::write(&custom, "{\"user\":true}").expect("restore fixture");
+ controller
+ .dispatch(Action::Install {
+ tool: Harness::Claude,
+ account: None,
+ settings_file: file.clone(),
+ route: "r".into(),
+ id: "public".into(),
+ preview_token: preview.data["preview_token"].as_str().map(str::to_string),
+ })
+ .expect("install");
+ assert_eq!(
+ preview.data["proposed"],
+ harness::inspect(Harness::Claude, std::slice::from_ref(&custom)).expect("inspect")
+ );
+ let restore_preview = controller
+ .dispatch(Action::PreviewRestore {
+ tool: Harness::Claude,
+ account: None,
+ settings_file: file.clone(),
+ })
+ .expect("restore preview");
+ controller
+ .dispatch(Action::Restore {
+ tool: Harness::Claude,
+ account: None,
+ settings_file: file,
+ preview_token: restore_preview.data["preview_token"]
+ .as_str()
+ .map(str::to_string),
+ })
+ .expect("restore");
+ assert_eq!(
+ std::fs::read_to_string(custom).expect("custom"),
+ "{\"user\":true}"
+ );
+ }
+
#[cfg(any(target_os = "macos", windows))]
#[test]
// A cached list must not let an untested key reach Keychain.
diff --git a/crates/switchyard-desktop/src/harness.rs b/crates/switchyard-desktop/src/harness.rs
index 735884ba6..296a2d013 100644
--- a/crates/switchyard-desktop/src/harness.rs
+++ b/crates/switchyard-desktop/src/harness.rs
@@ -541,7 +541,6 @@ fn configured(
Ok(incoming)
}
-#[cfg(test)]
pub fn install(
tool: Harness,
files: &[PathBuf],
diff --git a/crates/switchyard-desktop/src/sessions.rs b/crates/switchyard-desktop/src/sessions.rs
index ebdd58585..3f7538d94 100644
--- a/crates/switchyard-desktop/src/sessions.rs
+++ b/crates/switchyard-desktop/src/sessions.rs
@@ -1,6 +1,369 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
+//! This module starts CLI sessions with separate worktrees and model settings.
+
+use crate::harness::{self, Harness};
+use std::path::Path;
+
+// PendingSession attempts cleanup until open accepts the launch request.
+// A successful launch keeps the worktree and settings for the coding session.
+struct PendingSession {
+ project: std::path::PathBuf,
+ worktree: std::path::PathBuf,
+ private: std::path::PathBuf,
+ branch: String,
+ revision: String,
+ opened: bool,
+}
+
+impl Drop for PendingSession {
+ fn drop(&mut self) {
+ if self.opened {
+ return;
+ }
+ let _ = std::process::Command::new("git")
+ .arg("-C")
+ .arg(&self.project)
+ .args(["worktree", "remove"])
+ .arg(&self.worktree)
+ .output();
+ delete_session_branch(&self.project, &self.branch, &self.revision);
+ let _ = std::fs::remove_dir_all(&self.private);
+ }
+}
+
+// This deletes the session branch only while it still points at the session's starting commit.
+// The commit check makes `branch -D` safe. `branch -d` also requires a merge into the original
+// checkout's HEAD, so it fails after the user switches that checkout to an unrelated branch.
+fn delete_session_branch(repository: &Path, branch: &str, revision: &str) -> bool {
+ let tip = std::process::Command::new("git")
+ .arg("-C")
+ .arg(repository)
+ .args(["rev-parse", "--verify", "--quiet"])
+ .arg(format!("refs/heads/{branch}"))
+ .output();
+ tip.is_ok_and(|tip| {
+ tip.status.success() && String::from_utf8_lossy(&tip.stdout).trim() == revision
+ }) && std::process::Command::new("git")
+ .arg("-C")
+ .arg(repository)
+ .args(["branch", "-D", branch])
+ .output()
+ .is_ok_and(|output| output.status.success())
+}
+
pub(crate) fn quote(text: &str) -> String {
format!("'{}'", text.replace('\'', "'\\''"))
}
+
+pub fn preview(project: &Path) -> Result<serde_json::Value, String> {
+ if project.as_os_str().is_empty() {
+ return Err("Choose a Git checkout directory.".into());
+ }
+ let project = std::fs::canonicalize(crate::config::expand_home(project)?)
+ .map_err(|error| format!("Open project: {error}"))?;
+ let git = |args: &[&str]| -> Result<String, String> {
+ let output = std::process::Command::new("git")
+ .arg("-C")
+ .arg(&project)
+ .args(args)
+ .output()
+ .map_err(|error| error.to_string())?;
+ if !output.status.success() {
+ return Err("Choose a Git checkout with a committed HEAD.".into());
+ }
+ Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
+ };
+ let repository = git(&["rev-parse", "--show-toplevel"])?;
+ let repository_path = std::fs::canonicalize(&repository).map_err(|error| error.to_string())?;
+ let relative = project
+ .strip_prefix(&repository_path)
+ .map_err(|error| error.to_string())?;
+ Ok(serde_json::json!({
+ "repository": repository,
+ "project": project,
+ "relative_directory": relative,
+ "revision": git(&["rev-parse", "HEAD"])?,
+ "branch": git(&["branch", "--show-current"])?,
+ "dirty": !git(&["status", "--porcelain"])?.is_empty(),
+ "notice": "The session starts from committed HEAD. \
+ Uncommitted changes stay in the original checkout."
+ }))
+}
+
+fn session_root() -> Result<std::path::PathBuf, String> {
+ crate::config::expand_home(Path::new("~/.switchyard/worktrees"))
+}
+
+pub fn inventory() -> Result<Vec<serde_json::Value>, String> {
+ let root = session_root()?;
+ 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!("Read session inventory: {error}")),
+ };
+ let mut sessions = Vec::new();
+ for entry in entries {
+ let entry = entry.map_err(|error| error.to_string())?;
+ if entry
+ .file_type()
+ .map_err(|error| error.to_string())?
+ .is_dir()
+ && entry.file_name().to_string_lossy().ends_with("-settings")
+ {
+ let receipt = entry.path().join("session.json");
+ if receipt.exists() {
+ let mut value: serde_json::Value = serde_json::from_slice(
+ &std::fs::read(&receipt).map_err(|error| error.to_string())?,
+ )
+ .map_err(|error| format!("Read {}: {error}", receipt.display()))?;
+ value
+ .as_object_mut()
+ .ok_or("The session receipt does not match this worktree.")?
+ .insert("process_status".into(), serde_json::json!("unknown"));
+ sessions.push(value);
+ }
+ }
+ }
+ sessions.sort_by(|left, right| {
+ right["created_at"]
+ .as_str()
+ .cmp(&left["created_at"].as_str())
+ });
+ Ok(sessions)
+}
+
+pub fn launch(
+ tool: Harness,
+ project: &Path,
+ model: &str,
+ root: &str,
+ login: bool,
+ account: Option<&Path>,
+ revision: &str,
+) -> Result<String, String> {
+ let root = harness::validate(tool, root, model, login)?;
+ if let Some(account) = account {
+ crate::accounts::validate(tool, account)?;
+ }
+ if tool == Harness::CodexApp {
+ return Err("Choose Codex CLI to launch a worktree session. \
+ Codex app uses its own workspace controls."
+ .into());
+ }
+ let binary = harness::binary(tool).ok_or("Install the selected harness first.")?;
+ if project.as_os_str().is_empty() {
+ return Err("Choose a Git checkout directory.".into());
+ }
+ let project = crate::config::expand_home(project)?;
+ let project = std::fs::canonicalize(&project).map_err(|e| format!("Open project: {e}"))?;
+ let output = std::process::Command::new("git")
+ .arg("-C")
+ .arg(&project)
+ .args(["rev-parse", "--show-toplevel"])
+ .output()
+ .map_err(|e| e.to_string())?;
+ if !output.status.success() {
+ return Err("Choose a Git checkout directory.".into());
+ }
+ let repository = Path::new(
+ std::str::from_utf8(&output.stdout)
+ .map_err(|error| error.to_string())?
+ .trim(),
+ )
+ .to_path_buf();
+ let repository = std::fs::canonicalize(repository).map_err(|error| error.to_string())?;
+ let relative = project
+ .strip_prefix(&repository)
+ .map_err(|error| error.to_string())?
+ .to_path_buf();
+ let id = format!("sy-{}", uuid::Uuid::now_v7());
+ // Path resolution must succeed before launch creates directories or a worktree.
+ let default_files = harness::paths(tool)?;
+ let worktree = session_root()?.join(&id);
+ std::fs::create_dir_all(
+ worktree
+ .parent()
+ .ok_or("Worktree needs a parent directory")?,
+ )
+ .map_err(|e| e.to_string())?;
+ let output = std::process::Command::new("git")
+ .arg("-C")
+ .arg(&project)
+ .args(["worktree", "add", "-b"])
+ .arg(&id)
+ .arg(&worktree)
+ .arg(revision)
+ .output()
+ .map_err(|e| e.to_string())?;
+ if !output.status.success() {
+ return Err(format!(
+ "Could not create worktree: {}",
+ String::from_utf8_lossy(&output.stderr)
+ ));
+ }
+ let private = worktree
+ .parent()
+ .ok_or("Worktree needs a parent directory")?
+ .join(format!("{id}-settings"));
+ let mut pending = PendingSession {
+ project,
+ worktree: worktree.clone(),
+ private: private.clone(),
+ branch: id.clone(),
+ revision: revision.into(),
+ opened: false,
+ };
+ let files = match tool {
+ Harness::Pi => vec![private.join("models.json"), private.join("settings.json")],
+ _ => vec![private.join("settings.json")],
+ };
+ std::fs::create_dir_all(&private).map_err(|error| error.to_string())?;
+ if matches!(tool, Harness::Claude | Harness::Pi) {
+ harness::install(tool, &files, &root, model, None, login)?;
+ }
+ let receipt = serde_json::json!({"id":id,"tool":tool,"route":model,"repository":repository,"revision":preview(&worktree)?["revision"],"worktree":worktree,"branch":id,"created_at":chrono::Utc::now().to_rfc3339(),"settings_directory":private,"account_directory":account});
+ std::fs::write(
+ private.join("session.json"),
+ serde_json::to_vec_pretty(&receipt).map_err(|error| error.to_string())?,
+ )
+ .map_err(|error| error.to_string())?;
+ let account = account.or_else(|| match tool {
+ Harness::Claude if std::env::var_os("CLAUDE_CONFIG_DIR").is_none() => None,
+ _ => default_files[0].parent(),
+ });
+ let codex_args = [
+ "-c".to_string(),
+ format!("model={}", toml_edit::Value::from(model)),
+ "-c".into(),
+ "model_provider=\"sy\"".into(),
+ "-c".into(),
+ format!(
+ "model_providers.sy={{name=\"Switchyard\",base_url={},wire_api=\"responses\",\
+ requires_openai_auth={login},http_headers={{\"x-switchyard-session-id\"={},\
+ \"x-switchyard-origin\"=\"codex\"}}}}",
+ toml_edit::Value::from(format!("{}/v1", root.trim_end_matches('/'))),
+ toml_edit::Value::from(id.as_str())
+ ),
+ ];
+ #[cfg(windows)]
+ {
+ let mut environment = Vec::new();
+ let mut remove_environment = Vec::new();
+ let args = match tool {
+ Harness::CodexCli => codex_args.into(),
+ Harness::Claude => {
+ environment.push((
+ "ANTHROPIC_CUSTOM_HEADERS".into(),
+ format!("x-switchyard-session-id: {id}\nx-switchyard-origin: claude"),
+ ));
+ if login {
+ remove_environment.extend(
+ [
+ "ANTHROPIC_AUTH_TOKEN",
+ "ANTHROPIC_API_KEY",
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ ]
+ .map(String::from),
+ );
+ }
+ vec![
+ "--settings".into(),
+ files[0].display().to_string(),
+ "--model".into(),
+ model.into(),
+ ]
+ }
+ Harness::Pi => {
+ environment.push(("PI_CODING_AGENT_DIR".into(), private.display().to_string()));
+ vec![
+ "--provider".into(),
+ "switchyard".into(),
+ "--model".into(),
+ model.into(),
+ ]
+ }
+ Harness::CodexApp => return Err("Choose a CLI harness.".into()),
+ };
+ if let Some(path) = account {
+ match tool {
+ Harness::CodexCli => {
+ environment.push(("CODEX_HOME".into(), path.display().to_string()))
+ }
+ Harness::Claude => {
+ environment.push(("CLAUDE_CONFIG_DIR".into(), path.display().to_string()))
+ }
+ _ => {}
+ }
+ }
+ crate::windows::open_terminal(crate::windows::TerminalJob {
+ binary,
+ args,
+ directory: Some(worktree.join(&relative)),
+ environment,
+ remove_environment,
+ })?;
+ }
+ #[cfg(not(windows))]
+ {
+ let program = quote(&binary.display().to_string());
+ let command = match tool {
+ Harness::CodexCli => format!(
+ "{program} {}",
+ codex_args
+ .iter()
+ .map(|arg| quote(arg))
+ .collect::<Vec<_>>()
+ .join(" ")
+ ),
+ Harness::Claude => format!(
+ "env ANTHROPIC_CUSTOM_HEADERS={} {program} --settings {} --model {}",
+ quote(&format!(
+ "x-switchyard-session-id: {id}\nx-switchyard-origin: claude"
+ )),
+ quote(&files[0].display().to_string()),
+ quote(model)
+ ),
+ Harness::Pi => format!(
+ "env PI_CODING_AGENT_DIR={} {program} --provider switchyard --model {}",
+ quote(&private.display().to_string()),
+ quote(model)
+ ),
+ Harness::CodexApp => return Err("Choose a CLI harness.".into()),
+ };
+ let account_env = match (tool, account) {
+ (Harness::CodexCli, Some(path)) => {
+ format!("export CODEX_HOME={}\n", quote(&path.display().to_string()))
+ }
+ (Harness::Claude, Some(path)) => format!(
+ "export CLAUDE_CONFIG_DIR={}\n",
+ quote(&path.display().to_string())
+ ),
+ _ => String::new(),
+ };
+ let subscription_env = if tool == Harness::Claude && login {
+ "unset ANTHROPIC_AUTH_TOKEN ANTHROPIC_API_KEY CLAUDE_CODE_OAUTH_TOKEN\n"
+ } else {
+ ""
+ };
+ let script = format!(
+ "#!/bin/bash\n\
+ export PATH=\"$HOME/.cargo/bin:/opt/homebrew/bin:/usr/local/bin:$PATH\"\n\
+ rm -- \"$0\"\n\
+ cd {} || exit 1\n\
+ {account_env}{subscription_env}{command}",
+ quote(&worktree.join(relative).display().to_string())
+ );
+ crate::server::open_terminal_script("switchyard-session-", &script)?;
+ }
+ pending.opened = true;
+ Ok(format!(
+ "Opened Terminal to start the session.\n\
+ Worktree: {}\n\
+ Branch: {id}\n\
+ Model route: {model}\n\
+ Remove the worktree with git worktree remove after saving or discarding its changes.",
+ worktree.display()
+ ))
+}
diff --git a/crates/switchyard-desktop/src/tui.rs b/crates/switchyard-desktop/src/tui.rs
index 6d7f4a194..0a73f9dd4 100644
--- a/crates/switchyard-desktop/src/tui.rs
+++ b/crates/switchyard-desktop/src/tui.rs
@@ -1,8 +1,8 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
-//! The terminal app shows usage, recent calls, routes, and harness settings from controller
-//! snapshots, and it runs server, route, harness, and account actions.
+//! The terminal app shows usage, recent calls, routes, harness settings, and worktree sessions
+//! from controller snapshots, and it runs server, route, harness, account, and session actions.
//!
//! One worker thread owns the controller and refreshes its snapshots while the UI thread
//! draws and reads input.
@@ -53,7 +53,7 @@ const SPINNER: [char; 8] = ['⣷', '⣯', '⣟', '⡿', '⢿', '⣻', '⣽', '
type Key = (&'static str, &'static str, &'static str);
const GLOBAL_KEYS: &[Key] = &[
(
- "1-6",
+ "1-7",
"page",
"Switch pages. Tab, Shift-Tab, ← and → also switch pages.",
),
@@ -113,8 +113,8 @@ 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.",
+ "Choose the route to install. j, k, PgUp, PgDn, g, and G also move it. The Routes and \
+ Sessions pages select the same route, and the Routes filter limits the choices.",
),
("t", "harness", "Select the next harness."),
(
@@ -130,6 +130,29 @@ const HARNESSES_KEYS: &[Key] = &[
detected settings again.",
),
];
+const SESSIONS_KEYS: &[Key] = &[
+ (
+ "↑↓",
+ "route",
+ "Choose the route for a new session. j, k, PgUp, PgDn, g, and G also move it. The \
+ Routes and Harnesses pages select the same route.",
+ ),
+ (
+ "t",
+ "harness",
+ "Select the next harness for a new session. The Harnesses page selects the same one.",
+ ),
+ (
+ "a",
+ "account",
+ "Select the next saved account for a new session, then the harness's own login again.",
+ ),
+ (
+ "s",
+ "session",
+ "Select the next recorded session and show its details.",
+ ),
+];
const SETTINGS_KEYS: &[Key] = &[
("↑↓", "select", "Select an action. j, g, and G also move."),
(
@@ -284,6 +307,22 @@ const ACTIONS: &[ActionRow] = &[
ActionKind::ArchiveAccount,
],
),
+ (
+ Tab::Sessions,
+ 'l',
+ "launch",
+ "Asks for a Git project folder and shows the session review. After you type LAUNCH, \
+ it creates a worktree from committed HEAD and opens the harness there in a new \
+ terminal window.",
+ &[ActionKind::PreviewLaunch, ActionKind::Launch],
+ ),
+ (
+ Tab::Sessions,
+ 'n',
+ "add account",
+ "Creates a saved account and opens the harness's login in a new terminal window.",
+ &[ActionKind::AddAccount],
+ ),
(
Tab::Settings,
'o',
@@ -412,6 +451,15 @@ const HARNESS_COLUMNS: [(Column, bool); 4] = [
(("CURRENT SETTINGS", Constraint::Fill(3), false), true),
(("ACCOUNTS", Constraint::Length(8), true), false),
];
+/// The sessions table drops the columns marked `true` below 100 columns; the details still
+/// show them.
+const SESSION_COLUMNS: [(Column, bool); 5] = [
+ (("SESSION", Constraint::Length(39), false), false),
+ (("REPOSITORY", Constraint::Fill(2), false), true),
+ (("ROUTE", Constraint::Fill(1), false), false),
+ (("CREATED", Constraint::Length(8), true), true),
+ (("LAST CALL", Constraint::Length(9), true), false),
+];
/// Theme maps each kind of text to one style. NO_COLOR keeps the text modifiers.
#[derive(Clone, Copy)]
@@ -466,14 +514,16 @@ enum Tab {
Models,
Routes,
Harnesses,
+ Sessions,
Settings,
}
-const TABS: [Tab; 6] = [
+const TABS: [Tab; 7] = [
Tab::Overview,
Tab::Calls,
Tab::Models,
Tab::Routes,
Tab::Harnesses,
+ Tab::Sessions,
Tab::Settings,
];
impl Tab {
@@ -484,6 +534,7 @@ impl Tab {
Tab::Models => "Models",
Tab::Routes => "Routes",
Tab::Harnesses => "Harnesses",
+ Tab::Sessions => "Sessions",
Tab::Settings => "Settings",
}
}
@@ -586,6 +637,13 @@ enum FormKind {
/// The harness is the one selected when the form opened.
Account(Harness),
SettingsFile,
+ /// The harness, account, and route are the ones selected when the form opened.
+ Project {
+ tool: Harness,
+ account: Option<String>,
+ route: String,
+ id: String,
+ },
}
/// Choices names the list that ↑ and ↓ cycle through in a form field.
enum Choices {
@@ -887,6 +945,18 @@ impl Form {
}
return Ok(Submit::SettingsFile(path));
}
+ FormKind::Project {
+ tool,
+ account,
+ route,
+ id,
+ } => Action::PreviewLaunch {
+ tool: *tool,
+ account: account.clone(),
+ route: route.clone(),
+ id: id.clone(),
+ project: self.value(0),
+ },
}))
}
fn label(&self) -> &'static str {
@@ -906,6 +976,8 @@ impl Form {
Action::Install { .. } => "Installing the harness settings",
Action::Restore { .. } => "Restoring the harness settings",
Action::ArchiveAccount { .. } => "Archiving the account",
+ Action::Launch { .. } => "Launching the session",
+
_ => "Saving the route",
},
FormKind::Remove { .. } => "Deleting the route",
@@ -913,6 +985,7 @@ impl Form {
FormKind::ModelKey(_) => "Saving the key and loading models",
FormKind::Account(_) => "Adding the account",
FormKind::SettingsFile => "Choosing the settings file",
+ FormKind::Project { .. } => "Reviewing the session",
}
}
}
@@ -1047,6 +1120,21 @@ fn reviewed(previewed: Action, preview: &Value) -> Option<Action> {
name,
preview_token,
},
+ Action::PreviewLaunch {
+ tool,
+ account,
+ route,
+ id,
+ project,
+ } => Action::Launch {
+ preview_token,
+ tool,
+ account,
+ route,
+ id,
+ project,
+ },
+
_ => return None,
})
}
@@ -1187,7 +1275,8 @@ impl Tone {
}
}
-/// Destination is where the Harnesses page installs and restores settings.
+/// Destination is where the Harnesses page installs and restores settings. The Sessions page
+/// launches with its account, and with the harness's own login otherwise.
enum Destination {
/// The harness's own settings files.
Harness,
@@ -1224,6 +1313,10 @@ struct App {
/// 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 indexes `data.session_inventory`, newest first. It starts at the first
+ /// session, and it is `None` after a refresh stops listing the selected session, so no
+ /// action reaches another session.
+ managed: Option<usize>,
/// 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>,
@@ -1260,6 +1353,7 @@ impl App {
harness: 0,
destination: Destination::Harness,
install_preview: None,
+ managed: Some(0),
server_keys: None,
popup: None,
popup_generation: 0,
@@ -1418,6 +1512,18 @@ impl App {
current.then_some(preview)
}
+ fn selected_session(&self) -> Option<&Value> {
+ self.data.session_inventory.get(self.managed?)
+ }
+
+ /// This function returns the ID of the session that the open and remove keys use.
+ fn session_id(&self) -> Result<String, String> {
+ self.selected_session()
+ .and_then(|receipt| receipt["id"].as_str())
+ .map(str::to_owned)
+ .ok_or_else(|| "Press s to select a recorded session first.".into())
+ }
+
// 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;
@@ -1484,7 +1590,15 @@ impl App {
.filter(|_| self.selected > 0)
.map(|entry| (entry.ts.clone(), entry.model.clone(), entry.turn_id.clone()));
let route = self.selected_route_key();
+ let managed = self.session_id().ok();
self.data = *data;
+ if let Some(id) = managed {
+ self.managed = self
+ .data
+ .session_inventory
+ .iter()
+ .position(|receipt| receipt["id"] == id);
+ }
self.refreshed = Some(Instant::now());
self.rebuild_calls();
self.rebuild_routes(route);
@@ -1670,6 +1784,21 @@ impl App {
)));
}
}
+ // Like a route review, the launch review replaces the project form that asked for
+ // it, so a form that the user closed meanwhile stays closed.
+ (Some(ActionKind::PreviewLaunch), Ok(reply)) if popup_matches => {
+ if matches!(self.popup, Some(Popup::Form(_)))
+ && let Some(launch) = action.and_then(|action| reviewed(action, &reply.data))
+ {
+ self.set_popup(Some(Popup::review(
+ launch_lines(self.theme, &reply.data),
+ "Launch",
+ FormKind::Confirm("LAUNCH".into(), Box::new(launch)),
+ "Start this session?",
+ "Type LAUNCH to start it",
+ )));
+ }
+ }
(Some(ActionKind::Models), Ok(reply)) if popup_matches => {
let models: Vec<&str> = reply.data["models"]
.as_array()
@@ -1833,6 +1962,7 @@ impl App {
(None, false, Tab::Models) => MODELS_KEYS,
(None, false, Tab::Routes) => ROUTES_KEYS,
(None, false, Tab::Harnesses) => HARNESSES_KEYS,
+ (None, false, Tab::Sessions) => SESSIONS_KEYS,
(None, false, Tab::Settings) => SETTINGS_KEYS,
}
}
@@ -1882,7 +2012,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'..='6') => {
+ KeyCode::Char(digit @ '1'..='7') => {
self.tab = TABS[digit as usize - '1' as usize];
}
KeyCode::Tab | KeyCode::Right => self.tab = TABS[(self.tab.index() + 1) % TABS.len()],
@@ -1902,7 +2032,11 @@ impl App {
self.route_filter.clear();
self.refilter();
}
- Tab::Overview | Tab::Models | Tab::Harnesses | Tab::Settings => {}
+ Tab::Overview
+ | Tab::Models
+ | Tab::Harnesses
+ | Tab::Sessions
+ | Tab::Settings => {}
}
}
code => {
@@ -1927,6 +2061,7 @@ impl App {
},
Tab::Routes => self.routes_key(code),
Tab::Harnesses => self.harnesses_key(code),
+ Tab::Sessions => self.sessions_key(code),
Tab::Settings => return self.settings_key(code),
}
}
@@ -1977,8 +2112,8 @@ 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) {
+ /// harness. The Harnesses and Sessions pages share these keys and the selection.
+ fn selection_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;
@@ -1999,20 +2134,34 @@ impl App {
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 harnesses_key(&mut self, code: KeyCode) {
+ if code != KeyCode::Char('x') {
+ return self.selection_key(code);
+ }
+ 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(),
+ )],
+ ))));
+ }
+
+ /// The `s` key selects the next recorded session. Without a selection, it selects the
+ /// newest one.
+ fn sessions_key(&mut self, code: KeyCode) {
+ if code != KeyCode::Char('s') {
+ return self.selection_key(code);
+ }
+ let count = self.data.session_inventory.len().max(1);
+ self.managed = Some(self.managed.map_or(0, |index| (index + 1) % count));
+ }
+
fn filter_key(&mut self, key: KeyEvent) {
let control = key.modifiers.contains(KeyModifiers::CONTROL);
match key.code {
@@ -2231,6 +2380,26 @@ impl App {
let archive = Action::PreviewAccountArchive { tool, name };
request(archive, "Reviewing the account archive")
}
+ // The project form submits PreviewLaunch, and the review window submits Launch.
+ ActionKind::PreviewLaunch | ActionKind::Launch => {
+ let harness = self.harness()?;
+ let route = self.selected_route()?;
+ let title = format!(
+ "Launch a worktree session · {} · {}",
+ harness.label, route.label
+ );
+ let kind = FormKind::Project {
+ tool: harness.tool,
+ account: self.account(),
+ route: route.key.clone(),
+ id: route.id.clone(),
+ };
+ self.open(Form::new(
+ kind,
+ title,
+ vec![("Git project folder", String::new())],
+ ))
+ }
ActionKind::OpenConfig => request(Action::OpenConfig {}, "Opening the server config"),
ActionKind::CheckConfig => {
request(Action::CheckConfig {}, "Checking the server config")
@@ -2498,6 +2667,22 @@ fn age(ts: &str, now: DateTime<Utc>) -> String {
}
}
+/// This function shows a recorded time in local time with its age, or the recorded text when it
+/// is not an RFC 3339 time.
+fn local_time(ts: &str) -> String {
+ DateTime::parse_from_rfc3339(ts).map_or_else(
+ |_| ts.to_string(),
+ |time| {
+ format!(
+ "{} ({})",
+ time.with_timezone(&chrono::Local)
+ .format("%Y-%m-%d %H:%M:%S"),
+ age(ts, Utc::now())
+ )
+ },
+ )
+}
+
fn server_state(theme: Theme, running: bool) -> [Span<'static>; 2] {
[
Span::styled("● ", if running { theme.ok } else { theme.error }),
@@ -2575,6 +2760,10 @@ fn draw(frame: &mut Frame, app: &mut App) {
limited: _, // calls_block and draw_activity show this limit.
errors: _, // draw_errors
refresh_seconds: _, // App::refresh_due
+ // draw_session_table lists the inventory or shows the error that stopped reading it,
+ // and session_lines shows the selected session.
+ session_inventory: _,
+ session_inventory_error: _,
} = &app.data;
let area = frame.area();
app.width = area.width;
@@ -2595,6 +2784,7 @@ fn draw(frame: &mut Frame, app: &mut App) {
Tab::Models => draw_models(frame, app, body),
Tab::Routes => draw_routes(frame, app, body),
Tab::Harnesses => draw_harnesses(frame, app, body),
+ Tab::Sessions => draw_sessions(frame, app, body),
Tab::Settings => draw_settings(frame, app, body),
}
draw_status(frame, app, status);
@@ -3165,24 +3355,13 @@ fn draw_call_table(frame: &mut Frame, app: &mut App, area: Rect) {
fn detail_lines(theme: Theme, entry: &Entry) -> Vec<Line<'static>> {
let usage = ModelTokens::from(entry);
let field = |name: &str, value: String| labeled(theme, name, 9, value);
- let time = DateTime::parse_from_rfc3339(&entry.ts).map_or_else(
- |_| entry.ts.clone(),
- |time| {
- format!(
- "{} ({})",
- time.with_timezone(&chrono::Local)
- .format("%Y-%m-%d %H:%M:%S"),
- age(&entry.ts, Utc::now())
- )
- },
- );
let kind = if entry.tier == CLASSIFIER_TIER {
"Routing call (classifier or judge)"
} else {
"Answer call"
};
let mut lines = vec![
- field("Time", time),
+ field("Time", local_time(&entry.ts)),
field("Model", entry.model.clone()),
field("Kind", kind.into()),
field("Route", entry.route_id.clone()),
@@ -3808,6 +3987,211 @@ fn harness_lines(app: &App, harness: &ToolInfo) -> Vec<Line<'static>> {
lines
}
+fn draw_sessions(frame: &mut Frame, app: &App, area: Rect) {
+ let theme = app.theme;
+ let launch = Paragraph::new(new_session_lines(app)).wrap(Wrap { trim: false });
+ // The borders take two rows.
+ let rows = launch.line_count(area.width.saturating_sub(4)) as u16 + 2;
+ let [launch_area, inventory] = Layout::vertical([
+ Constraint::Length(rows.min(area.height / 2)),
+ Constraint::Fill(1),
+ ])
+ .areas(area);
+ frame.render_widget(
+ launch.block(block(theme, "New session").padding(Padding::horizontal(1))),
+ launch_area,
+ );
+ let Some(receipt) = app.selected_session() else {
+ draw_session_table(frame, app, inventory);
+ return;
+ };
+ let detail = Paragraph::new(session_lines(app, receipt)).wrap(Wrap { trim: false });
+ // The details go below the list at full width, because worktree paths are long. The list
+ // keeps its borders, header, and the selected row; the details get the rest.
+ let rows = detail.line_count(inventory.width.saturating_sub(4)) as u16 + 2;
+ let [list, detail_area] = Layout::vertical([
+ Constraint::Fill(1),
+ Constraint::Length(rows.min(inventory.height.saturating_sub(4))),
+ ])
+ .areas(inventory);
+ draw_session_table(frame, app, list);
+ let title = text(receipt, "id");
+ frame.render_widget(
+ detail.block(block(theme, &title).padding(Padding::horizontal(1))),
+ detail_area,
+ );
+}
+
+fn draw_session_table(frame: &mut Frame, app: &App, area: Rect) {
+ let theme = app.theme;
+ let sessions = &app.data.session_inventory;
+ let outer = block(theme, &format!("Recorded sessions [{}]", sessions.len()));
+ // A failed read lists no sessions, so its error replaces the empty-list text.
+ let empty = match &app.data.session_inventory_error {
+ Some(error) => Some(Line::styled(error.clone(), theme.error)),
+ None if sessions.is_empty() => Some(Line::styled(
+ "Switchyard has not recorded any managed sessions.",
+ theme.muted,
+ )),
+ None => None,
+ };
+ if let Some(line) = empty {
+ let paragraph = Paragraph::new(line).centered().wrap(Wrap { trim: false });
+ frame.render_widget(paragraph.block(outer), area);
+ return;
+ }
+ let wide = area.width >= 100;
+ let shown = |column: &(Column, bool)| wide || !column.1;
+ let now = Utc::now();
+ let rows: Vec<Row> = sessions
+ .iter()
+ .map(|receipt| {
+ let id = text(receipt, "id");
+ let last = last_call(&app.data, &id).map_or_else(|| "—".into(), |e| age(&e.ts, now));
+ let created = age(&text(receipt, "created_at"), now);
+ let cells = [
+ Cell::from(id),
+ Cell::from(Span::styled(text(receipt, "repository"), theme.muted)),
+ Cell::from(text(receipt, "route")),
+ right(Span::styled(created, theme.muted)),
+ right(last),
+ ];
+ Row::new(
+ cells
+ .into_iter()
+ .zip(&SESSION_COLUMNS)
+ .filter(|(_, column)| shown(column))
+ .map(|(cell, _)| cell),
+ )
+ })
+ .collect();
+ let columns: Vec<Column> = SESSION_COLUMNS
+ .iter()
+ .filter(|column| shown(column))
+ .map(|column| column.0)
+ .collect();
+ let selected = app.managed.filter(|&index| index < sessions.len());
+ let mut state = TableState::default().with_selected(selected);
+ frame.render_stateful_widget(
+ table(theme, &columns, rows)
+ .row_highlight_style(theme.selected)
+ .highlight_symbol("› ")
+ .block(outer),
+ area,
+ &mut state,
+ );
+}
+
+/// This function shows what the l key launches: the harness, the account, the route, and
+/// whether the harness can use the route.
+fn new_session_lines(app: &App) -> Vec<Line<'static>> {
+ const WIDTH: usize = 9;
+ let theme = app.theme;
+ let field = |name: &str, value: Span<'static>| {
+ Line::from(vec![
+ Span::styled(format!("{name:<WIDTH$}"), theme.muted),
+ value,
+ ])
+ };
+ let mut lines = Vec::new();
+ match app.harness() {
+ Ok(harness) => {
+ let (state, style) = if harness.available {
+ ("Detected", theme.ok)
+ } else {
+ ("Not detected", theme.warn)
+ };
+ lines.push(Line::from(vec![
+ Span::styled(format!("{:<WIDTH$}", "Harness"), theme.muted),
+ Span::raw(format!("{} · ", harness.label)),
+ Span::styled(state, style),
+ ]));
+ if harness.tool == Harness::CodexApp {
+ lines.push(Line::styled(
+ "Codex app workspaces are managed in the Codex app. Press t to choose a \
+ command line harness.",
+ theme.warn,
+ ));
+ }
+ let account = match &app.destination {
+ Destination::Account(name) => {
+ match harness.account_details.iter().find(|a| a.name == *name) {
+ Some(account) => Span::raw(format!(
+ "{name} · login status {} · {}",
+ account.login_status,
+ account.path.display()
+ )),
+ None => Span::styled(
+ format!("{name} is no longer listed. Press a to choose another."),
+ theme.warn,
+ ),
+ }
+ }
+ Destination::Harness | Destination::File(_) => Span::raw("Current login"),
+ };
+ lines.push(field("Account", account));
+ match app.selected_route() {
+ Ok(route) => {
+ lines.push(field("Route", Span::raw(route.label.clone())));
+ match route.compatibility.get(&harness.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(field("Route", Span::styled(error, theme.warn))),
+ }
+ }
+ Err(error) => lines.push(Line::styled(error, theme.warn)),
+ }
+ lines.extend([
+ Line::default(),
+ Line::styled(
+ "Each session is a new Git worktree from the project's committed HEAD, on its own \
+ branch. Uncommitted changes stay in the original checkout.",
+ theme.muted,
+ ),
+ ]);
+ lines
+}
+
+/// This function shows where the selected session lives and its newest recorded call.
+fn session_lines(app: &App, receipt: &Value) -> Vec<Line<'static>> {
+ let theme = app.theme;
+ let field = |name: &str, value: String| labeled(theme, name, 11, value);
+ let last = last_call(&app.data, receipt["id"].as_str().unwrap_or_default());
+ vec![
+ field("Repository", text(receipt, "repository")),
+ field("Branch", text(receipt, "branch")),
+ field("Route", text(receipt, "route")),
+ field("Worktree", text(receipt, "worktree")),
+ field("Created", local_time(&text(receipt, "created_at"))),
+ field(
+ "Last call",
+ last.map_or_else(
+ || "No recent recorded call".into(),
+ |entry| local_time(&entry.ts),
+ ),
+ ),
+ Line::default(),
+ Line::styled(
+ "Recorded calls do not establish that a process is running.",
+ theme.muted,
+ ),
+ ]
+}
+
+/// This function returns the session's newest call among the calls that the app loaded.
+fn last_call<'a>(data: &'a Snapshot, id: &str) -> Option<&'a Entry> {
+ let session = Some(id);
+ data.entries
+ .iter()
+ .rev()
+ .find(|entry| entry.session_id.as_deref() == session)
+}
+
/// 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 {
@@ -4288,6 +4672,14 @@ fn form_notes(app: &App, form: &Form) -> Vec<Line<'static>> {
),
Line::default(),
],
+ FormKind::Project { .. } => vec![
+ Line::from(
+ "Switchyard creates a Git worktree from the folder's committed HEAD and opens \
+ the harness there in a new terminal window. Uncommitted changes stay in the \
+ original checkout. The next step shows the review.",
+ ),
+ Line::default(),
+ ],
FormKind::Preferences
| FormKind::Update(_)
| FormKind::Confirm(..)
@@ -4447,6 +4839,51 @@ fn archive_lines(theme: Theme, preview: &Value) -> Vec<Line<'static>> {
]
}
+/// This function returns a text field of a controller reply, or `fallback` when it is empty
+/// or missing.
+fn text_or(value: &Value, key: &str, fallback: &str) -> String {
+ match value[key].as_str() {
+ Some(text) if !text.is_empty() => text.into(),
+ _ => fallback.into(),
+ }
+}
+
+/// This function shows a launch preview: where the session starts, what it uses, and what
+/// stays in the original checkout.
+fn launch_lines(theme: Theme, preview: &Value) -> Vec<Line<'static>> {
+ let field = |name: &str, value: String| labeled(theme, name, 17, value);
+ let folder = text(preview, "relative_directory");
+ let folder = if folder.is_empty() {
+ "New worktree root".into()
+ } else {
+ format!("{folder} within the new worktree")
+ };
+ let mut lines = vec![
+ field("Repository", text(preview, "repository")),
+ field("Starting folder", folder),
+ field("Branch", text_or(preview, "branch", "Detached HEAD")),
+ field("Revision", text(preview, "revision")),
+ field("Route", text(preview, "route")),
+ field(
+ "Account",
+ text_or(preview, "account_directory", "Current login"),
+ ),
+ Line::default(),
+ ];
+ if preview["dirty"] == true {
+ lines.push(Line::styled(
+ "Your checkout has uncommitted changes.",
+ theme.warn,
+ ));
+ }
+ lines.push(Line::from(text(preview, "notice")));
+ let settings = text(preview, "settings_notice");
+ if !settings.is_empty() {
+ lines.extend([Line::default(), Line::from(settings)]);
+ }
+ 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| {
@@ -4499,6 +4936,7 @@ fn help_lines(theme: Theme, width: usize) -> Vec<Line<'static>> {
("Models", MODELS_KEYS, Some(Tab::Models)),
("Routes", ROUTES_KEYS, Some(Tab::Routes)),
("Harnesses", HARNESSES_KEYS, Some(Tab::Harnesses)),
+ ("Sessions", SESSIONS_KEYS, Some(Tab::Sessions)),
("Settings", SETTINGS_KEYS, Some(Tab::Settings)),
] {
if !lines.is_empty() {
@@ -5389,6 +5827,8 @@ mod tests {
Tab::Models => &['p', '[', ']'],
Tab::Routes => &['/'],
Tab::Harnesses => &['t', 'a', 'x'],
+ // The arrows choose the route here, so k must keep moving it.
+ Tab::Sessions => &['t', 'a', 's', 'k'],
Tab::Overview | Tab::Settings => &[],
}
};
diff --git a/crates/switchyard-desktop/tests/windows_terminal.rs b/crates/switchyard-desktop/tests/windows_terminal.rs
new file mode 100644
index 000000000..2242174fd
--- /dev/null
+++ b/crates/switchyard-desktop/tests/windows_terminal.rs
@@ -0,0 +1,70 @@
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+#![cfg(windows)]
+
+#[test]
+fn native_and_npm_launchers_preserve_arguments_accounts_and_working_directory() {
+ use std::{
+ fs,
+ process::{Command, Stdio},
+ };
+ let root = tempfile::Builder::new()
+ .prefix("Terminal équipe space ")
+ .tempdir()
+ .expect("fixture");
+ let source = root.path().join("tool.rs");
+ fs::write(&source,r#"fn main() {
+ let output=std::env::var_os("FIXTURE_OUTPUT").unwrap();
+ let text=format!("{:?}\n{:?}\n{:?}\n{:?}",std::env::args().skip(1).collect::<Vec<_>>(),std::env::current_dir().unwrap(),std::env::var("CODEX_HOME"),std::env::var("ANTHROPIC_AUTH_TOKEN"));
+ std::fs::write(output,text).unwrap();
+ }"#).expect("tool source");
+ let tool = root.path().join("tool.exe");
+ assert!(
+ Command::new("rustc")
+ .arg(&source)
+ .arg("-o")
+ .arg(&tool)
+ .status()
+ .expect("compile fixture")
+ .success()
+ );
+ let shim = root.path().join("tool.cmd");
+ fs::write(&shim, "@echo off\r\n@\"%~dp0tool.exe\" %*\r\n").expect("npm shim");
+ let args = vec![
+ "space équipe".to_string(),
+ "a\"b".into(),
+ "%PATH%".into(),
+ "& echo injected > forbidden-file".into(),
+ "C:\\space équipe\\".into(),
+ "<input>|output^".into(),
+ ];
+ let output = root.path().join("arguments.txt");
+ let account = root.path().join("account équipe space");
+ for binary in [tool, shim] {
+ let launch = root.path().join("launch.json");
+ fs::write(&launch,serde_json::to_vec(&serde_json::json!({"binary":binary,"args":args,"directory":root.path(),"environment":[["CODEX_HOME",account.display().to_string()],["FIXTURE_OUTPUT",output.display().to_string()]],"remove_environment":["ANTHROPIC_AUTH_TOKEN"]})).expect("launch JSON")).expect("launch record");
+ let result = Command::new(env!("CARGO_BIN_EXE_switchyard-desktop"))
+ .arg("--terminal-job")
+ .arg(&launch)
+ .env("ANTHROPIC_AUTH_TOKEN", "must-be-removed")
+ .stdin(Stdio::null())
+ .output()
+ .expect("terminal job");
+ assert!(
+ result.status.success(),
+ "terminal launch failed for {binary:?}: status={:?}; stdout={}; stderr={}",
+ result.status,
+ String::from_utf8_lossy(&result.stdout),
+ String::from_utf8_lossy(&result.stderr)
+ );
+ let captured = fs::read_to_string(&output).expect("captured tool launch");
+ assert!(captured.starts_with(&format!("{args:?}\n")), "{captured}");
+ assert!(captured.contains(&format!("Ok({:?})", account.display().to_string())));
+ assert!(captured.contains("NotPresent"));
+ assert!(captured.contains(&format!("{:?}", root.path())));
+ assert!(!launch.exists());
+ assert!(!root.path().join("forbidden-file").exists());
+ fs::remove_file(&output).expect("reset output");
+ }
+}