Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,903 changes: 2,707 additions & 196 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ members = [
"crates/switchyard-nemo-relay-plugin",
"crates/switchyard-runner",
"crates/switchyard-desktop",
"crates/switchyard-menubar",
"crates/switchyard-costs",
"crates/switchyard-server",
"crates/switchyard-skill-distillation",
Expand Down
17 changes: 1 addition & 16 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@
# SPDX-License-Identifier: Apache-2.0

.DEFAULT_GOAL := help
.PHONY: help install-linux install-linux-dry-run uninstall-linux install-macos install-macos-dry-run uninstall-macos
.PHONY: help install-linux install-linux-dry-run uninstall-linux

help:
@echo "install-linux Install the systemd user service and Codex profile"
@echo "install-linux-dry-run Preview installation without changes"
@echo "uninstall-linux Remove the service and Codex profile"
@echo "install-macos Install the background server and menu bar app"
@echo "install-macos-dry-run Preview installation without changes"
@echo "uninstall-macos Remove the LaunchAgents and Codex profile"

## Install the Switchyard background server as a systemd user service.
install-linux:
Expand All @@ -23,15 +20,3 @@ install-linux-dry-run:
## Remove the systemd user service, the sy Codex profile, and the codex alias.
uninstall-linux:
@scripts/linux/uninstall.sh

## Install the Switchyard background server and menu bar app for this user.
install-macos:
@scripts/macos/install.sh

## Print what install-macos would do, without changing anything.
install-macos-dry-run:
@scripts/macos/install.sh --dry-run

## Remove the LaunchAgents, the sy Codex profile, and the codex alias.
uninstall-macos:
@scripts/macos/uninstall.sh
3 changes: 0 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,6 @@ Features and integrations recently merged into `main`.
- **2026-10-12 · Bring Switchyard to TypeScript and Pi**\
Select models in Node.js or try automatic routing through Pi’s virtual models. [TypeScript bindings →](bindings/typescript/README.md) · [Pi example →](examples/pi/README.md)

- **2026-10-08 · Run Codex with Switchyard on macOS**\
Install a background router and Codex profile, then track usage and estimated savings from the menu bar. [Setup guide →](crates/switchyard-menubar/README.md)

## Community and license

[Report an issue](https://github.com/NVIDIA-NeMo/Switchyard/issues) · [Contribute](CONTRIBUTING.md) · [Code of conduct](CODE_OF_CONDUCT.md)
Expand Down
1 change: 1 addition & 0 deletions crates/switchyard-desktop/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/gen
22 changes: 20 additions & 2 deletions crates/switchyard-desktop/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
[package]
name = "switchyard-desktop"
version.workspace = true
description = "Installer and usage summary for a local Switchyard server"
description = "Installer and desktop app for a local Switchyard server"
authors.workspace = true
edition.workspace = true
homepage = "https://github.com/NVIDIA-NeMo/Switchyard"
license.workspace = true
repository.workspace = true
rust-version.workspace = true
publish = false
default-run = "switchyard-desktop"

[dependencies]
switchyard-runner.workspace = true
Expand All @@ -24,8 +25,17 @@ tempfile = "3"
toml = "0.9"
toml_edit = "0.25"
url = "2"
uuid.workspace = true
ratatui = { version = "0.30.2", features = ["unstable-rendered-line-info"] }
shlex = "2"
strum = { version = "0.28", features = ["derive"] }

[target.'cfg(target_os = "macos")'.dependencies]
objc2-quartz-core = { version = "0.3.2", default-features = false, features = ["CALayer"] }
dispatch2 = "0.3"
objc2 = "0.6"
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["NSWorkspace", "NSAccessibility", "NSApplication", "NSPanel", "NSColor", "NSWindow", "NSView", "NSScreen", "NSEvent", "NSStatusItem", "NSStatusBarButton", "NSButton", "NSControl", "NSResponder", "objc2-quartz-core"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["NSString", "NSURL", "NSProcessInfo"] }
security-framework = "3"

[target.'cfg(unix)'.dependencies]
Expand All @@ -38,7 +48,15 @@ dbus-secret-service = { version = "4.1", features = ["crypto-rust", "vendored"]
[target.'cfg(windows)'.dependencies]
mslnk = "0.1.8"
self-replace = "1.5"
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_Security_Credentials", "Win32_System_Console", "Win32_Storage_FileSystem"] }
windows = { version = "0.62.2", features = ["Management_Deployment", "ApplicationModel"] }
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_Security_Credentials", "Win32_System_Console", "Win32_Storage_FileSystem", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }

[target.'cfg(any(target_os = "macos", windows))'.dependencies]
rfd = { version = "0.17", default-features = false }
tauri = { version = "2", features = ["tray-icon", "custom-protocol"] }

[target.'cfg(any(target_os = "macos", windows))'.build-dependencies]
tauri-build = "2"

[dev-dependencies]
image = { version = "0.25", default-features = false, features = ["png"] }
Expand Down
8 changes: 8 additions & 0 deletions crates/switchyard-desktop/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

/// Supported desktop platforms need Tauri resources and command metadata at build time.
fn main() {
#[cfg(any(target_os = "macos", windows))]
tauri_build::build();
}
153 changes: 153 additions & 0 deletions crates/switchyard-desktop/src/gui.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! The desktop window shows server health and recorded request and token counts.

use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use switchyard_desktop::{config::Config, health::Probe, rollup};
use tauri::State;

/// The window retains the probe and reader so refreshes reuse the health worker and log offset.
struct Desktop {
settings: PathBuf,
health: Probe,
reader: rollup::Reader,
}

#[derive(serde::Serialize)]
struct Counts {
requests: u64,
tokens: u64,
}

#[derive(serde::Serialize)]
struct Snapshot {
server_url: String,
health: serde_json::Value,
today: Option<Counts>,
week: Option<Counts>,
errors: Vec<String>,
refresh_seconds: u64,
}

type Shared = Arc<Mutex<Desktop>>;

/// The worker reads health and usage while the mutex prevents overlapping refreshes.
#[tauri::command]
async fn snapshot(state: State<'_, Shared>) -> Result<Snapshot, String> {
let shared = state.inner().clone();
tauri::async_runtime::spawn_blocking(move || {
let mut desktop = shared
.try_lock()
.map_err(|_| "A refresh is running. Try again when it finishes.".to_string())?;
let config = Config::load(&desktop.settings)?;
let health = desktop.health.details(&config.server_url);
let mut errors = Vec::new();
// A failed read leaves counts absent so the window cannot show incomplete usage as zero.
let usage = desktop
.reader
.read(&config.routing_log, chrono::Local::now().date_naive())
.map_err(|error| errors.push(format!("Could not read usage: {error}")))
.ok();
let counts = |totals: &rollup::Totals| Counts {
requests: totals.requests(),
tokens: totals.tokens(),
};
Ok(Snapshot {
server_url: config.server_url,
health,
today: usage.as_ref().map(|usage| counts(&usage.today)),
week: usage.as_ref().map(|usage| counts(&usage.week)),
errors,
refresh_seconds: config.refresh_seconds.max(1),
})
})
.await
.map_err(|error| error.to_string())?
}

#[derive(serde::Deserialize)]
#[serde(rename_all = "snake_case")]
enum FileKind {
Config,
Logs,
}

/// The worker waits for any refresh, then opens the configured file after releasing the mutex.
#[tauri::command]
async fn open_file(state: State<'_, Shared>, kind: FileKind) -> Result<(), String> {
let shared = state.inner().clone();
tauri::async_runtime::spawn_blocking(move || {
let config = {
let desktop = shared
.lock()
.map_err(|_| "Could not access desktop state after a worker failed.".to_string())?;
Config::load(&desktop.settings)?
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
};
let path = match kind {
FileKind::Config => config.config_file,
FileKind::Logs => config.routing_log,
};
#[cfg(target_os = "macos")]
{
let output = std::process::Command::new("open")
.arg("--")
.arg(&path)
.output()
.map_err(|error| format!("Could not open {}: {error}", path.display()))?;
if !output.status.success() {
return Err(format!(
"Could not open {}: {}",
path.display(),
String::from_utf8_lossy(&output.stderr).trim()
));
}
Ok(())
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::UI::{
Shell::ShellExecuteW, WindowsAndMessaging::SW_SHOWNORMAL,
};
let path: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let status = unsafe {
ShellExecuteW(
std::ptr::null_mut(),
std::ptr::null(),
path.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 (error {status})."))
}
}
})
.await
.map_err(|error| error.to_string())?
}

/// Quitting closes the window and stops the application.
#[tauri::command]
fn quit_app(app: tauri::AppHandle) {
app.exit(0);
}

/// The application owns one health probe and log reader for the lifetime of the window.
pub fn run(settings: PathBuf) -> Result<(), String> {
tauri::Builder::default()
.manage(Arc::new(Mutex::new(Desktop {
settings,
health: Probe::default(),
reader: rollup::Reader::default(),
})))
.invoke_handler(tauri::generate_handler![snapshot, open_file, quit_app])
.run(tauri::generate_context!())
.map_err(|error| error.to_string())
}
98 changes: 98 additions & 0 deletions crates/switchyard-desktop/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! The desktop window shows local server health and recorded usage.

#![cfg_attr(windows, windows_subsystem = "windows")]

use switchyard_desktop::config;
#[cfg(any(target_os = "macos", windows))]
mod gui;

use std::path::PathBuf;
use std::process::ExitCode;

use config::Config;

const USAGE: &str = "\
Usage: switchyard-desktop [--validate-toml] [FILE]

This app opens a window with server status and recorded usage.
The desktop window supports macOS and Windows.

FILE The app reads settings from FILE.
--validate-toml Parse FILE as TOML and exit.

Without FILE, the app uses bundled installation metadata to find desktop.toml.
Without that metadata, it uses $SY_HOME/desktop.toml, or ~/.switchyard/desktop.toml
when SY_HOME is unset.

Missing settings use the directory and port from adjacent install.toml, or the
settings file's directory and port 4123 when that metadata is absent.
The default server URL includes the port, such as http://127.0.0.1:4123.
A configured HTTP URL without a port uses port 80.";

/// The command checks TOML syntax or opens the desktop window.
fn main() -> ExitCode {
// A desktop launch may have no parent console, so attachment failure does not stop the app.
#[cfg(windows)]
let _ = unsafe {
windows_sys::Win32::System::Console::AttachConsole(
windows_sys::Win32::System::Console::ATTACH_PARENT_PROCESS,
)
};
let mut settings = None;
let mut validate_toml = false;
for arg in std::env::args().skip(1) {
match arg.as_str() {
"-h" | "--help" => {
println!("{USAGE}");
return ExitCode::SUCCESS;
}
"--validate-toml" => validate_toml = true,
_ if arg.starts_with('-') => {
eprintln!("switchyard-desktop: unknown option {arg}\n\n{USAGE}");
return ExitCode::FAILURE;
}
_ if settings.is_some() => {
eprintln!("switchyard-desktop: expected at most one settings file\n\n{USAGE}");
return ExitCode::FAILURE;
}
_ => settings = Some(PathBuf::from(arg)),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

if validate_toml {
let Some(path) = settings else {
eprintln!("switchyard-desktop: --validate-toml requires a file path");
return ExitCode::FAILURE;
};
if let Err(error) = config::validate_toml_file(&path) {
eprintln!("switchyard-desktop: {error}");
return ExitCode::FAILURE;
}
return ExitCode::SUCCESS;
}

let settings = match settings.map(Ok).unwrap_or_else(Config::default_path) {
Ok(path) => path,
Err(error) => {
eprintln!("switchyard-desktop: {error}");
return ExitCode::FAILURE;
}
};
#[cfg(any(target_os = "macos", windows))]
match gui::run(settings) {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("switchyard-desktop: {error}");
ExitCode::FAILURE
}
}
#[cfg(not(any(target_os = "macos", windows)))]
{
let _ = settings;
eprintln!("The desktop window supports macOS and Windows.");
ExitCode::FAILURE
}
}
32 changes: 32 additions & 0 deletions crates/switchyard-desktop/tauri.conf.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"productName": "Switchyard",
"version": "0.3.0",
"identifier": "com.nvidia.switchyard",
"build": {
"frontendDist": "ui"
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"label": "main",
"title": "Switchyard",
"width": 680,
"height": 500,
"minWidth": 440,
"minHeight": 400
}
],
"security": {
"csp": "default-src 'self'; script-src 'self'; style-src 'self'; connect-src ipc: http://ipc.localhost; img-src 'self' data:; object-src 'none'; frame-src 'none'; base-uri 'none'"
}
},
"bundle": {
"active": false,
"icon": [
"icons/icon.icns",
"icons/icon.png",
"icons/icon.ico"
]
}
}
Loading
Loading