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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,110 changes: 1,074 additions & 36 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ members = [
"crates/protocol",
"crates/switchyard-nemo-relay-plugin",
"crates/switchyard-runner",
"crates/switchyard-menubar",
"crates/switchyard-server",
"crates/switchyard-skill-distillation",
"crates/switchyard-soak",
Expand Down
6 changes: 3 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ help:
@echo "install-linux Install the systemd user service and Codex profile"
@echo "install-linux-dry-run Preview installation without changes"
@echo "uninstall-linux Remove the service and Codex profile"
@echo "install-macos Install the background server"
@echo "install-macos Install the background server and menu bar app"
@echo "install-macos-dry-run Preview installation without changes"
@echo "uninstall-macos Remove the LaunchAgents and Codex profile"

Expand All @@ -24,14 +24,14 @@ install-linux-dry-run:
uninstall-linux:
@scripts/linux/uninstall.sh

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

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

## Remove the LaunchAgent, the sy Codex profile, and the codex alias.
## Remove the LaunchAgents, the sy Codex profile, and the codex alias.
uninstall-macos:
@scripts/macos/uninstall.sh
29 changes: 29 additions & 0 deletions crates/switchyard-menubar/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "switchyard-menubar"
version.workspace = true
description = "macOS menu bar companion for a locally running Switchyard server"
authors.workspace = true
edition.workspace = true
homepage = "https://github.com/NVIDIA-NeMo/Switchyard"
license.workspace = true
repository.workspace = true
rust-version.workspace = true
publish = false

[dependencies]
chrono = { version = "0.4", default-features = false, features = ["std", "clock"] }
serde.workspace = true
serde_json.workspace = true
toml = "0.9"

[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.6"
objc2-app-kit = "0.3"
objc2-foundation = "0.3"
tray-icon = "0.25"

[dev-dependencies]
tempfile = "3"
101 changes: 101 additions & 0 deletions crates/switchyard-menubar/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# switchyard-menubar

A macOS menu bar companion for a Switchyard server running in the background.

The server does the routing. This process only reads what the server already
wrote, so quitting it never affects traffic.

Click the glyph to see whether the server is answering, today's and this
week's requests and tokens, estimated savings, and which models served the
week. It can also restart the server and open either config file.

## Install

From the repository root:

```sh
make install-macos # or install-macos-dry-run to see the steps first
make uninstall-macos
```

That builds `switchyard-server` and `switchyard-menubar` into
`~/.switchyard/bin`, writes a server config and menu bar settings, loads two
LaunchAgents, and writes a `sy` Codex profile. Use the CLI profile with
`codex -p sy`.

Your server config and menu bar settings are never overwritten once they
exist, so edits survive a reinstall. Logs are in `~/.switchyard/logs/`.

## Settings

`~/.switchyard/menubar.toml`. Any key may be omitted.

```toml
server_url = "http://127.0.0.1:4123"
routing_log = "~/.switchyard/routing.jsonl"
baseline_model = "gpt-5.6-sol"
refresh_seconds = 30

[prices."gpt-5.6-sol"]
input_per_mtok = 1.25
cached_input_per_mtok = 0.125
output_per_mtok = 10.0
```

## How savings are computed

The server writes one JSONL record per call, with the model that answered and
its token counts.

- **Actual** is every call priced at the model that served it, including
Switchyard's own classifier calls.
- **Baseline** is the caller-facing calls only, priced as if each had used
`baseline_model`. 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. Dollar figures stay hidden until every
model seen has a price, so a partial table cannot mislead.
Comment thread
messiaen marked this conversation as resolved.

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 installer prices that model at the `baseline_model` rates.
Each review then adds the same amount to the actual 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`, update
this price to match.

The menu bar needs a price for the model ID that the routing log records for
reviews, which is the reviewer target's `id`. Without that price, the menu bar
hides the Saved row for every period that includes a review. The installer does
not overwrite an existing `composite.toml` or `menubar.toml`, so an existing
install needs the route and the price added by hand.

Codex's "Approve for me" reviews need a price too. Use the reviewer target's
`id`, which is the model ID recorded in the routing log. The default reviewer
route uses `codex-auto-review`. With a ChatGPT login, these reviews also happen
without Switchyard. Add that ID to the price table at the `baseline_model`
rates, including the cached input rate. Each review then adds the same cost to
actual and baseline. Dollars saved stay the same; the percentage drops as the
baseline grows. Update this price when you change `baseline_model`.

If a reviewer uses another model ID, add a price for that ID. Any period with
an unpriced review hides its savings and shows the missing-price hint. Existing
`menubar.toml` files need these prices added by hand.

These are list-price estimates. On a ChatGPT login there is no per-token bill,
so read them as "what this traffic would have cost at API rates".

## Codex profiles

`codex --profile sy` reads `~/.codex/sy.config.toml`. The installer writes this
standalone profile and keeps your existing `~/.codex/config.toml` unchanged.
Reinstalling backs up the profile before replacing it if its contents change.

The profile sets `model`, `model_provider`, and the Switchyard provider details.
It leaves `approval_policy` and `sandbox_mode` to your existing Codex settings.

Codex.app cannot use the profile. The installer leaves its config unchanged.
For older installs that replaced `config.toml`, `make uninstall-macos` restores
`config.toml.direct` and keeps a copy of the active config before replacing it.
57 changes: 57 additions & 0 deletions crates/switchyard-menubar/src/app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Ties the pieces together: read the log, probe the server, build the rows.

use chrono::Local;

use crate::config::Config;
use crate::health::probe;
use crate::rollup;
use crate::summary::{Row, build};

/// Reads new log entries, probes the server, and builds the menu body.
pub fn refresh(config: &Config, log: &mut rollup::Reader) -> Vec<Row> {
let usage = log
.read(&config.routing_log, Local::now().date_naive())
.unwrap_or_else(|error| {
eprintln!(
"switchyard-menubar: read {}: {error}",
config.routing_log.display()
);
rollup::Usage::default()
});
build(probe(&config.server_url), &usage, config)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn reads_the_configured_log() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("routing.jsonl");
let ts = Local::now().to_rfc3339();
std::fs::write(
&path,
format!(
r#"{{"ts":"{ts}","model":"luna","tier":"","prompt_tokens":1000,"cached_tokens":0,"completion_tokens":100,"reasoning_tokens":0}}"#
) + "\n",
)
.expect("write log");

let rows = refresh(
&Config {
routing_log: path,
..Config::default()
},
&mut rollup::Reader::default(),
);

assert!(
rows.contains(&Row::Label("Today — 1 request · 1100 tokens".to_string())),
"unexpected rows: {rows:?}"
);
}
}
169 changes: 169 additions & 0 deletions crates/switchyard-menubar/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Menu bar settings, read from `~/.switchyard/menubar.toml`.

use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::pricing::PriceTable;

/// Everything the menu bar needs to find the server and price its traffic.
/// Missing keys fall back to [`Config::default`].
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
/// Base URL the server listens on, used for the health check.
pub server_url: String,
/// JSONL file the server appends routing records to.
pub routing_log: PathBuf,
/// Server TOML, opened by the "Open server config" menu item.
pub config_file: PathBuf,
/// LaunchAgent label used to restart the server.
pub launchd_label: String,
/// How often the menu contents are recomputed.
pub refresh_seconds: u64,
/// Model the traffic is assumed to have used without Switchyard.
pub baseline_model: String,
/// Per-model rates. Dollar figures are hidden while a seen model is absent.
pub prices: PriceTable,
}

impl Default for Config {
fn default() -> Self {
Self {
server_url: "http://127.0.0.1:4123".to_string(),
routing_log: PathBuf::from("~/.switchyard/routing.jsonl"),
config_file: PathBuf::from("~/.switchyard/composite.toml"),
launchd_label: "com.nvidia.switchyard.server".to_string(),
refresh_seconds: 30,
baseline_model: "gpt-5.6-sol".to_string(),
prices: PriceTable::new(),
}
}
}

impl Config {
/// Parses settings, falling back to defaults when the file is absent.
pub fn load(path: &Path) -> Result<Self, String> {
let mut config: Self = match std::fs::read_to_string(path) {
Ok(text) => toml::from_str(&text)
.map_err(|error| format!("parse {}: {error}", path.display()))?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Self::default(),
Err(error) => return Err(format!("read {}: {error}", path.display())),
};
config.routing_log = expand_home(&config.routing_log);
config.config_file = expand_home(&config.config_file);
Ok(config)
}

/// Default settings path, `~/.switchyard/menubar.toml`.
pub fn default_path() -> PathBuf {
expand_home(Path::new("~/.switchyard/menubar.toml"))
}
}

pub fn validate_toml_file(path: &Path) -> Result<(), String> {
let text = std::fs::read_to_string(path)
.map_err(|error| format!("read {}: {error}", path.display()))?;
toml::from_str::<toml::Value>(&text)
.map_err(|error| format!("parse {}: {error}", path.display()))?;
Ok(())
}

/// Rewrites a leading `~`. Paths are written by hand in the settings file,
/// where `~` is the natural way to spell a home path.
pub fn expand_home(path: &Path) -> PathBuf {
let home = std::env::var_os("HOME").map_or_else(|| PathBuf::from("."), PathBuf::from);
expand_under(path, &home)
}

fn expand_under(path: &Path, home: &Path) -> PathBuf {
match path.strip_prefix("~") {
Ok(rest) => home.join(rest),
Err(_) => path.to_path_buf(),
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn reads_settings_and_prices() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("menubar.toml");
std::fs::write(
&path,
r#"
server_url = "http://127.0.0.1:9000"
baseline_model = "sol"

[prices.luna]
input_per_mtok = 0.25
cached_input_per_mtok = 0.025
output_per_mtok = 2.0
"#,
)
.expect("write settings");

let config = Config::load(&path).expect("load");

assert_eq!(config.server_url, "http://127.0.0.1:9000");
assert_eq!(config.baseline_model, "sol");
assert_eq!(config.prices["luna"].cached_input_per_mtok, Some(0.025));
assert_eq!(config.refresh_seconds, 30, "unset keys keep their default");
}

#[test]
fn a_missing_file_yields_defaults() {
let dir = tempfile::tempdir().expect("tempdir");

let config = Config::load(&dir.path().join("absent.toml")).expect("load");

assert_eq!(config.server_url, "http://127.0.0.1:4123");
assert!(config.prices.is_empty());
let empty = dir.path().join("empty.toml");
std::fs::write(&empty, "").expect("write settings");
let loaded = Config::load(&empty).expect("load empty settings");
assert_eq!(config.routing_log, loaded.routing_log);
assert_eq!(config.config_file, loaded.config_file);
}

#[test]
fn rejects_unparsable_settings() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("menubar.toml");
std::fs::write(&path, "server_url = ").expect("write settings");

assert!(Config::load(&path).is_err());
}

#[test]
fn validates_arbitrary_toml_files() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("codex.toml");
std::fs::write(&path, "[model_providers.\"sy\"]\nname = \"Switchyard\"\n")
.expect("write config");

assert!(validate_toml_file(&path).is_ok());

std::fs::write(&path, "[model_providers.\"sy\"]\nname = ").expect("write config");
assert!(validate_toml_file(&path).is_err());
}

#[test]
fn expands_a_leading_tilde() {
let home = Path::new("/Users/example");

assert_eq!(
expand_under(Path::new("~/.switchyard/routing.jsonl"), home),
PathBuf::from("/Users/example/.switchyard/routing.jsonl")
);
assert_eq!(
expand_under(Path::new("/tmp/routing.jsonl"), home),
PathBuf::from("/tmp/routing.jsonl")
);
}
}
Loading
Loading