diff --git a/windows/src-tauri/src/autostart.rs b/windows/src-tauri/src/autostart.rs index b1a1306d..f563d429 100644 --- a/windows/src-tauri/src/autostart.rs +++ b/windows/src-tauri/src/autostart.rs @@ -2,20 +2,21 @@ //! executable. Linux: an XDG autostart .desktop file. No extra crates; both are a few //! lines of `reg` / plain file IO. -use anyhow::{anyhow, Context, Result}; +use anyhow::{anyhow, Result}; +#[cfg(any(target_os = "windows", target_os = "linux"))] +use anyhow::Context; +#[cfg(any(target_os = "windows", target_os = "linux"))] const APP_NAME: &str = "CodeBurn"; #[cfg(target_os = "windows")] const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run"; +/// Absolute `reg.exe` out of System32 -- see `cli::system_command`. #[cfg(target_os = "windows")] fn reg(args: &[&str]) -> Result { - use std::os::windows::process::CommandExt; - const CREATE_NO_WINDOW: u32 = 0x08000000; - std::process::Command::new("reg") + crate::cli::system_command("reg.exe") .args(args) - .creation_flags(CREATE_NO_WINDOW) .output() .with_context(|| "failed to run reg.exe") } diff --git a/windows/src-tauri/src/cli.rs b/windows/src-tauri/src/cli.rs index 84f2b358..53435547 100644 --- a/windows/src-tauri/src/cli.rs +++ b/windows/src-tauri/src/cli.rs @@ -18,14 +18,21 @@ const MAX_STDERR_BYTES: usize = 256 * 1024; const FETCH_TIMEOUT_SECS: u64 = 60; const VERSION_TIMEOUT_SECS: u64 = 20; -/// Oldest CLI that emits the `menubar-json` shape this app renders (history.daily with -/// per-day model breakdown, providers map). Older CLIs get the setup screen instead of a -/// half-rendered popover. -pub const MIN_CLI_VERSION: (u32, u32, u32) = (0, 7, 0); +/// Oldest CLI this app can talk to. 0.9.9 is the first release whose +/// `status --format menubar-json` accepts `--no-optimize`, which every quiet background +/// refresh passes; it also emits all the payload fields the popover reads +/// (`current.providers`, `current.cacheHitPercent`, `history.daily[].topModels`). Older CLIs +/// get the setup screen instead of a half-rendered popover or a stream of spawn failures. +pub const MIN_CLI_VERSION: (u32, u32, u32) = (0, 9, 9); #[cfg(windows)] const WINDOWS_CLI_NAMES: [&str; 2] = ["codeburn.cmd", "codeburn.exe"]; +#[cfg(windows)] +const CLAUDE_NAMES: [&str; 2] = ["claude.cmd", "claude.exe"]; +#[cfg(not(windows))] +const CLAUDE_NAMES: [&str; 1] = ["claude"]; + /// Alphanumerics plus `._/-` and space, with `\`, `:`, `(`, `)` also allowed on Windows /// so a user-supplied `CODEBURN_BIN` path like `C:\Users\...\codeburn.cmd` is accepted. /// None of these are shell metacharacters in a direct-argv spawn (we never invoke `sh -c`). @@ -247,14 +254,32 @@ pub fn parse_version(text: &str) -> Option<(u32, u32, u32)> { /// changed the user's PATH, so we also read the live PATH from the registry on Windows and /// probe the standard npm / node install prefixes. fn locate_cli() -> Option { + find_in_search_dirs(&candidate_names()) +} + +/// Same search for Claude Code's own binary, so "Connect Claude" spawns an absolute path +/// instead of letting the console shell resolve a bare `claude`. +fn locate_claude() -> Option { + find_in_search_dirs(&CLAUDE_NAMES) +} + +fn find_in_search_dirs(names: &[&str]) -> Option { let mut dirs: Vec = Vec::new(); if let Some(path) = env::var_os("PATH") { dirs.extend(env::split_paths(&path)); } dirs.extend(extra_search_dirs()); + find_in_dirs(&dirs, names) +} - for dir in dirs { - for name in candidate_names() { +/// The absolute-only filter is the security boundary, so it lives here where every search +/// goes through it. `env::split_paths` yields an empty `PathBuf` for `;;` or a trailing `;`, +/// and the registry PATH can hold relative entries too; `PathBuf::from("").join("codeburn.cmd")` +/// resolves against the current directory, which for a tray app launched at login is +/// whatever Explorer handed it. A binary planted there must never win. +fn find_in_dirs(dirs: &[PathBuf], names: &[&str]) -> Option { + for dir in dirs.iter().filter(|d| d.is_absolute()) { + for name in names { let candidate = dir.join(name); if candidate.is_file() { return Some(candidate.to_string_lossy().into_owned()); @@ -313,21 +338,42 @@ fn extra_search_dirs() -> Vec { out } +/// Windows' `CreateProcess` searches the current directory before `PATH`, so spawning +/// `reg` or `cmd` by bare name lets anything dropped next to the app impersonate a system +/// tool -- and the tray badge re-runs `reg query` every refresh. Always spawn the real one +/// out of `%SystemRoot%\System32`, falling back to the documented default when the +/// environment variable is missing or relative. +#[cfg(windows)] +pub fn system32_path(exe: &str) -> PathBuf { + let root = env::var_os("SystemRoot") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .unwrap_or_else(|| PathBuf::from(r"C:\Windows")); + root.join("System32").join(exe) +} + +/// `system32_path` plus the CREATE_NO_WINDOW flag every one of these callers wants. +#[cfg(windows)] +pub fn system_command(exe: &str) -> std::process::Command { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x08000000; + let mut cmd = std::process::Command::new(system32_path(exe)); + cmd.creation_flags(CREATE_NO_WINDOW); + cmd +} + /// Reads the user and machine PATH values from the registry via `reg.exe` so a PATH edit /// made after this process started (npm install adds `%APPDATA%\npm`) is still honoured. #[cfg(windows)] fn registry_path_dirs() -> Vec { - use std::os::windows::process::CommandExt; - const CREATE_NO_WINDOW: u32 = 0x08000000; let mut out = Vec::new(); let keys = [ r"HKCU\Environment", r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", ]; for key in keys { - let output = std::process::Command::new("reg") + let output = system_command("reg.exe") .args(["query", key, "/v", "Path"]) - .creation_flags(CREATE_NO_WINDOW) .output(); let Ok(output) = output else { continue }; let text = String::from_utf8_lossy(&output.stdout); @@ -391,11 +437,14 @@ pub fn spawn_in_terminal(app: &AppHandle, subcommand: &[&str]) -> Result<()> { } /// The Plan view's "Connect Claude" runs Claude Code's own login flow, not codeburn. The -/// bare name is deliberate: on Windows the console shell resolves `claude.exe` (native -/// installer) or `claude.cmd` (npm) through PATHEXT. +/// binary is located up front rather than handed to the console shell as a bare name, so +/// the same absolute-directory rule that protects the codeburn lookup applies here too. pub fn spawn_claude_login(app: &AppHandle) -> Result<()> { + let program = locate_claude().ok_or_else(|| { + anyhow!("Claude Code was not found on this machine. Install it, then try again.") + })?; let cli = CodeburnCli { - program: "claude".to_string(), + program, extra_args: vec![], }; spawn_program_in_terminal(app, &cli, &["login"]) @@ -408,27 +457,32 @@ fn spawn_program_in_terminal(_app: &AppHandle, cli: &CodeburnCli, subcommand: &[ #[cfg(target_os = "linux")] { - let terminals: [&[&str]; 4] = [ - &["x-terminal-emulator", "-e"], - &["gnome-terminal", "--", "bash", "-lc"], - &["konsole", "-e"], - &["xterm", "-e"], - ]; - for term in &terminals { - let program = term[0]; - let extras = &term[1..]; - if which::which(program).is_ok() { - let mut command_parts: Vec = vec![cli.program.clone()]; - command_parts.extend(cli.extra_args.clone()); - command_parts.extend(subcommand.iter().map(|s| s.to_string())); - // gnome-terminal wants the whole command as a single argv after `--` - // followed by `bash -lc`. The allowlist guarantees no quoting is needed. - let composite = command_parts.join(" "); - let mut cmd = std::process::Command::new(program); - cmd.args(extras); - cmd.arg(&composite); - cmd.spawn().with_context(|| format!("failed to launch {}", program))?; - return Ok(()); + let mut command_parts: Vec = vec![cli.program.clone()]; + command_parts.extend(cli.extra_args.clone()); + command_parts.extend(subcommand.iter().map(|s| s.to_string())); + // Terminal emulators take the command as one string that a shell then parses + // (gnome-terminal explicitly hands it to `bash -lc`). `cli.program` reaches here + // from PATH resolution, not only from the allowlisted CODEBURN_BIN, so re-check + // every part before joining; anything a shell could reinterpret skips the terminal + // and goes through the argv-only detached spawn below. + if command_parts.iter().all(|p| is_safe_arg(p)) { + let composite = command_parts.join(" "); + let terminals: [&[&str]; 4] = [ + &["x-terminal-emulator", "-e"], + &["gnome-terminal", "--", "bash", "-lc"], + &["konsole", "-e"], + &["xterm", "-e"], + ]; + for term in &terminals { + let program = term[0]; + let extras = &term[1..]; + if which::which(program).is_ok() { + let mut cmd = std::process::Command::new(program); + cmd.args(extras); + cmd.arg(&composite); + cmd.spawn().with_context(|| format!("failed to launch {}", program))?; + return Ok(()); + } } } // Fallback: run detached, output lost -- better than silently doing nothing. @@ -448,14 +502,16 @@ fn spawn_program_in_terminal(_app: &AppHandle, cli: &CodeburnCli, subcommand: &[ // 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. - let is_codeburn = cli.program.starts_with("codeburn"); - let program = if std::path::Path::new(&cli.program).is_absolute() || !is_codeburn { - cli.program.clone() - } else { + // 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() { locate_cli().unwrap_or_else(|| cli.program.clone()) + } else { + cli.program.clone() }; - let mut cmd = std::process::Command::new("cmd"); - cmd.arg("/C").arg("start").arg("").arg("cmd").arg("/K").arg(&program); + let cmd_exe = system32_path("cmd.exe"); + 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); } @@ -488,12 +544,58 @@ mod which { pub fn which(program: &str) -> Result { let path = env::var_os("PATH").ok_or(())?; - for dir in env::split_paths(&path) { - let candidate = dir.join(program); - if candidate.is_file() { - return Ok(candidate); - } - } - Err(()) + let dirs: Vec = env::split_paths(&path).collect(); + super::find_in_dirs(&dirs, &[program]).map(PathBuf::from).ok_or(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The `;;` / trailing-`;` case: an empty PATH entry must not turn into a + /// current-directory lookup, which is how a planted binary would win at login. + #[test] + fn find_in_dirs_skips_empty_and_relative_entries() { + let dir = std::env::temp_dir(); + let name = "codeburn-menubar-locate-probe"; + let planted = dir.join(name); + std::fs::write(&planted, b"probe").unwrap(); + + // Empty and relative entries are ignored even though the file is reachable + // through them once the process CWD is the temp dir. + let unsafe_dirs = vec![PathBuf::from(""), PathBuf::from("."), PathBuf::from("..")]; + assert_eq!(find_in_dirs(&unsafe_dirs, &[name]), None); + + // The same name behind an absolute entry is found. + let found = find_in_dirs(std::slice::from_ref(&dir), &[name]).expect("absolute entry should match"); + assert!(PathBuf::from(&found).is_absolute()); + assert!(found.ends_with(name)); + + // An unsafe entry ahead of a good one cannot shadow it. + let mixed = vec![PathBuf::from(""), dir.clone()]; + assert_eq!(find_in_dirs(&mixed, &[name]), Some(found)); + + std::fs::remove_file(&planted).ok(); + } + + #[test] + fn parse_version_reads_bare_and_prefixed_output() { + assert_eq!(parse_version("0.9.9"), Some((0, 9, 9))); + assert_eq!(parse_version("codeburn 0.9.20\n"), Some((0, 9, 20))); + assert_eq!(parse_version("1.0"), Some((1, 0, 0))); + assert_eq!(parse_version("0.10.0-beta.1"), Some((0, 10, 0))); + assert_eq!(parse_version("no version here"), None); + } + + /// The gate is a plain tuple compare, so the only thing worth pinning is that the + /// versions on either side of MIN_CLI_VERSION land on the right side of it. + #[test] + fn version_gate_rejects_only_older_clis() { + assert_eq!(MIN_CLI_VERSION, (0, 9, 9)); + assert!(parse_version("0.9.8").unwrap() < MIN_CLI_VERSION); + assert!(parse_version("0.9.9").unwrap() >= MIN_CLI_VERSION); + assert!(parse_version("0.9.20").unwrap() >= MIN_CLI_VERSION); + assert!(parse_version("0.10.0").unwrap() >= MIN_CLI_VERSION); } } diff --git a/windows/src-tauri/src/config.rs b/windows/src-tauri/src/config.rs index 29787ff1..3ec8c0ab 100644 --- a/windows/src-tauri/src/config.rs +++ b/windows/src-tauri/src/config.rs @@ -91,6 +91,8 @@ mod unix_lock { .create(true) .read(true) .write(true) + // A lock file only ever needs to exist; its contents are irrelevant. + .truncate(false) .open(super::lock_path()) .with_context(|| "failed to open config lock")?; @@ -107,9 +109,18 @@ mod unix_lock { } } -/// Windows has no flock; a create-new lock file gives the same mutual exclusion against -/// the CLI's own writer. Stale locks (crash mid-write) are ignored once older than -/// STALE_LOCK_SECS so a single crash can never wedge currency changes forever. +/// Windows has no flock; a create-new lock file is the closest equivalent. +/// +/// What this actually buys: mutual exclusion between writers that take this lock, which +/// today means only other instances of this app. The codeburn CLI writes `config.json` +/// without taking it, so a concurrent CLI write still races us -- the rename below keeps the +/// file from ever being torn, but a simultaneous CLI edit can still be the one that wins. +/// +/// A lock file left behind by a crash is treated as abandoned once it is older than +/// STALE_LOCK_SECS (three orders of magnitude longer than the read-modify-rename it guards), +/// so one crash cannot wedge currency changes forever. Upgrading to `LockFileEx`, which the +/// OS releases on process death and needs no staleness heuristic, only becomes worth it if +/// the CLI ever starts taking the lock too. #[cfg(windows)] mod windows_lock { use std::fs; @@ -124,10 +135,15 @@ mod windows_lock { pub struct Guard { path: PathBuf, + /// Kept open for the lifetime of the guard: Windows will not unlink a file that is + /// still open, so holding the handle is what stops the stale sweep below from ever + /// deleting a lock whose owner is alive. + file: Option, } impl Drop for Guard { fn drop(&mut self) { + self.file.take(); let _ = fs::remove_file(&self.path); } } @@ -136,10 +152,16 @@ mod windows_lock { let path = super::lock_path(); for _ in 0..MAX_RETRIES { match fs::OpenOptions::new().write(true).create_new(true).open(&path) { - Ok(_) => return Ok(Guard { path }), + Ok(file) => { + return Ok(Guard { + path, + file: Some(file), + }) + } Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => { - if is_stale(&path) { - let _ = fs::remove_file(&path); + // Only proceed on a successful unlink: a live holder still has the file + // open, so this fails for anything but an abandoned lock. + if is_stale(&path) && fs::remove_file(&path).is_ok() { continue; } sleep(RETRY_INTERVAL); diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs index d040f399..6064a916 100644 --- a/windows/src-tauri/src/lib.rs +++ b/windows/src-tauri/src/lib.rs @@ -83,10 +83,11 @@ pub fn run() { WindowEvent::CloseRequested { api, .. } => { api.prevent_close(); let _ = window.hide(); + mark_hidden(window.app_handle()); } WindowEvent::Focused(false) => { - LAST_HIDDEN_MS.store(now_ms(), Ordering::Relaxed); let _ = window.hide(); + mark_hidden(window.app_handle()); } _ => {} } @@ -274,13 +275,21 @@ fn now_ms() -> i64 { .as_millis() as i64 } +/// Every path that hides the popover goes through here, so the debounce stamp and the +/// frontend's visibility signal can never drift apart. The frontend drops to its idle +/// refresh cadence on `codeburn://hidden` and comes back on `codeburn://shown`. +fn mark_hidden(app: &AppHandle) { + LAST_HIDDEN_MS.store(now_ms(), Ordering::Relaxed); + let _ = app.emit("codeburn://hidden", ()); +} + fn toggle_popover(app: &AppHandle, anchor: Option<(i32, i32)>) { let Some(window) = app.get_webview_window(POPOVER_LABEL) else { return; }; if window.is_visible().unwrap_or(false) { - LAST_HIDDEN_MS.store(now_ms(), Ordering::Relaxed); let _ = window.hide(); + mark_hidden(app); return; } let last = LAST_HIDDEN_MS.load(Ordering::Relaxed); @@ -434,8 +443,8 @@ mod commands { #[tauri::command] pub fn hide_popover(app: AppHandle) { if let Some(window) = app.get_webview_window(POPOVER_LABEL) { - super::LAST_HIDDEN_MS.store(super::now_ms(), std::sync::atomic::Ordering::Relaxed); let _ = window.hide(); + super::mark_hidden(&app); } } diff --git a/windows/src-tauri/src/plan.rs b/windows/src-tauri/src/plan.rs index 165c1b33..98fbbff2 100644 --- a/windows/src-tauri/src/plan.rs +++ b/windows/src-tauri/src/plan.rs @@ -1,18 +1,17 @@ //! Claude subscription usage (the "Plan" insight). Mirrors the macOS SubscriptionClient: -//! read Claude Code's OAuth credentials, call the usage endpoint, refresh once on 401, and -//! keep a rolling snapshot file so a freshly reset window can still show last cycle's final. +//! read Claude Code's OAuth credentials, call the usage endpoint, adopt a token Claude Code +//! has already rotated on 401 (never spending the shared refresh token), and keep a rolling +//! snapshot file so a freshly reset window can still show last cycle's final. use std::fs; use std::path::PathBuf; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{bail, Context, Result}; use serde::{Deserialize, Serialize}; use tokio::sync::Mutex; const CREDENTIALS_RELATIVE_PATH: &str = ".claude/.credentials.json"; -const OAUTH_CLIENT_ID: &str = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"; -const REFRESH_URL: &str = "https://platform.claude.com/v1/oauth/token"; const USAGE_URL: &str = "https://api.anthropic.com/api/oauth/usage"; const BETA_HEADER: &str = "oauth-2025-04-20"; const USER_AGENT: &str = "claude-code/2.1.0"; @@ -78,24 +77,28 @@ impl PlanClient { let response = match fetch_usage(&creds.access_token).await { Ok(r) => r, + // Parity with mac/Sources/CodeBurnMenubar/Data/ClaudeCredentialStore.swift + // (`refreshAfter401`): Claude's refresh token is single-use and rotates, so + // spending it here would invalidate the token Claude Code itself is holding and + // break the user's `claude` login. Instead re-read Claude's own store for a + // token it has already rotated; if there is nothing fresher yet, report a + // transient failure and let the next refresh pick it up. Err(FetchError::Unauthorized) => { - let Some(refresh) = creds.refresh_token.as_deref().filter(|t| !t.is_empty()) else { + let rotated = load_credentials() + .ok() + .flatten() + .map(|c| c.access_token) + .filter(|t| *t != creds.access_token); + let Some(token) = rotated else { return Ok(PlanUsage::Failed { - message: "Claude session expired and no refresh token is available. Run `claude login`.".into(), + message: "Claude is refreshing its session. This clears itself once Claude Code renews the token; run `claude login` if it persists.".into(), }); }; - match refresh_access_token(refresh).await { - Ok(token) => match fetch_usage(&token).await { - Ok(r) => r, - Err(err) => { - return Ok(PlanUsage::Failed { - message: err.to_string(), - }) - } - }, + match fetch_usage(&token).await { + Ok(r) => r, Err(err) => { return Ok(PlanUsage::Failed { - message: format!("Token refresh failed: {err}"), + message: err.to_string(), }) } } @@ -144,7 +147,6 @@ impl PlanClient { struct StoredCredentials { access_token: String, - refresh_token: Option, rate_limit_tier: Option, } @@ -158,8 +160,6 @@ struct CredentialsRoot { struct OAuthBlock { #[serde(rename = "accessToken")] access_token: Option, - #[serde(rename = "refreshToken")] - refresh_token: Option, #[serde(rename = "rateLimitTier")] rate_limit_tier: Option, } @@ -195,7 +195,6 @@ fn load_credentials() -> Result> { } Ok(Some(StoredCredentials { access_token: token, - refresh_token: oauth.refresh_token, rate_limit_tier: oauth.rate_limit_tier, })) } @@ -253,11 +252,6 @@ struct Window { resets_at: Option, } -#[derive(Debug, Deserialize)] -struct TokenRefreshResponse { - access_token: String, -} - #[derive(Debug, thiserror::Error)] enum FetchError { #[error("Claude session is no longer authorized")] @@ -301,27 +295,6 @@ async fn fetch_usage(token: &str) -> Result { .map_err(|e| FetchError::Other(format!("Decode failed: {e}"))) } -async fn refresh_access_token(refresh_token: &str) -> Result { - let response = client() - .map_err(|e| anyhow!(e.to_string()))? - .post(REFRESH_URL) - .header("Accept", "application/json") - .form(&[ - ("grant_type", "refresh_token"), - ("refresh_token", refresh_token), - ("client_id", OAUTH_CLIENT_ID), - ]) - .send() - .await?; - let status = response.status(); - if !status.is_success() { - let body = response.text().await.unwrap_or_default(); - bail!("{} {}", status.as_u16(), truncate(&body, 200)); - } - let decoded: TokenRefreshResponse = response.json().await?; - Ok(decoded.access_token) -} - fn truncate(text: &str, max: usize) -> String { let mut out: String = text.chars().take(max).collect(); if text.chars().count() > max { @@ -345,31 +318,53 @@ struct Snapshot { effective_tokens: Option, } -fn snapshots_path() -> PathBuf { - let dir = std::env::var_os("CODEBURN_CACHE_DIR") +/// None when there is no cache dir and no home dir: writing the snapshot store into the +/// process's current directory would scatter a file wherever the tray happened to be +/// launched from, so we simply skip snapshots instead. +fn snapshots_path() -> Option { + std::env::var_os("CODEBURN_CACHE_DIR") .map(PathBuf::from) .or_else(|| dirs::home_dir().map(|h| h.join(".cache").join("codeburn"))) - .unwrap_or_else(|| PathBuf::from(".")); - dir.join(SNAPSHOT_FILENAME) + .map(|dir| dir.join(SNAPSHOT_FILENAME)) } fn load_snapshots() -> Vec { - fs::read(snapshots_path()) - .ok() + snapshots_path() + .and_then(|p| fs::read(p).ok()) .and_then(|bytes| serde_json::from_slice(&bytes).ok()) .unwrap_or_default() } +/// Mirrors `mac/Sources/CodeBurnMenubar/Security/SafeFile.swift`: write to a temp file with +/// owner-only permissions and rename over the target, and refuse a target that has been +/// replaced by a symlink pointing somewhere else. fn save_snapshots(all: &[Snapshot]) { - let path = snapshots_path(); + let Some(path) = snapshots_path() else { return }; + if let Ok(meta) = fs::symlink_metadata(&path) { + if meta.file_type().is_symlink() { + return; + } + } if let Some(parent) = path.parent() { let _ = fs::create_dir_all(parent); } - if let Ok(bytes) = serde_json::to_vec_pretty(all) { - let tmp = path.with_extension("tmp"); - if fs::write(&tmp, bytes).is_ok() { - let _ = fs::rename(&tmp, &path); - } + let Ok(bytes) = serde_json::to_vec_pretty(all) else { return }; + let tmp = path.with_extension("tmp"); + let mut options = fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let Ok(mut file) = options.open(&tmp) else { return }; + use std::io::Write; + if file.write_all(&bytes).is_ok() && file.flush().is_ok() { + drop(file); + let _ = fs::rename(&tmp, &path); + } else { + drop(file); + let _ = fs::remove_file(&tmp); } } diff --git a/windows/src-tauri/src/tray_badge.rs b/windows/src-tauri/src/tray_badge.rs index a372b858..5411d59f 100644 --- a/windows/src-tauri/src/tray_badge.rs +++ b/windows/src-tauri/src/tray_badge.rs @@ -80,6 +80,13 @@ const FONT_MAX_FRACTION: f32 = 0.95; const FONT_MIN_FRACTION: f32 = 0.5; const FONT_STEP_PX: f32 = 0.5; +/// Read and parsed once: the badge re-renders on every refresh and the font file does not +/// change under a running session. +fn font() -> Option<&'static fontdue::Font> { + static FONT: std::sync::OnceLock> = std::sync::OnceLock::new(); + FONT.get_or_init(load_font).as_ref() +} + fn load_font() -> Option { for path in FONT_CANDIDATES { if let Ok(bytes) = std::fs::read(path) { @@ -111,12 +118,12 @@ fn layout(font: &fontdue::Font, text: &str, px: f32) -> (Vec, f32, i32, } fn render_with_font(text: &str, size: u32, color: [u8; 3]) -> Option> { - let font = load_font()?; + let font = font()?; let limit = size as f32; let mut px = limit * FONT_MAX_FRACTION; let mut chosen = None; while px >= limit * FONT_MIN_FRACTION { - let (glyphs, width, top, bottom) = layout(&font, text, px); + let (glyphs, width, top, bottom) = layout(font, text, px); let height = (top - bottom) as f32; if width <= limit && height <= limit { chosen = Some((glyphs, width, top, bottom)); @@ -219,16 +226,15 @@ pub fn small_icon_size() -> u32 { /// with the taskbar, not the popover. #[cfg(target_os = "windows")] pub fn taskbar_is_dark() -> bool { - use std::os::windows::process::CommandExt; - const CREATE_NO_WINDOW: u32 = 0x08000000; - let output = std::process::Command::new("reg") + // Absolute `reg.exe` out of System32 -- this runs on every badge refresh, so a bare + // name here would be the single most reliably triggered planted-binary path. + let output = crate::cli::system_command("reg.exe") .args([ "query", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "/v", "SystemUsesLightTheme", ]) - .creation_flags(CREATE_NO_WINDOW) .output(); match output { Ok(out) => { diff --git a/windows/src/App.tsx b/windows/src/App.tsx index 4a4408f8..af923314 100644 --- a/windows/src/App.tsx +++ b/windows/src/App.tsx @@ -33,10 +33,14 @@ import { SettingsPanel, type ThemeChoice } from './components/SettingsPanel' const payloadCache = new PayloadCache() -/// Background cadence. Every tick refreshes today/all (tray tooltip, provider badges) and -/// the visible period/provider; entries younger than STALE_MS are left alone when the -/// popover is re-opened. -const REFRESH_INTERVAL_MS = 60_000 +/// Background cadence, mirroring mac/Sources/CodeBurnMenubar/RefreshCadence.swift: every +/// fetch is a full Node process, so the popover being closed has to cost less than it being +/// open. Visible, a tick refreshes today/all plus the selected period/provider with optimize +/// findings; hidden, a slower tick refreshes only today/all and skips optimize, since the +/// tray badge and tooltip are the only things anyone can see. Entries younger than STALE_MS +/// are left alone when the popover is re-opened. +const REFRESH_ACTIVE_MS = 60_000 +const REFRESH_IDLE_MS = 120_000 const STALE_MS = 60_000 type FetchOptions = { @@ -63,6 +67,8 @@ export function App() { const [theme, setTheme] = useState(() => currentTheme()) const [trayBadge, setTrayBadge] = useState(() => readSetting('trayBadge') !== 'off') const [showSettings, setShowSettings] = useState(false) + // The window starts hidden and is shown by a tray click, which emits `codeburn://shown`. + const [popoverVisible, setPopoverVisible] = useState(false) const [themeChoice, setThemeChoice] = useState(() => { const saved = readSetting('theme') return saved === 'dark' || saved === 'light' ? saved : 'system' @@ -88,10 +94,13 @@ export function App() { if (previous) json.optimize = previous.optimize } payloadCache.set(p, prov, json) - if (isSelected()) setPayload(json) + if (isSelected()) { + setPayload(json) + // "updated Xs ago" describes what the user is looking at, so only a fetch of the + // visible key may stamp it - a background today/all tick must not. + setLastUpdated(new Date()) + } if (p === 'today' && prov === 'all') setTodayPayload(json) - setLastUpdated(new Date()) - setCliStatus(prev => (prev && !(prev.found && prev.compatible) ? { ...prev, found: true, compatible: true, error: null } : prev)) } catch (err) { const message = err instanceof Error ? err.message : String(err) if (message.includes('CLI not found')) { @@ -114,17 +123,9 @@ export function App() { await fetchKey(p, prov, opts) }, [fetchKey]) - const probeCli = useCallback(async () => { - setCliChecking(true) - try { - setCliStatus(await invoke('cli_status')) - } catch { - // Leave the status unknown; the data views already tell the user if fetches fail. - } finally { - setCliChecking(false) - } - }, []) - + /// The single source of truth for the CLI gate. Nothing else writes a "compatible" + /// verdict: a payload that happens to parse does not prove the CLI is new enough, and a + /// probe from the settings panel must not be able to invent one either. const checkCli = useCallback(async () => { setCliChecking(true) try { @@ -140,33 +141,50 @@ export function App() { } }, [refreshAll]) + const cliReady = cliStatus !== null && cliStatus.found && cliStatus.compatible + + // Probe the gate before the first fetch: an old CLI emits a payload missing fields the + // popover reads, which used to blank the whole window instead of showing the setup screen. useEffect(() => { invoke('app_version').then(setVersion).catch(() => {}) - refreshAll({ includeOptimize: true, showOverlay: true }) - const id = setInterval(() => refreshAll({ includeOptimize: true, showOverlay: false }), REFRESH_INTERVAL_MS) + checkCli() + // Startup only; checkCli is re-run from the setup screen and settings on demand. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + useEffect(() => { + if (!cliReady) return + const tick = popoverVisible + ? () => refreshAll({ includeOptimize: true, showOverlay: false }) + : () => fetchKey('today', 'all', { includeOptimize: false, showOverlay: false }) + const id = setInterval(tick, popoverVisible ? REFRESH_ACTIVE_MS : REFRESH_IDLE_MS) return () => clearInterval(id) - }, [refreshAll]) + }, [cliReady, popoverVisible, refreshAll, fetchKey]) useEffect(() => { const cached = payloadCache.get(period, provider) setPayload(cached) + if (!cliReady) return if (!cached) { fetchKey(period, provider, { includeOptimize: true, showOverlay: true }) } else if (payloadCache.age(period, provider) > STALE_MS) { fetchKey(period, provider, { includeOptimize: true, showOverlay: false }) } - }, [period, provider, fetchKey]) + }, [period, provider, cliReady, fetchKey]) useEffect(() => { const unlistenRefresh = listen('codeburn://refresh', () => refreshAll({ includeOptimize: true, showOverlay: true })) const unlistenShown = listen('codeburn://shown', () => { + setPopoverVisible(true) const { period: p, provider: prov } = selection.current if (payloadCache.age(p, prov) > STALE_MS) refreshAll({ includeOptimize: true, showOverlay: false }) }) + const unlistenHidden = listen('codeburn://hidden', () => setPopoverVisible(false)) const unlistenTheme = listen('codeburn://toggle-theme', () => toggleTheme()) return () => { unlistenRefresh.then(fn => fn()) unlistenShown.then(fn => fn()) + unlistenHidden.then(fn => fn()) unlistenTheme.then(fn => fn()) } }, [refreshAll]) @@ -189,16 +207,18 @@ export function App() { return () => window.removeEventListener('keydown', onKey) }, []) - useEffect(() => { - if (!todayPayload) return - const text = `CodeBurn · ${formatCurrency(todayPayload.current.cost, currency)} today` - invoke('set_tray_tooltip', { text }).catch(() => {}) - }, [todayPayload, currency]) + const todayCost = todayPayload?.current?.cost ?? null useEffect(() => { - const text = trayBadge && todayPayload ? trayBadgeText(todayPayload.current.cost, currency) : null + if (todayCost === null) return + const text = `CodeBurn · ${formatCurrency(todayCost, currency)} today` + invoke('set_tray_tooltip', { text }).catch(() => {}) + }, [todayCost, currency]) + + useEffect(() => { + const text = trayBadge && todayCost !== null ? trayBadgeText(todayCost, currency) : null invoke('set_tray_badge', { text }).catch(err => setError(`Tray badge: ${String(err)}`)) - }, [todayPayload, currency, trayBadge]) + }, [todayCost, currency, trayBadge]) const chooseTheme = (choice: ThemeChoice) => { @@ -245,9 +265,13 @@ export function App() { const activeInsight = visibleModes.includes(insight) ? insight : 'trend' const cliBlocked = cliStatus !== null && (!cliStatus.found || !cliStatus.compatible) - const isFilteredEmpty = payload !== null && provider !== 'all' && payload.current.cost <= 0 && payload.current.calls === 0 + // The version gate above is what keeps these fields present; the optional reads are the + // backstop that turns a surprising payload into an empty state rather than a blank window. + const isFilteredEmpty = payload !== null && provider !== 'all' + && (payload.current?.cost ?? 0) <= 0 && (payload.current?.calls ?? 0) === 0 const neverAnyData = payload !== null && provider === 'all' - && payload.current.calls === 0 && payload.current.sessions === 0 && payload.history.daily.length === 0 + && (payload.current?.calls ?? 0) === 0 && (payload.current?.sessions ?? 0) === 0 + && (payload.history?.daily?.length ?? 0) === 0 const footnote = [version ? `CodeBurn v${version}` : 'CodeBurn', lastUpdated ? `updated ${relativePast(lastUpdated)}` : null] .filter(Boolean) @@ -280,7 +304,6 @@ export function App() { onTrayBadge={setTrayBadgePref} cliStatus={cliStatus} onCheckCli={checkCli} - onProbeCli={probeCli} cliChecking={cliChecking} onQuit={() => invoke('quit_app').catch(() => {})} /> @@ -302,12 +325,12 @@ export function App() { {activeInsight === 'plan' && ( )} - {activeInsight === 'trend' && } - {activeInsight === 'forecast' && } + {activeInsight === 'trend' && } + {activeInsight === 'forecast' && } {activeInsight === 'pulse' && payload && } {activeInsight === 'stats' && payload && } - {payload && ( + {payload?.current && ( <> void cliStatus: CliStatus | null onCheckCli: () => void - onProbeCli: () => void cliChecking: boolean onQuit: () => void } export function SettingsPanel({ onBack, version, currency, onCurrency, themeChoice, onThemeChoice, trayBadge, onTrayBadge, - cliStatus, onCheckCli, onProbeCli, cliChecking, onQuit, + cliStatus, onCheckCli, cliChecking, onQuit, }: Props) { const [loginItem, setLoginItem] = useState(null) const [loginError, setLoginError] = useState(null) + // No CLI probe here: App owns the gate and probes it on mount, so the panel only ever + // displays what that probe found. Its own probe could otherwise fail transiently and drop + // a working app onto the setup screen. useEffect(() => { invoke('launch_at_login').then(setLoginItem).catch(() => setLoginItem(false)) - if (!cliStatus) onProbeCli() - // Probe once when the panel opens; cliStatus arriving later must not re-trigger it. - // eslint-disable-next-line react-hooks/exhaustive-deps }, []) const toggleLogin = async () => { @@ -118,7 +118,7 @@ export function SettingsPanel({
About
- GitHub + diff --git a/windows/src/components/StarBanner.tsx b/windows/src/components/StarBanner.tsx index ca359deb..3b28676d 100644 --- a/windows/src/components/StarBanner.tsx +++ b/windows/src/components/StarBanner.tsx @@ -1,4 +1,5 @@ import { useState } from 'react' +import { openUrl } from '@tauri-apps/plugin-opener' import { readSetting, writeSetting } from '../lib/settings' import { StarIcon, XIcon } from './Icons' @@ -16,10 +17,10 @@ export function StarBanner() { return (
- +