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 the Settings page, server actions, and editor handoff (#1091)

Elyas Mehtabuddinb2345e8741ba
diff --git a/Cargo.lock b/Cargo.lock
index 47965ca9f..7f3c9fd98 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5407,6 +5407,7 @@ dependencies = [
"url",
"uuid",
"windows",
+ "windows-args",
"windows-sys 0.61.2",
]
@@ -7118,6 +7119,15 @@ dependencies = [
"windows-numerics",
]
+[[package]]
+name = "windows-args"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a461b757e38ae4fdf8cb97a017605010589ba4199486ced90a44ab3aade3d7e5"
+dependencies = [
+ "wtf8",
+]
+
[[package]]
name = "windows-collections"
version = "0.3.2"
@@ -7486,6 +7496,12 @@ dependencies = [
"x11-dl",
]
+[[package]]
+name = "wtf8"
+version = "0.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6b9309a86639c488a8eb2b5331cb5127cc9feb0a94a0db4b5d1ab5b84977956"
+
[[package]]
name = "x11"
version = "2.21.0"
diff --git a/crates/switchyard-desktop/Cargo.toml b/crates/switchyard-desktop/Cargo.toml
index e9f19d7d5..55d38d0bd 100644
--- a/crates/switchyard-desktop/Cargo.toml
+++ b/crates/switchyard-desktop/Cargo.toml
@@ -29,6 +29,7 @@ uuid.workspace = true
# Popups and the Data errors panel use Paragraph::line_count to size wrapped text.
ratatui = { version = "0.30.2", features = ["unstable-rendered-line-info"] }
shlex = "2"
+windows-args = "0.2"
strum = { version = "0.28", features = ["derive"] }
[target.'cfg(target_os = "macos")'.dependencies]
diff --git a/crates/switchyard-desktop/src/controller.rs b/crates/switchyard-desktop/src/controller.rs
index 6b4929da9..06b458550 100644
--- a/crates/switchyard-desktop/src/controller.rs
+++ b/crates/switchyard-desktop/src/controller.rs
@@ -4,14 +4,30 @@
//! The terminal controller reloads settings and combines usage and server health into snapshots.
//! It retains the log reader and health probe across refreshes.
-use crate::{config::Config, history, pricing, rollup};
-use serde::Serialize;
+use crate::{config::Config, history, pricing, rollup, server};
+use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::{collections::BTreeMap, path::PathBuf};
-/// Snapshot holds the terminal app's usage, recent calls, server health, errors, and refresh interval.
+#[derive(Clone, Debug, Deserialize, strum::EnumDiscriminants)]
+#[strum_discriminants(name(ActionKind), derive(strum::EnumIter))]
+#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
+pub enum Action {
+ OpenLogs {},
+ OpenUpdateLog {},
+ OpenConfig {},
+ OpenPrices {},
+ OpenSettings {},
+ CheckConfig {},
+ ServerKeys {},
+}
+
+/// Snapshot holds the data shown by the apps. The terminal app destructures every field,
+/// so adding a field requires an update to `draw`.
#[derive(Clone, Default, Serialize)]
pub struct Snapshot {
+ pub update_status: Value,
+ pub settings: Option<AppSettings>,
pub data_state: DataState,
pub metrics: Metrics,
pub today: chrono::NaiveDate,
@@ -28,6 +44,20 @@ pub struct Snapshot {
pub refresh_seconds: u64,
}
+/// AppSettings holds the app settings and their file path. `Controller::snapshot` destructures
+/// every `Config` field, so adding a setting requires an update here too.
+#[derive(Clone, Default, Serialize)]
+pub struct AppSettings {
+ pub path: PathBuf,
+ pub server_url: String,
+ pub routing_log: PathBuf,
+ pub config_file: PathBuf,
+ pub launchd_label: String,
+ pub refresh_seconds: u64,
+ pub baseline_model: String,
+ pub prices_file: Option<PathBuf>,
+}
+
#[derive(Clone, Default, Serialize)]
pub struct DataState {
pub usage: Source,
@@ -67,6 +97,20 @@ pub struct Counts {
pub tokens: u64,
}
+#[derive(Serialize)]
+pub struct Reply {
+ pub message: String,
+ pub data: Value,
+}
+impl Reply {
+ fn message(message: String) -> Self {
+ Self {
+ message,
+ data: Value::Null,
+ }
+ }
+}
+
pub struct Controller {
settings: PathBuf,
config: Config,
@@ -133,10 +177,30 @@ impl Controller {
history::History::default()
});
let activity = history::hourly_calls(&history.entries, chrono::Utc::now());
- let server_url = self.config.server_url.clone();
- let routing_log = self.config.routing_log.clone();
- let refresh_seconds = self.config.refresh_seconds;
+ let Config {
+ server_url,
+ routing_log,
+ config_file,
+ launchd_label,
+ refresh_seconds,
+ baseline_model,
+ prices_file,
+ } = self.config.clone();
+ let update_status = install_metadata(&self.settings)
+ .and_then(|path| switchyard_desktop::install::update_status(&path))
+ .unwrap_or_else(|error| json!({"state":"unavailable","message":error}));
Ok(Snapshot {
+ update_status,
+ settings: Some(AppSettings {
+ path: self.settings.clone(),
+ server_url: server_url.clone(),
+ routing_log: routing_log.clone(),
+ config_file,
+ launchd_label,
+ refresh_seconds,
+ baseline_model: baseline_model.clone(),
+ prices_file,
+ }),
data_state: DataState {
usage: Source {
state: usage_state,
@@ -165,7 +229,7 @@ impl Controller {
today,
analytics: usage,
estimates,
- baseline_model: self.config.baseline_model.clone(),
+ baseline_model,
activity,
sessions: history.sessions(),
entries: history.entries,
@@ -175,6 +239,89 @@ impl Controller {
refresh_seconds: refresh_seconds.max(1),
})
}
+ /// The TUI uses these file paths to run an editor in the foreground.
+ pub fn editor_target(&mut self, action: &Action) -> Result<Option<PathBuf>, String> {
+ match action {
+ Action::OpenSettings {} => Ok(Some(self.settings.clone())),
+ Action::OpenConfig {} => {
+ self.reload()?;
+ Ok(Some(self.config.config_file.clone()))
+ }
+ // When `prices_file` is unset, this arm returns `None` and `dispatch` describes the
+ // bundled rates.
+ Action::OpenPrices {} => {
+ self.reload()?;
+ Ok(self.config.prices_file.clone())
+ }
+ Action::OpenUpdateLog {} => self.update_log().map(Some),
+ Action::OpenLogs {} => logs_dir().map(Some),
+ _ => Ok(None),
+ }
+ }
+ fn update_log(&self) -> Result<PathBuf, String> {
+ let metadata =
+ switchyard_desktop::install::Settings::load(&install_metadata(&self.settings)?)?;
+ Ok(metadata.sy_home.join("logs/update.log"))
+ }
+ pub fn dispatch(&mut self, action: Action) -> Result<Reply, String> {
+ if matches!(action, Action::OpenSettings {}) {
+ server::command("open", &[&self.settings.display().to_string()])?;
+ return Ok(Reply::message("Opened app settings.".into()));
+ }
+ self.reload()?;
+ match action {
+ Action::OpenLogs {} => {
+ server::command("open", &[&logs_dir()?.display().to_string()])?;
+ Ok(Reply::message("Opened Switchyard logs.".into()))
+ }
+ Action::CheckConfig {} => server::check_config(&self.config)
+ .map(|()| Reply::message("Server config check passed.".into())),
+ Action::ServerKeys {} => Ok(Reply {
+ message: String::new(),
+ data: json!({"keys": server::server_keys(&self.config)?, "store": switchyard_desktop::install::credentials::STORE}),
+ }),
+ Action::OpenSettings {} => unreachable!(),
+ Action::OpenUpdateLog {} => {
+ let log = self.update_log()?;
+ server::command("open", &[&log.display().to_string()])?;
+ Ok(Reply::message("Opened the update log.".into()))
+ }
+ Action::OpenConfig {} => {
+ server::command("open", &[&self.config.config_file.display().to_string()])?;
+ Ok(Reply::message(
+ "Opened the server config in your default editor.".into(),
+ ))
+ }
+ Action::OpenPrices {} => {
+ let Some(path) = self.config.prices_file.as_ref() else {
+ return Ok(Reply::message("Bundled model prices are active. To use custom rates, set pricing_file in app settings and pass the same file to the server with --pricing-file.".into()));
+ };
+ server::command("open", &[&path.display().to_string()])?;
+ Ok(Reply::message(
+ "Opened the model prices in your default editor. Restart the server after \
+ you save them; it reads the prices when it starts."
+ .into(),
+ ))
+ }
+ }
+ }
+}
+fn logs_dir() -> Result<PathBuf, String> {
+ crate::config::expand_home(std::path::Path::new("~/.switchyard/logs"))
+}
+
+fn install_metadata(settings: &std::path::Path) -> Result<PathBuf, String> {
+ let executable = std::env::current_exe().map_err(|e| e.to_string())?;
+ let bundle = switchyard_desktop::install::bundle_metadata(&executable);
+ let metadata = if bundle.is_file() {
+ bundle
+ } else {
+ settings
+ .parent()
+ .ok_or("The settings file has no parent directory.")?
+ .join("install.toml")
+ };
+ Ok(metadata)
}
#[cfg(test)]
diff --git a/crates/switchyard-desktop/src/install/windows.rs b/crates/switchyard-desktop/src/install/windows.rs
index d5097cb39..f2ed8a78b 100644
--- a/crates/switchyard-desktop/src/install/windows.rs
+++ b/crates/switchyard-desktop/src/install/windows.rs
@@ -472,3 +472,26 @@ pub(crate) fn delete_credential(target: &str) -> Result<(), String> {
}
Ok(())
}
+
+pub fn open(value: &str) -> Result<(), String> {
+ use windows_sys::Win32::UI::{Shell::ShellExecuteW, WindowsAndMessaging::SW_SHOWNORMAL};
+ let value = wide(std::ffi::OsStr::new(value));
+ let verb = wide(std::ffi::OsStr::new("open"));
+ let status = unsafe {
+ ShellExecuteW(
+ std::ptr::null_mut(),
+ verb.as_ptr(),
+ value.as_ptr(),
+ std::ptr::null(),
+ std::ptr::null(),
+ SW_SHOWNORMAL,
+ )
+ } as isize;
+ if status > 32 {
+ Ok(())
+ } else {
+ Err(format!(
+ "Windows could not open the file or URL (error {status})."
+ ))
+ }
+}
diff --git a/crates/switchyard-desktop/src/main.rs b/crates/switchyard-desktop/src/main.rs
index 4c3e7cbc8..6e344401c 100644
--- a/crates/switchyard-desktop/src/main.rs
+++ b/crates/switchyard-desktop/src/main.rs
@@ -12,6 +12,7 @@ mod controller;
#[cfg(any(target_os = "macos", windows))]
mod gui;
mod pricing;
+mod server;
mod summary;
mod tui;
#[cfg(windows)]
diff --git a/crates/switchyard-desktop/src/server.rs b/crates/switchyard-desktop/src/server.rs
new file mode 100644
index 000000000..cdb286a04
--- /dev/null
+++ b/crates/switchyard-desktop/src/server.rs
@@ -0,0 +1,152 @@
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+//! This module checks server configs and saved key status and opens files.
+
+use std::io::Write;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+
+use switchyard_desktop::install::credentials::KeyStatus;
+
+use crate::config::Config;
+
+/// This function finds the installed helper, which is the only program that reads or writes
+/// server keys.
+fn helper() -> Result<PathBuf, String> {
+ Ok(
+ server_binary()?.with_file_name(switchyard_desktop::install::executable_name(
+ "switchyard-desktop-install",
+ )),
+ )
+}
+
+/// This function runs one of the helper's `key` commands. A key goes to the helper's standard
+/// input, never its command line, where other processes could read it.
+fn key_command(args: &[&str], key: Option<&str>) -> Result<String, String> {
+ let helper = helper()?;
+ let mut child = Command::new(&helper)
+ .arg("key")
+ .args(args)
+ .stdin(if key.is_some() {
+ Stdio::piped()
+ } else {
+ Stdio::null()
+ })
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|error| {
+ format!(
+ "Could not run {}: {error}. \
+ Run cargo desktop install from the Switchyard repository to install it.",
+ helper.display()
+ )
+ })?;
+ if let (Some(key), Some(mut stdin)) = (key, child.stdin.take()) {
+ stdin
+ .write_all(key.as_bytes())
+ .map_err(|error| format!("Could not pass the key to the helper: {error}"))?;
+ }
+ let output = child
+ .wait_with_output()
+ .map_err(|error| error.to_string())?;
+ if output.status.success() {
+ return Ok(String::from_utf8_lossy(&output.stdout).into_owned());
+ }
+ Err(String::from_utf8_lossy(&output.stderr)
+ .trim()
+ .trim_start_matches("switchyard-desktop-install: ")
+ .to_string())
+}
+
+/// This function reports which `api_key_env` variables in the server config have a saved key.
+pub fn server_keys(settings: &Config) -> Result<Vec<KeyStatus>, String> {
+ let config = std::fs::canonicalize(&settings.config_file).map_err(|error| error.to_string())?;
+ let output = key_command(&["status", "--config", &config.display().to_string()], None)?;
+ serde_json::from_str(&output).map_err(|error| error.to_string())
+}
+
+/// This function finds the installed server from the app's installation metadata.
+fn server_binary() -> Result<PathBuf, String> {
+ let executable = std::env::current_exe().map_err(|error| {
+ format!(
+ "Could not find switchyard-server next to the desktop app: {error}. \
+ Run cargo desktop install from the Switchyard repository to install it."
+ )
+ })?;
+ let metadata = switchyard_desktop::install::bundle_metadata(&executable);
+ if metadata.try_exists().map_err(|error| error.to_string())? {
+ return switchyard_desktop::install::Settings::load(&metadata)
+ .map(|settings| settings.binary("switchyard-server"));
+ }
+ Ok(
+ executable.with_file_name(switchyard_desktop::install::executable_name(
+ "switchyard-server",
+ )),
+ )
+}
+
+/// This function asks the installed helper to run the server's dry-run on `config` with the
+/// saved server keys, the same keys the installed server starts with.
+fn check(binary: &Path, config: &Path) -> Result<(), String> {
+ let config = std::fs::canonicalize(config).map_err(|error| error.to_string())?;
+ let helper = binary.with_file_name(switchyard_desktop::install::executable_name(
+ "switchyard-desktop-install",
+ ));
+ let mut validator = Command::new(&helper);
+ validator
+ .arg("validate")
+ .arg("--server")
+ .arg(binary)
+ .arg("--config")
+ .arg(&config);
+ let output = validator.output().map_err(|error| {
+ format!(
+ "Could not run {}: {error}. \
+ The config check needs the installed server and credential helper. \
+ Run cargo desktop install from the Switchyard repository to install them.",
+ helper.display()
+ )
+ })?;
+ if output.status.success() {
+ return Ok(());
+ }
+ let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
+ Err(if stderr.is_empty() { stdout } else { stderr })
+}
+
+pub fn check_config(settings: &Config) -> Result<(), String> {
+ check(&server_binary()?, &settings.config_file)
+}
+
+/// This function runs a command, returning its stdout or a message naming what failed.
+pub fn command(program: &str, args: &[&str]) -> Result<String, String> {
+ if program == "open" {
+ #[cfg(windows)]
+ {
+ return switchyard_desktop::install::windows::open(
+ args.first().ok_or("Choose a file or URL.")?,
+ )
+ .map(|()| String::new());
+ }
+ #[cfg(target_os = "linux")]
+ {
+ return command("xdg-open", args);
+ }
+ }
+
+ let output = Command::new(program)
+ .args(args)
+ .output()
+ .map_err(|error| format!("Could not run {program}: {error}"))?;
+ if !output.status.success() {
+ return Err(format!(
+ "{program} {} failed: {}",
+ args.join(" "),
+ String::from_utf8_lossy(&output.stderr).trim()
+ ));
+ }
+ Ok(String::from_utf8_lossy(&output.stdout).into_owned())
+}
diff --git a/crates/switchyard-desktop/src/tui.rs b/crates/switchyard-desktop/src/tui.rs
index 9e56d4998..ff49926ee 100644
--- a/crates/switchyard-desktop/src/tui.rs
+++ b/crates/switchyard-desktop/src/tui.rs
@@ -6,25 +6,30 @@
//! One worker thread owns the controller and refreshes its snapshots while the UI thread
//! draws and reads input.
-use crate::controller::{Availability, Controller, Snapshot};
+use crate::controller::{
+ Action, ActionKind, AppSettings, Availability, Controller, Reply, Snapshot,
+};
use crate::history::Entry;
use crate::pricing::Estimate;
use crate::rollup::{CLASSIFIER_TIER, ModelTokens, Totals, Usage};
use crate::summary::{money, tokens};
use chrono::{DateTime, Utc};
use ratatui::{
- Frame,
+ DefaultTerminal, Frame,
crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
layout::{Constraint, Layout, Rect},
style::{Color, Modifier, Style, Stylize},
text::{Line, Span},
widgets::{
- Bar, BarChart, Block, BorderType, Cell, Clear, Padding, Paragraph, Row, Scrollbar,
- ScrollbarOrientation, ScrollbarState, Table, TableState, Tabs, Wrap,
+ Bar, BarChart, Block, BorderType, Cell, Clear, List, ListItem, ListState, Padding,
+ Paragraph, Row, Scrollbar, ScrollbarOrientation, ScrollbarState, Table, TableState, Tabs,
+ Wrap,
},
};
+use serde_json::Value;
use std::{
collections::BTreeMap,
+ path::{Path, PathBuf},
sync::mpsc,
thread,
time::{Duration, Instant},
@@ -43,7 +48,7 @@ const SPINNER: [char; 8] = ['⣷', '⣯', '⣟', '⡿', '⢿', '⣻', '⣽', '
type Key = (&'static str, &'static str, &'static str);
const GLOBAL_KEYS: &[Key] = &[
(
- "1-3",
+ "1-4",
"page",
"Switch pages. Tab, Shift-Tab, ← and → also switch pages.",
),
@@ -84,6 +89,14 @@ const MODELS_KEYS: &[Key] = &[(
"period",
"Switch the period: today, the past 7 days, or the whole log. The [ and ] keys also work.",
)];
+const SETTINGS_KEYS: &[Key] = &[
+ ("↑↓", "select", "Select an action. j, g, and G also move."),
+ (
+ "⏎",
+ "run",
+ "Run the selected action. The letter beside each action also runs it.",
+ ),
+];
const FILTER_KEYS: &[Key] = &[
("⏎", "keep", "Keep the filter and go back to the list."),
("esc", "clear", "Clear the filter."),
@@ -91,6 +104,53 @@ const FILTER_KEYS: &[Key] = &[
];
const POPUP_KEYS: &[Key] = &[("↑↓", "scroll", ""), ("esc", "close", "")];
+/// The Settings page uses these entries for action labels, help text, and shortcut keys.
+const ACTIONS: &[(char, &str, &str, ActionKind)] = &[
+ (
+ 'o',
+ "Open server config",
+ "Opens the server config in $VISUAL or $EDITOR. Restart the server after you save it.",
+ ActionKind::OpenConfig,
+ ),
+ (
+ 'c',
+ "Check server config",
+ "Runs the installed server's config check. The running server keeps running.",
+ ActionKind::CheckConfig,
+ ),
+ (
+ 'a',
+ "Open app settings",
+ "Opens this app's settings file in $VISUAL or $EDITOR.",
+ ActionKind::OpenSettings,
+ ),
+ (
+ 'p',
+ "Open model prices",
+ "Opens the custom price file in $VISUAL or $EDITOR. With bundled prices, this explains \
+ how to set a custom file.",
+ ActionKind::OpenPrices,
+ ),
+ (
+ 'k',
+ "Check server keys",
+ "Lists the API key variables that the server config names and whether each is saved.",
+ ActionKind::ServerKeys,
+ ),
+ (
+ 'l',
+ "Open update log",
+ "Opens the log of the last source update in $VISUAL or $EDITOR.",
+ ActionKind::OpenUpdateLog,
+ ),
+ (
+ 'v',
+ "Open server logs",
+ "Opens the Switchyard server logs folder in $VISUAL or $EDITOR.",
+ ActionKind::OpenLogs,
+ ),
+];
+
/// Column is a table heading, its width, and whether its values are right-aligned.
type Column = (&'static str, Constraint, bool);
/// The calls table drops the columns marked `true` below 90 columns.
@@ -156,14 +216,16 @@ enum Tab {
Overview,
Calls,
Models,
+ Settings,
}
-const TABS: [Tab; 3] = [Tab::Overview, Tab::Calls, Tab::Models];
+const TABS: [Tab; 4] = [Tab::Overview, Tab::Calls, Tab::Models, Tab::Settings];
impl Tab {
fn name(self) -> &'static str {
match self {
Tab::Overview => "Overview",
Tab::Calls => "Calls",
Tab::Models => "Models",
+ Tab::Settings => "Settings",
}
}
fn index(self) -> usize {
@@ -241,9 +303,12 @@ impl Popup {
enum Job {
Refresh,
+ Run(Action),
}
enum Done {
+ Editor(PathBuf),
Finished {
+ reply: Option<Result<Reply, String>>,
/// The box keeps this message small; a snapshot holds every model and route total.
snapshot: Result<Box<Snapshot>, String>,
},
@@ -255,6 +320,13 @@ struct Request {
automatic: bool,
}
impl Request {
+ fn run(action: Action, label: &'static str) -> Self {
+ Self {
+ job: Job::Run(action),
+ label,
+ automatic: false,
+ }
+ }
fn refresh(automatic: bool) -> Self {
Self {
job: Job::Refresh,
@@ -265,6 +337,8 @@ impl Request {
}
struct Busy {
label: &'static str,
+ /// This field names the running action, so its reply can update the right view.
+ kind: Option<ActionKind>,
started: Instant,
/// The UI retains the refresh origin so automatic failures preserve the current popup.
automatic: bool,
@@ -287,6 +361,10 @@ struct App {
visible: Vec<usize>,
selected: usize,
offset: usize,
+ action: 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>,
popup: Option<Popup>,
toast: Option<Toast>,
busy: Option<Busy>,
@@ -310,6 +388,8 @@ impl App {
visible: Vec::new(),
selected: 0,
offset: 0,
+ action: 0,
+ server_keys: None,
popup: None,
toast: None,
busy: None,
@@ -365,8 +445,14 @@ impl App {
}
}
- fn finish(&mut self, snapshot: Result<Box<Snapshot>, String>) {
- let automatic = self.busy.take().is_some_and(|busy| busy.automatic);
+ fn finish(
+ &mut self,
+ reply: Option<Result<Reply, String>>,
+ snapshot: Result<Box<Snapshot>, String>,
+ ) {
+ let busy = self.busy.take();
+ let automatic = busy.as_ref().is_some_and(|busy| busy.automatic);
+ let kind = busy.and_then(|busy| busy.kind);
match snapshot {
Ok(data) => {
// A refresh follows the newest call or restores an older selection if it is still visible.
@@ -387,6 +473,10 @@ impl App {
}
}
Err(error) => {
+ // Settings offers the actions needed to repair a failed initial load.
+ if self.refreshed.is_none() && self.data.errors.is_empty() {
+ self.tab = Tab::Settings;
+ }
// Overview keeps the error after the status message is dismissed.
self.data.errors = vec![error.clone()];
if automatic {
@@ -400,13 +490,57 @@ impl App {
}
}
}
+ let Some(reply) = reply else {
+ return;
+ };
+ match (kind, reply) {
+ (Some(ActionKind::ServerKeys), Err(error)) => {
+ self.server_keys = None;
+ self.notify(error, true);
+ }
+ (_, Err(error)) => self.notify(error, true),
+ (Some(ActionKind::ServerKeys), Ok(reply)) => {
+ let text = key_lines(self.theme, Some(&reply.data))
+ .iter()
+ .map(ToString::to_string)
+ .collect::<Vec<_>>()
+ .join("\n");
+ self.server_keys = Some(reply.data);
+ self.popup = Some(Popup::Message {
+ title: "Server keys",
+ text,
+ error: false,
+ scroll: 0,
+ });
+ }
+ (_, Ok(reply)) => {
+ let details: Vec<&str> = reply.data["details"]
+ .as_array()
+ .map(|items| items.iter().filter_map(Value::as_str).collect())
+ .unwrap_or_default();
+ if details.is_empty() {
+ self.notify(reply.message, false);
+ } else {
+ self.popup = Some(Popup::Message {
+ title: "Details",
+ text: format!("{}\n\n{}", reply.message, details.join("\n")),
+ error: false,
+ scroll: 0,
+ });
+ }
+ }
+ }
}
- fn poll_results(&mut self, results: &mpsc::Receiver<Done>) -> Result<(), String> {
+ fn poll_results(&mut self, results: &mpsc::Receiver<Done>) -> Result<Option<PathBuf>, String> {
loop {
match results.try_recv() {
- Ok(Done::Finished { snapshot }) => self.finish(snapshot),
- Err(mpsc::TryRecvError::Empty) => return Ok(()),
+ Ok(Done::Finished { reply, snapshot }) => self.finish(reply, snapshot),
+ Ok(Done::Editor(path)) => {
+ self.busy = None;
+ return Ok((!self.quit).then_some(path));
+ }
+ Err(mpsc::TryRecvError::Empty) => return Ok(None),
Err(mpsc::TryRecvError::Disconnected) => {
return Err("The terminal operation worker stopped unexpectedly.".into());
}
@@ -429,10 +563,17 @@ impl App {
self.notify(text, true);
return Ok(());
}
- self.last_refresh = Instant::now();
+ let kind = match &request.job {
+ Job::Refresh => {
+ self.last_refresh = Instant::now();
+ None
+ }
+ Job::Run(action) => Some(ActionKind::from(action)),
+ };
jobs.send(request.job).map_err(|error| error.to_string())?;
self.busy = Some(Busy {
label: request.label,
+ kind,
started: Instant::now(),
automatic: request.automatic,
});
@@ -446,6 +587,7 @@ impl App {
(None, false, Tab::Overview) => &[],
(None, false, Tab::Calls) => CALLS_KEYS,
(None, false, Tab::Models) => MODELS_KEYS,
+ (None, false, Tab::Settings) => SETTINGS_KEYS,
}
}
@@ -472,7 +614,7 @@ impl App {
match key.code {
KeyCode::Char('q') => self.quit = true,
KeyCode::Char('?') => self.popup = Some(Popup::Help { scroll: 0 }),
- KeyCode::Char(digit @ '1'..='3') => {
+ KeyCode::Char(digit @ '1'..='4') => {
self.tab = TABS[digit as usize - '1' as usize];
}
KeyCode::Tab | KeyCode::Right => self.tab = TABS[(self.tab.index() + 1) % TABS.len()],
@@ -496,6 +638,7 @@ impl App {
KeyCode::Char('[') => self.period = self.period.previous(),
_ => {}
},
+ Tab::Settings => return self.settings_key(code),
},
}
None
@@ -562,6 +705,45 @@ impl App {
self.rebuild_calls();
}
+ /// Action letters come first, so `k` checks the server keys here instead of moving up.
+ fn settings_key(&mut self, code: KeyCode) -> Option<Request> {
+ if let KeyCode::Char(letter) = code
+ && let Some(index) = ACTIONS.iter().position(|action| action.0 == letter)
+ {
+ self.action = index;
+ return self.start_action(ACTIONS[index].3);
+ }
+ if let Some(action) = step(code, self.action, ACTIONS.len() - 1) {
+ self.action = action;
+ return None;
+ }
+ if code == KeyCode::Enter {
+ return self.start_action(ACTIONS[self.action].3);
+ }
+ None
+ }
+
+ /// This function starts a Settings action. The match has no wildcard arm, so adding a
+ /// controller action breaks the build until the terminal app can run it.
+ fn start_action(&mut self, kind: ActionKind) -> Option<Request> {
+ let request = |action, label| Some(Request::run(action, label));
+ match kind {
+ ActionKind::OpenConfig => request(Action::OpenConfig {}, "Opening the server config"),
+ ActionKind::CheckConfig => {
+ request(Action::CheckConfig {}, "Checking the server config")
+ }
+ ActionKind::OpenSettings => {
+ request(Action::OpenSettings {}, "Opening the app settings")
+ }
+ ActionKind::OpenPrices => request(Action::OpenPrices {}, "Opening the model prices"),
+ ActionKind::ServerKeys => request(Action::ServerKeys {}, "Checking the server keys"),
+ ActionKind::OpenUpdateLog => {
+ request(Action::OpenUpdateLog {}, "Opening the update log")
+ }
+ ActionKind::OpenLogs => request(Action::OpenLogs {}, "Opening the server logs"),
+ }
+ }
+
fn popup_key(&mut self, key: KeyEvent) -> Option<Request> {
let popup = self.popup.as_mut()?;
match key.code {
@@ -765,6 +947,8 @@ fn block(theme: Theme, title: &str) -> Block<'static> {
fn draw(frame: &mut Frame, app: &mut App) {
// This exhaustive destructuring requires an update when Snapshot gains a field.
let Snapshot {
+ update_status: _, // draw_settings shows the last update status.
+ settings: _, // draw_settings shows the app settings.
data_state: _, // draw_overview shows health; draw_models checks usage
metrics: _, // draw_header and the Overview cards
today: _, // the Overview "Today" card title
@@ -796,6 +980,7 @@ fn draw(frame: &mut Frame, app: &mut App) {
Tab::Overview => draw_overview(frame, app, body),
Tab::Calls => draw_calls(frame, app, body),
Tab::Models => draw_models(frame, app, body),
+ Tab::Settings => draw_settings(frame, app, body),
}
draw_status(frame, app, status);
draw_popup(frame, app, body);
@@ -1511,6 +1696,137 @@ fn draw_models(frame: &mut Frame, app: &App, area: Rect) {
frame.render_widget(table(theme, &columns, routes), routes_area);
}
+/// 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 {
+ return vec![Line::styled(
+ "Press k to check which keys are saved.",
+ theme.muted,
+ )];
+ };
+ let keys = data["keys"]
+ .as_array()
+ .map(Vec::as_slice)
+ .unwrap_or_default();
+ if keys.is_empty() {
+ return vec![Line::from(
+ "The server config names no keys with api_key_env.",
+ )];
+ }
+ let mut lines = vec![Line::styled(
+ format!(
+ "Stored in {}",
+ data["store"].as_str().unwrap_or("Not recorded")
+ ),
+ theme.muted,
+ )];
+ lines.extend(keys.iter().map(|key| {
+ let saved = key["saved"] == true;
+ Line::from(vec![
+ Span::raw(format!("{} ", key["name"].as_str().unwrap_or_default())),
+ if saved {
+ Span::styled("saved", theme.ok)
+ } else {
+ Span::styled("not saved", theme.warn)
+ },
+ ])
+ }));
+ lines
+}
+
+fn draw_settings(frame: &mut Frame, app: &App, area: Rect) {
+ let theme = app.theme;
+ let [list_area, info_area] =
+ Layout::horizontal([Constraint::Length(30), Constraint::Fill(1)]).areas(area);
+ let items: Vec<ListItem> = ACTIONS
+ .iter()
+ .map(|(letter, name, ..)| {
+ ListItem::new(Line::from(vec![
+ Span::styled(format!("{letter} "), theme.key),
+ Span::raw(*name),
+ ]))
+ })
+ .collect();
+ let mut state = ListState::default().with_selected(Some(app.action));
+ frame.render_stateful_widget(
+ List::new(items)
+ .highlight_style(theme.selected)
+ .highlight_symbol("› ")
+ .block(block(theme, "Actions")),
+ list_area,
+ &mut state,
+ );
+ let row = |name: &str, value: String| labeled(theme, name, 15, value);
+ let heading = |text: &'static str| Line::styled(text, theme.muted.bold());
+ let mut lines = vec![Line::from(ACTIONS[app.action].2), Line::default()];
+ if !app.data.errors.is_empty() {
+ lines.extend(
+ app.data
+ .errors
+ .iter()
+ .map(|error| Line::styled(error.clone(), theme.error)),
+ );
+ lines.push(Line::default());
+ }
+ // This destructuring has no `..`, so adding an app setting requires an update here.
+ match &app.data.settings {
+ Some(AppSettings {
+ path,
+ server_url,
+ routing_log,
+ config_file,
+ launchd_label,
+ refresh_seconds,
+ baseline_model,
+ prices_file,
+ }) => lines.extend([
+ heading("APP SETTINGS"),
+ row("Settings file", path.display().to_string()),
+ row("Server URL", server_url.clone()),
+ row("Server config", config_file.display().to_string()),
+ row("Routing log", routing_log.display().to_string()),
+ row("Service label", launchd_label.clone()),
+ row("Baseline model", baseline_model.clone()),
+ row(
+ "Refresh",
+ format!("every {}", plural(*refresh_seconds, "second", "seconds")),
+ ),
+ row(
+ "Model prices",
+ prices_file
+ .as_ref()
+ .map_or("Bundled rates".into(), |file| file.display().to_string()),
+ ),
+ row("Editor", editor()),
+ ]),
+ None => lines.push(Line::styled(
+ "App settings could not be loaded. Press a to open them, then r to check them again.",
+ theme.warn,
+ )),
+ }
+ let update = &app.data.update_status;
+ let update = ["state", "stage", "message"]
+ .into_iter()
+ .filter_map(|field| update[field].as_str())
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join(" · ");
+ lines.extend([Line::default(), heading("UPDATE FROM SOURCE")]);
+ lines.push(Line::from(if update.is_empty() {
+ "No update has run".to_string()
+ } else {
+ update
+ }));
+ lines.extend([Line::default(), heading("SERVER KEYS")]);
+ lines.extend(key_lines(theme, app.server_keys.as_ref()));
+ frame.render_widget(
+ Paragraph::new(lines)
+ .wrap(Wrap { trim: false })
+ .block(block(theme, ACTIONS[app.action].1).padding(Padding::horizontal(1))),
+ info_area,
+ );
+}
+
fn draw_status(frame: &mut Frame, app: &App, area: Rect) {
let theme = app.theme;
let left = if app.filtering {
@@ -1674,6 +1990,7 @@ fn help_lines(theme: Theme, width: usize) -> Vec<Line<'static>> {
("Calls", CALLS_KEYS),
("While filtering calls", FILTER_KEYS),
("Models", MODELS_KEYS),
+ ("Settings", SETTINGS_KEYS),
] {
if !lines.is_empty() {
lines.push(Line::default());
@@ -1711,6 +2028,84 @@ impl Drop for PasteMode {
}
}
+/// This function returns $VISUAL, then $EDITOR, then the platform default.
+fn editor() -> String {
+ ["VISUAL", "EDITOR"]
+ .into_iter()
+ .filter_map(|name| std::env::var(name).ok())
+ .find(|value| !value.trim().is_empty())
+ .unwrap_or_else(|| if cfg!(windows) { "notepad" } else { "vi" }.into())
+}
+
+/// This function builds the editor command using Windows or POSIX quoting without starting it.
+/// The Windows file check keeps an existing unquoted executable path with spaces as one program.
+fn editor_command(editor: &str, windows: bool) -> Result<std::process::Command, String> {
+ let parts = if windows {
+ let whole = editor.trim();
+ if whole.is_empty() {
+ Vec::new()
+ } else if Path::new(whole).is_file() {
+ vec![whole.to_string()]
+ } else {
+ windows_args::Args::parse_cmd(whole).collect()
+ }
+ } else {
+ shlex::split(editor).ok_or("The editor command has an unmatched quote.")?
+ };
+ let (program, arguments) = parts
+ .split_first()
+ .ok_or("Set VISUAL or EDITOR to an editor command.")?;
+ let mut command = std::process::Command::new(program);
+ command.args(arguments);
+ Ok(command)
+}
+
+/// This function runs the editor on an absolute path. The caller restores normal terminal input
+/// first. The path stays one literal argument, even if its name starts with '-'.
+fn edit_file(path: &Path) -> Result<(), String> {
+ let mut command = editor_command(&editor(), cfg!(windows))?;
+ let program = command.get_program().to_string_lossy().into_owned();
+ let path = if path.is_absolute() {
+ path.to_path_buf()
+ } else {
+ std::env::current_dir()
+ .map_err(|error| error.to_string())?
+ .join(path)
+ };
+ let status = command
+ .arg(path)
+ .status()
+ .map_err(|error| format!("Could not start the editor {program}: {error}"))?;
+ if !status.success() {
+ return Err(format!("The editor {program} exited with {status}."));
+ }
+ Ok(())
+}
+
+/// This function gives the terminal to the editor and takes it back afterward. The outer error
+/// means the terminal could not be switched; the inner result comes from the editor.
+fn edit_in_foreground(
+ terminal: &mut DefaultTerminal,
+ path: &Path,
+) -> std::io::Result<Result<(), String>> {
+ use ratatui::crossterm::{
+ execute,
+ terminal::{EnterAlternateScreen, enable_raw_mode},
+ };
+ execute!(std::io::stdout(), event::DisableBracketedPaste)?;
+ terminal.show_cursor()?;
+ ratatui::try_restore()?;
+ let edited = edit_file(path);
+ enable_raw_mode()?;
+ execute!(
+ std::io::stdout(),
+ EnterAlternateScreen,
+ event::EnableBracketedPaste
+ )?;
+ terminal.clear()?;
+ Ok(edited)
+}
+
pub fn run(mut controller: Controller) -> Result<(), String> {
let mut app = App::new(Theme::new(color_enabled()));
ratatui::crossterm::execute!(std::io::stdout(), event::EnableBracketedPaste)
@@ -1720,9 +2115,19 @@ pub fn run(mut controller: Controller) -> Result<(), String> {
let (done, results) = mpsc::channel::<Done>();
// One worker owns the controller while the terminal continues to draw and read input.
let worker = thread::spawn(move || {
- while let Ok(Job::Refresh) = inbox.recv() {
- let finished = Done::Finished {
- snapshot: controller.snapshot().map(Box::new),
+ while let Ok(job) = inbox.recv() {
+ let finished = match job {
+ Job::Refresh => Done::Finished {
+ reply: None,
+ snapshot: controller.snapshot().map(Box::new),
+ },
+ Job::Run(action) => match controller.editor_target(&action) {
+ Ok(Some(path)) => Done::Editor(path),
+ target => Done::Finished {
+ reply: Some(target.and_then(|_| controller.dispatch(action))),
+ snapshot: controller.snapshot().map(Box::new),
+ },
+ },
};
if done.send(finished).is_err() {
break;
@@ -1733,7 +2138,15 @@ pub fn run(mut controller: Controller) -> Result<(), String> {
// The initial refresh starts after terminal setup so a blocked read cannot delay drawing.
app.start(&jobs, Request::refresh(true))?;
loop {
- app.poll_results(&results)?;
+ if let Some(path) = app.poll_results(&results)? {
+ match edit_in_foreground(terminal, &path).map_err(|error| error.to_string())? {
+ Ok(()) => {
+ app.notify(format!("Closed the editor for {}.", path.display()), false)
+ }
+ Err(error) => app.notify(error, true),
+ }
+ app.start(&jobs, Request::refresh(false))?;
+ }
if app.quit && app.busy.is_none() {
return Ok(());
}
@@ -1817,19 +2230,19 @@ mod tests {
})
};
let mut app = App::new(Theme::new(false));
- app.finish(Ok(snapshot(&["first", "second"])));
+ app.finish(None, Ok(snapshot(&["first", "second"])));
assert_eq!(app.visible.len(), 2);
assert_eq!(
app.selected_entry().expect("newest").turn_id.as_deref(),
Some("second")
);
- app.finish(Ok(snapshot(&["first", "second", "third"])));
+ app.finish(None, Ok(snapshot(&["first", "second", "third"])));
assert_eq!(
app.selected_entry().expect("newest").turn_id.as_deref(),
Some("third")
);
app.calls_key(KeyCode::Down);
- app.finish(Ok(snapshot(&["first", "second", "third", "fourth"])));
+ app.finish(None, Ok(snapshot(&["first", "second", "third", "fourth"])));
assert_eq!(
app.selected_entry().expect("selected").turn_id.as_deref(),
Some("second")
@@ -1849,18 +2262,24 @@ mod tests {
};
let mut app = App::new(Theme::new(false));
app.tab = Tab::Calls;
- app.finish(Ok(Box::new(Snapshot {
- entries: vec![entry("opened-turn")],
- ..Snapshot::default()
- })));
+ app.finish(
+ None,
+ Ok(Box::new(Snapshot {
+ entries: vec![entry("opened-turn")],
+ ..Snapshot::default()
+ })),
+ );
app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
app.key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
// The popup must retain its call when newer calls arrive or history no longer contains it.
for entries in [vec![entry("opened-turn"), entry("newer-turn")], vec![]] {
- app.finish(Ok(Box::new(Snapshot {
- entries,
- ..Snapshot::default()
- })));
+ app.finish(
+ None,
+ Ok(Box::new(Snapshot {
+ entries,
+ ..Snapshot::default()
+ })),
+ );
assert!(matches!(app.popup, Some(Popup::Detail { scroll: 1, .. })));
let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("terminal");
terminal
@@ -1883,11 +2302,127 @@ mod tests {
assert!(app.popup.is_none());
}
+ // The last key must remain reachable when the results exceed the Settings pane's height.
+ #[test]
+ fn server_key_results_remain_readable_in_a_scrollable_popup() {
+ let mut app = App::new(Theme::new(false));
+ app.tab = Tab::Settings;
+ let request = app
+ .key(KeyEvent::new(KeyCode::Char('k'), KeyModifiers::NONE))
+ .expect("key action");
+ let (jobs, _inbox) = mpsc::channel();
+ app.start(&jobs, request).expect("start key check");
+ let keys = json!({
+ "store": "test credential store",
+ "keys": (0..20).map(|index| json!({"name": format!("API_KEY_{index:02}"), "saved": index % 2 == 0})).collect::<Vec<_>>()
+ });
+ app.finish(
+ Some(Ok(super::Reply {
+ message: String::new(),
+ data: keys.clone(),
+ })),
+ Ok(Box::new(Snapshot::default())),
+ );
+ assert_eq!(app.server_keys, Some(keys));
+ assert!(matches!(app.popup, Some(Popup::Message { scroll: 0, .. })));
+ app.key(KeyEvent::new(KeyCode::End, KeyModifiers::NONE));
+ let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("terminal");
+ terminal.draw(|frame| draw(frame, &mut app)).expect("draw");
+ let text: String = terminal
+ .backend()
+ .buffer()
+ .content()
+ .iter()
+ .map(|cell| cell.symbol())
+ .collect();
+ assert!(text.contains("API_KEY_19 not saved"), "{text}");
+ }
+
+ // These fixtures check the parsed arguments without requiring a Windows editor to run.
+ #[test]
+ fn editor_commands_preserve_platform_quoting_and_paths() {
+ for (windows, raw, program, arguments) in [
+ (
+ true,
+ r"C:\Windows\System32\notepad.exe",
+ r"C:\Windows\System32\notepad.exe",
+ vec![],
+ ),
+ (
+ true,
+ r#""C:\Program Files\Editor\editor.exe" --wait "two words""#,
+ r"C:\Program Files\Editor\editor.exe",
+ vec!["--wait", "two words"],
+ ),
+ (
+ true,
+ r#"C:\Tools\editor.exe --wait "\\server\share\file with spaces""#,
+ r"C:\Tools\editor.exe",
+ vec!["--wait", r"\\server\share\file with spaces"],
+ ),
+ (
+ true,
+ r#"C:\Tools\editor.exe --title "" --wait"#,
+ r"C:\Tools\editor.exe",
+ vec!["--title", "", "--wait"],
+ ),
+ (
+ true,
+ r#"C:\Tools\editor.exe --title "two words"#,
+ r"C:\Tools\editor.exe",
+ vec!["--title", "two words"],
+ ),
+ (
+ false,
+ "'editor with spaces' --wait 'two words'",
+ "editor with spaces",
+ vec!["--wait", "two words"],
+ ),
+ ] {
+ let command = super::editor_command(raw, windows).expect("editor command");
+ assert_eq!(
+ command.get_program(),
+ std::ffi::OsStr::new(program),
+ "{raw}"
+ );
+ assert_eq!(
+ command.get_args().collect::<Vec<_>>(),
+ arguments
+ .iter()
+ .map(std::ffi::OsStr::new)
+ .collect::<Vec<_>>(),
+ "{raw}"
+ );
+ }
+ for (windows, raw, error) in [
+ (true, " ", "Set VISUAL or EDITOR to an editor command."),
+ (false, " ", "Set VISUAL or EDITOR to an editor command."),
+ (
+ false,
+ "'unterminated",
+ "The editor command has an unmatched quote.",
+ ),
+ ] {
+ assert_eq!(
+ super::editor_command(raw, windows).err().as_deref(),
+ Some(error)
+ );
+ }
+ let directory = tempfile::tempdir().expect("directory");
+ let path = directory.path().join("editor with spaces.exe");
+ std::fs::write(&path, "").expect("editor file");
+ let command =
+ super::editor_command(path.to_str().expect("UTF-8 path"), true).expect("editor path");
+ assert_eq!(command.get_program(), path.as_os_str());
+ assert_eq!(command.get_args().count(), 0);
+ }
+
// Esc dismisses the status message while Overview keeps the refresh error.
#[test]
fn refresh_errors_remain_in_overview_after_dismissing_the_toast() {
let mut app = App::new(Theme::new(false));
- app.finish(Err("Could not read settings.".into()));
+ app.finish(None, Err("Could not read settings.".into()));
+ app.tab = Tab::Overview;
app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("terminal");
terminal.draw(|frame| draw(frame, &mut app)).expect("draw");
@@ -1925,6 +2460,7 @@ mod tests {
app.start(&jobs, Request::refresh(false))
.expect("manual refresh");
done.send(Done::Finished {
+ reply: None,
snapshot: Err(error.into()),
})
.expect("result");
@@ -1939,6 +2475,7 @@ mod tests {
app.start(&jobs, Request::refresh(true))
.expect("automatic refresh");
done.send(Done::Finished {
+ reply: None,
snapshot: Err(error.into()),
})
.expect("result");