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 tray usage popup (#1115)
Elyas Mehtabuddinaec5e2c2ed9e
diff --git a/INSTALLATION.md b/INSTALLATION.mdindex 613493c19..2f92ec443 100644--- a/INSTALLATION.md+++ b/INSTALLATION.md@@ -49,14 +49,75 @@ On Linux, open the installed app with `~/.switchyard/bin/switchyard-desktop --tuSee [Desktop setup](crates/switchyard-desktop/SETUP.md) for these steps.Uninstall keeps settings, history, and recovery copies.-The installer requires the repository's Rust toolchain. macOS uses LaunchAgents;-Linux requires a systemd user session. Windows requires MSVC build tools,-WebView2, and a Task Scheduler user session.+## Server Keys++In a server config, each LLM client and decision client names its API key+variable with `api_key_env`. A server you start from a terminal reads those+variables from your shell, as it always has. The installed server does not: on+macOS launchd starts it, on Linux systemd, and on Windows Task Scheduler. None+of them runs your shell, so the installed server never sees the variables that+`~/.zshrc` or `~/.bashrc` exports.++The installed server reads each key from the system credential store instead:+macOS Keychain, Windows Credential Manager, or the Linux Secret Service (GNOME+Keyring on Ubuntu and GNOME, KDE Wallet on Plasma). A key is saved under its+variable name, such as `NVIDIA_API_KEY`. Before each start, the installed+helper reads the keys that the config names and passes them to the server. A+saved key replaces any value the service manager passes. If a variable has no+saved key, the server does not start, and the server log names the variable.++To save, replace, or remove a key in the desktop app, open **Settings → Server+keys**. Type or paste the key, or choose **Import from shell** to read the+variable once from your login shell. From a terminal on macOS or Linux, run the+installed helper:-On Windows, run install and uninstall from the source checkout with Cargo.-The installed helper rejects changes to its own installation because Windows-locks running executables. The app's Update command uses a temporary helper-copy. The installed helper still supports `uninstall --dry-run`.+```bash+~/.switchyard/bin/switchyard-desktop-install key status --config ~/.switchyard/composite.toml+~/.switchyard/bin/switchyard-desktop-install key set NVIDIA_API_KEY # prompts without echo+~/.switchyard/bin/switchyard-desktop-install key import NVIDIA_API_KEY # reads it from your login shell+~/.switchyard/bin/switchyard-desktop-install key remove NVIDIA_API_KEY+```++On Windows, the installer puts the helper in+`%LOCALAPPDATA%\Programs\Switchyard`, or `%USERPROFILE%\AppData\Local\Programs\Switchyard`+when `LOCALAPPDATA` is unset. There `key set` reads the key from+standard input without a prompt, and `key import` reads the variable from your+Windows environment variables. From PowerShell:++```powershell+$local = if ($env:LOCALAPPDATA) { $env:LOCALAPPDATA } else { "$env:USERPROFILE\AppData\Local" }+$helper = "$local\Programs\Switchyard\switchyard-desktop-install.exe"+& $helper key status --config "$env:USERPROFILE\.switchyard\composite.toml"+[Net.NetworkCredential]::new('', (Read-Host 'Key' -AsSecureString)).Password | & $helper key set NVIDIA_API_KEY+& $helper key import NVIDIA_API_KEY+& $helper key remove NVIDIA_API_KEY+```++Restart the server after you change a key. If you rename a variable in+`api_key_env`, save a key under the new name. The old key stays saved until you+remove it in Keychain Access, Credential Manager, or Seahorse.++`cargo desktop install` never saves, reads, or changes a key, even when your+terminal sets the variable. It checks the config without keys, then lists each+variable that has no saved key. On a first install, the server starts after you+save those keys in **Settings → Server keys** and restart it. In the terminal+app, press `7` to open the Settings page. There `k` lists the variables that the+config names and whether each has a saved key, `s` saves a key, and `i` imports+it from your login shell. Press `b` and then `y` to restart the server.+Uninstalling keeps the saved keys, the config, and history. Switchyard never+writes keys to app settings, service definitions, or logs. Model-list keys that+you enter in Routes are stored separately.++On macOS, Keychain ties each key to the helper that saved it. Keychain treats a+rebuilt helper as a new program, so after `cargo desktop install` macOS may ask+once per key whether to allow `switchyard-desktop-install`. Choose **Always+Allow**.++On Linux, the login keyring must be unlocked. A desktop login normally unlocks+it. When the server service starts after login, it waits up to a minute for the+keyring to unlock. Over SSH without a desktop session, or with a window manager+that does not unlock the keyring, the server does not start and its log says+the keyring is locked.## Linux Codex Service@@ -68,13 +129,16 @@ port while the service is stopped and receive your login and prompts.From a checkout, preview or install the service:```bash-make install-linux-dry-run-make install-linux+cargo desktop install --dry-run+cargo desktop installsystemctl --user status switchyardcodex -p sy```-The installer builds and installs `~/.switchyard/bin/switchyard-server`.+The installer builds and installs `~/.switchyard/bin/switchyard-server` and+`~/.switchyard/bin/switchyard-desktop`. Run the same command to reinstall from+the current checkout; update the checkout first to install newer code.+Run `~/.switchyard/bin/switchyard-desktop --tui` to open the terminal app.It creates `~/.switchyard/composite.toml` if missing and keeps existing edits.It replaces `~/.config/systemd/user/switchyard.service` and restarts the service.It writes `~/.codex/sy.config.toml`, backing up a changed profile first.@@ -84,20 +148,62 @@ The profile format requires [Codex 0.134.0 or newer](https://developers.openai.cRemove any old `[profiles.sy]` table from `~/.codex/config.toml` before using it.Set `SY_HOME` or `SY_PORT` to change the server directory or port (default 4123).-`SY_HOME` must not contain whitespace, control characters, or a trailing-backslash; `SY_PORT` must contain only digits. `XDG_CONFIG_HOME` and `CODEX_HOME`+`SY_HOME` must be an absolute UTF-8 path without ASCII control characters.+`SY_PORT` must be a number from 1 to 65535. `XDG_CONFIG_HOME` and `CODEX_HOME`set the systemd and Codex config directories.Read server logs with `journalctl --user -u switchyard`. Routing records arestored in `~/.switchyard/routing.jsonl`. Use `systemctl --user edit switchyard`for service changes that survive reinstalling.-Remove the service and profile with `make uninstall-linux`. This also removes+Remove the service and profile with `cargo desktop uninstall`. This also removesmarked Codex aliases left by older installs from existing `.bashrc` and`.zshrc` files. If upgrading an older install, uninstall first and run`unalias codex` in any open shell. The server directory, routing records,-profile backups, and systemd drop-in files stay in place. Use the same path-overrides when installing and uninstalling.+profile backups, and systemd drop-in files stay in place. Uninstall uses the+recorded installation. Conflicting environment overrides require+`cargo desktop uninstall --settings FILE` to select it explicitly.++## Windows Desktop App++From PowerShell in the repository, run:++```powershell+cargo desktop install --dry-run+cargo desktop install+```++Windows needs the Rust MSVC toolchain, Visual Studio C++ build tools, and+[WebView2](https://v2.tauri.app/start/prerequisites/#windows).+The installer uses Task Scheduler for the current logged-in user. It installs+executables in `%LOCALAPPDATA%\Programs\Switchyard`, falling back to+`%USERPROFILE%\AppData\Local\Programs\Switchyard` when `LOCALAPPDATA` is unset.+It saves that location and adds a Start menu shortcut. Two independent tasks+start the server and desktop app after login with ordinary user privileges.+Quitting the app leaves the server running.++Run `cargo desktop install` again to build and install the current checkout.+This Cargo command waits for installation to finish. The app's source update+uses the saved checkout and runs from a temporary Rust executable so Windows+can release and replace the installed files; read `SY_HOME\logs\update.log` for+its progress and errors. The installed installer cannot install, update, or+uninstall its own installation, because Windows keeps a running program from+being replaced. Use `cargo desktop` from the source checkout instead.+The installer builds and validates before stopping the tasks. If a binary+replacement fails, it tries to restore the previous binaries. If restoration+also fails, the error names the directory containing recovery files.+Rerun installation if a later task or settings operation fails; the complete+installation is not one transaction.++Settings, server config, and routing history stay in `SY_HOME`, which defaults+to `%USERPROFILE%\.switchyard`. Named accounts stay in+`%USERPROFILE%\.switchyard\accounts` whatever `SY_HOME` is. Server and app+logs are in `SY_HOME\logs`. Model-list keys entered in Routes are saved in the+current user's Windows Credential Manager. Coding tools keep their own login files.++Use `cargo desktop uninstall` to stop and remove both tasks, the shortcut, and+the installed executables. Uninstall preserves settings, accounts, and history,+and makes a recovery copy of the Codex profile before removing it.## Rust Libraries@@ -128,3 +234,6 @@ uv run pytest tests/ -vThe `dev` dependency group contains testing and linting tools and is not exposedin the published wheel metadata.++See the [desktop and terminal quickstart](crates/switchyard-desktop/README.md) for+first-run setup, reviewed settings changes, usage, recovery, and safe uninstall.diff --git a/Makefile b/Makefiledeleted file mode 100644index eadc87cff..000000000--- a/Makefile+++ /dev/null@@ -1,22 +0,0 @@-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0--.DEFAULT_GOAL := help-.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"--## Install the Switchyard background server as a systemd user service.-install-linux:- @scripts/linux/install.sh--## Print what install-linux would do, without changing anything.-install-linux-dry-run:- @scripts/linux/install.sh --dry-run--## Remove the systemd user service, the sy Codex profile, and the codex alias.-uninstall-linux:- @scripts/linux/uninstall.shdiff --git a/README.md b/README.mdindex da365228f..aed6d3706 100644--- a/README.md+++ b/README.md@@ -99,6 +99,9 @@ The standalone server is provided only for demos and local evaluation. It is not[Evaluate routing locally](docs/operations/local_evaluation.md) with the standalone server and your own model pool, then [verify routing is active](docs/operations/local_evaluation.md#verify-routing-is-active).+The [desktop and terminal quickstart](crates/switchyard-desktop/README.md) covers+local installation, coding-tool connections, sessions, usage, recovery, and uninstall.+Agent-specific guides are available for [pi](docs/integrations/pi.md) and[Oh My Pi](docs/integrations/oh_my_pi.md).diff --git a/crates/switchyard-desktop/README.md b/crates/switchyard-desktop/README.mdnew file mode 100644index 000000000..e028d95d2--- /dev/null+++ b/crates/switchyard-desktop/README.md@@ -0,0 +1,546 @@+# Switchyard desktop and terminal apps++The macOS and Windows desktop apps and terminal app show usage, edit routes, install+harness settings, and open sessions in separate Git worktrees. The server+handles routing and continues when the app quits. The desktop app uses Tauri 2;+the terminal app uses Ratatui.++## Install and update++Install the app from the repository root with the repository's pinned Rust+toolchain (currently Rust 1.99). Install Rust through rustup and keep Cargo on+`PATH`. Native dependencies also need a C compiler and linker: Xcode Command+Line Tools on macOS, or GCC/Clang and the system development libraries on Linux.+Cargo downloads dependencies on the first build. The default Codex profile+requires Codex CLI 0.134.0 or newer and a ChatGPT login. Sign in with Codex+before using it.++```sh+cargo desktop install+```++Run the same command to replace an existing installation. The command builds+the current checkout; update the checkout first to install newer code.++On macOS, the Rust installer builds the desktop app and server, installs+`~/Applications/Switchyard.app`, and loads two per-user LaunchAgents. It signs+the app ad hoc for local use. The app has no Developer ID signature or+notarization. Reinstalling keeps existing server settings, prices, accounts, and+log history.++The installer builds the binaries and validates the server config before+stopping services. On macOS, it also signs the replacement app before stopping+services. Each file replacement is atomic, but the complete installation is not.+If installation fails after services stop, fix the reported error and run `cargo+desktop install` again. Install and uninstall share a lock for your home+directory. If another installation holds it, wait for that command to finish and+retry.++By default, the source installer writes `~/.codex/sy.config.toml` for+`codex -p sy` and keeps `~/.codex/config.toml` unchanged. Set `SY_PROFILE` to+choose another profile name. The installer writes `$SY_PROFILE.config.toml` in+the Codex config directory. For example:++```sh+export SY_PROFILE=composite-gpt-6-sol-gpt-6-luna+cargo desktop install+codex -p "$SY_PROFILE"+```++Remove the app and recorded profile with `cargo desktop uninstall`. Uninstall+uses the saved installation location and profile. Conflicting shell overrides+require an explicit `uninstall --settings FILE` selection. Uninstall keeps an+exact recovery copy of the selected profile before removal. Restore harness+routing from **Connect tools** first; custom and account settings remain and+may still point at the removed server. Preview removal of a selected installation+without changing files or services:++```sh+cargo desktop uninstall --settings FILE --dry-run+```++Set `SY_MODEL` to choose an existing public route ID. New installs use+`composite-gpt-6-sol-gpt-6-luna`. Existing server configs stay saved, so set+`SY_MODEL` to one of their routes when installing with a custom config. The+profile leaves `approval_policy` and `sandbox_mode` to your existing Codex+settings. Reinstalling backs up the profile before updating its managed keys. It+preserves unrelated profile settings. Updates from Settings preserve the entire+profile. `SY_PROFILE` must start with an ASCII letter or digit, use only ASCII+letters, digits, underscores, or hyphens, and contain at most 128 characters.+For example, the installer rejects `SY_PROFILE=team.dev` before creating app or+config files.++Open the app from Finder or Spotlight. Closing the window removes the running+app from the Dock and keeps the tray menu. Opening the window from the tray+restores the Dock icon. A shortcut you pinned to the Dock stays there.+Left-click the tray icon to see whether the server responds, today's and this+week's requests, tokens, spending, and savings, and each model's share of this+week's tokens. A note explains missing savings, such as a baseline model without+rates. On macOS the popup opens like a status item menu: its left edge follows+the icon, its top sits just below the menu bar, and it uses the system font and+the system light or dark appearance. The popup rereads the routing log every+`refresh_seconds` (at least 5) while it is open. **Restart server** and **Open+server config…** run from the popup and show their result there. **Settings…**,+**Connect tools…**, and **Open Switchyard** open the corresponding desktop view+and close the popup. **Quit Switchyard** quits the app. Escape or a click outside+the popup dismisses it. Clicking the tray icon again also closes it.++**Settings → Appearance** chooses **System**, **Dark**, or **Light** for the app+window. System follows the device's light or dark appearance. Existing saved+Canary preferences select Dark.++On macOS, the navigation sidebar shows native regular glass where supported,+with the native sidebar material as a fallback. The popup uses the same glass+effect with a popover material fallback. The page header, editors, charts, and+tables use solid backgrounds. The app checks macOS Reduce Transparency and Reduce+Motion settings every second in both windows. Reduce Transparency covers the+native material with opaque backgrounds; a failed accessibility check also+restores opaque backgrounds. Windows uses opaque backgrounds.++Right-click the tray icon for the same summary as text rows, followed by+**Restart server**, **Open server config…**, **Settings…**, **Open+Switchyard**, **Connect tools…**, and **Quit Switchyard**. The menu rereads the+routing log every `refresh_seconds` (at least 5), like the earlier menu bar app.+A failed restart opens the app window with the error. Choose+**Open Switchyard** to return or **Quit Switchyard** to exit. Quit waits for a+queued or running operation to finish. The server continues running after the+app quits.++**Settings → Review update…** shows the checkout and planned changes. **Build+and reinstall** starts the Rust installer from the checkout used for this+installation. It builds that checkout's current commit and preserves the current+Codex profile. Review the checkout, local changes, and planned actions before+starting. Settings shows the update stage and outcome. The updater keeps running+when installation stops the desktop app. Only one update runs at a time.+Progress and errors go to `~/.switchyard/logs/update.log` (under `SY_HOME` when+customized). Keep the checkout and a Rust toolchain available. Update the+checkout first to choose the code you want to build.++Preview installation with `cargo desktop install --dry-run`. On Linux, the same+command installs the terminal app and a systemd user service for the server.+Linux installation requires an active systemd user session. Containers,+SSH sessions without a user service manager, and distributions without systemd need+separate service setup. The repository targets x86-64-v3 CPUs on Linux x86_64+and Neoverse N1 CPUs on Linux aarch64; older CPUs may not run the binaries.+The desktop GUI runs on macOS and Windows. Windows requires the MSVC build tools, WebView2, and a Task Scheduler user session.+On Linux, login and session launch open the terminal program named by `TERMINAL`,+or a detected terminal program. Open-file actions use `xdg-open`. Model discovery+needs `curl`; session creation needs Git and the selected harness.+With a custom Linux `SY_HOME`, pass the settings file explicitly:++```sh+"$SY_HOME/bin/switchyard-desktop" "$SY_HOME/desktop.toml" --tui+```++Run the terminal app with:++```sh+~/.switchyard/bin/switchyard-desktop --tui+# This command runs the terminal app from a checkout.+cargo run -p switchyard-desktop -- --tui+```++The terminal app runs every action that the desktop app sends. It has seven+pages: Overview, Calls, Models, Routes, Harnesses, Sessions, and Settings. When+the full page names do not fit, the tab bar shows the first three letters of+each name. Overview shows the server, today's and the past seven days' calls,+spending, and savings, calls per hour, and the top models; it has no keys of its+own. The status bar shows the current page's keys, and `?` opens a window that+lists the keys of every page:++| Page | Key | What it does |+|---|---|---|+| Every page | `1`–`7`, Tab, Shift-Tab, ←, → | Switch pages |+| Every page | `r`, F5 | Reload usage, calls, and server health |+| Every page | `?` | Show or hide the list of keys |+| Every page | `q`, Ctrl-C | Quit the app; the server keeps running |+| Calls | ↑, ↓, `j`, `k`, PgUp, PgDn, `g`, `G` | Select a call |+| Calls | `/` | Filter by model, route, session, or turn |+| Calls | `s` | Show one session at a time, then all sessions again |+| Calls | Enter | Open the selected call's details |+| Calls | Esc | Clear the filter and the session |+| Models | `p`, `]`, `[` | Switch between today, the past 7 days, and the whole log |+| Routes | ↑, ↓, `j`, PgUp, PgDn, `g`, `G` | Select a route |+| Routes | `/` | Filter by public model ID, config name, algorithm, endpoint, or model |+| Routes | Esc | Clear the filter |+| Routes | `e` | Edit the route's algorithm and models |+| Routes | `a` | Create a route |+| Routes | `n` | Rename the route |+| Routes | `c` | Duplicate the route |+| Routes | `d` | Delete the route |+| Routes | `m` | Load the model IDs that an endpoint offers |+| Routes | `k` | Save an endpoint's model-list key, then load its model IDs |+| Harnesses | ↑, ↓, `j`, `k`, PgUp, PgDn, `g`, `G` | Choose the route to install |+| Harnesses | `t` | Select the next harness |+| Harnesses | `a` | Select the next saved account, then the harness's own settings again |+| Harnesses | `x` | Use a custom settings file; leave it empty to use the detected settings |+| Harnesses | `p` | Preview the settings diff |+| Harnesses | `i` | Review and apply routing to the harness |+| Harnesses | `u` | Review and restore the original settings |+| Harnesses | `n` | Sign in to another subscription account |+| Harnesses | `l` | Sign in to the selected account again |+| Harnesses | `o` | Open the selected account folder in the editor |+| Harnesses | `d` | Archive the selected account |+| Sessions | ↑, ↓, `j`, `k`, PgUp, PgDn, `g`, `G` | Choose the route for a new session |+| Sessions | `t` | Select the next harness for a new session |+| Sessions | `a` | Select the next saved account for a new session |+| Sessions | `s` | Select the next recorded session |+| Sessions | `l` | Review and launch a worktree session |+| Sessions | `n` | Sign in to another subscription account |+| Sessions | `o` | Open the selected session folder in the editor |+| Sessions | `d` | Review and remove the selected session |+| Settings | ↑, ↓, `j`, `g`, `G` | Select an action |+| Settings | Enter | Run the selected action |+| Settings | `o` | Open the server config |+| Settings | `c` | Check the server config |+| Settings | `b` | Restart the server |+| Settings | `a` | Open the app settings |+| Settings | `e` | Change the baseline model and refresh interval |+| Settings | `p` | Open the model prices |+| Settings | `k` | Check the saved server keys |+| Settings | `s` | Save a server key |+| Settings | `i` | Import a server key from your login shell |+| Settings | `x` | Remove a saved server key |+| Settings | `u` | Review an update from source |+| Settings | `l` | Open the update log |+| Settings | `v` | Open the server logs folder |++The Harnesses and Sessions pages share the selected harness, account, and+route, and the Routes filter limits the routes that they offer. The Harnesses+page shows the settings preview only while the harness, account, and route+still match it.++Actions that change files ask you to type a confirmation, and most show a+review first. Editing, creating, renaming, and duplicating a route ask for+`SAVE`. Deleting a route asks for its public model ID, and archiving an account+asks for the account name. Applying routing asks for `INSTALL`, restoring+settings asks for `RESTORE`, launching a session asks for `LAUNCH`, removing a+session asks for `REMOVE`, and source updates ask for `UPDATE`. Restarting the+server asks you to press `y`. In a review, ↑ and ↓ scroll the preview, Enter+confirms the typed word, and Esc cancels.++While you filter calls or routes, Enter keeps the filter, Esc clears it, Ctrl-U+erases the text, and Ctrl-W erases the last word. Short messages appear in the+status bar, and Esc dismisses them. Errors and warnings stay until you dismiss+them. A warning means an action did only part of its work, such as saving a+route when the server could not restart. Long messages and results with details+open a window that ↑ and ↓ scroll and Esc, Enter, or `q` closes.++In forms, Tab and Shift-Tab change fields, ↑ and ↓ choose algorithms and+endpoints, and Enter submits. Esc cancels, and Ctrl-U clears a field. The left+and right arrow keys, Home, End, Backspace, Delete, and paste edit text. Key+fields show one bullet per character. A failed submission keeps the form and+its values. The terminal restores its screen and input mode on exit. `--print`+prints the usage summary without opening either app. `--tui` cannot be combined+with `--print` or `--validate-toml`.++## Routes++**Create route…** asks for the public model ID that harnesses request, the config+name for the route's table, the routing algorithm, and one endpoint and model for+each model the algorithm uses. For example, **Stage router** asks for a capable+and an efficient model, and **Random split** starts with two models and can add+more. The config name follows the public model ID until you edit it. Switching+algorithms keeps the models that both algorithms use.++Every choice field in the app is a searchable list. Type any letters of a name in+order, such as `g6l` for `gpt-6-luna`, and separate words to match each one.+Arrow keys move through the list, Enter picks, and Escape closes it. Model fields+also accept an ID that the list does not show.++The route library searches public model IDs, algorithms, endpoints, and model+choices. Select a route to edit its algorithm and model roles. The app opens one+editor at a time, even when the config contains hundreds of routes. **Refresh+suggestions** loads the endpoint's list; you can also type an unlisted model ID.+ChatGPT's private Codex endpoint uses the saved Codex model list and configured+targets. The diagram shows the selected algorithm's model roles; click a role+to focus its endpoint field. At narrow widths, **Route library** and **Selected+route** switch between the route list and selected editor. **Review changes…**+shows the changes before **Save and restart** applies them. The app keeps drafts+during the app session until saving or+**Discard unsaved edits…**. Discarding changes only resets the editor. **Delete+route…** removes the selected route after confirmation, preserves its targets+and endpoint settings, and uses the same validation, backup, and restart as+saving. Refresh keeps drafts and scroll and restores focus to matching form fields.+Drafts belong to their config file. Selecting another file keeps the drafts for+the original file. Switching algorithms preserves each algorithm's full set of choices.++**Save and restart** asks the installed helper to check the complete edited file+with the installed server's `--dry-run`. The check uses the saved server keys,+which are the keys the server starts with. If the edited file names a key that+is not saved, the check fails. See [Server Keys](../../INSTALLATION.md#server-keys).+The app preserves comments and unrelated tables, saves a backup+beside the config, and restarts the server. A failed check leaves the file+unchanged. A restart failure after saving is reported separately. The app re-reads+the config and rejects concurrent changes detected before replacement. A draft+from a different server config file is rejected before saving.++Switching algorithms writes the new algorithm's default settings and removes+settings specific to the old algorithm. Targets keep their existing model+settings, such as `extra_body` and `omit_body_fields`; the review names those+settings before saving when a model family changes. Check them if the new+provider rejects requests. Shared targets are copied when an edit would change+another route.++API keys entered for model lists stay in macOS Keychain or Windows Credential Manager. The app sends keys to+curl through stdin and omits them from frontend snapshots. An endpoint must be+configured to use authentication before it accepts a model-list key. An entered+key applies only to that endpoint's exact `base_url`. On macOS and Windows, submitting a key+always requests a fresh model list; a rejected key is not saved and leaves+the cached list unchanged. Model-list keys do not replace the server's+`api_key_env` keys, which you save under **Settings → Server keys**. The app and+server LaunchAgents do not load shell startup files.++On other platforms, the app rejects entered model-list keys; set the environment+variable named by the endpoint's `api_key_env` and make it available to the app+instead.++## Server keys++**Settings → Server keys** lists each variable that the server config names+with `api_key_env` and says whether a key is saved for it. The installed server+reads only these saved keys, never your shell's variables. To save a key, type+or paste it in the hidden field and press Enter. Select **Show key** to check+what you typed, or choose **Import from shell** to read the variable once. On+macOS and Linux it reads the variable from your login shell; on Windows it reads+your Windows environment variables. **Remove…** deletes a saved key after you+confirm. The installed helper saves each key in macOS Keychain, Windows+Credential Manager, or the Linux Secret Service keyring (GNOME Keyring or KDE+Wallet).+The app passes the key to the helper through standard input and never stores+it. Restart the server to use a changed key. After a change, the section shows+**Restart server now**.++## Install harness settings++**Connect tools** has one harness selector for Codex CLI, Codex app, Claude+Code, and Pi. A harness is an app or CLI that sends model requests through+Switchyard. macOS finds the Codex app by its registered bundle identity,+including copies renamed to `ChatGPT.app`. Windows reads the current user's+`OpenAI.Codex` MSIX registration to find the app. Choose a route and settings location+to compare the current and proposed settings and their exact file paths.+Credential values stay hidden. The preview changes no files. **Apply routing…**+shows a confirmation before saving. Apply compares the reviewed file contents+with the current files and requires a new review if they changed. Progress+appears while the action runs. One dismissible notification shows the result,+with backup paths and diagnostics in **Details**. If the settings already match,+the button reads **Routing already applied**. An optional absolute file path+selects settings in another location. For Pi, choose `models.json`; the app also+uses `settings.json` beside it. A custom file cannot be combined with a saved+account.++The app's **Connect tools** page defaults to `sy.config.toml` for Codex CLI and+`codex -p sy`. The source installer's `SY_PROFILE` choice does not change this+destination. Select a custom file to update another profile. With the normal+user settings location, the Codex app option changes shared defaults in+`config.toml` for both the app and CLI. A custom file or saved account changes+only that destination; the harness must load those settings separately.+Claude Code gets environment settings in `settings.json`. Pi gets a custom+provider in `models.json` and defaults in `settings.json`. Unrelated settings+remain.++Codex compacts a thread when its usage nears the model's context window, but it+does not know a Switchyard route ID. When the route sets `context_window` in the+server config, the Codex settings get `model_context_window` with that value, and+Pi's `contextWindow` uses it too. Without it, Codex never compacts on the route,+and Pi uses 128,000. A `model_catalog_json` entry for the route takes precedence+over `model_context_window`, so a catalog that lists the route with the wrong+window makes Codex compact at that size. Correct the catalog entry instead.++The app backs up each original file as `<filename>.switchyard-original`. If a+file did not exist, `<filename>.switchyard-original-missing` records its+absence. **Review restore…** lists the files and original backups. **Restore+settings** keeps a copy of each current file, then restores its backup or+removes the file if it was originally absent. The result lists the recovery+copies. A successful restore retires the original backup, so the next+installation backs up your current settings. If backup cleanup fails, retry+Restore before installing another route.++Install and Restore check every selected file before replacing any file.+Malformed settings and symlink settings files are rejected before writes. Each+replacement is atomic. If a later replacement fails, the app tries to restore+earlier files. A crash can leave Pi's two files out of sync, and rollback can+fail. Another process running as the same user can also change a file after the+app checks it. A failed replacement keeps original backups for manual recovery.+If backup cleanup fails after restoration, the remaining receipts keep the+restored contents available for a retry. Recovery copies remain until you remove+them.++Caller login routes require a matching harness and provider: Codex for+ChatGPT or Claude Code for Anthropic. Pi requires a route whose API credentials+the server owns. Configure those credentials on the server before installing+the route. Claude settings with a user API key or bearer token must be cleared+before installing a subscription route. Switching from an API route installed+by Switchyard removes its placeholder credentials only when the existing model+settings and local endpoint match that installation. If the local endpoint has+changed, restore the original settings first. Restart the harness after+changing its defaults. Project settings, shell variables, and command-line+options can override them; check Claude's `/status` for shell overrides.++## Start sessions with separate logins and worktrees++Codex CLI and Claude Code support named accounts. Expand **Sign in to another+subscription account…** and enter a name. **Open login in Terminal…** opens the+harness’s own login command. Complete the login, refresh, and select the account.+Switchyard keeps account directories under `~/.switchyard/accounts`; the harness+owns their login files. The selected account determines where **Connect+tools** saves settings and which login a new session uses. Existing sessions+keep their login. Switchyard does not read, copy, or rotate OAuth tokens or+combine subscription quotas.++In **Sessions**, choose a route and login, enter an absolute Git project path,+and click **Review session**, then **Open Terminal…**. Each session starts from+that checkout's HEAD on a new branch in `~/.switchyard/worktrees` and opens in+Terminal. Uncommitted files stay in the original checkout. Each launched session+has its own model settings; launching another session does not change user+defaults. Codex app uses its own workspace controls; choose Codex CLI for+worktree sessions.++Codex and Claude launches send a session ID for usage correlation. Pi stores its+session under the private agent directory beside the worktree. Its requests+need an integration that sends session and turn IDs to appear as a correlated+session. Otherwise, Usage lists its calls under **All sessions**.++Use `git worktree list` and `git worktree remove` to manage checkouts after+saving or discarding changes. Successful launches keep their branches and+private settings directories until you remove them. Named account directories+also remain until you remove them. If launch setup fails, the app tries to+remove the worktree, branch, and private settings it created; cleanup can fail.++The app does not show provider reset windows or manage task dependencies,+session resume, remote workspaces, or review comments. Provider limits still apply.++## Usage++Usage displays up to 100 calls per page. **Previous calls** and **Next calls** move+through the filtered results. **Copy filtered calls** copies all matching calls,+including calls on other pages. Sidebar navigation stays available while the app+refreshes the displayed data.++**Usage** lists the actual model, public route, timestamp, input, cached, and+output tokens, and recorded session and turn IDs for each completed model call.+Filter by session or search for a turn, model, or route. A user turn may contain+several calls. Classifier calls are marked as routing overhead. Missing IDs+appear as **Session not recorded** or **Turn not recorded** in the desktop app+and **Not recorded** on the terminal app's Calls page. Switchyard does not+infer them from prompts.++Recent history reads the last 8 MiB of the log plus one byte to check whether the+first record is complete. It keeps at most 5,000 complete records and excludes+partial records. Usage labels a limited view and counts unreadable records.+Overview starts with model totals. Use **Period** to select today, the past+seven local calendar days, or all retained history. **Compare** switches between+models, routes, and sessions; **Measure** switches between tokens and calls.+The chart shows the ten largest totals, and the table lists every matching+name with exact counts. Click a name to see its recent calls with the same+period filter. The daily chart shows usage by model for the past seven days.++Model, route, and daily totals use the incremental full-log reader. Session+comparisons and per-turn details use the bounded recent history and label its+limits. Replacing or truncating the log resets full-log totals. The calls-per-hour+chart on the terminal app's Overview page also uses recent history.++Charts use Apache ECharts 6.1.0, bundled in `ui/vendor` with its Apache license+and NOTICE. They load locally and require no CDN or frontend build tool.+The minified dependency adds about 1.1 MB before compression. Tooltips render+on the canvas, and tables provide readable counts and keyboard links.++Routing history stores no prompt or response text.+Observed tokens do not report provider quotas, reset windows, or authoritative+billing. Both apps refresh usage at the configured `refresh_seconds` interval.++## Settings++The app reads `$SY_HOME/desktop.toml` on refresh and before each operation.+An installed app uses the `SY_HOME` it was installed with. `SY_HOME` defaults to+`~/.switchyard`, so by default the file is `~/.switchyard/desktop.toml`:++```toml+server_url = "http://127.0.0.1:4123"+routing_log = "~/.switchyard/routing.jsonl"+config_file = "~/.switchyard/composite.toml"+# This optional file replaces the bundled price table.+# pricing_file = "~/.switchyard/prices.toml"+launchd_label = "com.nvidia.switchyard.server"+baseline_model = "gpt-6-sol"+refresh_seconds = 30+```++Use **Settings → Open server config** to edit advanced routing options and+**Settings → Open model price override** to edit a configured price file. Without an+override, **About model prices** explains how to configure one.+Model lists are cached beside the app settings in `model-lists.json`.+Usage remains readable when the route config is missing or malformed.++## How costs and savings are computed++The server writes one JSONL record per call, with the model that answered, its+token counts, and its cost. The server and app use the same+[bundled rates](../switchyard-costs/prices.toml) by default. To replace the table,+pass `--pricing-file PATH` to the server and set `pricing_file` to the same TOML or JSON+file in app settings. The [Pi cost guide](../../docs/integrations/pi.md#estimate-the-cost)+describes the file format. If an explicitly configured file is missing or invalid,+the server and app report an error instead of using bundled rates.++For each answer, the server records the charge that the provider reports, from+`usage.cost` in the response or, for a buffered LiteLLM response, from the+`x-litellm-response-cost` header. Otherwise it records an estimate from those+rates. The server cannot see the headers of classifier and judge calls, so+those calls use `usage.cost` or the estimate. The app adds up these recorded+costs and does not price calls itself. The log covers the calls that the server+observed; a request cancelled before its answer finished may have no record.++- **Cost** is every recorded call, including Switchyard's own classifier calls.+- **Baseline** is the caller-facing calls only, with their tokens priced at the+ `baseline_model` rates from the selected price table. Classifier calls have no+ baseline counterpart, because without Switchyard they would not happen.++Savings are the difference, so routing overhead counts against the figure and a+bad day shows a negative number. A period shows savings only when every call in+it has a recorded cost, every answer has token counts, and the selected table has+rates for `baseline_model`, including `cache_write_1h` when answers wrote to a+one-hour cache. Calls recorded before the server priced calls have no cost, and+neither do calls to a model that has no rates and no provider charge. Overview counts these calls and+explains costs under **How costs work**.++The server loads rates when it starts, so restart it after editing an override+file. Bundled rates change only when you install a version with updated rates.+Each record keeps the cost from when its call finished, so editing rates does+not change past totals.++The bundled table includes OpenAI and Claude text-token rates in USD per million+tokens. For GPT-5.6 and newer, `cache_write` uses OpenAI's 30-minute rate, which+is 1.25 times the input rate. Older OpenAI models use the ordinary input rate+for separately counted writes, with no extra write fee. Claude rates distinguish+five-minute writes (`cache_write`) from one-hour writes (`cache_write_1h`).+Estimates exclude long-context and service-tier adjustments, OpenAI's 12-hour+cache-write pricing, tool fees, and time-based cache storage. Entries with provider+prefixes use list-rate estimates; billed charges may differ.++Installation uses bundled rates without creating a price file and preserves+existing custom price files.+For older `[prices]` settings, remove the table to use bundled rates, or convert+it to the shared TOML or JSON rate format and select it with `pricing_file`. The+installer does not migrate old settings.++Codex's "Approve for me" reviews count too. The server config that the+installer writes sends them to `codex-auto-review` on the ChatGPT backend. With+a ChatGPT login, Codex sends these reviews to `codex-auto-review` even without+Switchyard, so the bundled rates price that model at the `gpt-6-sol`+rates. Each review then adds the same amount to the cost and to the baseline,+so reviews do not change the dollar amount saved. They do lower the percentage+a little, because the baseline grows. If you change `baseline_model`, use a+custom replacement table with matching `codex-auto-review` rates.++The server needs rates for the model ID that the routing log records for+reviews, which is the reviewer target's `id`. Without them, a review that the+provider does not price has no recorded cost, and the app hides the savings for+every period that includes it. The installer does not overwrite an existing+`composite.toml` or an existing price override. Older installations may need the+review route added by hand. The bundled table includes `codex-auto-review`; a+custom replacement table must include its own reviewer rates. If a reviewer+uses another model ID, add rates for that ID.++These are list-price estimates unless the provider reports a charge. On a+ChatGPT login there is no per-token bill, so read them as "what this traffic+would have cost at API rates".diff --git a/crates/switchyard-desktop/src/gui.rs b/crates/switchyard-desktop/src/gui.rsindex 08d79fad4..cb1fcd267 100644--- a/crates/switchyard-desktop/src/gui.rs+++ b/crates/switchyard-desktop/src/gui.rs@@ -3,6 +3,9 @@//! Tauri manages the window and tray, and runs blocking operations on worker threads.+#[cfg(target_os = "macos")]+mod panel;+use crate::controller::{Action, Controller, Reply, Snapshot};use crate::summary::Overview;use std::path::PathBuf;@@ -14,7 +17,7 @@ use std::time::Duration;use tauri::{Manager, State,menu::{Menu, MenuItem, PredefinedMenuItem},- tray::TrayIconBuilder,+ tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},};struct Shared {@@ -276,6 +279,13 @@ async fn action(app: tauri::AppHandle, action: Action) -> Result<Reply, String>dispatch(app, action).await}#[tauri::command]+async fn tray_overview(app: tauri::AppHandle) -> Result<TrayView, String> {+ // The overview probes the server, so it runs on a worker thread.+ tauri::async_runtime::spawn_blocking(move || refresh_tray(&app))+ .await+ .map_err(|e| e.to_string())+}+#[tauri::command]fn quit_app(app: tauri::AppHandle) {quit(&app);}@@ -403,6 +413,194 @@ fn accessibility() -> serde_json::Value {serde_json::json!({"native_material": false, "reduce_transparency": true, "reduce_motion": false})}+/// POPUP_WIDTH matches the width of macOS status item menus such as Wi-Fi and Sound.+const POPUP_WIDTH: f64 = 320.0;++// The webview measures popup height; invalid sizes must not reach AppKit.+fn popup_height(height: f64) -> Result<f64, String> {+ if !height.is_finite() || height <= 0.0 {+ return Err("The popup height must be a positive number.".into());+ }+ Ok(height.clamp(120.0, 620.0))+}++#[tauri::command]+fn tray_size(app: tauri::AppHandle, height: f64) -> Result<(), String> {+ let height = popup_height(height)?;+ #[cfg(target_os = "macos")]+ app.state::<panel::TrayPanel>().resize(height);+ #[cfg(windows)]+ if let Some(window) = app.get_webview_window("tray") {+ let anchor = {+ let mut placement = app.state::<TrayPopup>().lock();+ placement.height = height;+ placement.anchor+ };+ // The popup moves as well as resizes, so a popup above a bottom taskbar stays+ // against it when its height changes.+ match (anchor, window.current_monitor().map_err(|e| e.to_string())?) {+ (Some(anchor), Some(monitor)) => {+ place_popup(&window, &monitor, anchor, height).map_err(|e| e.to_string())?;+ }+ _ => window+ .set_size(tauri::LogicalSize::new(POPUP_WIDTH, height))+ .map_err(|e| e.to_string())?,+ }+ }+ Ok(())+}++#[tauri::command]+fn tray_page(app: tauri::AppHandle, page: String) -> Result<(), String> {+ if !matches!(page.as_str(), "overview" | "install" | "settings" | "setup") {+ return Err("Choose Overview, Connect tools, or Settings.".into());+ }+ open_page(&app, &page);+ dismiss_tray(app)+}+#[tauri::command]+fn dismiss_tray(app: tauri::AppHandle) -> Result<(), String> {+ #[cfg(target_os = "macos")]+ app.state::<panel::TrayPanel>().dismiss();+ #[cfg(windows)]+ if let Some(window) = app.get_webview_window("tray") {+ window.hide().map_err(|error| error.to_string())?;+ }+ Ok(())+}+/// TrayPopup keeps what Windows needs to place the popup: the content height that the webview+/// last measured, in points, and the tray icon's rectangle from the click that opened it.+#[cfg(windows)]+struct TrayPopup(std::sync::Mutex<TrayPlacement>);+#[cfg(windows)]+#[derive(Clone, Copy)]+struct TrayPlacement {+ height: f64,+ anchor: Option<tauri::Rect>,+}+#[cfg(windows)]+impl TrayPopup {+ fn new() -> Self {+ // The first opening uses the largest height until the webview measures its content.+ Self(std::sync::Mutex::new(TrayPlacement {+ height: 620.0,+ anchor: None,+ }))+ }+ fn lock(&self) -> std::sync::MutexGuard<'_, TrayPlacement> {+ self.0+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ }+}+#[cfg(windows)]+fn place_popup(+ window: &tauri::WebviewWindow,+ monitor: &tauri::Monitor,+ anchor: tauri::Rect,+ height: f64,+) -> tauri::Result<()> {+ let (position, size) =+ popup_geometry(anchor, monitor.work_area(), monitor.scale_factor(), height);+ window.set_size(size)?;+ window.set_position(position)+}+/// Pressing the tray icon takes focus from the popup before the click arrives. The popup+/// stays open for that focus loss, so the click closes it instead of reopening it.+#[cfg(windows)]+fn cursor_on_tray_icon(window: &tauri::Window) -> bool {+ let Some(anchor) = window.state::<TrayPopup>().lock().anchor else {+ return false;+ };+ let (Ok(cursor), Ok(scale)) = (window.cursor_position(), window.scale_factor()) else {+ return false;+ };+ let origin = anchor.position.to_physical::<f64>(scale);+ let size = anchor.size.to_physical::<f64>(scale);+ cursor.x >= origin.x+ && cursor.x < origin.x + size.width+ && cursor.y >= origin.y+ && cursor.y < origin.y + size.height+}+// Windows uses physical coordinates to keep the popup within the target monitor's work area.+#[cfg(windows)]+fn popup_geometry(+ rect: tauri::Rect,+ area: &tauri::PhysicalRect<i32, u32>,+ scale: f64,+ height: f64,+) -> (tauri::PhysicalPosition<i32>, tauri::PhysicalSize<u32>) {+ let origin = rect.position.to_physical::<f64>(scale);+ let icon = rect.size.to_physical::<f64>(scale);+ let size = tauri::PhysicalSize::new(+ (POPUP_WIDTH * scale)+ .min(f64::from(area.size.width))+ .round() as u32,+ (height * scale).min(f64::from(area.size.height)).round() as u32,+ );+ let x = (origin.x + icon.width / 2.0 - f64::from(size.width) / 2.0).clamp(+ f64::from(area.position.x),+ f64::from(area.position.x) + f64::from(area.size.width - size.width),+ );+ let y = (origin.y + icon.height + 6.0 * scale).clamp(+ f64::from(area.position.y),+ f64::from(area.position.y) + f64::from(area.size.height - size.height),+ );+ (+ tauri::PhysicalPosition::new(x.round() as i32, y.round() as i32),+ size,+ )+}++fn toggle_tray(+ tray: &tauri::tray::TrayIcon,+ position: tauri::PhysicalPosition<f64>,+ rect: tauri::Rect,+) -> tauri::Result<()> {+ let app = tray.app_handle();+ #[cfg(target_os = "macos")]+ {+ let _ = (position, rect);+ // AppKit frames avoid converting Tauri's physical, top-left coordinates back to points.+ let Some((anchor, area)) = panel::status_item_frames(tray) else {+ return Ok(());+ };+ if app.state::<panel::TrayPanel>().toggle(anchor, area)+ && let Some(window) = app.get_webview_window("tray")+ {+ window.eval("window.dispatchEvent(new Event('switchyard-tray-open'))")?;+ }+ Ok(())+ }+ #[cfg(windows)]+ {+ let Some(window) = app.get_webview_window("tray") else {+ return Ok(());+ };+ if window.is_visible()? {+ return window.hide();+ }+ if let Some(monitor) = window.available_monitors()?.into_iter().find(|monitor| {+ let origin = monitor.position();+ let size = monitor.size();+ position.x >= f64::from(origin.x)+ && position.x < f64::from(origin.x) + f64::from(size.width)+ && position.y >= f64::from(origin.y)+ && position.y < f64::from(origin.y) + f64::from(size.height)+ }) {+ let height = {+ let mut placement = app.state::<TrayPopup>().lock();+ placement.anchor = Some(rect);+ placement.height+ };+ place_popup(&window, &monitor, rect, height)?;+ }+ window.show()?;+ window.set_focus()?;+ window.eval("window.dispatchEvent(new Event('switchyard-tray-open'))")?;+ Ok(())+ }+}fn open_page(app: &tauri::AppHandle, page: &str) {if let Some(window) = app.get_webview_window("main") {// Only the fixed page names from the tray menu reach this script.@@ -431,6 +629,9 @@ fn activation(app: &tauri::AppHandle, visible: bool) -> tauri::Result<()> {}}fn show(app: &tauri::AppHandle) {+ if let Err(error) = dismiss_tray(app.clone()) {+ eprintln!("switchyard-desktop: could not hide the preview: {error}");+ }if let Some(window) = app.get_webview_window("main")&& let Err(e) = activation(app, true).and_then(|()| window.show())@@ -458,6 +659,10 @@ pub fn run(controller: Controller, settings: PathBuf) -> Result<(), String> {choose_path,appearance,accessibility,+ tray_size,+ tray_page,+ tray_overview,+ dismiss_tray,quit_app]).setup(|app| {@@ -469,6 +674,37 @@ pub fn run(controller: Controller, settings: PathBuf) -> Result<(), String> {tauri::window::EffectState::FollowsWindowActiveState,))?;}+ let tray_window = tauri::WebviewWindowBuilder::new(+ app,+ "tray",+ tauri::WebviewUrl::App("tray.html".into()),+ )+ .title("Switchyard usage")+ .inner_size(POPUP_WIDTH, 620.0)+ .transparent(cfg!(target_os = "macos"))+ .decorations(false)+ .resizable(false)+ .always_on_top(true)+ .skip_taskbar(true)+ .visible(false)+ .focused(false)+ .build()?;+ #[cfg(target_os = "macos")]+ {+ // Like a menu, the popup keeps the active material although it never activates+ // the app.+ tray_window.set_effects(material(+ tauri::window::Effect::Popover,+ Some(panel::CORNER_RADIUS),+ tauri::window::EffectState::Active,+ ))?;+ app.manage(panel::TrayPanel::new(&tray_window).map_err(std::io::Error::other)?);+ }+ #[cfg(windows)]+ {+ let _ = tray_window;+ app.manage(TrayPopup::new());+ }let tray_pixels = include_bytes!("../icons/tray.rgba");TrayIconBuilder::with_id(TRAY_ID)@@ -476,6 +712,22 @@ pub fn run(controller: Controller, settings: PathBuf) -> Result<(), String> {.icon_as_template(false).tooltip("Switchyard — routes and usage").menu(&tray_menu(app.handle(), &["Reading usage…".into()])?)+ .show_menu_on_left_click(false)+ .on_tray_icon_event(|tray, event| {+ if let TrayIconEvent::Click {+ position,+ rect,+ button: MouseButton::Left,+ button_state: MouseButtonState::Up,+ ..+ } = event+ && let Err(error) = toggle_tray(tray, position, rect)+ {+ eprintln!(+ "switchyard-desktop: could not show or hide the usage preview: {error}"+ );+ }+ }).on_menu_event(|app, event| match event.id.as_ref() {"restart" => run_tray_action(app, Action::Restart {}),"open-config" => run_tray_action(app, Action::OpenConfig {}),@@ -486,7 +738,7 @@ pub fn run(controller: Controller, settings: PathBuf) -> Result<(), String> {_ => {}}).build(app)?;- // Like the menu bar app, the tray rereads usage on the settings interval.+ // Like the earlier menu bar app, the tray rereads usage on the settings interval.let handle = app.handle().clone();std::thread::spawn(move || {loop {@@ -508,10 +760,23 @@ pub fn run(controller: Controller, settings: PathBuf) -> Result<(), String> {}}}+ #[cfg(windows)]+ if window.label() == "tray"+ && matches!(event, tauri::WindowEvent::Focused(false))+ && !cursor_on_tray_icon(window)+ && let Err(error) = window.hide()+ {+ eprintln!("switchyard-desktop: could not hide the usage preview: {error}");+ }if let tauri::WindowEvent::CloseRequested { api, .. } = event {api.prevent_close();-+ if window.label() == "tray" {+ if let Err(error) = dismiss_tray(window.app_handle().clone()) {+ eprintln!("switchyard-desktop: could not hide the usage preview: {error}");+ }+ return;+ }// Accessory removes the running Dock entry while keeping the tray menu.if let Err(e) = window.hide().and_then(|()| {if window.label() == "main" {diff --git a/crates/switchyard-desktop/src/gui/panel.rs b/crates/switchyard-desktop/src/gui/panel.rsnew file mode 100644index 000000000..5b1acd36c--- /dev/null+++ b/crates/switchyard-desktop/src/gui/panel.rs@@ -0,0 +1,183 @@+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+// SPDX-License-Identifier: Apache-2.0++//! This module configures a nonactivating tray panel to join other apps' fullscreen Spaces.++use dispatch2::MainThreadBound;+use objc2::{DefinedClass, MainThreadOnly, define_class, msg_send, rc::Retained};+use objc2_app_kit::{+ NSApplication, NSBackingStoreType, NSColor, NSEvent, NSEventType, NSPanel,+ NSPopUpMenuWindowLevel, NSWindow, NSWindowCollectionBehavior, NSWindowStyleMask,+};+use objc2_foundation::{MainThreadMarker, NSProcessInfo, NSRect};+use std::cell::Cell;++/// MENU_GAP matches the space macOS leaves between the menu bar and a status item's menu.+const MENU_GAP: f64 = 5.0;++/// CORNER_RADIUS matches the corners of macOS 26 menus; the glass and tray.css use it too.+pub(super) const CORNER_RADIUS: f64 = 12.0;++// Like a status item's menu, the panel's left edge follows the icon and its top edge sits+// just below the menu bar. AppKit supplies points, so the frame needs no scale conversion.+fn popup_frame(anchor: NSRect, area: NSRect, height: f64) -> NSRect {+ let mut frame = area;+ frame.size.width = frame.size.width.min(super::POPUP_WIDTH);+ frame.size.height = frame.size.height.min(height);+ frame.origin.x = anchor.origin.x.clamp(+ area.origin.x,+ area.origin.x + area.size.width - frame.size.width,+ );+ let top = anchor.origin.y.min(area.origin.y + area.size.height) - MENU_GAP;+ frame.origin.y = (top - frame.size.height).clamp(+ area.origin.y,+ area.origin.y + area.size.height - frame.size.height,+ );+ frame+}++/// This function returns the status item's frame and its screen's visible frame in points.+pub(super) fn status_item_frames(tray: &tauri::tray::TrayIcon) -> Option<(NSRect, NSRect)> {+ tray.with_inner_tray_icon(|inner| {+ let mtm = MainThreadMarker::new()?;+ let window = inner.ns_status_item()?.button(mtm)?.window()?;+ Some((window.frame(), window.screen()?.visibleFrame()))+ })+ .ok()+ .flatten()+}++#[derive(Default)]+struct PopupState {+ anchor: Cell<NSRect>,+ area: Cell<NSRect>,+ height: Cell<f64>,+}++define_class!(+ // SAFETY: The panel is initialized as an NSPanel, and every method runs on the main thread.+ #[unsafe(super = NSPanel)]+ #[thread_kind = MainThreadOnly]+ #[ivars = PopupState]+ struct Popup;++ impl Popup {+ #[unsafe(method(canBecomeKeyWindow))]+ fn can_become_key(&self) -> bool { true }++ #[unsafe(method(canBecomeMainWindow))]+ fn can_become_main(&self) -> bool { false }++ #[unsafe(method(resignKeyWindow))]+ fn resign_key(&self) {+ // SAFETY: These inherited AppKit methods have no additional requirements.+ unsafe {+ let _: () = msg_send![super(self), resignKeyWindow];+ let mouse = NSEvent::mouseLocation();+ let anchor = self.ivars().anchor.get();+ // A left-click on the tray icon must reach toggle_tray before focus loss hides the panel.+ let tray_click = NSApplication::sharedApplication(self.mtm()).currentEvent()+ .is_some_and(|event| matches!(event.r#type(), NSEventType::LeftMouseDown | NSEventType::LeftMouseUp));+ if !tray_click || mouse.x < anchor.origin.x || mouse.x > anchor.origin.x + anchor.size.width+ || mouse.y < anchor.origin.y || mouse.y > anchor.origin.y + anchor.size.height {+ self.orderOut(None);+ }+ }+ }+ }+);++// MainThreadBound also releases the panel on the main thread during shutdown.+pub(super) struct TrayPanel(MainThreadBound<Retained<Popup>>);++impl TrayPanel {+ pub(super) fn new(window: &tauri::WebviewWindow) -> Result<Self, String> {+ let mtm = MainThreadMarker::new().ok_or("The tray panel must start on the main thread.")?;+ let pointer = window.ns_window().map_err(|error| error.to_string())?;+ // SAFETY: Tauri supplies a live NSWindow; its hidden window retains the webview and IPC registration.+ unsafe {+ let source = &*pointer.cast::<NSWindow>();+ let view = source+ .contentView()+ .ok_or("The tray webview has no content view.")?;+ let responder = source.firstResponder();+ let allocated = Popup::alloc(mtm).set_ivars(PopupState {+ anchor: Cell::new(NSRect::default()),+ area: Cell::new(source.frame()),+ height: Cell::new(620.0),+ });+ let panel: Retained<Popup> = msg_send![super(allocated),+ initWithContentRect: source.frame(),+ styleMask: NSWindowStyleMask::NonactivatingPanel,+ backing: NSBackingStoreType::Buffered,+ defer: false+ ];+ panel.setReleasedWhenClosed(false);+ panel.setOpaque(false);+ panel.setBackgroundColor(Some(&NSColor::clearColor()));+ panel.setHasShadow(true);+ panel.setTitle(&source.title());+ panel.setHidesOnDeactivate(false);+ panel.setBecomesKeyOnlyIfNeeded(false);+ panel.setLevel(NSPopUpMenuWindowLevel);+ let mut behavior = NSWindowCollectionBehavior::CanJoinAllSpaces+ | NSWindowCollectionBehavior::FullScreenAuxiliary+ | NSWindowCollectionBehavior::Stationary+ | NSWindowCollectionBehavior::IgnoresCycle;+ if NSProcessInfo::processInfo()+ .operatingSystemVersion()+ .majorVersion+ >= 13+ {+ behavior |= NSWindowCollectionBehavior::CanJoinAllApplications;+ }+ panel.setCollectionBehavior(behavior);+ source.setContentView(None);+ panel.setContentView(Some(&view));+ // Clipping the glass and the webview to one rounded shape also rounds the shadow.+ view.setWantsLayer(true);+ if let Some(layer) = view.layer() {+ layer.setCornerRadius(CORNER_RADIUS);+ layer.setMasksToBounds(true);+ }+ panel.makeFirstResponder(responder.as_deref());+ Ok(Self(MainThreadBound::new(panel, mtm)))+ }+ }++ pub(super) fn dismiss(&self) {+ self.0.get_on_main(|panel| panel.orderOut(None));+ }++ pub(super) fn resize(&self, height: f64) {+ self.0.get_on_main(|panel| {+ let state = panel.ivars();+ state.height.set(height);+ panel.setFrame_display(+ popup_frame(state.anchor.get(), state.area.get(), height),+ true,+ );+ panel.invalidateShadow();+ });+ }++ /// This function shows the panel below `anchor`, the status item's frame, within `area`,+ /// the visible frame of the status item's screen. It returns false when it hid the panel.+ pub(super) fn toggle(&self, anchor: NSRect, area: NSRect) -> bool {+ self.0.get_on_main(|panel| {+ // A panel visible on another Space must be shown here rather than hidden by this click.+ if panel.isVisible() && panel.isOnActiveSpace() {+ panel.orderOut(None);+ return false;+ }+ let state = panel.ivars();+ state.anchor.set(anchor);+ state.area.set(area);+ panel.setFrame_display(popup_frame(anchor, area, state.height.get()), true);+ panel.orderFrontRegardless();+ panel.makeKeyWindow();+ panel.invalidateShadow();+ true+ })+ }+}diff --git a/crates/switchyard-desktop/src/tui.rs b/crates/switchyard-desktop/src/tui.rsindex 7ff817096..7d3c0eab4 100644--- a/crates/switchyard-desktop/src/tui.rs+++ b/crates/switchyard-desktop/src/tui.rs@@ -5557,6 +5557,50 @@ mod tests {}}+ // Model lists and preview replies must preserve edits in a form opened after the request.+ #[test]+ fn preview_and_model_replies_preserve_replacement_forms() {+ let actions = [+ Action::Models {+ client: "endpoint".into(),+ refresh: true,+ key: None,+ base_url: None,+ },+ Action::PreviewRouteChange {+ generation: 0,+ operation: "create".into(),+ route: String::new(),+ name: "route".into(),+ id: "public".into(),+ algorithm: None,+ choices: vec![],+ },+ Action::PreviewSessionCleanup {+ id: "session".into(),+ },+ ];+ for action in actions {+ let mut app = App::new(Theme::new(false));+ app.harnesses_key(KeyCode::Char('x'));+ let (jobs, _inbox) = mpsc::channel();+ app.start(&jobs, Request::run(action, "Refreshing"))+ .expect("start");+ app.harnesses_key(KeyCode::Char('x'));+ app.paste("replacement");+ app.finish(+ Some(Ok(super::Reply {+ message: "Done".into(),+ data: json!({}),+ })),+ Ok(Box::new(Snapshot::default())),+ );+ let form = app.popup.as_mut().and_then(Popup::form_mut).expect("form");+ assert_eq!(form.value(0), "replacement");+ assert!(form.error.is_empty());+ }+ }+// The automatic key check must preserve the form opened while the save was running.#[test]fn key_refresh_after_saving_does_not_replace_a_new_form() {diff --git a/crates/switchyard-desktop/tests/frontend.test.cjs b/crates/switchyard-desktop/tests/frontend.test.cjsnew file mode 100644index 000000000..8d76c610d--- /dev/null+++ b/crates/switchyard-desktop/tests/frontend.test.cjs@@ -0,0 +1,88 @@+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+// SPDX-License-Identifier: Apache-2.0+'use strict';+const {test} = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const vm = require('node:vm');+function editor(invoke = () => new Promise(() => {})) {+ const elements = new Map();+ const element = selector => {+ if(!elements.has(selector))elements.set(selector,{dataset:{},append(){},querySelectorAll(){return [];},setAttribute(){},focus(){this.focused=true;}});+ return elements.get(selector);+ };+ const context = vm.createContext({+ window: {__TAURI__: {core: {invoke}}},+ document: {createElement:()=>({append(){}}),querySelector: element, querySelectorAll: () => []},+ setTimeout: () => {},structuredClone,+ });+ const source=fs.readFileSync(path.join(__dirname, '../ui/app.js'), 'utf8');+ // The fixture loads the real functions without starting the app's initial refresh.+ vm.runInContext(source.slice(0,source.indexOf("\ncontent.append(node('p','Loading Switchyard…'")), context);+ return context;+}+// The classifier occupies position zero, so copying by position would replace the capable model.+test('algorithm switches preserve model roles instead of positions', () => {+ const context = editor();+ const result = vm.runInContext(`+ const route = {kind:'composite',choices:[{model:'judge'},{model:'capable'},{model:'efficient'}]};+ const draft = {algorithm:'stage_router',choices:route.choices,memory:new Map([['Judge',route.choices[0]],['Capable',route.choices[1]],['Efficient',route.choices[2]]])};+ [roleChoice(draft,route,{tier:'Capable'},0).model,roleChoice(draft,route,{tier:'Efficient'},1).model];+ `, context);+ assert.deepEqual(Array.from(result), ['capable', 'efficient']);+});+// A successful editor redraw must preserve the distinction between a saved route and a failed restart.+test('editor redraw retains the saved route and restart result', async () => {+ const context = editor((command, args) => command === 'snapshot'+ ? new Promise(() => {})+ : Promise.resolve({message: args.action.kind === 'editor' ? 'Single model.' : 'Saved the route. Restart failed.',data:{warning:args.action.kind!=='editor'}}));+ const result = await vm.runInContext(`(async () => {+ busy = false;+ await run({kind:'apply'}, false);+ await run({kind:'editor'}, false);+ return status.textContent;+ })()`, context);+ assert.equal(result, 'Attention: Saved the route. Restart failed.');+});++// Navigation during a pending Usage refresh must not restore Usage's scroll position on Settings.+test('a pending refresh preserves the destination page scroll position', async () => {+ let release;+ const context=editor(()=>new Promise(resolve=>{release=resolve;}));+ vm.runInContext(`+ snapshot={};page='usage';scroller.scrollTop=200;+ scroller.scrollTo=(x,y)=>{scroller.scrollTop=y;};+ capturePageState=()=>({scroll:scroller.scrollTop});+ restorePageState=saved=>scroller.scrollTo(0,saved.scroll);+ render=()=>{};+ const pendingRefresh=refresh();+ `,context);+ await new Promise(setImmediate);+ vm.runInContext("navigate('settings')",context);+ release({errors:[]});+ await vm.runInContext('pendingRefresh',context);+ assert.equal(vm.runInContext('page',context),'settings');+ assert.equal(vm.runInContext('scroller.scrollTop',context),0);+});++test('route creation keeps pending model lists with their endpoint', async () => {+ const context=editor();+ vm.runInContext(`+ const controls=new Map();let load,resolveModels;+ node=()=>({dataset:{},isConnected:true,append(){},replaceChildren(){}});+ combobox=(options,value)=>({value,setOptions(options){this.options=options;}});+ field=(parent,label,control)=>{controls.set(label,control);return control;};+ modelField=(parent,label,client,value)=>{const control=combobox([],value);controls.set(label,control);return control;};+ actions=()=>({});button=(parent,label,callback)=>{load=callback;return {};};+ snapshot={settings:{config_file:'fixture'},clients:[{name:'A',host:'a'},{name:'B',host:'b'}],algorithms:[{kind:'passthrough',title:'Single',summary:'Single',roles:[{label:'Model'}]}]};+ readAction=()=>new Promise(resolve=>{resolveModels=resolve;});+ routeModels({append(){}});+ const pending=load();+ controls.get('Endpoint').value='B';controls.get('Endpoint').onchange();+ resolveModels({data:{models:['A/model'],source:'endpoint'}});+ `,context);+ await vm.runInContext('pending',context);+ const result=vm.runInContext(`[lists.get(modelListKey('A'))?.models,lists.has(modelListKey('B')),controls.get('Model').options]`,context);+ assert.deepEqual(JSON.parse(JSON.stringify(result)),[['A/model'],false,[]]);+});diff --git a/crates/switchyard-desktop/ui/tray.css b/crates/switchyard-desktop/ui/tray.cssnew file mode 100644index 000000000..e60a33b0d--- /dev/null+++ b/crates/switchyard-desktop/ui/tray.css@@ -0,0 +1,60 @@+/* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. */+/* SPDX-License-Identifier: Apache-2.0 */+/* The popup follows macOS menu bar menus: the system font and label colors, the system+ light or dark appearance, the native material behind transparent content, and menu rows+ that highlight with the accent color. AppKit clips the panel to rounded corners, so the+ page itself draws nothing outside #popup. */+:root {+ --label: rgba(0, 0, 0, .85); --secondary: rgba(0, 0, 0, .55); --separator: rgba(0, 0, 0, .1);+ --fill: rgba(0, 0, 0, .05); --opaque: #ECECEC; --success: #1A8B3A; --warning: #B25000; --danger: #C42B1C;+ --bar: #CD744F;+ font: 13px/1.35 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;+ -webkit-font-smoothing: antialiased; -webkit-user-select: none; user-select: none; cursor: default;+}+@media (prefers-color-scheme: dark) {+ :root { --label: rgba(255, 255, 255, .88); --secondary: rgba(255, 255, 255, .58); --separator: rgba(255, 255, 255, .12);+ --fill: rgba(255, 255, 255, .07); --opaque: #2C2C2E; --success: #32D74B; --warning: #FF9F0A; --danger: #FF6961; }+}+* { box-sizing: border-box; }+/* A background on html or body would fill the whole rectangular page, so only #popup paints. */+html, body { margin: 0; overflow: hidden; background: transparent; }+#popup { display: flex; flex-direction: column; max-height: 100vh; padding: 5px; border-radius: 12px; color: var(--label); }+/* macOS materials already become opaque with Reduce Transparency. Windows has no material and+ an opaque rectangular window, so the popup fills it. */+:root[data-native-material="false"] #popup { border-radius: 0; background: var(--opaque); }++header { flex-shrink: 0; display: flex; align-items: baseline; justify-content: space-between; gap: 8px; padding: 6px 9px 2px; }+header strong { font-weight: 600; }+.connection { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; color: var(--secondary); white-space: nowrap; }+.connection::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--warning); }+.connection.running::before { background: var(--success); }++main { flex: 0 1 auto; min-height: 0; overflow: auto; padding: 0 9px 4px; color-scheme: light dark; }+p { margin: 0; }+.detail { font-size: 12px; color: var(--secondary); overflow-wrap: anywhere; }+#server-url { margin-bottom: 2px; }+#error { margin: 6px 0; padding: 6px 8px; border-radius: 6px; background: var(--fill); font-size: 12px; color: var(--danger); white-space: pre-line; overflow-wrap: anywhere; }+#empty, #note { margin-top: 8px; }+h2 { margin: 10px 0 2px; font-size: 12px; font-weight: 600; color: var(--secondary); }+.period p { font-variant-numeric: tabular-nums; }+.period p + p { margin-top: 1px; }+.period .saved { color: var(--success); }+.period .detail { overflow-wrap: anywhere; }++#model-list { display: grid; gap: 5px; margin: 4px 0 0; padding: 0; list-style: none; }+#model-list li { display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: 8px; row-gap: 3px; }+#model-list .model { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+#model-list .share { font-size: 12px; color: var(--secondary); font-variant-numeric: tabular-nums; }+#model-list .track { grid-column: 1 / -1; height: 4px; border-radius: 2px; background: var(--fill); overflow: hidden; }+#model-list .track i { display: block; height: 100%; border-radius: 2px; background: var(--bar); }++footer { flex-shrink: 0; }+nav { display: grid; padding: 4px 0; }+/* Like menu separators, the line stops short of the rounded edges. */+nav::before { content: ""; height: 1px; margin: 0 9px 4px; background: var(--separator); }+nav:last-child { padding-bottom: 0; }+button { all: unset; display: block; height: 24px; padding: 0 9px; border-radius: 6px; line-height: 24px; color: var(--label); white-space: nowrap; }+button.active:not(:disabled), button:focus-visible:not(:disabled) { background: #0A84FF; background: -apple-system-control-accent; color: #FFFFFF; }+button:focus { outline: none; }+#status:empty { display: none; }+#status { padding: 2px 9px 4px; font-size: 12px; color: var(--secondary); white-space: pre-line; overflow-wrap: anywhere; }diff --git a/crates/switchyard-desktop/ui/tray.html b/crates/switchyard-desktop/ui/tray.htmlnew file mode 100644index 000000000..00efc2db1--- /dev/null+++ b/crates/switchyard-desktop/ui/tray.html@@ -0,0 +1,36 @@+<!doctype html>+<!-- SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -->+<!-- SPDX-License-Identifier: Apache-2.0 -->+<html lang="en">+<head>+<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">+<title>Switchyard usage</title><link rel="stylesheet" href="tray.css">+<script defer src="appearance.js"></script>+<script defer src="tray.js"></script>+</head>+<body>+<div id="popup">+<header><strong>Switchyard</strong><span id="connection" class="connection">Checking…</span></header>+<main>+<p id="server-url" class="detail"></p>+<p id="error" role="status" aria-live="polite" hidden></p>+<p id="empty" class="detail" hidden></p>+<div id="periods"></div>+<section id="models" hidden><h2>This week by model</h2><ol id="model-list"></ol></section>+<p id="note" class="detail" hidden></p>+</main>+<footer>+<nav aria-label="Server actions">+<button data-action="restart">Restart server</button>+<button data-action="open_config">Open server config…</button>+<button data-page="settings">Settings…</button>+<button data-page="install">Connect tools…</button>+<p id="status" role="status" aria-live="polite"></p>+</nav>+<nav aria-label="App actions">+<button data-page="overview">Open Switchyard</button>+<button id="quit">Quit Switchyard</button>+</nav>+</footer>+</div>+</body></html>diff --git a/crates/switchyard-desktop/ui/tray.js b/crates/switchyard-desktop/ui/tray.jsnew file mode 100644index 000000000..607e9d5b7--- /dev/null+++ b/crates/switchyard-desktop/ui/tray.js@@ -0,0 +1,80 @@+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+// SPDX-License-Identifier: Apache-2.0+'use strict';+const invoke=window.__TAURI__.core.invoke,$=id=>document.getElementById(id);+let refreshing=false,refreshTimer,running=false;+function node(tag,text,className) {const element=document.createElement(tag);if(text!==undefined)element.textContent=text;if(className)element.className=className;return element;}+function message(text) {$('error').textContent=text;$('error').hidden=!text;}+function show(id,text) {$(id).textContent=text||'';$(id).hidden=!text;}+// The tray menu shows the same overview as text rows; the popup groups it into sections.+function render(view) {+ const overview=view.overview;+ message(view.errors.join('\n'));+ $('connection').textContent=overview?(overview.running?'Server running':'Server not responding'):'Usage unavailable';+ $('connection').classList.toggle('running',Boolean(overview?.running));+ show('server-url',overview?.server_url);+ show('empty',overview?.empty);+ $('periods').replaceChildren(...(overview?.periods||[]).map(period=>{+ const section=node('section',undefined,'period');+ section.append(node('h2',period.name),node('p',period.traffic),node('p',period.spent,'detail'));+ if(period.saved)section.append(node('p',period.saved,'detail saved'));+ return section;+ }));+ const models=overview?.models||[];+ $('models').hidden=!models.length;+ $('model-list').replaceChildren(...models.map(share=>{+ const row=node('li'),name=node('span',share.model,'model'),track=node('span',undefined,'track'),bar=node('i');+ name.title=share.model;bar.style.width=`${share.percent}%`;track.append(bar);+ row.append(name,node('span',`${share.percent.toFixed(0)}%`,'share'),track);+ return row;+ }));+ show('note',overview?.note);+}+async function refresh() {+ clearTimeout(refreshTimer);if(refreshing)return;refreshing=true;let seconds=5;+ try {const view=await invoke('tray_overview');seconds=view.refresh_seconds;render(view);}+ catch(error){message(`Could not read usage: ${error}`);}+ finally{refreshing=false;if(document.hasFocus())refreshTimer=setTimeout(refresh,seconds*1000);}+}+async function command(name,args) {try{await invoke(name,args);}catch(error){message(`Could not open or close the window: ${error}`);}}+const actionButtons=[...document.querySelectorAll('[data-action]')];+for(const button of actionButtons)button.onclick=async()=>{+ if(running)return;running=true;actionButtons.forEach(other=>{other.disabled=true;});+ $('status').textContent=button.dataset.action==='restart'?'Restarting the server…':'Opening the server config…';+ try {const reply=await invoke('action',{action:{kind:button.dataset.action}});$('status').textContent=reply.message;}+ catch(error){$('status').textContent=String(error);}+ finally{running=false;actionButtons.forEach(other=>{other.disabled=false;});refresh();}+};+for(const button of document.querySelectorAll('[data-page]'))button.onclick=()=>command('tray_page',{page:button.dataset.page});+$('quit').onclick=()=>command('quit_app');+// Rows highlight like menu items: under the pointer or from the arrow keys, and never left+// over from the last time the popup was open.+const rows=[...document.querySelectorAll('nav button')];+function highlight(row) {rows.forEach(other=>other.classList.toggle('active',other===row));if(row)row.focus({preventScroll:true});else document.activeElement?.blur();}+for(const row of rows){row.onpointerenter=()=>highlight(row);row.onpointerleave=()=>highlight(null);}+document.addEventListener('keydown',event=>{+ if(event.key==='Escape'){command('dismiss_tray');return;}+ if(event.key!=='ArrowDown'&&event.key!=='ArrowUp')return;+ event.preventDefault();+ const enabled=rows.filter(row=>!row.disabled),current=enabled.indexOf(document.activeElement);+ const next=event.key==='ArrowDown'?(current+1)%enabled.length:(current<=0?enabled.length:current)-1;+ highlight(enabled[next]);+});+window.addEventListener('switchyard-tray-open',()=>{highlight(null);refresh();});window.addEventListener('focus',refresh);+window.addEventListener('blur',()=>{clearTimeout(refreshTimer);highlight(null);});+// Loading once at startup gives the first opening its final height instead of a resize.+refresh();++// The native panel takes its height from the content, up to the limit that tray_size applies.+let measuredHeight=0;+function sizePopup() {+ const style=getComputedStyle($('popup')),padding=parseFloat(style.paddingTop)+parseFloat(style.paddingBottom);+ const height=Math.ceil(padding+document.querySelector('header').offsetHeight+document.querySelector('main').scrollHeight+document.querySelector('footer').offsetHeight);+ if(height!==measuredHeight){measuredHeight=height;command('tray_size',{height});}+}+if(typeof ResizeObserver==='function') {+ const observer=new ResizeObserver(sizePopup);+ for(const tag of ['header','main','footer'])observer.observe(document.querySelector(tag));+ new MutationObserver(()=>requestAnimationFrame(sizePopup)).observe(document.body,{childList:true,subtree:true,characterData:true});+}+window.addEventListener('switchyard-tray-open',sizePopup);diff --git a/crates/switchyard-server/README.md b/crates/switchyard-server/README.mdindex 9b1a74d65..ece622f12 100644--- a/crates/switchyard-server/README.md+++ b/crates/switchyard-server/README.md@@ -158,7 +158,10 @@ at startup, and saved costs do not change when prices change. An unreadable or i`--pricing-file` stops startup; the server does not use bundled rates instead.The [pi guide](../../docs/integrations/pi.md#estimate-the-cost) explains how to supply-rates for your own models.+rates for your own models. The desktop app uses the same bundled rates by default.+For custom rates, point its `pricing_file` setting at the same TOML or JSON file as+the server's `--pricing-file`. The desktop app totals these recorded costs, so its totals+can differ from what your provider bills.Clients can send `x-switchyard-origin: codex-cli` (or another client label) to include an`origin` field in each routing record. Missing, empty, or non-text header values produce@@ -302,7 +305,7 @@ rule to `~/.codex/rules/default.rules`. See Codex's[Agent approvals & security](https://learn.chatgpt.com/docs/agent-approvals-security)page.-The installer, `scripts/linux/install.sh`, does not overwrite an existing+The installer, `cargo desktop install`, does not overwrite an existing`~/.switchyard/composite.toml`.If you installed Switchyard before this route was added, add the`[targets.reviewer]` and `[routes.codex_auto_review]` blocks to that file by@@ -327,8 +330,8 @@ hand, then restart the server.| `GET` | `/health` | Liveness |Requests name a route by its `id`, so `POST /v1/chat/completions` with `"model": "switchyard/general"`-routes through the `[routes.general]` entry above. Any of the three request formats can address any-route, and the server translates between them.+routes through the `[routes.general]` entry above. The server translates between request formats+supported by the selected route and its forwarding clients.Set the top-level `fallback_client` to an entry under `[llm_clients]` to proxy any otherwiseunmatched method and path through that client. The fallback client does not need a target. Requestsdiff --git a/scripts/common.sh b/scripts/common.shdeleted file mode 100644index cd27254f1..000000000--- a/scripts/common.sh+++ /dev/null@@ -1,117 +0,0 @@-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0--SY_HOME="${SY_HOME:-$HOME/.switchyard}"-SY_PORT="${SY_PORT:-4123}"-CODEX_DIR="${CODEX_HOME:-$HOME/.codex}"-# Both installers use Codex's standalone profile file for the CLI.-CODEX_PROFILE_CONFIG="$CODEX_DIR/sy.config.toml"-ALIAS_START="# >>> switchyard codex alias >>>"-ALIAS_END="# <<< switchyard codex alias <<<"--say() { printf '%s\n' "$*"; }-step() { printf '\n==> %s\n' "$*"; }--strip_block() {- local path="$1" start="$2" end="$3" label="${4:-the switchyard block}"- if [[ ! -f "$path" ]] || ! grep -qF "$start" "$path"; then- return 1- fi- if ! grep -qF "$end" "$path"; then- say " $path has no end marker for $label; not editing it" >&2- return 1- fi- if (( DRY_RUN )); then- say " would remove $label from $path"- return 0- fi- local temp- temp="$(mktemp)"- awk -v start="$start" -v end="$end" '- index($0, start) { skipping = 1 }- !skipping { print }- index($0, end) { skipping = 0 }- END { if (skipping) exit 1 }- ' "$path" > "$temp"- cat "$temp" > "$path"- rm -f "$temp"- say " removed $label from $path"- return 0-}--run() {- if (( DRY_RUN )); then- say " would run: $*"- else- "$@"- fi-}--write_once() {- local path="$1"- if [[ -f "$path" ]]; then- say " keeping existing $path"- cat >/dev/null- return- fi- if (( DRY_RUN )); then- say " would create $path"- cat >/dev/null- else- mkdir -p "$(dirname "$path")"- cat > "$path"- say " created $path"- fi-}--write_with_backup() {- local path="$1"- if (( DRY_RUN )); then- [[ -f "$path" ]] && say " would back up $path"- say " would write $path"- cat >/dev/null- return- fi- mkdir -p "$(dirname "$path")"- local incoming- incoming="$(mktemp)"- cat > "$incoming"- if [[ -f "$path" ]] && cmp -s "$incoming" "$path"; then- say " $path is already up to date"- rm -f "$incoming"- return- fi- if [[ -f "$path" ]]; then- local backup- backup="$path.switchyard-backup.$(date +%Y%m%d%H%M%S)"- cp "$path" "$backup"- say " backed up $path to $backup"- fi- cat "$incoming" > "$path"- rm -f "$incoming"- say " wrote $path"-}--write_always() {- local path="$1"- if (( DRY_RUN )); then- say " would write $path"- cat >/dev/null- else- mkdir -p "$(dirname "$path")"- cat > "$path"- say " wrote $path"- fi-}--remove_file() {- local path="$1"- if [[ ! -e "$path" ]]; then- say " nothing to remove at $path"- elif (( DRY_RUN )); then- say " would delete $path"- else- rm -f "$path"- say " deleted $path"- fi-}diff --git a/scripts/linux/common.sh b/scripts/linux/common.shdeleted file mode 100644index 3a9b7782e..000000000--- a/scripts/linux/common.sh+++ /dev/null@@ -1,8 +0,0 @@-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0-#-# shellcheck source=scripts/common.sh-source "$(dirname "${BASH_SOURCE[0]}")/../common.sh"--SERVICE_NAME="switchyard.service"-SYSTEMD_USER_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"diff --git a/scripts/linux/install.sh b/scripts/linux/install.shdeleted file mode 100755index c296ebcfc..000000000--- a/scripts/linux/install.sh+++ /dev/null@@ -1,97 +0,0 @@-#!/usr/bin/env bash-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0-#-# Installs the Switchyard background server as a systemd --user service and sets-# up a `sy` Codex profile.-#-# Keeps existing composite.toml, replaces the service unit, and backs up-# sy.config.toml before replacing it. Use systemctl --user edit switchyard-# for service changes that survive reinstalling.-# Run with --dry-run to print what would happen.--set -euo pipefail--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"--DRY_RUN=0-case "$#:${1:-}" in- 0:) ;;- 1:--dry-run) DRY_RUN=1 ;;- *) printf 'Usage: %s [--dry-run]\n' "$0" >&2; exit 2 ;;-esac--# shellcheck source=scripts/linux/common.sh-source "$SCRIPT_DIR/common.sh"--if [[ "$SY_HOME" =~ [[:space:][:cntrl:]] || "$SY_HOME" == *\\ ]]; then- say "SY_HOME must not contain whitespace, control characters, or a trailing backslash." >&2- exit 1-fi-if [[ ! "$SY_PORT" =~ ^[0-9]+$ ]]; then- say "SY_PORT must contain only digits." >&2- exit 1-fi--if [[ "$(uname -s)" != "Linux" ]]; then- say "This installer is for Linux only." >&2- exit 1-fi--step "Building release binary"-run cargo build --release --manifest-path "$REPO_ROOT/Cargo.toml" -p switchyard-server--step "Installing binary into $SY_HOME/bin"-run mkdir -p "$SY_HOME/bin"-run install -m 755 "$REPO_ROOT/target/release/switchyard-server" "$SY_HOME/bin/switchyard-server"--step "Writing server config"-write_once "$SY_HOME/composite.toml" < "$REPO_ROOT/scripts/config/composite.toml"--step "Validating the server config"-if (( DRY_RUN )); then- say " would run: $SY_HOME/bin/switchyard-server --config $SY_HOME/composite.toml --dry-run"-else- "$SY_HOME/bin/switchyard-server" --config "$SY_HOME/composite.toml" --dry-run-fi--step "Writing the systemd user service"-write_always "$SYSTEMD_USER_DIR/$SERVICE_NAME" <<EOF-[Unit]-Description=Switchyard LLM router server--[Service]-Type=simple-ExecStart=$SY_HOME/bin/switchyard-server --config $SY_HOME/composite.toml --host 127.0.0.1 --port $SY_PORT --routing-log-file $SY_HOME/routing.jsonl-Restart=on-failure-Environment=RUST_LOG=info--[Install]-WantedBy=default.target-EOF--step "Loading the systemd user service"-run systemctl --user daemon-reload-run systemctl --user enable "$SERVICE_NAME"-run systemctl --user restart "$SERVICE_NAME"-run sleep 2-if (( ! DRY_RUN )) && ! systemctl --user is-active --quiet "$SERVICE_NAME"; then- say "Service failed to start. See: journalctl --user -u switchyard" >&2- exit 1-fi--step "Adding the sy Codex profile"-# This profile only changes which router answers. Approval and sandbox-# settings are deliberately left out, so the profile cannot loosen how Codex-# asks before it acts. Set those yourself if you want them.-sed "s/@SY_PORT@/$SY_PORT/g" "$REPO_ROOT/scripts/config/codex.sy.toml" | write_with_backup "$CODEX_PROFILE_CONFIG"--step "Done"-say "Server: http://127.0.0.1:$SY_PORT"-say "Logs: journalctl --user -u switchyard"-say "Manage it with: systemctl --user {status,restart,stop} $SERVICE_NAME"-say "Use it with: codex -p sy (requires Codex CLI 0.134.0 or newer)"-say ""-say "If you want the server running even when you are logged out, run:"-say " loginctl enable-linger \$USER"diff --git a/scripts/linux/uninstall.sh b/scripts/linux/uninstall.shdeleted file mode 100755index f968a030d..000000000--- a/scripts/linux/uninstall.sh+++ /dev/null@@ -1,51 +0,0 @@-#!/usr/bin/env bash-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0-#-# Removes what install.sh added: the systemd user service, the `sy` Codex-# profile, and any codex alias from an older install. Config and binaries stay-# put; the paths are printed so you can delete them yourself.-#-# Run with --dry-run to print what would happen.--set -euo pipefail--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"--DRY_RUN=0-case "$#:${1:-}" in- 0:) ;;- 1:--dry-run) DRY_RUN=1 ;;- *) printf 'Usage: %s [--dry-run]\n' "$0" >&2; exit 2 ;;-esac--# shellcheck source=scripts/linux/common.sh-source "$SCRIPT_DIR/common.sh"--step "Removing the sy Codex profile"-remove_file "$CODEX_PROFILE_CONFIG"--step "Removing the codex alias"-for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do- if [[ -f "$rc" ]] && grep -qF "$ALIAS_START" "$rc"; then- strip_block "$rc" "$ALIAS_START" "$ALIAS_END" "the codex alias"- else- say " no alias in $rc"- fi-done--step "Stopping the systemd user service"-if (( DRY_RUN )); then- say " would run: systemctl --user disable --now $SERVICE_NAME"- say " would delete $SYSTEMD_USER_DIR/$SERVICE_NAME"-else- systemctl --user disable --now "$SERVICE_NAME" 2>/dev/null || true- rm -f "$SYSTEMD_USER_DIR/$SERVICE_NAME"- systemctl --user daemon-reload- say " stopped and removed $SERVICE_NAME"-fi--step "Done"-say "Left in place, delete them if you want:"-say " $SY_HOME (binary, config, routing log)"-say " $CODEX_PROFILE_CONFIG.switchyard-backup.* (backups taken at install time)"diff --git a/tests/test_linux_install.py b/tests/test_linux_install.pydeleted file mode 100644index 7d070c8e3..000000000--- a/tests/test_linux_install.py+++ /dev/null@@ -1,197 +0,0 @@-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0--import os-import shutil-import subprocess-from pathlib import Path--import pytest--REPO = Path(__file__).resolve().parents[1]-START = "# >>> switchyard codex alias >>>"-END = "# <<< switchyard codex alias <<<"-RC = f"before\n{START}\nalias codex='codex -p sy'\n{END}\nafter\n"---def setup(tmp_path):- scripts = tmp_path / "repo" / "scripts" / "linux"- shutil.copytree(REPO / "scripts" / "linux", scripts)- shutil.copy(REPO / "scripts" / "common.sh", scripts.parent / "common.sh")- shutil.copytree(REPO / "scripts" / "config", scripts.parent / "config")- home = tmp_path / "home"- home.mkdir()- bin_dir = tmp_path / "bin"- bin_dir.mkdir()- env = {- **os.environ,- "HOME": str(home),- "SY_HOME": str(home / ".switchyard"),- "SY_PORT": "4123",- "XDG_CONFIG_HOME": str(home / ".config"),- "CODEX_HOME": str(home / ".codex"),- "TMPDIR": str(tmp_path),- "PATH": f"{bin_dir}:/usr/bin:/bin",- "SYSTEMCTL_LOG": str(tmp_path / "systemctl.log"),- "FAIL_SYSTEMCTL": "",- }- stubs = {- "cargo": "exit 0\n",- "uname": "echo Linux\n",- "sleep": "exit 0\n",- "install": 'printf "#!/bin/sh\\nexit 0\\n" > "$4"\nchmod +x "$4"\n',- "systemctl": 'echo "$*" >> "$SYSTEMCTL_LOG"\n'- '[[ "$*" != *"$FAIL_SYSTEMCTL"* || -z "$FAIL_SYSTEMCTL" ]]\n',- }- for name, body in stubs.items():- stub = bin_dir / name- stub.write_text("#!/bin/bash\nset -eu\n" + body)- stub.chmod(0o755)- return scripts, home, bin_dir, env---def run(setup, script, *args):- scripts, _, _, env = setup- return subprocess.run(- ["bash", str(scripts / script), *args],- env=env,- capture_output=True,- text=True,- timeout=10,- )--[email protected]("script", ["install.sh", "uninstall.sh"])[email protected]("args", [["--dryrun"], ["--help"], ["-n"], ["--dry-run", "extra"], [""]])-def test_bad_arguments_leave_files_unchanged(setup, script, args):- _, home, _, env = setup- rc = home / ".bashrc"- rc.write_text(RC)- result = run(setup, script, *args)- assert result.returncode == 2- assert "Usage:" in result.stderr- assert rc.read_text() == RC- assert not Path(env["SYSTEMCTL_LOG"]).exists()--[email protected]("failure", ["mktemp", "awk", "missing-end", "second-missing-end"])-def test_uninstall_failure_preserves_shell_files(setup, failure):- _, home, bin_dir, _ = setup- contents = RC- if failure == "missing-end":- contents = RC.replace(END + "\n", "")- elif failure == "second-missing-end":- contents += f"{START}\nalias codex='codex -p sy'\ntail\n"- else:- (bin_dir / failure).write_text("#!/bin/bash\nexit 1\n")- (bin_dir / failure).chmod(0o755)- for name in [".zshrc", ".bashrc"]:- (home / name).write_text(contents)- result = run(setup, "uninstall.sh")- assert result.returncode != 0- for name in [".zshrc", ".bashrc"]:- assert (home / name).read_text() == contents---def test_uninstall_cleans_profile_and_aliases_before_systemctl_failure(setup):- _, home, _, env = setup- env["FAIL_SYSTEMCTL"] = "--user"- profile = Path(env["CODEX_HOME"]) / "sy.config.toml"- profile.parent.mkdir()- profile.write_text("old profile\n")- for name in [".zshrc", ".bashrc"]:- (home / name).write_text(RC)- result = run(setup, "uninstall.sh")- assert result.returncode != 0- assert not profile.exists()- for name in [".zshrc", ".bashrc"]:- assert (home / name).read_text() == "before\nafter\n"--[email protected]("script", ["install.sh", "uninstall.sh"])-def test_dry_run_leaves_files_unchanged(setup, script):- _, home, _, env = setup- (home / ".bashrc").write_text(RC)- result = run(setup, script, "--dry-run")- assert result.returncode == 0, result.stderr- assert (home / ".bashrc").read_text() == RC- assert sorted(path.name for path in home.iterdir()) == [".bashrc"]- assert not Path(env["SYSTEMCTL_LOG"]).exists()--- "key,value",- [- ("SY_HOME", "/tmp/with space"),- ("SY_HOME", "/tmp/line\nbreak"),- ("SY_HOME", "/tmp/control\x01"),- ("SY_HOME", "/tmp/backslash\\"),- ("SY_PORT", "bad"),- ("SY_PORT", "4123\n"),- ],-)-def test_invalid_unit_values_fail_before_install(setup, key, value):- _, home, _, env = setup- env[key] = value- result = run(setup, "install.sh")- assert result.returncode != 0- assert key in result.stderr- assert not list(home.iterdir())---def test_reinstall_restarts_service_and_keeps_user_config(setup):- _, home, _, env = setup- (home / ".bashrc").write_text("user settings\n")- assert run(setup, "install.sh").returncode == 0- config = Path(env["SY_HOME"]) / "composite.toml"- config.write_text("user config\n")- env["SY_PORT"] = "5000"- result = run(setup, "install.sh")- assert result.returncode == 0, result.stderr- assert config.read_text() == "user config\n"- assert (home / ".bashrc").read_text() == "user settings\n"- assert not (home / ".zshrc").exists()- profile = Path(env["CODEX_HOME"]) / "sy.config.toml"- assert "127.0.0.1:5000/v1" in profile.read_text()- backups = list(profile.parent.glob("sy.config.toml.switchyard-backup.*"))- assert len(backups) == 1- assert "127.0.0.1:4123/v1" in backups[0].read_text()- calls = Path(env["SYSTEMCTL_LOG"]).read_text().splitlines()- assert (- calls- == [- "--user daemon-reload",- "--user enable switchyard.service",- "--user restart switchyard.service",- "--user is-active --quiet switchyard.service",- ]- * 2- )---def test_failed_start_leaves_existing_profile_unchanged(setup):- _, _, _, env = setup- env["FAIL_SYSTEMCTL"] = "is-active"- profile = Path(env["CODEX_HOME"]) / "sy.config.toml"- profile.parent.mkdir()- profile.write_text("user profile\n")- result = run(setup, "install.sh")- assert result.returncode != 0- assert "journalctl" in result.stderr- assert profile.read_text() == "user profile\n"---def test_default_make_only_prints_help(setup):- _, home, _, env = setup- result = subprocess.run(- ["make", "-f", str(REPO / "Makefile")],- cwd=REPO,- env=env,- capture_output=True,- text=True,- timeout=10,- )- assert result.returncode == 0, result.stderr- assert "install-linux-dry-run" in result.stdout- assert not list(home.iterdir())