diff --git a/windows/src-tauri/src/cli.rs b/windows/src-tauri/src/cli.rs index 08602432..6e725f70 100644 --- a/windows/src-tauri/src/cli.rs +++ b/windows/src-tauri/src/cli.rs @@ -595,10 +595,6 @@ fn spawn_program_in_terminal(_app: &AppHandle, cli: &CodeburnCli, subcommand: &[ #[cfg(target_os = "windows")] { - // `start` treats the first quoted argument as the window title, so we pass an - // explicit empty title. `/K` keeps the console open for non-interactive commands - // (export) so the user can read where the file went; the TUI (report/optimize) - // owns the window until the user quits it either way. // Only the unresolved default name is worth a second lookup; anything else is // either already absolute or a CODEBURN_BIN the user chose. let program = if cli.program == default_program_name() { @@ -606,16 +602,19 @@ fn spawn_program_in_terminal(_app: &AppHandle, cli: &CodeburnCli, subcommand: &[ } else { cli.program.clone() }; - let cmd_exe = system32_path("cmd.exe"); + let mut argv: Vec = vec![program]; + argv.extend(cli.extra_args.iter().cloned()); + argv.extend(subcommand.iter().map(|s| s.to_string())); + + // `start` treats the first quoted argument as the window title, so we pass an + // explicit empty title. It also detaches, which is what keeps the console the + // reader gets from being a child of this GUI process. let mut cmd = system_command("cmd.exe"); - cmd.arg("/C").arg("start").arg("").arg(&cmd_exe).arg("/K").arg(&program); - for a in &cli.extra_args { - cmd.arg(a); + cmd.arg("/C").arg("start").arg(""); + for arg in PreferredTerminal::resolved().launch_argv(&argv) { + cmd.arg(arg); } - for a in subcommand { - cmd.arg(a); - } - cmd.spawn().with_context(|| "failed to open cmd.exe")?; + cmd.spawn().with_context(|| "failed to open a terminal")?; } #[cfg(target_os = "macos")] @@ -631,6 +630,155 @@ fn spawn_program_in_terminal(_app: &AppHandle, cli: &CodeburnCli, subcommand: &[ Ok(()) } +/// The Windows counterpart of mac/.../Security/PreferredTerminal.swift, and it exists for the +/// same reason: a user preference must never become a free-form string inside a command line. +/// The stored value is parsed back through `parse`, anything unrecognised collapses to the +/// default, and every executable named below is a compile-time literal resolved from +/// %SystemRoot% or %LOCALAPPDATA%. +/// +/// Only consoles that can hold a command open in a live window are listed. That is what +/// Full Report and Optimize need: a window that stays after the command exits. +#[cfg(target_os = "windows")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreferredTerminal { + WindowsTerminal, + PowerShell, + CommandPrompt, +} + +#[cfg(target_os = "windows")] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TerminalOption { + pub id: &'static str, + pub installed: bool, +} + +#[cfg(target_os = "windows")] +impl PreferredTerminal { + pub const ALL: [PreferredTerminal; 3] = [ + PreferredTerminal::WindowsTerminal, + PreferredTerminal::PowerShell, + PreferredTerminal::CommandPrompt, + ]; + + pub fn id(self) -> &'static str { + match self { + PreferredTerminal::WindowsTerminal => "windowsTerminal", + PreferredTerminal::PowerShell => "powershell", + PreferredTerminal::CommandPrompt => "commandPrompt", + } + } + + fn parse(value: &str) -> Option { + Self::ALL.into_iter().find(|term| term.id() == value) + } + + /// Windows Terminal ships as an app-execution alias in the per-user WindowsApps folder; + /// PowerShell and the Command Prompt are always where %SystemRoot% says. + fn path(self) -> PathBuf { + match self { + PreferredTerminal::WindowsTerminal => dirs::data_local_dir() + .unwrap_or_else(|| PathBuf::from(r"C:\")) + .join("Microsoft") + .join("WindowsApps") + .join("wt.exe"), + PreferredTerminal::PowerShell => system32_path("WindowsPowerShell") + .join("v1.0") + .join("powershell.exe"), + PreferredTerminal::CommandPrompt => system32_path("cmd.exe"), + } + } + + pub fn is_installed(self) -> bool { + self.path().is_file() + } + + /// The stored choice, falling back to whatever is actually installed. The Command Prompt + /// is the last rung and is always present, so this can never come back empty. + pub fn resolved() -> Self { + let stored = crate::settings::read() + .get("terminal") + .and_then(serde_json::Value::as_str) + .and_then(Self::parse); + match stored { + Some(term) if term.is_installed() => term, + _ => Self::ALL + .into_iter() + .find(|term| term.is_installed()) + .unwrap_or(PreferredTerminal::CommandPrompt), + } + } + + /// The argv that opens this console on `argv`, ready to hand to `cmd /C start ""`. + /// + /// `argv` is the codeburn command, token by token; every token has already passed + /// `is_safe_arg`, so none of them carries a quote, a `$`, a backtick or a `;`. That is + /// what makes the PowerShell line safe to build: it is the one case where the tokens are + /// re-parsed by a shell rather than passed straight through as argv. + fn launch_argv(self, argv: &[String]) -> Vec { + let cmd_exe = system32_path("cmd.exe").to_string_lossy().into_owned(); + let hold_open = |program: String| { + let mut out = vec![program, "/K".to_string()]; + out.extend(argv.iter().cloned()); + out + }; + match self { + PreferredTerminal::CommandPrompt => hold_open(cmd_exe), + // Windows Terminal takes the command line to run as its trailing arguments, so + // the console that actually holds the command open is still cmd. + PreferredTerminal::WindowsTerminal => { + let mut out = vec![self.path().to_string_lossy().into_owned()]; + out.extend(hold_open(cmd_exe)); + out + } + PreferredTerminal::PowerShell => { + if !argv.iter().all(|token| is_safe_arg(token)) { + return hold_open(cmd_exe); + } + let script = std::iter::once(format!("& '{}'", argv[0])) + .chain(argv[1..].iter().cloned()) + .collect::>() + .join(" "); + vec![ + self.path().to_string_lossy().into_owned(), + "-NoExit".to_string(), + "-Command".to_string(), + script, + ] + } + } + } +} + +/// What the settings window lists, with the ones that are not on this machine marked so the +/// "(not installed)" hint stays honest. +#[cfg(target_os = "windows")] +pub fn terminals() -> Vec { + PreferredTerminal::ALL + .into_iter() + .map(|term| TerminalOption { + id: term.id(), + installed: term.is_installed(), + }) + .collect() +} + +/// Linux and macOS pick a terminal by probing for one at launch, so there is nothing for the +/// settings window to offer; it hides the control when this list is empty. +#[cfg(not(target_os = "windows"))] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TerminalOption { + pub id: &'static str, + pub installed: bool, +} + +#[cfg(not(target_os = "windows"))] +pub fn terminals() -> Vec { + Vec::new() +} + /// Minimal dependency: we only use `which` inside spawn_in_terminal on Linux. Vendored here /// so the crate graph stays tiny. Gated so the unused-function warning doesn't fire on Mac /// or Windows builds. diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs index c63948e0..ab9676c1 100644 --- a/windows/src-tauri/src/lib.rs +++ b/windows/src-tauri/src/lib.rs @@ -166,6 +166,7 @@ pub fn run() { commands::settings_section, commands::settings_load, commands::settings_patch, + commands::terminals, commands::claude_config_dirs, commands::set_claude_config_dirs, commands::pick_directory, @@ -792,13 +793,18 @@ mod commands { app: AppHandle, severity: String, today_cost: Option, + today_tokens: Option, ) -> Result<(), String> { let severity = crate::tray_status::Severity::parse(&severity) .ok_or_else(|| format!("unknown quota severity `{severity}`"))?; - let over_budget = match (today_cost, crate::tray_status::daily_budget()) { - (Some(cost), Some(budget)) => cost >= budget, + // Either alert can be armed, and the mac tints the flame when the armed one is + // passed, so both are checked rather than only the one the metric happens to show. + let over = |value: Option, limit: Option| match (value, limit) { + (Some(value), Some(limit)) => value >= limit, _ => false, }; + let over_budget = over(today_cost, crate::tray_status::daily_budget()) + || over(today_tokens, crate::tray_status::daily_token_budget()); super::apply_tray_tint(&app, crate::tray_status::tint_for(severity, over_budget)) } @@ -959,6 +965,13 @@ mod commands { Ok(Value::Object(merged)) } + /// The consoles the settings window offers, each marked with whether it is on this + /// machine, so the "(not installed)" hint stays honest. + #[tauri::command] + pub fn terminals() -> Vec { + crate::cli::terminals() + } + #[tauri::command] pub fn claude_config_dirs() -> Vec { crate::settings::claude_config_dirs() diff --git a/windows/src/App.tsx b/windows/src/App.tsx index 8009a5d9..33b494e5 100644 --- a/windows/src/App.tsx +++ b/windows/src/App.tsx @@ -94,6 +94,10 @@ type FetchOptions = { showOverlay: boolean } +/// The two daily alert thresholds from the CLI config. Only the one the display metric is +/// measured in is ever shown, as on the mac; `null` means that alert is off. +type Budgets = { cost: number | null; tokens: number | null } + export function App() { const [period, setPeriod] = useState('today') // Days picked in the calendar. Non-empty overrides the period, as isDayMode does on @@ -119,7 +123,7 @@ export function App() { const [quota, setQuota] = useState(EMPTY_QUOTA) // The window starts hidden and is shown by a tray click, which emits `codeburn://shown`. const [popoverVisible, setPopoverVisible] = useState(false) - const [dailyBudget, setDailyBudget] = useState(null) + const [budgets, setBudgets] = useState({ cost: null, tokens: null }) // Every preference the settings window owns arrives here through one store, so a change // made in that window reaches this one without a reload. const [settings, setSettings] = useState(DEFAULT_SETTINGS) @@ -234,14 +238,22 @@ export function App() { useEffect(() => { if (!cliReady) return + // Manual never spawns on a timer; usage then only refreshes when the popover opens or + // Refresh is pressed. A chosen cadence applies whether the popover is open or not, since + // the reader asked for that number specifically. + const cadence = settings.usageRefreshSeconds + if (cadence === 0) return + const period = cadence > 0 + ? cadence * 1000 + : popoverVisible ? REFRESH_ACTIVE_MS : REFRESH_IDLE_MS const tick = popoverVisible ? () => refreshAll({ includeOptimize: true, showOverlay: false }) // Hidden, the tray figure is the only thing anyone can see, so only its key is // refreshed and the optimize pass is skipped. : () => fetchKey(menubarRef.current, { includeOptimize: false, showOverlay: false }) - const id = setInterval(tick, popoverVisible ? REFRESH_ACTIVE_MS : REFRESH_IDLE_MS) + const id = setInterval(tick, period) return () => clearInterval(id) - }, [cliReady, popoverVisible, refreshAll, fetchKey]) + }, [cliReady, popoverVisible, refreshAll, fetchKey, settings.usageRefreshSeconds]) const selectionKeyValue = selectionKey(current) useEffect(() => { @@ -271,8 +283,8 @@ export function App() { }) const unlistenHidden = listen('codeburn://hidden', () => setPopoverVisible(false)) const unlistenTheme = listen('codeburn://toggle-theme', () => toggleTheme()) - const unlistenBudget = listen<{ cost: number | null }>('codeburn://budget-changed', event => { - setDailyBudget(event.payload?.cost ?? null) + const unlistenBudget = listen('codeburn://budget-changed', event => { + if (event.payload) setBudgets(event.payload) }) const unlistenCurrency = listen('codeburn://currency-changed', event => { if (event.payload) setCurrency(event.payload) @@ -306,7 +318,7 @@ export function App() { // The limit lives in the CLI config, which package C's settings window will write, so // it is re-read whenever the popover comes back rather than cached for the session. const readDailyBudget = () => { - invoke('daily_budget').then(setDailyBudget).catch(() => {}) + invoke('daily_budgets').then(setBudgets).catch(() => {}) } useEffect(readDailyBudget, []) @@ -398,9 +410,14 @@ export function App() { // The flame carries the worst connected provider's quota severity. Rust decides whether // today's spend is over the daily budget, since the limit lives in the CLI's config. + const todayTokens = todayPayload?.current + ? todayPayload.current.inputTokens + todayPayload.current.outputTokens + : null + // `budgets` is in the list although Rust reads the limits from the config itself: without + // it, arming an alert would not tint the flame until the next refresh moved a figure. useEffect(() => { - invoke('set_tray_severity', { severity: worstSeverity(quota), todayCost }).catch(() => {}) - }, [quota, todayCost]) + invoke('set_tray_severity', { severity: worstSeverity(quota), todayCost, todayTokens }).catch(() => {}) + }, [quota, todayCost, todayTokens, budgets]) useEffect(() => { const span = MENUBAR_PERIODS.find(p => p.id === settings.menubarPeriod)?.label ?? 'Today' @@ -530,7 +547,8 @@ export function App() { currency={currency} periodLabel={label} isToday={days.length === 0 && period === 'today'} - dailyBudget={dailyBudget} + metric={settings.metric} + dailyBudget={isTokenMetric ? budgets.tokens : budgets.cost} combinedScope={effectiveScope === 'combined'} /> = dailyBudget + const measured = isTokenMetric ? inputTokens + outputTokens : cost + const overBudget = isToday && !combinedScope && dailyBudget !== null && payload !== null && measured >= dailyBudget const savings = combined ? 0 : payload?.current.localModelSavings?.totalUSD ?? 0 return ( @@ -39,28 +53,35 @@ export function HeroSection({ payload, currency, periodLabel, isToday, dailyBudg
{payload ? ( -
{formatCurrency(cost, currency)}
+
{headline}
) : (
)}
- {payload ? ( - <> - {calls.toLocaleString()} {calls === 1 ? 'call' : 'calls'} - {plural(sessions, 'session')} - - ) : ( + {!payload ? ( <> + ) : metric === 'tokens' ? ( + <> + {formatTokens(outputTokens)} + {formatTokens(inputTokens)} + + ) : ( + <> + {calls.toLocaleString()} {calls === 1 ? 'call' : 'calls'} + {plural(sessions, 'session')} + )}
{overBudget && dailyBudget !== null && (
- Daily budget of {formatCurrency(dailyBudget, USD)} exceeded + + Daily budget of {isTokenMetric ? `${formatTokens(dailyBudget)} tok` : formatCurrency(dailyBudget, USD)} exceeded +
)} {combined ? ( diff --git a/windows/src/lib/appSettings.ts b/windows/src/lib/appSettings.ts index 6c8c7bbd..a211fba2 100644 --- a/windows/src/lib/appSettings.ts +++ b/windows/src/lib/appSettings.ts @@ -49,7 +49,9 @@ export type ThemeChoice = 'system' | 'light' | 'dark' /// UsageRefreshCadence. Auto is the adaptive default, manual never auto-spawns. export const USAGE_CADENCES: Array<{ id: number; label: string }> = [ - { id: -1, label: 'Auto (2m, less on battery)' }, + // The mac's label promises "less on battery", which is the adaptive refresh that comes + // with the data-layer work; this one says what it actually does today. + { id: -1, label: 'Auto (1m open, 2m closed)' }, { id: 0, label: 'Manual' }, { id: 60, label: '1 minute' }, { id: 300, label: '5 minutes' }, diff --git a/windows/src/settings/GeneralPane.tsx b/windows/src/settings/GeneralPane.tsx index ae7056fb..1737e56f 100644 --- a/windows/src/settings/GeneralPane.tsx +++ b/windows/src/settings/GeneralPane.tsx @@ -5,7 +5,7 @@ import type { CurrencyState } from '../lib/currency' import { CURRENCY_CODES, CURRENCY_NAMES, USD } from '../lib/currency' import { ACCENT_PRESETS, accentById, applyAccent } from '../lib/accent' import { - DISPLAY_METRICS, MENUBAR_PERIODS, subscribeSettings, writeSettings, + DISPLAY_METRICS, MENUBAR_PERIODS, TERMINALS, USAGE_CADENCES, subscribeSettings, writeSettings, type AppSettings, type DisplayMetric, type MenubarPeriod, type MenubarScope, type ThemeChoice, } from '../lib/appSettings' import { applyTheme } from '../lib/settings' @@ -17,7 +17,7 @@ import { writeDockPrefs, type DockPrefs, } from '../lib/dockPrefs' import { ProviderGlyph } from '../providerIcons' -import { Group, Note, Pane, Row, Select, Slider, Switch } from './controls' +import { Field, Group, Note, Pane, Row, Select, Slider, Switch } from './controls' /// The mac's GeneralSettingsTab. Display first, because it is what the reader came for; the /// Windows-only rows (login item, tray badge) sit under System at the end, where the mac @@ -160,6 +160,29 @@ export function GeneralPane({ quota, anchor }: Props) { + + writeSettings({ usageRefreshSeconds })} + /> + } + /> + + How often the tray figure re-reads your local session data. Auto refreshes every + minute while the popover is open and every two minutes when it is closed. Manual only + refreshes when you open the popover or press Refresh. + + + + + + + ) } + +/// The mac's Terminal section. Only consoles that can hold a command open in a live window +/// are listed, and Rust says which of them are actually on this machine. +function TerminalSection({ settings }: { settings: AppSettings }) { + const [installed, setInstalled] = useState | null>(null) + + useEffect(() => { + invoke>('terminals') + .then(list => setInstalled(Object.fromEntries(list.map(t => [t.id, t.installed])))) + .catch(() => setInstalled({})) + }, []) + + // Nothing to choose on Linux, where a terminal is found by probing at launch. + if (installed === null || Object.keys(installed).length === 0) return null + + return ( + + ({ + id: term.id, + label: installed[term.id] === false ? `${term.label} (not installed)` : term.label, + }))} + onChange={terminal => writeSettings({ terminal })} + /> + } + /> + + Where Full Report and Optimize open. If the chosen console is not installed, CodeBurn + falls back to the Command Prompt, which always is. + + + ) +} + +/// The mac's Alerts section. The budget tracks whatever the tray figure shows: dollars for +/// the Cost metric, tokens for the two token metrics. Both are stored beside the currency in +/// the CLI config, because the tray reads them before any webview exists. +const COST_PRESETS = [0, 25, 50, 100, 200, 500] +const TOKEN_PRESETS = [0, 1e6, 5e6, 10e6, 25e6, 50e6, 100e6] +const CUSTOM = -1 + +function AlertsSection({ settings }: { settings: AppSettings }) { + const [budgets, setBudgets] = useState<{ cost: number | null; tokens: number | null }>({ cost: null, tokens: null }) + const [custom, setCustom] = useState(false) + const [draft, setDraft] = useState('') + + const isTokens = settings.metric === 'tokens' || settings.metric === 'totalTokens' + const stored = isTokens ? budgets.tokens : budgets.cost + const presets = isTokens ? TOKEN_PRESETS : COST_PRESETS + const key = isTokens ? 'dailyTokenBudget' : 'dailyBudget' + const unit = isTokens ? 1e6 : 1 + + const read = () => { + invoke<{ cost: number | null; tokens: number | null }>('daily_budgets') + .then(next => { + setBudgets(next) + const value = (settings.metric === 'tokens' || settings.metric === 'totalTokens') ? next.tokens : next.cost + const list = (settings.metric === 'tokens' || settings.metric === 'totalTokens') ? TOKEN_PRESETS : COST_PRESETS + // A stored amount that is not one of the presets is a custom one, so the field opens + // with it rather than the picker silently rounding it to a preset. + if (value !== null && !list.includes(value)) { + setCustom(true) + setDraft(trim(value / ((settings.metric === 'tokens' || settings.metric === 'totalTokens') ? 1e6 : 1))) + } + }) + .catch(() => {}) + } + useEffect(read, [settings.metric]) + + const write = (amount: number | null) => { + invoke('set_daily_budget', { key, amount }) + .then(() => setBudgets(current => ({ ...current, [isTokens ? 'tokens' : 'cost']: amount }))) + .catch(() => {}) + } + + const choose = (value: number) => { + if (value === CUSTOM) { + setCustom(true) + setDraft(stored ? trim(stored / unit) : '') + return + } + setCustom(false) + write(value > 0 ? value : null) + } + + const applyDraft = (text: string) => { + setDraft(text) + const value = Number(text.trim()) + write(Number.isFinite(value) && value > 0 ? value * unit : null) + } + + const label = (value: number) => { + if (value === 0) return 'Off' + return isTokens ? `${trim(value / 1e6)}M` : `$${trim(value)}` + } + + const armed = stored !== null && stored > 0 + const help = custom && !armed + ? 'Enter an amount above, or the alert stays off.' + : `The tray flame turns yellow when today's ${isTokens ? 'tokens pass' : 'cost passes'} the daily budget.` + + return ( + + ({ id: value, label: label(value) })), + { id: CUSTOM, label: 'Custom...' }, + ]} + onChange={choose} + /> + } + /> + {custom && ( + + } + /> + )} + {help} + + ) +} + +function trim(value: number): string { + return value === Math.round(value) ? String(Math.round(value)) : String(value) +} diff --git a/windows/src/styles.css b/windows/src/styles.css index ae3e219d..d41dc1d1 100644 --- a/windows/src/styles.css +++ b/windows/src/styles.css @@ -2116,3 +2116,9 @@ code { font-family: var(--font-mono); } .stg-readout { font-family: var(--font-mono); font-size: 11px; color: var(--label-2); min-width: 38px; text-align: right; } .stg-provider { display: inline-flex; align-items: center; gap: 7px; } .stg-attention { font-size: 10px; color: var(--danger); } +/* The Tokens metric swaps calls and sessions for an up and down pair, so those two rows + carry a glyph as well as a figure. */ +.hero-calls, .hero-sessions { display: inline-flex; align-items: center; gap: 2px; } +/* The native popup is painted by the OS in its own colours, so an option that only inherits + the select's colour is white on white in the dark theme. Both are stated here. */ +.stg-select option { background: var(--surface-window); color: var(--label); }