Skip to content
Open
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 @@ -11,6 +11,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
17 changes: 16 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
# SPDX-License-Identifier: Apache-2.0

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

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

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

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

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

## Remove the LaunchAgents, the sy Codex profile, and the codex alias.
uninstall-macos:
@scripts/macos/uninstall.sh
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"
77 changes: 77 additions & 0 deletions crates/switchyard-menubar/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# 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, writes a `sy` Codex profile, and routes Codex.app through
Switchyard. 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.

@elyasmnvidian elyasmnvidian Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could the README say which model ID needs a price for reviews? Someone who points the reviewer route at another model otherwise loses the Saved row without knowing why.

Suggested change
model seen has a price, so a partial table cannot mislead.
model seen has a price, so a partial table cannot mislead.
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.


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`. A `[profiles.sy]` table
inside `config.toml` is legacy config the CLI now refuses to start with, so the
installer removes one if an older version left it there.

The profile sets only `model` and `model_provider`. It deliberately leaves
`approval_policy` and `sandbox_mode` alone, because routing should not quietly
change how Codex asks before it acts.

**Codex.app cannot use the profile.** The installer builds
`~/.codex/config.sy.toml` from your original config, backs up that original to
`~/.codex/config.toml.direct`, and installs the routed config as
`~/.codex/config.toml`. `make uninstall-macos` restores the original and keeps
a copy of the active config before replacing it.
53 changes: 53 additions & 0 deletions crates/switchyard-menubar/src/app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// 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};

/// Rereads the log, probes the server, and builds the menu body.
pub fn refresh(config: &Config) -> Vec<Row> {
let usage =
rollup::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()
});

assert!(
rows.contains(&Row::Label("Today — 1 request · 1100 tokens".to_string())),
"unexpected rows: {rows:?}"
);
}
}
167 changes: 167 additions & 0 deletions crates/switchyard-menubar/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
// 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 text = match std::fs::read_to_string(path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(Self::default());
}
Err(error) => return Err(format!("read {}: {error}", path.display())),
};
let mut config: Self =
toml::from_str(&text).map_err(|error| format!("parse {}: {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());
}

#[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