Skip to content
Draft
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,100 changes: 1,069 additions & 31 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
16 changes: 16 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

.PHONY: install-macos install-macos-dry-run uninstall-macos

## 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"
87 changes: 87 additions & 0 deletions crates/switchyard-menubar/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# 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 aliases `codex` to use it.

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.

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.** It still writes profiles in the legacy
format its own bundled CLI rejects. So it gets a whole config instead: the
installer builds `~/.codex/config.toml.sy`, which is your `config.toml` with
the routing inlined at the top level, the one format both accept. Swap it in
and restart the app:

```sh
cp ~/.codex/config.toml.sy ~/.codex/config.toml # route
cp ~/.codex/config.toml.direct ~/.codex/config.toml # back to normal
```

`config.toml.direct` is a snapshot of your unrouted config, never taken while
`config.toml` is already routed, and restored by `make uninstall-macos`.

Swapping routes everything the app does. Unlike the CLI alias, there is no
unrouted escape hatch while it is in place.
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:?}"
);
}
}
146 changes: 146 additions & 0 deletions crates/switchyard-menubar/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// 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"))
}
}

/// 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 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