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): add named harness accounts to the Harnesses page (#1106)

Elyas Mehtabuddin3204554a1d99
diff --git a/crates/switchyard-desktop/src/accounts.rs b/crates/switchyard-desktop/src/accounts.rs
index 0b34bb7f9..58d2a862d 100644
--- a/crates/switchyard-desktop/src/accounts.rs
+++ b/crates/switchyard-desktop/src/accounts.rs
@@ -6,6 +6,18 @@
use crate::harness::{self, Harness};
use std::path::{Path, PathBuf};
+// PendingAccount removes only an empty directory if login setup fails.
+// The harness may already have saved login files, which must stay.
+struct PendingAccount(Option<PathBuf>);
+
+impl Drop for PendingAccount {
+ fn drop(&mut self) {
+ if let Some(path) = &self.0 {
+ let _ = std::fs::remove_dir(path);
+ }
+ }
+}
+
fn root(tool: Harness) -> Result<PathBuf, String> {
let name = match tool {
Harness::CodexCli => "codex",
@@ -88,3 +100,95 @@ pub fn config_paths(tool: Harness, account: Option<&Path>) -> Result<Vec<PathBuf
_ => harness::paths(tool),
}
}
+
+pub fn add(tool: Harness, name: &str) -> Result<String, String> {
+ if name.is_empty()
+ || name.len() > 64
+ || !name
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
+ {
+ return Err("Account names need 1–64 letters, numbers, hyphens, or underscores.".into());
+ }
+ let root = root(tool)?;
+ harness::binary(tool).ok_or("Install the selected harness first.")?;
+ std::fs::create_dir_all(&root).map_err(|e| e.to_string())?;
+ let path = root.join(name);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::DirBuilderExt;
+ std::fs::DirBuilder::new()
+ .mode(0o700)
+ .create(&path)
+ .map_err(|e| {
+ format!(
+ "Create account: {e}. \
+ Pick an existing account after Refresh, or choose a new name."
+ )
+ })?;
+ }
+ #[cfg(not(unix))]
+ std::fs::create_dir(&path).map_err(|e| e.to_string())?;
+ let mut pending = PendingAccount(Some(path.clone()));
+ login(tool, &path, name)?;
+ pending.0 = None;
+ Ok(format!(
+ "Opened the harness's login in Terminal for account {name}. Complete login, \
+ click Refresh, and select this account. Switchyard does not read the login tokens. \
+ The selected account applies to new sessions only. Account directory: {}",
+ path.display()
+ ))
+}
+
+pub fn login(tool: Harness, path: &Path, name: &str) -> Result<String, String> {
+ validate(tool, path)?;
+ let binary = harness::binary(tool).ok_or("Install the selected harness first.")?;
+ let variable = match tool {
+ Harness::CodexCli => "CODEX_HOME",
+ Harness::Claude => "CLAUDE_CONFIG_DIR",
+ _ => return Err("Choose a supported harness.".into()),
+ };
+ #[cfg(windows)]
+ crate::windows::open_terminal(crate::windows::TerminalJob {
+ binary: binary.clone(),
+ args: match tool {
+ Harness::CodexCli => vec!["login".into()],
+ _ => vec!["auth".into(), "login".into()],
+ },
+ directory: None,
+ environment: vec![(variable.into(), path.display().to_string())],
+ remove_environment: vec![],
+ })?;
+ #[cfg(not(windows))]
+ {
+ let login = match tool {
+ Harness::CodexCli => "login",
+ _ => "auth login",
+ };
+ let script = format!(
+ "#!/usr/bin/env bash\n\
+ rm -- \"$0\"\n\
+ export PATH=\"/opt/homebrew/bin:/usr/local/bin:$PATH\"\n\
+ export {variable}={}\n\
+ {} {login}",
+ crate::sessions::quote(&path.display().to_string()),
+ crate::sessions::quote(&binary.display().to_string())
+ );
+ crate::server::open_terminal_script("switchyard-login-", &script)?;
+ }
+ Ok(format!(
+ "Opened login in Terminal for account {name}. Finish login in the harness. \
+ Login status remains unknown until the harness confirms it."
+ ))
+}
+
+pub fn archive(tool: Harness, path: &Path) -> Result<String, String> {
+ validate(tool, path)?;
+ let archived = path.with_file_name(format!(".archived-{}", uuid::Uuid::now_v7()));
+ std::fs::rename(path, &archived).map_err(|error| error.to_string())?;
+ Ok(format!(
+ "Archived the account folder at {}. Login files are preserved. \
+ Existing sessions may still use the old directory and need a new login.",
+ archived.display()
+ ))
+}
diff --git a/crates/switchyard-desktop/src/controller.rs b/crates/switchyard-desktop/src/controller.rs
index d39144390..16ed9f7f5 100644
--- a/crates/switchyard-desktop/src/controller.rs
+++ b/crates/switchyard-desktop/src/controller.rs
@@ -97,6 +97,27 @@ pub enum Action {
settings_file: Option<String>,
preview_token: Option<String>,
},
+ AddAccount {
+ tool: Harness,
+ name: String,
+ },
+ LoginAccount {
+ tool: Harness,
+ name: String,
+ },
+ PreviewAccountArchive {
+ tool: Harness,
+ name: String,
+ },
+ ArchiveAccount {
+ tool: Harness,
+ name: String,
+ preview_token: Option<String>,
+ },
+ OpenAccount {
+ tool: Harness,
+ name: String,
+ },
Restart {},
PreviewUpdate {},
Update {
@@ -402,7 +423,7 @@ 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)>,
}
@@ -416,7 +437,7 @@ impl Controller {
generation: 0,
route_reviews: Default::default(),
tool_review: None,
-
+ account_archive: None,
route_change: None,
update_review: None,
}
@@ -749,7 +770,9 @@ 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.
+ Action::OpenAccount { tool, name } => account_path(*tool, Some(name)),
_ => Ok(None),
}
}
@@ -1081,6 +1104,52 @@ impl Controller {
Err(error) => Err(error),
}
}
+ Action::AddAccount { tool, name } => {
+ accounts::add(tool, name.trim()).map(Reply::message)
+ }
+ Action::LoginAccount { tool, name } => {
+ let path = account_path(tool, Some(&name))?.ok_or("Choose an account.")?;
+ accounts::login(tool, &path, &name).map(Reply::message)
+ }
+ Action::PreviewAccountArchive { tool, name } => {
+ let path = account_path(tool, Some(&name))?.ok_or("Choose an account.")?;
+ let token = uuid::Uuid::now_v7().to_string();
+ self.account_archive = Some((tool, name.clone(), token.clone()));
+ Ok(Reply {
+ message: String::new(),
+ data: json!({
+ "name": name,
+ "path": path,
+ "preview_token": token,
+ "notice": "Archive moves this account out of the picker and preserves all \
+ login files. Existing sessions using its old directory may \
+ need a new login."
+ }),
+ })
+ }
+ Action::ArchiveAccount {
+ tool,
+ name,
+ preview_token,
+ } => {
+ let (expected_tool, expected_name, token) = self
+ .account_archive
+ .as_ref()
+ .ok_or("Review account archive first.")?;
+ if tool != *expected_tool
+ || name != *expected_name
+ || preview_token.as_deref() != Some(token.as_str())
+ {
+ return Err("Review account archive again.".into());
+ }
+ let path = account_path(tool, Some(&name))?.ok_or("Choose an account.")?;
+ accounts::archive(tool, &path).map(Reply::message)
+ }
+ Action::OpenAccount { tool, name } => {
+ let path = account_path(tool, Some(&name))?.ok_or("Choose an account.")?;
+ server::command("open", &[&path.display().to_string()])?;
+ Ok(Reply::message("Opened the account folder.".into()))
+ }
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())),
diff --git a/crates/switchyard-desktop/src/main.rs b/crates/switchyard-desktop/src/main.rs
index df0985779..d3be66918 100644
--- a/crates/switchyard-desktop/src/main.rs
+++ b/crates/switchyard-desktop/src/main.rs
@@ -17,6 +17,7 @@ mod models;
mod pricing;
mod server;
mod server_config;
+mod sessions;
mod summary;
mod tui;
#[cfg(windows)]
@@ -53,6 +54,17 @@ Recorded spending remains visible when savings are unknown.";
/// The command selects the graphical app, terminal app, printed summary, or TOML validation.
fn main() -> ExitCode {
+ #[cfg(windows)]
+ if let Some(result) = windows::terminal_job() {
+ return match result {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(error) => {
+ eprintln!("switchyard-desktop: {error}");
+ ExitCode::FAILURE
+ }
+ };
+ }
+
#[cfg(windows)]
windows::attach_console();
let mut settings = None;
diff --git a/crates/switchyard-desktop/src/server.rs b/crates/switchyard-desktop/src/server.rs
index c9b0d4968..4ff8072f6 100644
--- a/crates/switchyard-desktop/src/server.rs
+++ b/crates/switchyard-desktop/src/server.rs
@@ -504,6 +504,133 @@ pub fn command(program: &str, args: &[&str]) -> Result<String, String> {
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
+// This function saves the script before opening a terminal so a save error cannot launch it.
+// Callers supply scripts that remove themselves on startup, so the script's absence shows that
+// a terminal started it. If none does in time, this function removes the script itself, so a
+// terminal that starts later finds nothing to run.
+#[cfg(not(windows))]
+pub fn open_terminal_script(prefix: &str, text: &str) -> Result<(), String> {
+ let mut script = tempfile::Builder::new()
+ .prefix(prefix)
+ .suffix(".command")
+ .tempfile()
+ .map_err(|e| e.to_string())?;
+ writeln!(script, "{text}").map_err(|e| e.to_string())?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ script
+ .as_file()
+ .set_permissions(std::fs::Permissions::from_mode(0o700))
+ .map_err(|e| e.to_string())?;
+ }
+ let (_, path) = script.keep().map_err(|e| e.to_string())?;
+ if let Err(error) = run_in_terminal(&path) {
+ return match std::fs::remove_file(&path) {
+ // The terminal started the script after the wait ended.
+ Err(removed) if removed.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ _ => Err(error),
+ };
+ }
+ Ok(())
+}
+
+/// A terminal has this long to start the script before the launch counts as failed.
+#[cfg(not(windows))]
+const TERMINAL_START: std::time::Duration = std::time::Duration::from_secs(15);
+
+#[cfg(not(windows))]
+enum Start {
+ Started,
+ /// The terminal program exited with an error before it started the script.
+ Failed,
+ TimedOut,
+}
+
+#[cfg(not(windows))]
+fn wait_for_start(path: &Path, mut terminal: Option<&mut std::process::Child>) -> Start {
+ let deadline = std::time::Instant::now() + TERMINAL_START;
+ loop {
+ if !path.exists() {
+ return Start::Started;
+ }
+ // A launcher such as gnome-terminal exits successfully before its window runs the
+ // script, so only a failed exit ends the wait early.
+ if let Some(terminal) = terminal.as_deref_mut()
+ && matches!(terminal.try_wait(), Ok(Some(status)) if !status.success())
+ {
+ return Start::Failed;
+ }
+ if std::time::Instant::now() >= deadline {
+ return Start::TimedOut;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ }
+}
+
+#[cfg(not(windows))]
+fn timed_out() -> String {
+ format!(
+ "The terminal did not start within {} seconds. Nothing was run.",
+ TERMINAL_START.as_secs()
+ )
+}
+
+// macOS `open` runs a `.command` file in Terminal.
+#[cfg(not(any(windows, target_os = "linux")))]
+fn run_in_terminal(path: &Path) -> Result<(), String> {
+ command("open", &[&path.display().to_string()])?;
+ match wait_for_start(path, None) {
+ Start::Started => Ok(()),
+ Start::Failed | Start::TimedOut => Err(timed_out()),
+ }
+}
+
+// xdg-open may open the script in an editor, so this function starts a terminal program that runs it.
+// It tries $TERMINAL first and then common terminal programs, and uses the first one that runs it.
+#[cfg(target_os = "linux")]
+fn run_in_terminal(path: &Path) -> Result<(), String> {
+ let preferred = std::env::var("TERMINAL")
+ .ok()
+ .filter(|name| !name.is_empty());
+ let terminals = preferred
+ .as_deref()
+ .map(|name| (name, "-e"))
+ .into_iter()
+ .chain([
+ ("x-terminal-emulator", "-e"),
+ ("gnome-terminal", "--"),
+ ("konsole", "-e"),
+ ("xterm", "-e"),
+ ]);
+ for (program, flag) in terminals {
+ let Ok(mut terminal) = Command::new(program)
+ .arg(flag)
+ .arg(path)
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ else {
+ continue;
+ };
+ let start = wait_for_start(path, Some(&mut terminal));
+ // A thread waits for the terminal so the exited process does not stay a zombie.
+ std::thread::spawn(move || terminal.wait());
+ match start {
+ Start::Started => return Ok(()),
+ Start::Failed => continue,
+ Start::TimedOut => return Err(timed_out()),
+ }
+ }
+ Err(
+ "Could not start a terminal. Switchyard tried $TERMINAL, x-terminal-emulator, \
+ gnome-terminal, konsole, and xterm. Set the TERMINAL environment variable to your \
+ terminal program, for example TERMINAL=xterm, and try again."
+ .into(),
+ )
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/switchyard-desktop/src/sessions.rs b/crates/switchyard-desktop/src/sessions.rs
new file mode 100644
index 000000000..ebdd58585
--- /dev/null
+++ b/crates/switchyard-desktop/src/sessions.rs
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+pub(crate) fn quote(text: &str) -> String {
+ format!("'{}'", text.replace('\'', "'\\''"))
+}
diff --git a/crates/switchyard-desktop/src/tui.rs b/crates/switchyard-desktop/src/tui.rs
index 90b498b28..6d7f4a194 100644
--- a/crates/switchyard-desktop/src/tui.rs
+++ b/crates/switchyard-desktop/src/tui.rs
@@ -11,6 +11,7 @@ use crate::controller::{
AccountInfo, Action, ActionKind, AppSettings, Availability, Controller, Dependent, Reply,
RouteInfo, Snapshot, ToolInfo,
};
+use crate::harness::Harness;
use crate::history::Entry;
use crate::pricing::Estimate;
use crate::rollup::{CLASSIFIER_TIER, ModelTokens, Totals, Usage};
@@ -251,6 +252,38 @@ const ACTIONS: &[ActionRow] = &[
type RESTORE.",
&[ActionKind::PreviewRestore, ActionKind::Restore],
),
+ (
+ Tab::Harnesses,
+ 'n',
+ "add account",
+ "Creates a saved account and opens the harness's login in a new terminal window.",
+ &[ActionKind::AddAccount],
+ ),
+ (
+ Tab::Harnesses,
+ 'l',
+ "login",
+ "Opens the selected account's login again in a new terminal window.",
+ &[ActionKind::LoginAccount],
+ ),
+ (
+ Tab::Harnesses,
+ 'o',
+ "open account",
+ "Opens the selected account folder in $VISUAL or $EDITOR.",
+ &[ActionKind::OpenAccount],
+ ),
+ (
+ Tab::Harnesses,
+ 'd',
+ "archive",
+ "Moves the selected account out of the list after you type its name. Its login files \
+ are kept.",
+ &[
+ ActionKind::PreviewAccountArchive,
+ ActionKind::ArchiveAccount,
+ ],
+ ),
(
Tab::Settings,
'o',
@@ -550,6 +583,8 @@ 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>),
+ /// The harness is the one selected when the form opened.
+ Account(Harness),
SettingsFile,
}
/// Choices names the list that ↑ and ↓ cycle through in a form field.
@@ -841,6 +876,10 @@ impl Form {
key: Some(self.value(1)),
base_url: urls.get(&self.value(0)).cloned(),
},
+ FormKind::Account(tool) => Action::AddAccount {
+ tool: *tool,
+ name: self.value(0),
+ },
FormKind::SettingsFile => {
let path = self.value(0);
if !path.is_empty() && !std::path::Path::new(&path).is_absolute() {
@@ -866,13 +905,13 @@ impl Form {
FormKind::Confirm(_, action) => match **action {
Action::Install { .. } => "Installing the harness settings",
Action::Restore { .. } => "Restoring the harness settings",
-
+ Action::ArchiveAccount { .. } => "Archiving the account",
_ => "Saving the route",
},
FormKind::Remove { .. } => "Deleting the route",
FormKind::Models => "Loading models",
FormKind::ModelKey(_) => "Saving the key and loading models",
-
+ FormKind::Account(_) => "Adding the account",
FormKind::SettingsFile => "Choosing the settings file",
}
}
@@ -1003,6 +1042,11 @@ fn reviewed(previewed: Action, preview: &Value) -> Option<Action> {
settings_file,
preview_token,
},
+ Action::PreviewAccountArchive { tool, name } => Action::ArchiveAccount {
+ tool,
+ name,
+ preview_token,
+ },
_ => return None,
})
}
@@ -1321,6 +1365,14 @@ impl App {
}
}
+ /// Account actions change one saved account, so this function rejects other destinations.
+ fn selected_account(&self) -> Result<(Harness, String), String> {
+ let name = self
+ .account()
+ .ok_or("Press a to select a saved account first.")?;
+ Ok((self.harness()?.tool, name))
+ }
+
/// This function builds the install preview of the selected route for the selected
/// harness and destination.
fn install_action(&self) -> Result<Action, String> {
@@ -1471,6 +1523,8 @@ impl App {
// Saved settings no longer match an earlier diff, and a failed preview has none.
(Some(Action::Install { .. } | Action::Restore { .. }), true)
| (Some(Action::PreviewInstall { .. }), false) => self.install_preview = None,
+ // The archived account leaves the list, so the harness's own settings are next.
+ (Some(Action::ArchiveAccount { .. }), true) => self.destination = Destination::Harness,
_ => {}
}
match (kind, reply) {
@@ -1558,6 +1612,20 @@ impl App {
)));
}
}
+ (Some(ActionKind::PreviewAccountArchive), Ok(reply)) if popup_matches => {
+ if let Some(archive) = action.and_then(|action| reviewed(action, &reply.data))
+ && let Action::ArchiveAccount { name, .. } = &archive
+ {
+ let name = name.clone();
+ self.set_popup(Some(Popup::review(
+ archive_lines(self.theme, &reply.data),
+ "Archive",
+ FormKind::Confirm(name.clone().into(), Box::new(archive)),
+ format!("Archive the account {name}?"),
+ "Type the account name to archive",
+ )));
+ }
+ }
// 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 => {
@@ -2135,6 +2203,34 @@ impl App {
};
request(restore, "Reading the original settings")
}
+ ActionKind::AddAccount => {
+ let harness = self.harness()?;
+ let title = format!("Sign in to another {} account", harness.label);
+ let kind = FormKind::Account(harness.tool);
+ self.open(Form::new(
+ kind,
+ title,
+ vec![("Account name", String::new())],
+ ))
+ }
+ ActionKind::LoginAccount => {
+ let (tool, name) = self.selected_account()?;
+ request(Action::LoginAccount { tool, name }, "Opening the login")
+ }
+ // Controller::editor_target returns the account folder, so it opens in the editor.
+ ActionKind::OpenAccount => {
+ let (tool, name) = self.selected_account()?;
+ request(
+ Action::OpenAccount { tool, name },
+ "Opening the account folder",
+ )
+ }
+ // The review window names the account folder and submits ArchiveAccount.
+ ActionKind::PreviewAccountArchive | ActionKind::ArchiveAccount => {
+ let (tool, name) = self.selected_account()?;
+ let archive = Action::PreviewAccountArchive { tool, name };
+ request(archive, "Reviewing the account archive")
+ }
ActionKind::OpenConfig => request(Action::OpenConfig {}, "Opening the server config"),
ActionKind::CheckConfig => {
request(Action::CheckConfig {}, "Checking the server config")
@@ -4184,6 +4280,14 @@ fn form_notes(app: &App, form: &Form) -> Vec<Line<'static>> {
),
Line::default(),
],
+ FormKind::Account(_) => vec![
+ Line::from(
+ "Use 1–64 ASCII letters, digits, hyphens, or underscores. Login opens in a new \
+ terminal window; finish it there. API routes use credentials configured on \
+ the server. The Codex app manages its own account.",
+ ),
+ Line::default(),
+ ],
FormKind::Preferences
| FormKind::Update(_)
| FormKind::Confirm(..)
@@ -4334,6 +4438,15 @@ fn restore_lines(theme: Theme, preview: &Value) -> Vec<Line<'static>> {
lines
}
+fn archive_lines(theme: Theme, preview: &Value) -> Vec<Line<'static>> {
+ vec![
+ Line::from(text(preview, "notice")),
+ Line::default(),
+ labeled(theme, "Account", 11, text(preview, "name")),
+ labeled(theme, "Directory", 11, text(preview, "path")),
+ ]
+}
+
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| {
diff --git a/crates/switchyard-desktop/src/windows.rs b/crates/switchyard-desktop/src/windows.rs
index d36a5e7f7..e61326e75 100644
--- a/crates/switchyard-desktop/src/windows.rs
+++ b/crates/switchyard-desktop/src/windows.rs
@@ -1,7 +1,13 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
-use std::path::PathBuf;
+//! Harnesses run in their own Windows console with explicit arguments and account directories.
+
+use serde::{Deserialize, Serialize};
+use std::{
+ path::{Path, PathBuf},
+ process::Command,
+};
/// This function reads current-user MSIX registrations without launching or changing the Codex app.
pub fn codex_app() -> Option<PathBuf> {
@@ -22,6 +28,38 @@ pub fn codex_app() -> Option<PathBuf> {
None
}
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct TerminalJob {
+ pub binary: PathBuf,
+ pub args: Vec<String>,
+ pub directory: Option<PathBuf>,
+ pub environment: Vec<(String, String)>,
+ pub remove_environment: Vec<String>,
+}
+/// The child reads structured launch settings so arguments and account directories remain separate.
+pub fn open_terminal(job: TerminalJob) -> Result<(), String> {
+ use std::io::Write;
+ let mut file = tempfile::Builder::new()
+ .prefix("switchyard-terminal-")
+ .suffix(".json")
+ .tempfile()
+ .map_err(|e| e.to_string())?;
+ file.write_all(&serde_json::to_vec(&job).map_err(|e| e.to_string())?)
+ .map_err(|e| e.to_string())?;
+ let mut child = Command::new(std::env::current_exe().map_err(|e| e.to_string())?);
+ // The child deletes the file, so the file must be kept before the child starts.
+ let path = file
+ .into_temp_path()
+ .keep()
+ .map_err(|error| error.to_string())?;
+ child.arg("--terminal-job").arg(&path);
+ if let Err(error) = child.spawn() {
+ let _ = std::fs::remove_file(&path);
+ return Err(error.to_string());
+ }
+ Ok(())
+}
pub fn attach_console() {
unsafe {
windows_console(false);
@@ -49,3 +87,51 @@ unsafe fn windows_console(allocate: bool) {
}
}
}
+pub fn terminal_job() -> Option<Result<(), String>> {
+ use std::io::IsTerminal;
+ let args: Vec<_> = std::env::args_os().skip(1).collect();
+ if args.first().is_none_or(|v| v != "--terminal-job") {
+ return None;
+ }
+ Some((|| {
+ if args.len() != 2 {
+ return Err("The terminal job requires one saved launch file.".into());
+ }
+ let path = Path::new(&args[1]);
+ let job: TerminalJob =
+ serde_json::from_slice(&std::fs::read(path).map_err(|e| e.to_string())?)
+ .map_err(|e| e.to_string())?;
+ std::fs::remove_file(path).map_err(|e| e.to_string())?;
+ allocate_console();
+ let mut child = Command::new(&job.binary);
+ child.args(&job.args).envs(job.environment);
+ for name in job.remove_environment {
+ child.env_remove(name);
+ }
+ if let Some(directory) = job.directory {
+ child.current_dir(directory);
+ }
+ let (message, result) = match child.status() {
+ Ok(status) => {
+ let message = format!("Harness exited with {status}.");
+ let result = if status.success() {
+ Ok(())
+ } else {
+ Err(message.clone())
+ };
+ (message, result)
+ }
+ Err(error) => {
+ let message = format!("Could not start the harness: {error}");
+ (message.clone(), Err(message))
+ }
+ };
+ // The console closes when this process exits, so every outcome waits for Enter.
+ println!("{message} Press Enter to close this window.");
+ if std::io::stdin().is_terminal() {
+ let mut line = String::new();
+ let _ = std::io::stdin().read_line(&mut line);
+ }
+ result
+ })())
+}