mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-25 06:17:20 +00:00
feat(windows): usage refresh, terminal and daily budget settings
The last three sections of the mac's General pane, and the pieces of the app that read them. Usage Refresh replaces the two hard-coded intervals. Manual never spawns on a timer, so usage refreshes only when the popover opens or Refresh is pressed; a chosen cadence applies open or closed, since the reader asked for that number specifically; Auto keeps what the app already did. The label says "1m open, 2m closed" rather than the mac's "less on battery", which is the adaptive refresh that comes with the data-layer work and would be a promise this build does not keep. Terminal picks which console Full Report and Optimize open in. It exists for the same reason as the mac's PreferredTerminal: a user preference must never become a free-form string in a command line. The stored value parses back through a closed set, every executable is a compile-time literal resolved from %SystemRoot% or %LOCALAPPDATA%, and the one case that is re-parsed by a shell rather than passed as argv, the PowerShell line, is only built when every token has already passed the argument allowlist. Anything not installed falls back to the Command Prompt, which always is. Alerts arm the daily budget the tray flame is judged against. It follows the display metric: dollars for Cost, millions of tokens for the two token metrics, with the mac's presets plus Custom. Both thresholds live beside the currency in the CLI config, because the tray reads them before any webview exists, and a change reaches the popover and the flame at once rather than at the next refresh. The hero follows the metric too, so the popover and the tray can never disagree about what the day cost: the token metrics put the total in the headline, and Tokens replaces calls and sessions with the up and down split, as the mac's hero does. Also here because the dark theme made it obvious: a native select popup is painted by the OS in its own colours, so options that only inherited the select's colour were white on white. Both are stated now.
This commit is contained in:
parent
9af1384384
commit
aacc42b13b
7 changed files with 414 additions and 39 deletions
|
|
@ -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<String> = 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> {
|
||||
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<String> {
|
||||
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::<Vec<_>>()
|
||||
.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<TerminalOption> {
|
||||
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<TerminalOption> {
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -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<f64>,
|
||||
today_tokens: Option<f64>,
|
||||
) -> 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<f64>, limit: Option<f64>| 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::TerminalOption> {
|
||||
crate::cli::terminals()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn claude_config_dirs() -> Vec<String> {
|
||||
crate::settings::claude_config_dirs()
|
||||
|
|
|
|||
|
|
@ -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<Period>('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<QuotaState>(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<number | null>(null)
|
||||
const [budgets, setBudgets] = useState<Budgets>({ 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<AppSettings>(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<Budgets>('codeburn://budget-changed', event => {
|
||||
if (event.payload) setBudgets(event.payload)
|
||||
})
|
||||
const unlistenCurrency = listen<CurrencyState>('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<number | null>('daily_budget').then(setDailyBudget).catch(() => {})
|
||||
invoke<Budgets>('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'}
|
||||
/>
|
||||
<PeriodTabs
|
||||
|
|
|
|||
|
|
@ -3,20 +3,24 @@ import type { CurrencyState } from '../lib/currency'
|
|||
import { USD, formatCurrency, formatTokens, plural } from '../lib/currency'
|
||||
import { prettyDate, todayKey } from '../lib/dates'
|
||||
import { SectionCaption } from './CollapsibleSection'
|
||||
import { LeafIcon, MonitorIcon, WarningIcon } from './Icons'
|
||||
import { ArrowDownRight, ArrowUpRight, LeafIcon, MonitorIcon, WarningIcon } from './Icons'
|
||||
import type { DisplayMetric } from '../lib/appSettings'
|
||||
|
||||
type Props = {
|
||||
payload: MenubarPayload | null
|
||||
currency: CurrencyState
|
||||
periodLabel: string
|
||||
isToday: boolean
|
||||
/// Today spend limit from the CLI config, or null when the alert is off.
|
||||
/// Today's limit from the CLI config, in whatever the metric counts, or null when the
|
||||
/// alert is off.
|
||||
dailyBudget: number | null
|
||||
/// The settings window's Display metric, so the hero and the tray figure never disagree.
|
||||
metric: DisplayMetric
|
||||
/// True when the reader asked for every paired device, not just this one.
|
||||
combinedScope: boolean
|
||||
}
|
||||
|
||||
export function HeroSection({ payload, currency, periodLabel, isToday, dailyBudget, combinedScope }: Props) {
|
||||
export function HeroSection({ payload, currency, periodLabel, isToday, dailyBudget, metric, combinedScope }: Props) {
|
||||
const todayLabel = prettyDate(todayKey())
|
||||
// Pulling the peers is best effort in the CLI, so combined scope can come back with local
|
||||
// totals and no `combined` block. The hero then reads as a plain local view, plus a note.
|
||||
|
|
@ -25,13 +29,23 @@ export function HeroSection({ payload, currency, periodLabel, isToday, dailyBudg
|
|||
const cost = totals?.cost ?? payload?.current.cost ?? 0
|
||||
const calls = totals?.calls ?? payload?.current.calls ?? 0
|
||||
const sessions = totals?.sessions ?? payload?.current.sessions ?? 0
|
||||
const inputTokens = totals?.inputTokens ?? payload?.current.inputTokens ?? 0
|
||||
const outputTokens = totals?.outputTokens ?? payload?.current.outputTokens ?? 0
|
||||
|
||||
// Both token metrics put the total in the headline, as the mac's heroText does; only the
|
||||
// Tokens metric replaces calls and sessions with the up and down split.
|
||||
const isTokenMetric = metric === 'tokens' || metric === 'totalTokens'
|
||||
const headline = isTokenMetric
|
||||
? `${formatTokens(inputTokens + outputTokens)} tok`
|
||||
: formatCurrency(cost, currency)
|
||||
|
||||
const label = payload?.current.label || periodLabel
|
||||
const caption = combined ? `Combined · ${label}` : isToday ? `Today · ${todayLabel}` : label
|
||||
// The budget is defined in USD, matching the CLI config and the presets the settings
|
||||
// window will offer, so it is compared and printed in USD rather than converted. Combined
|
||||
// window offers, so it is compared and printed in USD rather than converted. Combined
|
||||
// totals are several machines' spend, which the limit was never set against.
|
||||
const overBudget = isToday && !combinedScope && dailyBudget !== null && payload !== null && cost >= 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
|
|||
<SectionCaption text={caption} />
|
||||
<div className="hero-row">
|
||||
{payload ? (
|
||||
<div className="hero-amount">{formatCurrency(cost, currency)}</div>
|
||||
<div className="hero-amount">{headline}</div>
|
||||
) : (
|
||||
<div className="hero-amount hero-skeleton" aria-label="Loading" />
|
||||
)}
|
||||
<div className="hero-meta">
|
||||
{payload ? (
|
||||
<>
|
||||
<span className="hero-calls">{calls.toLocaleString()} {calls === 1 ? 'call' : 'calls'}</span>
|
||||
<span className="hero-sessions">{plural(sessions, 'session')}</span>
|
||||
</>
|
||||
) : (
|
||||
{!payload ? (
|
||||
<>
|
||||
<span className="hero-skeleton-line" />
|
||||
<span className="hero-skeleton-line short" />
|
||||
</>
|
||||
) : metric === 'tokens' ? (
|
||||
<>
|
||||
<span className="hero-calls"><ArrowUpRight size={9} />{formatTokens(outputTokens)}</span>
|
||||
<span className="hero-sessions"><ArrowDownRight size={9} />{formatTokens(inputTokens)}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="hero-calls">{calls.toLocaleString()} {calls === 1 ? 'call' : 'calls'}</span>
|
||||
<span className="hero-sessions">{plural(sessions, 'session')}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{overBudget && dailyBudget !== null && (
|
||||
<div className="hero-note hero-note-warn">
|
||||
<WarningIcon size={10} />
|
||||
<span>Daily budget of {formatCurrency(dailyBudget, USD)} exceeded</span>
|
||||
<span>
|
||||
Daily budget of {isTokenMetric ? `${formatTokens(dailyBudget)} tok` : formatCurrency(dailyBudget, USD)} exceeded
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{combined ? (
|
||||
|
|
|
|||
|
|
@ -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' },
|
||||
|
|
|
|||
|
|
@ -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) {
|
|||
|
||||
<CapacityDockSection quota={quota} />
|
||||
|
||||
<Group title="Usage Refresh">
|
||||
<Row
|
||||
label="Update every"
|
||||
control={
|
||||
<Select
|
||||
ariaLabel="Usage refresh cadence"
|
||||
value={settings.usageRefreshSeconds}
|
||||
options={USAGE_CADENCES}
|
||||
onChange={usageRefreshSeconds => writeSettings({ usageRefreshSeconds })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Note>
|
||||
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.
|
||||
</Note>
|
||||
</Group>
|
||||
|
||||
<TerminalSection settings={settings} />
|
||||
|
||||
<AlertsSection settings={settings} />
|
||||
|
||||
<Group title="System">
|
||||
<Row
|
||||
label="Theme"
|
||||
|
|
@ -347,3 +370,147 @@ function CapacityDockSection({ quota }: { quota: QuotaState }) {
|
|||
</Group>
|
||||
)
|
||||
}
|
||||
|
||||
/// 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<Record<string, boolean> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
invoke<Array<{ id: string; installed: boolean }>>('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 (
|
||||
<Group title="Terminal">
|
||||
<Row
|
||||
label="Open commands in"
|
||||
control={
|
||||
<Select
|
||||
ariaLabel="Terminal"
|
||||
value={settings.terminal}
|
||||
options={TERMINALS.map(term => ({
|
||||
id: term.id,
|
||||
label: installed[term.id] === false ? `${term.label} (not installed)` : term.label,
|
||||
}))}
|
||||
onChange={terminal => writeSettings({ terminal })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Note>
|
||||
Where Full Report and Optimize open. If the chosen console is not installed, CodeBurn
|
||||
falls back to the Command Prompt, which always is.
|
||||
</Note>
|
||||
</Group>
|
||||
)
|
||||
}
|
||||
|
||||
/// 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 (
|
||||
<Group title="Alerts">
|
||||
<Row
|
||||
label="Daily budget"
|
||||
control={
|
||||
<Select
|
||||
ariaLabel="Daily budget"
|
||||
value={custom ? CUSTOM : stored ?? 0}
|
||||
options={[
|
||||
...presets.map(value => ({ id: value, label: label(value) })),
|
||||
{ id: CUSTOM, label: 'Custom...' },
|
||||
]}
|
||||
onChange={choose}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{custom && (
|
||||
<Row
|
||||
label={isTokens ? 'Millions of tokens' : 'Amount in USD'}
|
||||
control={
|
||||
<Field
|
||||
ariaLabel="Custom daily budget"
|
||||
placeholder="Amount"
|
||||
value={draft}
|
||||
onChange={applyDraft}
|
||||
width={110}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<Note>{help}</Note>
|
||||
</Group>
|
||||
)
|
||||
}
|
||||
|
||||
function trim(value: number): string {
|
||||
return value === Math.round(value) ? String(Math.round(value)) : String(value)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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); }
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue