diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 438c0d88..fc790f02 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -33,17 +33,30 @@ jobs: # Scoping (tests/ only, app/ excluded) lives in the package.json test # script since #948, so CI and a contributor's `npm test` can never drift. - name: Test suite (parallel) - run: npm test + run: npm test -- --reporter=default --reporter=json --outputFile.json=test-report.json + - name: Slowest tests + if: always() + run: node scripts/slowest-tests.mjs test-report.json # Single forked worker, so lock contention comes only from the child # processes the tests spawn deliberately. Serial because the suite is # parallelism-sensitive (fails under full worker pressure, passes # serially). After #904 the loser of a stale-lock contest may be # timed-out or completed-by-other; this step gates CI. - # Step-level timeout so a stalled lock suite fails this job instead of - # eating the 15-minute budget and cancelling a green parallel suite. + # This step takes 12-18s on every Node version (64-job sample, no upward + # trend). Every failure so far has been a hang that printed nothing at + # all - not one line of vitest output after its RUN banner - which the + # 5-minute step limit then killed silently. Cap each attempt at 90s (5x + # the worst passing run) so the log shows a bounded failure, and retry + # once: a hang a change actually introduced reproduces on the second + # attempt and still fails the job, while the startup hang that has never + # once produced a wrong result costs 90s instead of a whole re-run. The + # warning keeps every occurrence visible rather than silently green. - name: Cache-lock suite (serial) - timeout-minutes: 5 - run: npm run test:locks + timeout-minutes: 4 + run: | + timeout 90 npm run test:locks && exit 0 + echo "::warning::cache-lock suite did not finish in 90s (normal 12-18s) - retrying once" + timeout 90 npm run test:locks # The CLI is shipped to macOS and Windows users, and the Windows tray app depends on it # there. One run per platform on the newest Node 22, without the serial lock suite, which @@ -67,7 +80,10 @@ jobs: - name: Typecheck run: npx tsc --noEmit - name: Test suite - run: npm test -- --maxWorkers=3 + run: npm test -- --maxWorkers=3 --reporter=default --reporter=json --outputFile.json=test-report.json + - name: Slowest tests + if: always() + run: node scripts/slowest-tests.mjs test-report.json desktop: runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index e94fcd98..1111f202 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,15 @@ ## Unreleased +### Changed +- **The resident `codeburn serve` process gives its memory back once the cold start is over.** On a first run the desktop's serve child parses the whole corpus to seal the daily summaries, and then kept every byte of what it read: an unscoped session cache the load memo served to every later request whatever range it asked for, and the lifetime parse trees, with nothing to retire them once the polls stopped. On a 170 MB shard set that was 2,198 MB resident, unchanged across ten minutes of idle, against 364 MB of live heap. The cold start now releases what it can re-read from disk the moment its summaries are written — the poll that follows loads only the month shards its own range covers (141,154 cached calls resident, down to 90,094; five lifetime parse trees, down to one day's) — and then collects, because V8 hands the pages back only on a later collection and returns none of them on its own. Steady resident after a cold start falls from 2,198 MB to 700 MB, and a warm start, which has no fill to release after but the same opening burst behind it, from 900 MB to 781 MB. Nothing is dropped that the cache is the only record of: a held shard-publish window is published before the release, not discarded, and a durable provider's section never waits in that window at all. Answers are unchanged — every period is leaf-identical to before, cold and warm — and a poll costs the same; the whole cost is a one-off 1.6 CPU-seconds of collection after a cold start. +- **The resident `codeburn serve` process stops re-reading the whole corpus, and re-writing a whole month of cache, on every poll.** While the desktop app is open its serve child answers a status poll every 30-60 seconds, and as long as any agent is writing a transcript each of those polls re-walked every project directory and re-stat'd every session file (17,611 stats and 2,460 readdirs on a 4,530-transcript corpus) and then republished the current month's cache shard — 49 MB rewritten, and read back on the next poll, because one file gained a line. Both are now driven by the root watchers that already exist. The discovery sweep reuses the directory listing and the dev/ino/mtime/size of any path no filesystem event has named, re-reading only the paths the watcher named and the directories those sit in. Nothing derived is reused — every file is still reconciled against its cached fingerprint by the same code as before — and the sweep falls back to reading everything whenever the watcher cannot vouch for the answer: no watcher at all (every one-shot CLI run), a watcher that failed to arm or errored, an event that arrived unscoped or overflowed the tracked-path bound, a path outside every armed root, a WSL/UNC path, a SQLite-backed or virtual-suffix source whose fingerprint is not the path an event would name, the first parse after start, anything remembered longer than four and a half minutes, and a wall-clock jump the monotonic clock did not see. Shard publication is coalesced to at most once every ninety seconds in the resident process — longer than the slowest poll, or the window would expire before every poll and coalesce nothing — and is always flushed when the app closes its stdin. One-shot CLI runs keep writing immediately. A publish the window swallows writes nothing at all, so the on-disk cache is never newer-looking than its content: the cost of losing a window is that the next start re-parses those appends, and a held publish is dropped rather than written if another process has published since. Measured on a 4,530-transcript corpus with one session appended every three seconds, polling as the desktop does: 0.71 to 0.33 CPU-seconds per poll at a 30-second cadence, 17,611 to 11,592 stats, 2,460 to 324 readdirs, three shard publishes down to one. A quiet corpus was already free and still is. Time-to-reflect is unchanged — 1.23 s before, 1.19 s after — including for a new project directory, a new session file, a deleted file, a file replaced by rename, an append landing mid-poll, a change burst past the watcher's tracking bound, and a corpus changed while the watcher is unhealthy. +- **Vercel AI Gateway spend is no longer added to your totals, because it was being counted twice.** The gateway's reporting API returns one row per day per model — a cost, a token count and a `request_count`, with no request ids, no timestamps and no attribution. The requests behind those rows came from the local tools you pointed at the gateway (Claude Code via `ANTHROPIC_BASE_URL`, Codex, OpenCode, Cline/Roo/Kilo, Cursor), and every one of those tools writes its own session file that CodeBurn already parses. Nothing in a gateway row can be matched against those sessions, so there is no way to reconcile the two — which meant every headline, model row, daily row and history point carried the same spend twice for anyone with a gateway credential. **If you use the gateway, your headline totals will go down.** The gateway is still shown, always: its own provider row carries the full amount (marked "not in total" in the desktop app), the JSON report gains `overview.excludedGatewayCost` when something is excluded, and the terminal report and dashboard print a one-line footnote. `--provider vercel-gateway` is unaffected and reports the full amount. The rule lives in one place — the parse that every surface reads — so `models`, `sessions`, `export`, `compare`, `compare-periods`, `spend`, `yield`, `audit`, `budget`, the Ink dashboard's panels and the Teams sync push all agree with the headline instead of each report deciding for itself, and no detail panel (By tool, Top models, Top projects, By activity, the JSON `projects[]`) lists spend the total beside it is not counting. The gateway still appears once, clearly labelled: its own `By tool` row with no share, its own provider row in the payload and in `--format json` (`overview.excludedProviders`), and a one-line footnote under any total that left it out. The daily cache and the session cache are the deliberate exception: they keep storing the gateway slice, because a past day's aggregate row can never be fetched again. To count it in totals anyway, run `codeburn gateway-totals include` (`exclude` to undo, no argument to see the current setting). The exclusion is read-side only — the daily cache still seals the gateway slice on every day — so turning it on applies retroactively to sealed days without re-fetching anything, which matters because a gateway row cannot be re-derived from disk. Also fixed alongside it: `request_count` was parsed and then ignored, so a day+model row with 300 requests counted as one call; the gateway's call count now reflects the real figure on every surface. +- **A Hermes mid-session price change lands on the day it is observed, and sealed days are never rewritten.** This was already the behaviour; it is now the stated rule, documented where the observation is stamped (`src/providers/hermes.ts`). + ### Fixed +- **OpenClaw and Pi lose the cost they reported the same way Warp did, and it is fixed the same way.** Both write what a message actually cost into `usage.cost.total`, and neither was on the reported-cost pass-through, so every read — cold as well as warm — replaced it with a token estimate. On fixtures that is $0.011325 reported against $0.056495 billed for OpenClaw and $0.012908 against $0.409660 for Pi. The rule is now per call rather than per provider: a cost that came from the tool's own record is carried through the cache and served verbatim, while a call whose reported cost is absent or zero (Pi writes `total: 0` for xai-oauth, OpenClaw omits the field) keeps storing no cost at all, so it is still re-priced from its tokens and a later pricing update reaches it. Both providers' parse versions move, so already-cached calls re-derive once and the daily cache rebuilds the affected days from the transcripts, which are still on disk. `omp`, which shares Pi's parser, is unchanged. The growing chain of provider names behind this decision is now one named `REPORTED_COST_PROVIDERS` set with the same membership. +- **Warp's own billing figures now survive the cache instead of being replaced by a token estimate on every read.** 0.9.25 taught the Warp parser to read what Warp actually charged a conversation (`total_provider_cost_in_cents`, then the `total_charged_usage` cents, then `credits_spent` at the published credit rate), but `warp` was missing from the reported-cost pass-through in the session cache — and every non-Claude/Codex provider reaches a report only through that cache, so the derived dollars were dropped on the cold run too, not just on a warm one. Every Warp read, in the CLI, the menu bar and the desktop app alike, was re-pricing the conversation from the token floor against the aliased LiteLLM model. On a three-conversation fixture that is $0.15 reported against $1.22 actually billed. A billing-derived cost is now carried through the cache and frozen at the billed amount; a conversation with no billing record keeps storing no cost at all, so it is still re-priced from its tokens and a later pricing update reaches it. Warp's parse version and the daily-cache version are bumped, so already-cached calls re-derive once and finalized days rebuild from Warp's durable sqlite — call counts do not move, so no day can be double counted or lowered by the rebuild. - **Bundled pricing is refreshed, and the refresh can no longer drop a model's pricing or re-price a model it still covers.** 5,942 primary entries against the 0.9.24 bundle (1,215 added, 182 repriced by upstream's own data; among the additions, the Grok Build family makes `grok-4.6-build` priceable so the Grok parser's authoritative-model rule now prefers the real modelUsage id), with the fallback moving from 203 to 212 entries. Three bundler rules make that true. Coverage carry is exact-key only: the runtime resolver (`getModelCosts`) looks the queried id up verbatim, peels segments and strips variant suffixes, but never adds a vendor prefix — so a `~x-ai/grok-latest` primary does not answer a bare `grok-latest` query, and the first version of this carry, which also accepted a vendor-prefixed form, dropped exactly that way: 96 previously-priced fallback ids resolved to null while their model kept only a prefixed key. The completeness guard in the prefixed pass is strictly slot-filling: a richer upstream row may fill cache-write/cache-read slots an entry lacks, but only when its input and output rates are identical to the entry already present (every filled slot must also survive verbatim) — completeness alone was swapping in a different row's rates (grok-3 $3/$15 became $1.25/$2.50, mistral-large-latest $8/$24 became $0.50/$1.50; 43 input/output and 34 cache rates moved that way), which a refresh has no authority to do, and a sparser alias still cannot displace the publisher's entry (a `nebius/MiniMaxAI/MiniMax-M3` row without cache-read rates can never replace the MiniMax entry that carries them). And what a refresh would otherwise drop stays priced: the previous fallback's entries and the previous primary rows the new upstream data dropped or renamed (this cycle, twelve ids — the gpt-image-2 family, the Bedrock marengo embeds, the friendliai llama-3.1 rows) carry forward verbatim into the fallback tier. Verified by resolving every id from either bundle through the real resolver: nothing that priced on 0.9.24 prices as null now, and no rate changed except where upstream repriced the row itself. ### Fixed (desktop) @@ -10,6 +18,8 @@ - **Packaging no longer aborts on a checkout whose path contains a UUID.** `app/scripts/stage-cli.mjs` resolved the CLI's production dependency closure by matching each `npm ls --parseable` line against the checkout's absolute `/node_modules/` prefix, and npm 11 and later redact UUID-shaped path segments to `***` in that output — so on CI runners and scratch worktrees under a UUID directory the match found nothing and packaging died with the misleading "is the root npm installed?". The top-level package name is now read by position (after the N-th `/node_modules` occurrence, N counted off the real root path, which the redaction cannot move) instead of by absolute-prefix match, so redacted, Windows-separated and nested-checkout shapes all resolve; a missing `npm_execpath` also fails with its own message instead of degrading into the empty-closure one. Fixes #1466. ### Fixed +- **`codeburn export -f json` into a folder writes the file inside it.** The desktop app passes the folder you picked, and the JSON writer appended `.json` to it, so choosing `~/Exports` produced `~/Exports.json` beside the folder rather than a file in it. An existing folder now gets a dated file inside it, `codeburn-export-YYYY-MM-DD.json`, matching the dated subfolder a CSV export already nests there; a path written with a trailing separator says folder too, and is created if it is not there yet; `-o report` still writes `report.json`. +- **`codeburn menubar` replaces the copy you already have instead of adding a second one.** The installer only ever looked at `~/Applications`, so a `CodeBurnMenubar.app` in `/Applications` was left where it was and a second bundle, with its own login item, appeared alongside it. The install now goes to whichever copy is already there, in the same order the desktop app's Menu bar card looks. A folder it cannot write to is never escalated into: the install falls back to `~/Applications`, the old copy is asked to quit, and it is named on stdout for you to move to the Trash. - **`codeburn yield` stops calling work abandoned that shipped through a merge the session's window missed.** A session was labeled abandoned when no commit credited to it landed on main, but commits are credited by timestamp window, so a feature branch merged after the session ended — or merged as a GitHub squash, which lands the work under a brand-new SHA the window can never see — left fully shipped sessions reading as dead. When the session logs record the git branch it ran on (Claude Code captures this per turn; most providers do not), yield now rescues a session whose branch demonstrably shipped through a squash merge: the branch carries commits of its own, its tip's tree hash matches a commit on main (the squashed tree is byte-identical to the branch tip, with the tip different from the branch's base so an untouched or self-reverted branch cannot match), and at least one of those commits was made inside the session's own window — the session contributed the work rather than merely having run on the branch. Every matching ref is examined (a stale local copy cannot hide a merged remote-tracking one). Abandoned and ambiguous sessions rescue to productive; reverted keeps its verdict, which already describes shipped-then-undone work. The rescue is confined to computeYield: sync attribution records keep the pure timestamp-window methodology, and the JSON methodology field is unchanged for compat. Fixes #1442. ### Added @@ -26,7 +36,7 @@ ### Added (macOS) - **The menubar acts on a Capacity Dock change made from outside it, and can be asked to quit or uninstall itself.** The desktop app's new Menu bar card turns the rail on and off by writing the menubar's own preference from another process. `UserDefaults.didChangeNotification` never carries a write made outside the process, so the rail sat where it was until the next launch; the dock now watches its one key with KVO, which cfprefsd does deliver across processes, and the rail appears or goes within a second. The app also answers one new key with a quit, and with an uninstall that first unregisters its login item — `SMAppService` speaks only for the app that calls it, so no other process can drop that registration on its behalf. Both clear the key before acting, so a command that outlives the process cannot quit the next launch. Nothing else reads the key, and a build that does not know it is simply signalled instead. - **Clicking a live session in the Capacity Dock card raises the terminal it is running in.** The row's process is found from Claude Code's own `~/.claude/sessions/.json` or, for Kimi Code, from the one `kimi` working in the session's directory, and the process tree is walked up to the application that owns it: Terminal.app and iTerm2 get the exact tab selected by tty, every other terminal is brought to the front. A row whose process cannot be found stays inert, with no pointer change and no tooltip. -- **Launching the menubar app replaces the copy already running instead of stacking a second Capacity Dock on the screen edge.** At launch it terminates only *strictly older* instances of its own bundle identifier, so two simultaneous launches cannot quit each other and leave none, and an older copy that ignores the polite quit is forced out a few seconds later. +- **Launching the menubar app replaces the copy already running instead of stacking a second Capacity Dock on the screen edge.** At launch it terminates the other instances of its own bundle identifier, and a copy that ignores the polite quit is forced out a few seconds later. - **The menubar tells you when a quota window crosses 80% and again when it hits its limit.** Every connected provider's windows — the same list the menu-bar flame and the popover warning row are built from — are checked on the quota refresh that already runs, with no new polling: crossing 80% posts `Claude · Weekly at 80%`, reaching the limit posts `Claude · Weekly limit reached`. Each fires once per window per cycle, a window that hits its limit without ever having been seen at 80% posts only the limit notice, and the cycle's reset instant is part of the identity, so the next cycle re-arms both while an absent or failed fetch keeps what was already announced. The fired set is persisted, so a relaunch does not repeat a crossing. Notification authorization is requested on the first real crossing and never at launch. Settings → Notifications gains a switch, on by default. - **The macOS menubar app speaks Simplified Chinese, and follows your system language to decide.** Every user-facing string in the popover, the Capacity Dock, the status-item menu, the update alerts and all of Settings now resolves through a `Localizable.strings` catalog shipped for `en` and `zh-Hans` with no third-party library: 628 keys, whose key *is* the English copy, so an untranslated string degrades to correct English rather than a visible identifier. AppKit picks the table from the user's preferred languages; Settings > General > Language overrides it for CodeBurn alone by writing `AppleLanguages` into the app's own preferences domain, which is the same key `CFBundleLocalizations` makes System Settings > Language & Region > Applications write, so the two surfaces are one setting rather than two. Enum raw values that double as persistence or cache keys (`Period`, `MenubarScope`, `InsightMode`, `AccentPreset`, `ProviderFilter`) keep their raw value and gained a separate display label, so nothing a user has saved changes meaning. Three display-only date formatters that were pinned to `en_US_POSIX` with fixed patterns now follow the locale, and the calendar popover's weekday row comes from the locale's own short symbols clipped to two units, so a Chinese UI reads `2026年9月` and `周一 周二` while English keeps `Mo Tu We`. That locale move is the one place English output changes: `EEE MMM d` reads `Sat, Sep 12` in en_US and `Sat 12 Sep` in en_GB, and `MMM d` reads `12 Sep` in en_GB. Provider, model and plan names, units, currency codes, shell commands and anything the `codeburn` CLI itself produces stay verbatim in every locale. Adding a language is now one more `.lproj`; a test fails the build if the two tables disagree on keys, leave a value blank, or disagree on format specifiers, and a second test reads `mac/Sources` itself and fails when a user-facing literal never reaches the catalog at all — the drift a catalog-versus-catalog diff cannot see, because both tables stay in perfect agreement while a bare `Text("…")` ships English to a zh-Hans user. This covers the menubar half of #1219 only, not the CLI output or the web dashboard. (#1219) - **The menubar tells you when a vendor resets your quota early.** Vendors sometimes reset a usage window ahead of schedule as a goodwill gesture; CodeBurn showed the new percentage but never said it had happened, so the free capacity went unused. Two signals now catch it on the refresh lifecycle that already runs, with no new polling: a reset time that jumps to a new cycle while the stored one still had time to run, and usage emptying (a fall of at least 40 points landing at or under 10%) while the advertised reset time stands still. A system notification through the existing notifier names the provider, the window and the lead, worded for the signal that saw it ("Claude's weekly limit reset 18h early. You're back to 100%." when the cycle rolled over, "Claude cleared your weekly usage 18h before its reset. You're back to 100%." when the counter emptied but the reset time held). One goodwill reset is one notification per provider however many windows it empties, and a reset already announced is never announced again — after a relaunch, or when the vendor briefly serves the old cycle back. It stays silent on a normal scheduled reset, a plan change, clock or timestamp skew, a window appearing or disappearing between fetches, a window's first observation, a reconnect after a terminal failure or a fresh bootstrap, and a window whose length the adapter does not validate; a missing or malformed stored reading is no opinion rather than an event. Settings → General → Notifications turns the notification off, default on. Claude is the provider wired up today, because it is the one whose quota readings are persisted. (#725) @@ -77,6 +87,7 @@ - **Finding live Kimi Code sessions no longer walks the whole session store.** The scan recursed through `/sessions` looking for `wire.jsonl`, so every blob and file-history entry an agent had ever written was listed to find the wire files among them — about 18,000 entries for 2,000 wires, and roughly 250ms on every payload build. It now walks only the levels the layout actually uses (work dir, session, agent) and stats `wire.jsonl` there, which is about 23ms on the same store. A decoy `wire.jsonl` buried in `blobs/` or `file-history/` was also being reported as a session of its own, and no longer is; a missing store is still silent. ### Fixed (menubar) +- **Two copies starting at once can no longer both quit and leave no menu bar at all.** Which copy stays is decided by the start time the kernel reports for each process, so both copies rank each other off the same number instead of each reasoning from what it can see on its own; the newest start wins, and a process id only breaks an exact tie. A copy whose start time the kernel will not report is left out of the comparison altogether — neither retired nor able to retire anything — so the worst case is two menu bars, which you can see and close, and never none. - **The pointing-hand cursor no longer sticks after a session row disappears under it.** The Capacity Dock's click-to-raise rows pushed the cursor on hover and popped it on exit, but a row that vanishes while hovered — the session leaves the ten-minute window, or the dock hides — never fires an exit, so the pushed cursor stayed on system-wide until something else replaced it. The row now pops what it pushed on the way out. Clicking such a row could also raise the wrong terminal: Claude Code writes a fresh `~/.claude/sessions/.json` on every resume and never removes the old one, so several files name the same session and the first one the directory happened to list was taken. The newest is now taken instead, and if its pid fails the recycled-pid guard the row stays inert rather than falling back to a stale file. - **The localization catalog test can now see argument-order drift, and every multi-argument key spells its slots positionally.** The catalog comparison matched specifier lists, so a key whose placeholders are all `%@` passed even when the Chinese value bound the arguments into the wrong slots — exactly the drift that shipped in three early-reset keys and was only caught by rendering real data bilingually. All 42 multi-argument keys in both tables now use positional specifiers (`%1$@`, `%2$lld`, …), the parity check compares slot to verb so Chinese word order stays free while each slot keeps its type, and a new test fails on any multi-argument key that is not positional. The source scanner also stopped being blind to three shapes that put copy on screen looking like machinery: a ternary (`Text(flag ? "A" : "B")`), a concatenation (`.help(prefix + " suffix")`), and a literal bound to a `let` and passed by name — `Text(verbatim:)` stays the explicit opt-out, and the four provider-name fallbacks the new rules surfaced in HeatmapSection now route through the catalog as verbatim entries. (#1331) - **A quota window that resets now refreshes now.** The menubar's 30s tick compared the reset times it already holds — Claude's 5-hour and weekly windows, Codex's two windows, every Capacity Dock provider's — against the previous tick, and forces a refresh for the provider whose window just rolled over instead of leaving the pre-reset percentage on screen for up to five minutes. Each reset instant fires once; everything else keeps the existing cadence. @@ -88,12 +99,14 @@ - **The desktop shell stops re-rendering the whole tree once a second.** AppMain owned a wall-clock `setInterval(1000)` that existed only so the footer could print "refreshed Ns ago", but every tick re-rendered the sidebar, the hero, the daily chart, the heatmap and every table 60 times a minute whether or not any data had changed. The per-second tick now lives in a leaf `RefreshedAt` component that owns just that label, and the shell itself re-renders only on real state changes plus a 15-second day check that fires exactly when the local calendar rolls over — that rollover matters because the overview memo keys bake in a today/month boundary, so midnight must produce one re-render to keep "Today" honest. Renderer render-count regressions are pinned by a churn test that fails if the shell re-renders on the per-second tick or on same-day clock checks. ### Fixed (desktop) +- **Changing the menu bar app's language no longer re-asks for permission to access data from other apps.** macOS holds whoever asked LaunchServices to open an app responsible for it, so a menu bar quit and reopened by the desktop app was a new process under a new responsible process and the prompt came back on every language change. The menu bar is asked to restart itself instead, and the desktop app opens it only if that restart does not bring it back. +- **The export toast names the file or folder that was actually written.** Both formats put the export inside the folder you pick, so the toast reported a path with nothing at it; it now reads the path the CLI prints. - **The renderer ships half the splash video weight.** The cold-start splash video is re-encoded at VP9 CRF 30 (SSIM 0.994 against the source), taking `app/renderer/assets/splash-loader.webm` from 2,582,836 bytes to 1,294,904 bytes — about half. ## 0.9.24 - 2026-09-04 ### Added -- **The CLI now computes the anonymous usage aggregate the desktop app and the Windows tray send, so both report the identical shape.** `codeburn status --format menubar-json` gains a `telemetrySnapshot` block (schema 2) built by `src/telemetry-snapshot.ts` from the payload and its own turn-level reports. Its headline signal is the model x task cross: up to 8 models, each with a cost bucket, a turn bucket, a one-shot rate and up to 6 task categories with their share of that model's turns, alongside up to 12 task categories with their top models, providers, MCP servers, skills, tools, a session count and median-length bucket, and cache-hit and retry-tax shares. Every magnitude is a bucket label, never an exact dollar amount, count or duration, and every name is a model or configuration identifier: nothing in the block is derived from a working directory, project name, branch name, file path or message text. The desktop app sends the block verbatim as the once-daily `usage_snapshot` event when the CLI provides it and falls back to its own renderer-side builder for an older CLI, and it adds five name-only interaction events (`optimize_apply`, `plan_set`, `export`, `compare_view`, `settings_change`). Telemetry remains consent-gated behind the onboarding screen, off by default in the EU/EEA/UK/CH, and switchable at any time in Settings > Privacy & data; README documents exactly what each event carries. `STATUS_SNAPSHOT_VERSION` moves to 4 so persisted status snapshots re-derive with the new field. +- **The CLI now computes the anonymous usage aggregate the desktop app and the Windows tray send, so both report the identical shape.** `codeburn status --format menubar-json` gains a `telemetrySnapshot` block (schema 2) built by `src/telemetry-snapshot.ts` from the payload and its own turn-level reports. Its headline signal is the model x task cross: up to 8 models, each with a cost bucket, a turn bucket, a one-shot rate and up to 6 task categories with their share of that model's turns, alongside up to 12 task categories with their top models, providers, MCP servers, skills, tools, a session count and median-length bucket, and cache-hit and retry-tax shares. Every magnitude is a bucket label, never an exact dollar amount, count or duration, and every name is a model or configuration identifier: nothing in the block is derived from a working directory, project name, branch name, file path or message text. The desktop app sends the block verbatim as the once-daily `usage_snapshot` event when the CLI provides it and falls back to its own renderer-side builder for an older CLI, and it adds five name-only interaction events (`optimize_apply`, `plan_set`, `export`, `compare_view`, `settings_change`). Telemetry is off by default in the EU/EEA/UK/CH and when the region is unknown, on by default elsewhere (the first-run consent screen is not shown in this version; onboarding completes with that regional default), and switchable at any time in Settings > Privacy & data; README documents exactly what each event carries. `STATUS_SNAPSHOT_VERSION` moves to 4 so persisted status snapshots re-derive with the new field. - **Bundled pricing is refreshed for this release.** The primary LiteLLM snapshot moves from 4669 to 4739 models: 71 added, 1 removed (`azure_ai/deepseek-v4-flash-0731`, re-added under LiteLLM's new casing) and 18 repriced. The fallback table moves from 200 to 203 rows: 4 added (`claude-fable-5.1:batch`, `gemini-3.8-flash:batch`, `glm-flash-latest`), 1 removed and 4 repriced. Among models CodeBurn users actually run, `kimi-k2.5`, `kimi-k2.6` and their Azure rows plus `azure_ai/deepseek-v4-flash` and `azure_ai/deepseek-v4-pro` gain a cache-write price; `deepseek-v4-flash-0731` moves to $0.20 input and $0.40 output per million; `mistral-medium`, `magistral-medium-latest` and `magistral-small-latest` are repriced with a cache-write rate added; `Qwen/Qwen3.8-2.4T-A95B` drops to $2.00 input and $6.00 output per million with its cache-write rate halved; and `gpt-realtime-2` output rises from $16 to $24 per million. New rows of note are `gemini-3.8-flash`, `grok-build-latest`, `gpt-6-astra`, `glm-5p3-flash`, `azure_ai/kimi-k2.7-code` and the us-gov Bedrock Claude Opus 4.8 and Sonnet 5 rows. (#1254) - **`codeburn quota` prints live capacity for every coding tool you are signed in to on this machine.** The new command lists each provider's quota windows as a table, or as machine-readable output with `--format json`. Ten adapters ship with it: Antigravity, Claude, ClinePass, Codex, Copilot, Cursor, Gemini, Grok, Kimi and Z.ai. It landed together with the Windows Capacity Dock, which is its first consumer. (#1228) - **A provider that records tokens but no dollar cost stays visible in the agent tabs.** The tabs filtered strictly on `cost > 0`, so Hermes on a flat subscription, free-tier models and any unpriced model vanished from the strip even though their usage existed. The menubar payload now carries a per-provider activity signal and the tab strip keys visibility off that instead: a provider with real usage stays listed at $0 recorded cost, while a provider merely discovered on disk stays hidden. The same rule is applied across the macOS menubar, the Electron renderer and the Windows payload, and an older payload without the signal keeps the previous detected-provider behaviour. (#1214) Thanks @MiguelMachado-dev. diff --git a/README.md b/README.md index 81679231..5235ddfb 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,8 @@ Get CodeBurn from the Microsoft Store Download for Linux (.deb) Download for Linux (.rpm) - Download for Linux (AppImage) + Download for Linux (AppImage)
+ 🍎 macOS builds are signed with a Developer ID and notarized by Apple — no security warning on open. Web
@@ -788,7 +789,7 @@ These are starting points, not verdicts. A 60% cache hit on a single experimenta | **IBM Bob** | `User/globalStorage/ibm.bob-code/tasks//` (GA `IBM Bob` and preview `Bob-IDE` app folders) | Reads `ui_messages.json` for API request token/cost records and `api_conversation_history.json` for the selected model. | | **Kimi Code CLI** | `$KIMI_SHARE_DIR/sessions///` or `~/.kimi/sessions///` | Reads `wire.jsonl` `StatusUpdate.token_usage` records, mapping `input_other`, `input_cache_read`, `input_cache_creation`, and `output` into the standard token columns; includes subagents under each session's `subagents/` folder. | | **LingTai TUI** | `~/.lingtai//logs/token_ledger.jsonl` plus project homes from `~/.lingtai-tui/registry.jsonl` (`/.lingtai//logs/token_ledger.jsonl`); honors `LINGTAI_HOME` / `LINGTAI_TUI_HOME` | Reads LingTai's append-only token ledger, mapping `input - cached` to fresh input, `cached` to cache reads, `output` to output, and `thinking` to reasoning. Nested daemon ledgers are skipped because parent ledgers already mirror daemon usage with `source`/`run_id` tags. | -| **Vercel AI Gateway** | [Vercel AI Gateway reporting API](https://vercel.com/docs/ai-gateway/capabilities/custom-reporting) (cloud, not local logs) | Set `AI_GATEWAY_API_KEY` or `VERCEL_OIDC_TOKEN` (from `vercel env pull` / `vercel dev`); requires a Vercel plan with Custom Reporting. Without credentials, it's skipped silently in the combined dashboard. | +| **Vercel AI Gateway** | [Vercel AI Gateway reporting API](https://vercel.com/docs/ai-gateway/capabilities/custom-reporting) (cloud, not local logs) | Set `AI_GATEWAY_API_KEY` or `VERCEL_OIDC_TOKEN` (from `vercel env pull` / `vercel dev`); requires a Vercel plan with Custom Reporting. Without credentials, it's skipped silently in the combined dashboard. Rows are **daily aggregates per model** with no request identity, so they may duplicate spend the local tools you pointed at the gateway already report — gateway spend is shown as its own row but **excluded from totals by default**. Include it with `codeburn gateway-totals include`. | CodeBurn deduplicates messages (by API message ID for Claude, by cumulative token cross-check for Codex, by conversation/timestamp for Cursor, by session ID for Gemini, by session+message ID for OpenCode, by responseId for Pi/OMP, by chat folder + message ID for Codebuff, by session+message ID for Kimi), filters by date range per entry, and classifies each turn. diff --git a/RELEASING.md b/RELEASING.md index 1f218ed6..22d4e263 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -149,7 +149,7 @@ The `.github/workflows/release-menubar.yml` workflow automatically detects the ` 1. Checks out the repo 2. Runs `mac/Scripts/package-app.sh v0.9.8` -3. Signs the app bundle (ad-hoc signing) +3. Signs the app bundle with the Developer ID Application certificate, notarizes it with Apple, and staples the ticket 4. Creates a zip file: `CodeBurnMenubar-v0.9.8.zip` 5. Computes a SHA-256 checksum: `CodeBurnMenubar-v0.9.8.zip.sha256` 6. Uploads both to a GitHub Release named "Menubar v0.9.8" diff --git a/app/DISTRIBUTION.md b/app/DISTRIBUTION.md index e213e432..5adfe6e6 100644 --- a/app/DISTRIBUTION.md +++ b/app/DISTRIBUTION.md @@ -1,9 +1,10 @@ # Distributing CodeBurn Desktop This document describes how to produce distributable macOS, Windows, and Linux -builds of the Electron desktop app. The macOS build is ad-hoc-signed and -**not notarized** (no paid Apple Developer account); the Windows and Linux -builds are **unsigned**. Windows NSIS packages are built and checked by the +builds of the Electron desktop app. Release macOS builds are signed with a +Developer ID Application certificate and notarized by Apple (see "macOS code +signing and notarization" below); the Windows and Linux builds are +**unsigned**. Windows NSIS packages are built and checked by the `Build Windows installer` GitHub Actions workflow; the other desktop packages are still produced by hand. All three targets are produced by `electron-builder`. @@ -272,17 +273,23 @@ separate `electron-builder.yml`): - `afterPack: "./scripts/after-pack.cjs"` — copies the staged CLI bundle (`app/build/cli`) into `Contents/Resources/cli` after packaging and before signing. -- `mac.identity: "-"` — forces ad-hoc signing. **`identity: null` does NOT - ad-hoc sign — it skips signing entirely**, which produces a bundle with a - broken/absent seal (`codesign --verify --deep --strict` fails with +- `mac.identity: "-"` — forces ad-hoc signing by default. **`identity: null` + does NOT ad-hoc sign — it skips signing entirely**, which produces a bundle + with a broken/absent seal (`codesign --verify --deep --strict` fails with `code has no resources but signature indicates they must be present`, and Apple Silicon refuses to run it at all). `"-"` is the same ad-hoc identity - `mac/Scripts/package-app.sh` uses for the menubar app's local/CI builds. -- `mac.hardenedRuntime: false` — hardened runtime is for notarized builds; - leaving it on for an ad-hoc signature with no entitlements can prevent the - app from launching. + `mac/Scripts/package-app.sh` falls back to for the menubar app's local/CI + builds. This is the local/dev default; signed release builds pass the real + Developer ID identity as a CLI override instead of changing this file (see + "macOS code signing and notarization" below) — worth baking into `build.mac` + directly so a release can't accidentally ship ad-hoc. +- `mac.hardenedRuntime: false` — matches the ad-hoc default above (hardened + runtime needs a Developer ID signature). Signed release builds turn this on + via the same CLI override. - `mac.gatekeeperAssess: false` — skips electron-builder's post-sign - `spctl` check, which would always fail for an unnotarized app. + `spctl` check, which always fails for an ad-hoc/unnotarized build. A signed, + notarized release build passes Gatekeeper's real check regardless of this + setting. - `icon: build/icon.png` — a pre-existing 1024x1024 PNG at `app/build/icon.png`. No `.icns` exists in the repo; electron-builder generates one from the PNG at build time. This is the same source PNG @@ -467,10 +474,14 @@ existing `desktop-v` tag and require the verification job to pass. ```sh codesign -dv --verbose=2 app/release/mac-arm64/CodeBurn.app codesign --verify --deep --strict app/release/mac-arm64/CodeBurn.app +spctl --assess --type execute --verbose app/release/mac-arm64/CodeBurn.app ``` -Expect `Signature=adhoc`, a real `Identifier=org.agentseal.codeburn-desktop`, -and `Sealed Resources` present. The deep-verify command should exit 0. +A local ad-hoc build shows `Signature=adhoc`; a signed release build shows +`Authority=Developer ID Application: Resham Joshi (XRVP7P7F9M)` and `spctl` +reports `source=Notarized Developer ID` once the notarization ticket is +stapled. Either way expect a real `Identifier=org.agentseal.codeburn-desktop` +and `Sealed Resources` present, and the deep-verify command should exit 0. To smoke-test that the packaged renderer actually loads (the classic failure is a white screen from a wrong `loadFile` path once assets are behind @@ -488,73 +499,92 @@ processes and keeps running with no stderr output. `main.ts`'s prints to that same stderr if the packaged `loadFile(path.join(__dirname, '..', 'renderer', 'index.html'))` path is ever wrong. -## The Gatekeeper story (no paid Apple Developer account) +## macOS code signing and notarization -Ad-hoc signing satisfies the *kernel's* code-signing requirement (Apple -Silicon refuses to execute anything with no signature at all), but it is not -a Developer ID signature and the app is not notarized. Concretely: +Release macOS builds — the desktop `.dmg`/`.zip` files and the +`CodeBurnMenubar-.zip` menubar app — are signed with the Developer +ID Application certificate **"Developer ID Application: Resham Joshi +(XRVP7P7F9M)"** (team `XRVP7P7F9M`), built with hardened runtime **on**, and +notarized by Apple via `xcrun notarytool` (using the `codeburn-notary` +keychain profile), then stapled. `spctl --assess` reports +`source=Notarized Developer ID`, and the app opens with **no Gatekeeper +warning at all** — no right-click → Open, no quarantine removal, no +"unidentified developer" dialog. -- `spctl --assess --type execute` on the built app returns **`rejected`**, - ad-hoc-signed or not, quarantined or not. `spctl`'s static assessment - checks for a Developer ID + notarization ticket, which this build does - not have and cannot have without a paid account. -- Any file downloaded through a browser (or unzipped by Finder's Archive - Utility from a browser download) gets a `com.apple.quarantine` extended - attribute. The first time a quarantined, non-notarized app is opened, - Gatekeeper blocks a plain double-click with "Apple could not verify that - \[CodeBurn] is free of malware." -- **This is expected and correct for an unpaid, unnotarized build.** Being - a known GitHub author, signing the repo's commits, or ad-hoc signing the - binary does **not** change this — none of that is a substitute for an - Apple-issued Developer ID certificate plus notarization. +### Entitlements -### First-open instructions for users +Hardened runtime needs a handful of entitlements or Electron's JIT-compiled +renderer fails to start: -**Field-verified on macOS 15+ (Sequoia/Tahoe): an ad-hoc-signed, quarantined -app gets the harsher "\[CodeBurn] is damaged and can't be opened. You should -move it to the Trash." dialog, and the classic right-click → Open bypass does -NOT work for it** (that trick only helps Developer-ID-signed, unnotarized -apps). The reliable path is stripping the quarantine attribute: +- `com.apple.security.cs.allow-jit` +- `com.apple.security.cs.allow-unsigned-executable-memory` +- `com.apple.security.cs.allow-dyld-environment-variables` +- `com.apple.security.cs.disable-library-validation` + +### Two gotchas + +- **electron-builder rejects the `Developer ID Application:` prefix in the + identity argument.** Pass the bare certificate common name — + `"Resham Joshi (XRVP7P7F9M)"` — not the full + `"Developer ID Application: Resham Joshi (XRVP7P7F9M)"` string `codesign` + itself accepts. +- **electron-builder notarizes the `.app`, not the `.dmg`.** Once + `electron-builder --mac` finishes signing and notarizing the app bundle, + the `.dmg` it produces around that app still needs its own + codesign + notarize + staple pass: + ```sh + codesign --force --sign "Resham Joshi (XRVP7P7F9M)" CodeBurn--arm64.dmg + xcrun notarytool submit CodeBurn--arm64.dmg --keychain-profile codeburn-notary --wait + xcrun stapler staple CodeBurn--arm64.dmg + ``` + (repeat for the `x64` dmg). + +### Release builds vs. the committed config + +`app/package.json`'s committed `build.mac` still declares `identity: "-"` +and `hardenedRuntime: false` — the ad-hoc/local-dev default described in +"Build configuration" above. A signed release build passes the real +Developer ID settings as `electron-builder` CLI overrides instead of +changing that file: ```sh -# after dragging CodeBurn.app from the dmg into /Applications -xattr -cr /Applications/CodeBurn.app +npx electron-builder --mac \ + -c.mac.identity="Resham Joshi (XRVP7P7F9M)" \ + -c.mac.hardenedRuntime=true \ + -c.mac.entitlements=build/entitlements.mac.plist \ + -c.mac.entitlementsInherit=build/entitlements.mac.plist \ + -c.mac.gatekeeperAssess=true ``` -One time only; subsequent launches work normally. **System Settings → -Privacy & Security → "Open Anyway"** may also appear after a blocked attempt -and works when offered, but is not shown in all cases for ad-hoc builds — -document the `xattr` path as primary anywhere user-facing. +This works, but it is easy to forget on a manual release — baking these +settings into `build.mac` directly (falling back to ad-hoc only when no +Developer ID identity is present in the keychain) would remove the risk of a +release accidentally shipping unsigned. -None of these steps are needed for a `dmg`/`zip` built and opened locally on -the same machine (no quarantine attribute is applied to files that were never -downloaded) — they only apply to a build distributed to someone else, e.g. -via a GitHub Release. +The menubar app (`mac/Scripts/package-app.sh`) picks up the same identity +through its existing `CODESIGN_IDENTITY` environment variable — set +`CODESIGN_IDENTITY="Resham Joshi (XRVP7P7F9M)"` before running it — and then +needs the same notarize-and-staple pass as the dmg above, run against the +built `.app` before it is zipped. -### Folder-access prompts re-appear on every update +### Ad-hoc is still the fallback + +Building locally with no Developer ID identity in the keychain (or in CI, +where none is configured) falls back to ad-hoc signing, same as before: +enough to satisfy the kernel's code-signing check on Apple Silicon, but not +Gatekeeper. A quarantined ad-hoc build still shows the "Apple could not +verify..." / "is damaged and can't be opened" dialogs, and stripping the +quarantine attribute (`xattr -cr /Applications/CodeBurn.app`) is still the +workaround for a build tested this way. This path is for local development +only — the distributed release builds are signed and notarized and never +hit it. + +### Folder-access prompts CodeBurn requests access to folders like Documents, Desktop, and Downloads (via `mac.extendInfo` in `app/package.json`) to read local AI coding tool -session logs. Because each ad-hoc/unsigned build has no stable Developer ID, -macOS TCC treats every rebuild as a new app identity, so users get -re-prompted for folder access after each update even though nothing else -changed. Signing with a stable Developer ID certificate (see "Upgrade path" -below) fixes this — TCC grants persist across updates once the app's -identity is stable. - -## Upgrade path: paid account + notarization - -When a paid Apple Developer Program membership is available, the same -`electron-builder` config takes the upgrade with a few changes, no new -tooling: - -- Set `mac.identity` to the real `"Developer ID Application: ()"` - certificate name (or let electron-builder auto-discover it from the - keychain by removing `identity` entirely), and set `mac.hardenedRuntime: - true` with an entitlements file. -- Add a `notarize` block (or the `afterSign` hook electron-builder's - `@electron/notarize` integration expects) with an app-specific password or - API key, and remove `gatekeeperAssess: false` so electron-builder verifies - the notarized result itself. -- Everything else — `appId`, `files`, `mac.target` (dmg/zip, arm64+x64), - `icon`, `directories.output` — stays as-is. +session logs. Signed release builds use the stable Developer ID identity +above, so macOS TCC treats every release build as the same app and folder +grants persist across updates. This only regresses for an ad-hoc/local-dev +build: with no stable Developer ID, TCC treats each rebuild as a new app +identity and re-prompts for folder access every time. diff --git a/app/README.md b/app/README.md index c59af884..fcd5f157 100644 --- a/app/README.md +++ b/app/README.md @@ -55,13 +55,12 @@ Supported M1 periods are `today`, `week`, `30days`, `month`, and `all`. Provider ## Packaging -`npm run package` produces an ad-hoc-signed macOS `.dmg`/`.zip` (arm64 and x64) via `electron-builder`, no paid Apple Developer account required. Packaging rebuilds the root CLI and bundles it into the app (`Resources/cli`), so installs need nothing on the target machine. See `DISTRIBUTION.md` for build instructions, the bundled-CLI mechanism, artifact locations, and the Gatekeeper first-open story. +`npm run package` produces a macOS `.dmg`/`.zip` (arm64 and x64) via `electron-builder`. Release builds are signed with a Developer ID Application certificate and notarized by Apple (ad-hoc signing is only a fallback when no signing identity is configured). Packaging rebuilds the root CLI and bundles it into the app (`Resources/cli`), so installs need nothing on the target machine. See `DISTRIBUTION.md` for build instructions, the bundled-CLI mechanism, artifact locations, and the notarization process. ## M2 Backlog - Add Electron `autoUpdater` (the app already bundles its own version-matched CLI, so end-user installs need nothing on the machine; auto-update is the remaining piece). - Keep npm as a separate CLI-user channel at the same version as the desktop app. -- Add macOS code signing with a paid Developer ID and notarization (ad-hoc packaging exists today; see `DISTRIBUTION.md`). - Add a `codeburn desktop` launcher subcommand. - Implement in-app pairing, approve, pull, and visibility mutations currently shown as M2 affordances. - Build the Models Compare sheet. diff --git a/app/build/icon.icns b/app/build/icon.icns index 166e1132..6cec028b 100644 Binary files a/app/build/icon.icns and b/app/build/icon.icns differ diff --git a/app/build/icon.png b/app/build/icon.png index f7588300..c735ff99 100644 Binary files a/app/build/icon.png and b/app/build/icon.png differ diff --git a/app/electron/cli.test.ts b/app/electron/cli.test.ts index e7748864..0fe2f373 100644 --- a/app/electron/cli.test.ts +++ b/app/electron/cli.test.ts @@ -5,7 +5,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, chmodSync import { tmpdir } from 'node:os' import { delimiter, dirname, join, isAbsolute, relative, win32, posix } from 'node:path' -import { spawnCli, spawnCliAction, spawnEnvFor, spawnSpecFor, startServe, killAll, shutdownAll, CliError, cmdShimArgs, escapeForCmd, nodeManagerDirs, notFoundStage, reapOrphanServe, resolveCodeburnPath, resolveTarget } from './cli' +import { spawnCli, spawnCliAction, spawnEnvFor, spawnSpecFor, startServe, killAll, serveUsage, shutdownAll, CliError, cmdShimArgs, escapeForCmd, nodeManagerDirs, notFoundStage, reapOrphanServe, resolveCodeburnPath, resolveTarget } from './cli' let dir: string const originalBin = process.env.CODEBURN_BIN @@ -14,6 +14,7 @@ const originalPathFile = process.env.CODEBURN_CLI_PATH_FILE const originalViteUrl = process.env.VITE_DEV_SERVER_URL const originalBundled = process.env.CODEBURN_BUNDLED_CLI const originalDevRepoRoot = process.env.CODEBURN_DEV_REPO_ROOT +const originalServeIdle = process.env.CODEBURN_SERVE_IDLE_MS /** * Windows has no catchable SIGTERM: child.kill() is TerminateProcess, which ends the child @@ -117,6 +118,8 @@ afterEach(() => { else process.env.CODEBURN_BUNDLED_CLI = originalBundled if (originalDevRepoRoot === undefined) delete process.env.CODEBURN_DEV_REPO_ROOT else process.env.CODEBURN_DEV_REPO_ROOT = originalDevRepoRoot + if (originalServeIdle === undefined) delete process.env.CODEBURN_SERVE_IDLE_MS + else process.env.CODEBURN_SERVE_IDLE_MS = originalServeIdle rmSync(dir, { recursive: true, force: true }) }) @@ -1126,33 +1129,42 @@ describe('resident serve single-flight', { timeout: 30_000 }, () => { expect(readMaybe(files.actionsFile)).toBe('a') }) - posixOnly('SIGTERMs the outgoing resident on a mutation restart instead of hard-killing it', async () => { - // A settings mutation replaces a child that may hold the cache refresh lock. - // Same hazard as a timeout, so it gets the same grace: only a catchable - // signal lets the outgoing child unlink its own lock instead of leaving it - // for the next parse's stale-pid takeover. + posixOnly('retires the outgoing resident on EOF, and signals it only if it ignores EOF', async () => { + // A settings mutation replaces a child that may hold the cache refresh lock + // and a held shard window. Closing stdin lets it publish that window and + // unlink its own lock on the way out; SIGTERM is the fallback for a child + // that does not end on EOF, not the first move. + const eofFile = join(dir, 'restart-eof') const signalFile = join(dir, 'restart-signals') - fakeBin( - 'sigterm-aware-resident.js', + const residentBin = (ignoreEof: boolean): string => `const fs = require('node:fs'); const readline = require('node:readline'); const command = process.argv[2]; if (command === 'serve') { process.on('SIGTERM', () => { fs.appendFileSync(${JSON.stringify(signalFile)}, 'TERM'); process.exit(0); }); const rl = readline.createInterface({ input: process.stdin }); + if (${ignoreEof}) setInterval(() => {}, 1000); + else rl.on('close', () => { fs.appendFileSync(${JSON.stringify(eofFile)}, 'EOF'); process.exit(0); }); rl.on('line', line => { const request = JSON.parse(line); process.stdout.write(JSON.stringify({ id: request.id, ok: true, output: JSON.stringify({ via: 'serve' }) }) + '\\n'); }); } else { process.stdout.write('currency updated'); - }`, - ) - startServe() + }` + fakeBin('eof-aware-resident.js', residentBin(false)) + startServe() await expect(spawnCli(['status'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve' }) await expect(spawnCliAction(['currency', 'EUR'], { timeoutMs: 5_000 })).resolves.toMatchObject({ ok: true }) + await waitFor(() => readMaybe(eofFile) === 'EOF') + expect(readMaybe(signalFile)).toBe('') - await waitFor(() => readMaybe(signalFile) === 'TERM') + killAll() + fakeBin('eof-aware-resident.js', residentBin(true)) + startServe() + await expect(spawnCli(['status'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve' }) + await expect(spawnCliAction(['currency', 'EUR'], { timeoutMs: 5_000 })).resolves.toMatchObject({ ok: true }) + await waitFor(() => readMaybe(signalFile) === 'TERM', 10_000) }) it('preserves the unexpected-death budget across mutation restarts', async () => { @@ -1313,6 +1325,192 @@ describe('resident serve single-flight', { timeout: 30_000 }, () => { }) }) +/** A resident that reports how it was retired, so a retire is observable without + * probing pids (a signalled child is briefly a zombie, which answers + * `kill(pid, 0)`). It goes away on stdin EOF — like `serve --stdio`, which + * publishes its coalesced shard window there — and records any SIGTERM it + * received separately, so a test can pin that none was sent. `--slow` delays one + * answer; `lateExitMs` holds the exit open past the replacement's start; + * `ignoreEof` models a child that does not end on EOF and must still be reaped. */ +function fakeRetiringBin(lateExitMs = 0, ignoreEof = false): { + startsFile: string + deathsFile: string + signalsFile: string + oneShotsFile: string +} { + const startsFile = join(dir, 'retire-starts') + const deathsFile = join(dir, 'retire-deaths') + const signalsFile = join(dir, 'retire-signals') + const oneShotsFile = join(dir, 'retire-one-shots') + fakeBin( + 'retiring-resident.js', + `const fs = require('node:fs'); const readline = require('node:readline'); + const command = process.argv[2]; + if (command === 'serve') { + fs.appendFileSync(${JSON.stringify(startsFile)}, 's'); + const generation = fs.readFileSync(${JSON.stringify(startsFile)}, 'utf8').length; + const retire = () => { + fs.appendFileSync(${JSON.stringify(deathsFile)}, 'x'); + setTimeout(() => process.exit(0), ${lateExitMs}); + }; + process.on('SIGTERM', () => { fs.appendFileSync(${JSON.stringify(signalsFile)}, 'T'); retire(); }); + const rl = readline.createInterface({ input: process.stdin }); + if (${ignoreEof}) setInterval(() => {}, 1000); else rl.on('close', retire); + rl.on('line', line => { + const request = JSON.parse(line); + const answer = () => process.stdout.write(JSON.stringify({ + id: request.id, + ok: true, + output: JSON.stringify({ via: 'serve', generation }), + usage: generation === 1 ? { cpuSec: 12, rssMb: 1234 } : { cpuSec: 1, rssMb: 10 }, + }) + '\\n'); + if (request.args.includes('--slow')) setTimeout(answer, 300); else answer(); + }); + } else if (command === 'currency') { + process.stdout.write('currency updated'); + } else { + fs.appendFileSync(${JSON.stringify(oneShotsFile)}, 'o'); + process.stdout.write(JSON.stringify({ via: 'spawn' })); + }`, + ) + return { startsFile, deathsFile, signalsFile, oneShotsFile } +} + +describe('resident serve idle retire', { timeout: 30_000 }, () => { + beforeEach(() => { process.env.CODEBURN_SERVE_IDLE_MS = '50' }) + + posixOnly('retires an idle child and serves the next request from a new resident', async () => { + const files = fakeRetiringBin() + startServe() + + await expect(spawnCli(['status', '--warm'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve', generation: 1 }) + await waitFor(() => readMaybe(files.deathsFile) === 'x') + + await expect(spawnCli(['status', '--after-retire'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve', generation: 2 }) + expect(readMaybe(files.startsFile)).toBe('ss') + expect(readMaybe(files.oneShotsFile)).toBe('') + }) + + posixOnly('never spends the unexpected-death budget, however often it retires', async () => { + const files = fakeRetiringBin() + startServe() + + for (let round = 1; round <= 5; round += 1) { + await expect(spawnCli(['status', '--round', String(round)], { timeoutMs: 5_000 })) + .resolves.toEqual({ via: 'serve', generation: round }) + await waitFor(() => readMaybe(files.deathsFile).length === round) + } + + // Three unexpected deaths disable serve for the app run; retires are + // deliberate, so the sixth request still reaches a resident. + await expect(spawnCli(['status', '--sixth'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve', generation: 6 }) + expect(readMaybe(files.oneShotsFile)).toBe('') + }) + + posixOnly('never retires a child with a request in flight or queued behind one', async () => { + const files = fakeRetiringBin() + startServe() + + // The slow answer takes 6 idle windows; the queued request takes its turn in + // the microtask right after it, which is the one moment a timer could slip in. + const slow = spawnCli(['status', '--slow'], { timeoutMs: 5_000 }) + const queued = spawnCli(['models', '--queued'], { timeoutMs: 5_000 }) + + await expect(slow).resolves.toEqual({ via: 'serve', generation: 1 }) + await expect(queued).resolves.toEqual({ via: 'serve', generation: 1 }) + expect(readMaybe(files.deathsFile)).toBe('') + expect(readMaybe(files.oneShotsFile)).toBe('') + + await waitFor(() => readMaybe(files.deathsFile) === 'x') + expect(readMaybe(files.startsFile)).toBe('s') + }) + + posixOnly('keeps the serve usage peak across a retire', async () => { + const files = fakeRetiringBin() + startServe() + + await spawnCli(['status', '--peak'], { timeoutMs: 5_000 }) + await waitFor(() => readMaybe(files.deathsFile) === 'x') + await spawnCli(['status', '--after-peak'], { timeoutMs: 5_000 }) + + // app_close reports what the resident cost, so a replacement's counters + // restarting at zero must not erase the peak. + expect(serveUsage()).toEqual({ cpuSec: 12, rssMb: 1234 }) + }) + + posixOnly('keeps the child resident for good when the idle window is 0', async () => { + process.env.CODEBURN_SERVE_IDLE_MS = '0' + const files = fakeRetiringBin() + startServe() + + await spawnCli(['status', '--no-retire'], { timeoutMs: 5_000 }) + await new Promise(resolve => setTimeout(resolve, 250)) + + expect(readMaybe(files.deathsFile)).toBe('') + await expect(spawnCli(['status', '--still-warm'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve', generation: 1 }) + expect(readMaybe(files.startsFile)).toBe('s') + }) + + posixOnly('ignores a retired child that exits only after its replacement is serving', async () => { + const files = fakeRetiringBin(200) + startServe() + + await spawnCli(['status', '--warm'], { timeoutMs: 5_000 }) + await waitFor(() => readMaybe(files.deathsFile) === 'x') + + // The retired child's exit and stdout EOF land while the replacement is + // mid-request: they must reject nothing and requeue nothing. + await expect(spawnCli(['status', '--slow'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve', generation: 2 }) + expect(readMaybe(files.startsFile)).toBe('ss') + expect(readMaybe(files.oneShotsFile)).toBe('') + }) + + posixOnly('closes stdin first and never signals a child that exits on EOF', async () => { + // EOF is what makes `serve --stdio` publish its coalesced shard window on + // the way out. SIGTERM is caught only to unlink the cache lock and is then + // re-raised, so signalling here would kill the flush. + const files = fakeRetiringBin() + startServe() + + await expect(spawnCli(['status', '--warm'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve', generation: 1 }) + await waitFor(() => readMaybe(files.deathsFile) === 'x') + expect(readMaybe(files.signalsFile)).toBe('') + + // Still exactly one resident per generation, and no one-shot fallback. + await expect(spawnCli(['status', '--after-retire'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve', generation: 2 }) + expect(readMaybe(files.startsFile)).toBe('ss') + expect(readMaybe(files.oneShotsFile)).toBe('') + expect(readMaybe(files.signalsFile)).toBe('') + }) + + posixOnly('signals a retired child that ignores EOF, but only after the grace', async () => { + const files = fakeRetiringBin(0, true) + startServe() + + await expect(spawnCli(['status', '--warm'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve', generation: 1 }) + // Inside the grace: stdin is closed, nothing has been signalled yet. + await new Promise(resolve => setTimeout(resolve, 400)) + expect(readMaybe(files.signalsFile)).toBe('') + + await waitFor(() => readMaybe(files.signalsFile) === 'T', 10_000) + expect(readMaybe(files.deathsFile)).toBe('x') + }) + + posixOnly('leaves one child behind when a mutation restart lands in the idle window', async () => { + const files = fakeRetiringBin() + startServe() + + await expect(spawnCli(['status', '--before'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve', generation: 1 }) + await expect(spawnCliAction(['currency', 'EUR'], { timeoutMs: 5_000 })).resolves.toMatchObject({ ok: true }) + // Issued without yielding to the timer queue: whichever of the retire and + // the restart ran first, exactly one child is alive to answer this. + await expect(spawnCli(['status', '--after'], { timeoutMs: 5_000 })).resolves.toEqual({ via: 'serve', generation: 2 }) + + expect(readMaybe(files.startsFile)).toBe('ss') + expect(readMaybe(files.oneShotsFile)).toBe('') + }) +}) + describe('killAll', () => { it('reaps an in-flight child so its promise settles', async () => { fakeBin('hang-kill.js', 'setInterval(() => {}, 1000)') diff --git a/app/electron/cli.ts b/app/electron/cli.ts index 9589031e..c92c134e 100644 --- a/app/electron/cli.ts +++ b/app/electron/cli.ts @@ -77,6 +77,12 @@ const MAX_RUNTIME_MS = 15 * 60_000 // dead pid — self-healing, but via the stale-takeover path rather than a clean // release. Neither signal publishes a partial parse; nothing does. const KILL_GRACE_MS = 5_000 +// How long a deliberately retired serve child may take to publish its coalesced +// shard window after stdin EOF before it is signalled anyway. Measured at +// ~0.9-1.0s on a large corpus; 2.5s leaves headroom without making a retire +// visible to anything (nothing waits on it — the next request starts a fresh +// child immediately). +const SERVE_FLUSH_GRACE_MS = 2_500 // Quit has a stricter user-visible budget than ordinary request timeouts. Give // the CLI enough time to catch SIGTERM and release its cache locks, then reap // every remaining process-group member before Electron exits. @@ -559,6 +565,28 @@ function killGracefully(child: ChildProcess): void { grace.unref?.() } +/** Retire a serve child the way `serve --stdio` expects: EOF on stdin ends its + * read loop, which publishes the coalesced shard window on the way out. No + * signal is sent while that runs — SIGTERM is caught only to unlink the cache + * lock and is then re-raised (src/session-cache.ts), so it kills the flush. + * Only a child still alive after the grace is handed to {@link killGracefully}. + * The child stays in `activeChildren` throughout, so a quit landing inside the + * window still reaps it. */ +function retireWithFlush(child: ChildProcess): void { + activeChildren.add(child) + let grace: NodeJS.Timeout | undefined + const settle = () => { activeChildren.delete(child); if (grace) clearTimeout(grace) } + child.once('exit', () => { if (!ownedTreeAlive(child)) settle() }) + // A child whose stdin is already gone never sees a new EOF; the grace still + // bounds it and the signal below still lands. + try { child.stdin?.end() } catch { /* already closed */ } + grace = setTimeout(() => { + if (ownedTreeAlive(child)) killGracefully(child) + else settle() + }, SERVE_FLUSH_GRACE_MS) + grace.unref?.() +} + /** Progress heartbeats share the stderr stream with real diagnostics, and every * read spawn now enables them — so they must never become the error message. */ function withoutProgressLines(stderr: string): string { @@ -685,6 +713,8 @@ async function runScheduledCli( // runs an artificial warm-up query beside a duplicate one-shot child; // - progress frames from serve are forwarded through the same onStderr hook // used by a one-shot cold start; +// - a child left idle for CODEBURN_SERVE_IDLE_MS retires; the next request +// restarts one through the same lazy path a crash uses; // - any serve failure falls back to a normal spawn for that call; // - three child deaths permanently disable serve for this app run. const SERVE_ROUTED = new Set(['status', 'models', 'sessions', 'compare', 'yield', 'spend', 'optimize', 'audit', 'report']) @@ -712,6 +742,14 @@ class ServeClient { private warmed = false private destroyed = false private requestTail: Promise = Promise.resolve() + private idleTimer: NodeJS.Timeout | undefined + // The renderer stops polling while the window is hidden, so an idle resident + // would otherwise hold its parsed cache (GBs on a large corpus) forever. After + // this much silence the child retires; the next request restarts it through + // the lazy path in spawnCli. 0 (or garbage) keeps the child resident for good. + // 15 minutes: longer than the slowest cadence a visible window can use (10 min), + // so only a window nobody is looking at gives the child up. + private readonly idleMs = Number(process.env.CODEBURN_SERVE_IDLE_MS ?? 900_000) constructor(private readonly spec: SpawnSpec, private readonly pidFile?: string) {} @@ -745,6 +783,30 @@ class ServeClient { this.onDeath(child) killGracefully(child) }) + this.armIdle() + } + + /** (Re)start the retire countdown, and cancel any older one. Only an idle, + * running client arms it, so a request in flight can never be retired out + * from under its caller, and a stale timer from a previous generation is + * always cleared by the start/death that replaced it. */ + private armIdle(): void { + clearTimeout(this.idleTimer) + if (!(this.idleMs > 0) || this.pending.size > 0 || !this.child) return + this.idleTimer = setTimeout(() => { + const child = this.child + // A request admitted after the timer was armed clears it, but re-check + // anyway: nothing else may kill a child that has work on the wire. + if (this.pending.size > 0 || !child) return + // Deliberate, like a mutation restart: detach first so the exit event + // cannot spend the unexpected-death budget, then close its stdin so it + // publishes its held shard window and exits on its own. No restart here — + // the next request lazily starts one, and the outgoing child's late exit + // is inert once it is no longer `this.child`. + this.onDeath(child, false) + retireWithFlush(child) + }, this.idleMs) + this.idleTimer.unref?.() } private onData(child: ReturnType, chunk: string): void { @@ -762,8 +824,15 @@ class ServeClient { } const line = rawLine.trim() if (!line) continue - let msg: { id?: number; ready?: boolean; progress?: string; ok?: boolean; refused?: boolean; output?: string; error?: string } + let msg: { id?: number; ready?: boolean; progress?: string; ok?: boolean; refused?: boolean; output?: string; error?: string; usage?: { cpuSec?: number; rssMb?: number } } try { msg = JSON.parse(line) } catch { continue } + if (msg.usage) { + // Kept as a running max: a replaced child's counters restart at zero. + serveUsagePeak = { + cpuSec: Math.max(serveUsagePeak?.cpuSec ?? 0, Number(msg.usage.cpuSec) || 0), + rssMb: Math.max(serveUsagePeak?.rssMb ?? 0, Number(msg.usage.rssMb) || 0), + } + } if (msg.ready) continue if (typeof msg.id !== 'number') continue const waiter = this.pending.get(msg.id) @@ -789,6 +858,7 @@ class ServeClient { } else { waiter.reject(new CliError('nonzero', msg.error ?? 'serve request failed')) } + this.armIdle() } // Complete lines are bounded above before parsing. Bound the partial frame // too, otherwise a child that never emits '\n' can grow this buffer forever. @@ -842,17 +912,21 @@ class ServeClient { waiter.reject(new CliError('nonzero', 'codeburn serve exited')) } this.pending.clear() + // No child left to retire: this only cancels a timer armed for the one that + // just went away, so a later generation cannot inherit its countdown. + this.armIdle() } restartAfterMutation(): void { const child = this.child if (child) { // This is an intentional replacement, not a crash. Detach first so the - // later exit event cannot consume the unexpected-death budget. The - // outgoing child may hold the refresh lock, so it gets the same SIGTERM - // grace a timed-out one does and can unlink that lock on its way out. + // later exit event cannot consume the unexpected-death budget, then close + // its stdin: the outgoing child publishes its held shard window and exits + // cleanly, releasing the refresh lock it may hold. Only if it is still + // alive after the grace does it get the old SIGTERM treatment. this.onDeath(child, false) - killGracefully(child) + retireWithFlush(child) } this.start() } @@ -868,6 +942,7 @@ class ServeClient { } private requestNow(args: string[], timeoutMs: number, onStderr?: (chunk: string) => void): Promise { + clearTimeout(this.idleTimer) const child = this.child if (!child?.stdin) return Promise.reject(new CliError('nonzero', 'serve not running')) const id = this.nextId++ @@ -908,6 +983,7 @@ class ServeClient { } destroy(): ChildProcess | null { + clearTimeout(this.idleTimer) this.destroyed = true this.deaths = SERVE_MAX_RESTARTS const child = this.child @@ -919,6 +995,15 @@ class ServeClient { let serveClient: ServeClient | null = null +/** What the resident serve child has reported about itself (src/serve.ts), or + * null when it never answered. Serve does the heavy parsing but is invisible to + * Electron's app.getAppMetrics(), so the desktop's app_close event reads it here. */ +let serveUsagePeak: { cpuSec: number; rssMb: number } | null = null + +export function serveUsage(): { cpuSec: number; rssMb: number } | null { + return serveUsagePeak +} + /** Start the resident serve child without issuing a query. The first real panel * request is accepted immediately (even before the ready frame) and performs * the one cold-cache hydration while streaming progress back to the splash. diff --git a/app/electron/mac-menubar.test.ts b/app/electron/mac-menubar.test.ts index 64d24727..359ef09d 100644 --- a/app/electron/mac-menubar.test.ts +++ b/app/electron/mac-menubar.test.ts @@ -4,7 +4,7 @@ import { mkdtempSync, mkdirSync, existsSync, readFileSync, statSync, writeFileSy import { tmpdir } from 'node:os' import { join } from 'node:path' -import { DOCK_ENABLED_KEY, MENUBAR_BUNDLE_ID, NO_ANSWER, OLDEST_ASKABLE, REMOTE_COMMAND_KEY, MacMenubar, installErrorMessage, installPhase, isOlderThan } from './mac-menubar' +import { DOCK_ENABLED_KEY, MENUBAR_BUNDLE_ID, NO_ANSWER, OLDEST_ASKABLE, REMOTE_COMMAND_KEY, MacMenubar, installErrorMessage, installPhase, isOlderThan, leftoverBundle } from './mac-menubar' const HOME = '/Users/tester' const USER_APP = `${HOME}/Applications/CodeBurnMenubar.app` @@ -25,9 +25,16 @@ function harness(opts: { honoursRemoteCommand?: boolean /** How many `open` calls no-op before one actually brings the process up. */ flakyOpen?: number + /** A menubar that takes the relaunch command, goes down, and never starts itself again. */ + relaunchDies?: boolean + /** A menubar that takes the relaunch command and stays exactly as it was: the process + * that answered is still the one running, so nothing was actually restarted. */ + relaunchStalls?: boolean } = {}) { const present = new Set(opts.present ?? []) let running = Boolean(opts.running) + // A restart is a new process, and that is what a relaunch has to be confirmed by. + let pid = 4242 let opensToIgnore = opts.flakyOpen ?? 0 // The command the menubar has not taken out of its defaults yet. A menubar that watches the // key consumes it as it acts, which is what settings() waits for. @@ -38,15 +45,18 @@ function harness(opts: { calls.push([command, args]) if (command.endsWith('mdfind')) return opts.mdfind ?? '' if (command.endsWith('PlistBuddy')) return opts.version ?? '9.9.9' - if (command.endsWith('pgrep')) return running ? '4242' : null + if (command.endsWith('pgrep')) return running ? String(pid) : null if (command.endsWith('pkill')) { running = false; return '' } if (command.endsWith('defaults') && args[0] === 'read') { return args[2] === REMOTE_COMMAND_KEY ? pendingCommand : (opts.dock ?? null) } if (command.endsWith('defaults') && args[0] === 'write') { if (args[2] === REMOTE_COMMAND_KEY) { + // `relaunch` and `settings` leave the process up: the first restarts itself. if (opts.honoursRemoteCommand === false) pendingCommand = args[4] - else if (args[4] !== 'settings') running = false + else if (args[4] === 'quit' || args[4] === 'uninstall') running = false + else if (opts.relaunchDies && args[4] === 'relaunch') running = false + else if (args[4] === 'relaunch' && !opts.relaunchStalls) pid += 1 } return '' } @@ -55,7 +65,7 @@ function harness(opts: { return '' } if (command.endsWith('osascript')) { running = false; return '' } - if (command.endsWith('open')) { if (opensToIgnore > 0) opensToIgnore--; else running = true; return '' } + if (command.endsWith('open')) { if (opensToIgnore > 0) opensToIgnore--; else { running = true; pid += 1 } ; return '' } return null }) const runCli = vi.fn(async (args: string[]) => { @@ -302,17 +312,48 @@ describe('MacMenubar.settings', () => { expect(calls.some(([cmd, args]) => cmd.endsWith('defaults') && args[0] === 'delete' && args[2] === REMOTE_COMMAND_KEY)).toBe(true) }) - // AppKit reads AppleLanguages only at launch, so a running menu bar must be quit and - // reopened for the switch to show — and the quit is AppleScript, which every version honors. - it('writes AppleLanguages and relaunches a running menu bar so it re-reads it', async () => { - const { menubar, calls } = harness({ present: [USER_APP], running: true }) + // AppKit reads AppleLanguages only at launch, so a running menu bar has to come back + // up. Reopening it from here made the desktop app its responsible process and macOS + // re-asked for "access data from other apps" every time, so it is asked to do it itself. + it('writes AppleLanguages and asks a running menu bar to relaunch itself', async () => { + const { menubar, calls, isRunning } = harness({ present: [USER_APP], running: true }) await menubar.setLanguage('zh-Hans') const write = calls.find(([cmd, args]) => cmd.endsWith('defaults') && args[0] === 'write' && args[2] === 'AppleLanguages') expect(write?.[1].at(-1)).toBe('zh-Hans') + const command = calls.find(([cmd, args]) => cmd.endsWith('defaults') && args[0] === 'write' && args[2] === REMOTE_COMMAND_KEY) + expect(command?.[1]).toEqual(['write', MENUBAR_BUNDLE_ID, REMOTE_COMMAND_KEY, '-string', 'relaunch']) + expect(calls.some(([cmd]) => cmd.endsWith('osascript'))).toBe(false) + expect(calls.some(([cmd, args]) => cmd.endsWith('open') && args[0] === USER_APP)).toBe(false) + expect(isRunning()).toBe(true) + }) + + // A menubar too old to watch the key never answers, and the switch has to keep working. + it('falls back to quitting and reopening a menu bar that does not answer', async () => { + const { menubar, calls } = harness({ present: [USER_APP], running: true, honoursRemoteCommand: false }) + await menubar.setLanguage('ja') const quitIdx = calls.findIndex(([cmd]) => cmd.endsWith('osascript')) const openIdx = calls.findIndex(([cmd, args]) => cmd.endsWith('open') && args[0] === USER_APP) expect(quitIdx).toBeGreaterThanOrEqual(0) expect(openIdx).toBeGreaterThan(quitIdx) + // Left behind, the command would relaunch the next launch instead. + expect(calls.some(([cmd, args]) => cmd.endsWith('defaults') && args[0] === 'delete' && args[2] === REMOTE_COMMAND_KEY)).toBe(true) + }) + + // The command was taken, so the fallback below never runs; without a check on the + // relaunch actually landing, a menubar that goes down and stays down is left gone. + it('opens the menu bar itself when a consumed relaunch never brings it back', async () => { + const { menubar, calls, isRunning } = harness({ present: [USER_APP], running: true, relaunchDies: true }) + await menubar.setLanguage('ja') + expect(calls.some(([cmd, args]) => cmd.endsWith('open') && args[0] === USER_APP)).toBe(true) + expect(isRunning()).toBe(true) + }) + + // The old process still answers pgrep while it is tearing itself down, so waiting for + // "something is running" passed instantly and a relaunch that never happened looked fine. + it('opens the menu bar itself when the process that took the relaunch never gives way', async () => { + const { menubar, calls } = harness({ present: [USER_APP], running: true, relaunchStalls: true }) + await menubar.setLanguage('ja') + expect(calls.some(([cmd, args]) => cmd.endsWith('open') && args[0] === USER_APP)).toBe(true) }) it('clears the override for System and never quits a menu bar that is down', async () => { @@ -325,7 +366,7 @@ describe('MacMenubar.settings', () => { // The `open` right after a quit can activate the dying instance and no-op, // leaving the switch with a dead menu bar; the relaunch must be confirmed. it('opens again when the first relaunch does not bring the menu bar up', async () => { - const { menubar, calls, isRunning } = harness({ present: [USER_APP], running: true, flakyOpen: 1 }) + const { menubar, calls, isRunning } = harness({ present: [USER_APP], running: true, honoursRemoteCommand: false, flakyOpen: 1 }) await menubar.setLanguage('ja') const opens = calls.filter(([cmd, args]) => cmd.endsWith('open') && args[0] === USER_APP) expect(opens.length).toBe(2) @@ -530,4 +571,33 @@ describe('install progress', () => { await menubar.install() expect(seen).toEqual(['Downloading', 'Downloading', 'Verifying', 'Installing', 'Installing', 'Starting']) }) + + it('collects the leftover bundles the CLI reports, and asks for them', async () => { + let env: NodeJS.ProcessEnv | undefined + const menubar = new MacMenubar({ + platform: 'darwin', mas: false, home: HOME, + run: async () => null, + exists: () => true, + runCli: async (_args, opts) => { + env = opts?.extraEnv + opts?.onStdout?.('An older copy is still at /Applications/CodeBurnMenubar.app. Move it to the Trash.\n') + opts?.onStdout?.('CODEBURN_LEFTOVER /Applications/CodeBurnMenubar.app\n') + return { ok: true, stdout: '', stderr: '', code: 0 } + }, + }) + + const result = await menubar.install() + + // The prose line is the terminal's; only the marker reaches the card. + expect(result.leftovers).toEqual(['/Applications/CodeBurnMenubar.app']) + expect(env).toEqual({ CODEBURN_PROGRESS: '1' }) + }) +}) + +describe('leftoverBundle', () => { + it('reads the path off a marker line and ignores everything else', () => { + expect(leftoverBundle('CODEBURN_LEFTOVER /Applications/CodeBurnMenubar.app')).toBe('/Applications/CodeBurnMenubar.app') + expect(leftoverBundle('An older copy is still at /Applications/CodeBurnMenubar.app.')).toBeNull() + expect(leftoverBundle('CODEBURN_LEFTOVER ')).toBeNull() + }) }) diff --git a/app/electron/mac-menubar.ts b/app/electron/mac-menubar.ts index 6aea22d7..919fb61c 100644 --- a/app/electron/mac-menubar.ts +++ b/app/electron/mac-menubar.ts @@ -28,6 +28,14 @@ export const NO_ANSWER = 'The menu bar app did not respond. Update it and try ag /** The steps of an install worth naming while a person waits ~30s for it. */ export type InstallPhase = 'Downloading' | 'Verifying' | 'Installing' | 'Starting' +/** Wire marker for the CLI's leftover-bundle lines (src/menubar-installer.ts: LEFTOVER_LINE_PREFIX). */ +const LEFTOVER_LINE_PREFIX = 'CODEBURN_LEFTOVER ' + +/** The path of an older bundle the CLI could not remove, or null for any other line. */ +export function leftoverBundle(line: string): string | null { + return line.startsWith(LEFTOVER_LINE_PREFIX) ? line.slice(LEFTOVER_LINE_PREFIX.length).trim() || null : null +} + /** * The CLI narrates its own install on stdout (src/menubar-installer.ts). Reading those lines * beats inventing a second progress protocol, and a line this does not know simply keeps the @@ -96,7 +104,7 @@ export type MacMenubarDeps = { /** `process.mas` is true only inside a Mac App Store build. */ mas: boolean home?: string - runCli?: (args: string[], opts?: { timeoutMs?: number; onStdout?: (chunk: string) => void }) => Promise + runCli?: (args: string[], opts?: { timeoutMs?: number; extraEnv?: NodeJS.ProcessEnv; onStdout?: (chunk: string) => void }) => Promise /** Named steps of a running install, pushed to the card so a 30-second wait says something. */ onPhase?: (phase: InstallPhase) => void /** The desktop app's own executable, which is also the Node that runs the CLI it carries. */ @@ -229,35 +237,41 @@ export class MacMenubar { * the app's own SingleInstanceGuard retires anything that outlived that, so this cannot end * with two. */ - async install(): Promise<{ ok: boolean; error: string | null; status: MacMenubarStatus }> { - if (!this.supported()) return { ok: false, error: 'The menu bar app is macOS only.', status: NOT_SUPPORTED } + async install(): Promise<{ ok: boolean; error: string | null; status: MacMenubarStatus; leftovers: string[] }> { + if (!this.supported()) return { ok: false, error: 'The menu bar app is macOS only.', status: NOT_SUPPORTED, leftovers: [] } if (this.deps.mas) { - return { ok: false, error: 'Get the menu bar app from the website.', status: await this.status() } + return { ok: false, error: 'Get the menu bar app from the website.', status: await this.status(), leftovers: [] } } const runCli = this.deps.runCli - if (!runCli) return { ok: false, error: 'The codeburn CLI is not available.', status: await this.status() } + if (!runCli) return { ok: false, error: 'The codeburn CLI is not available.', status: await this.status(), leftovers: [] } // Before the install, not after: the CLI records a persistent codeburn path for the // menubar and refuses to go on without one, and a desktop-only user has none on PATH. await this.writeCliLauncher() const already = Boolean(await this.locate()) this.deps.onPhase?.('Downloading') let pending = '' + const leftovers: string[] = [] const result = await runCli(already ? ['menubar', '--force'] : ['menubar'], { timeoutMs: INSTALL_TIMEOUT_MS, + // What turns the CLI's leftover-bundle advice into machine-readable lines. + extraEnv: { CODEBURN_PROGRESS: '1' }, onStdout: chunk => { // Chunks split mid-line, so only whole lines are read and the tail is kept. pending += chunk const lines = pending.split('\n') pending = lines.pop() ?? '' for (const line of lines) { - const phase = installPhase(line.trim()) + const text = line.trim() + const leftover = leftoverBundle(text) + if (leftover) leftovers.push(leftover) + const phase = installPhase(text) if (phase) this.deps.onPhase?.(phase) } }, }) const status = await this.status() - if (result.ok && status.installed) return { ok: true, error: null, status } - return { ok: false, error: installErrorMessage(result), status } + if (result.ok && status.installed) return { ok: true, error: null, status, leftovers } + return { ok: false, error: installErrorMessage(result), status, leftovers } } /** `open` on a running LSUIElement app activates the one that is up rather than starting a @@ -278,8 +292,17 @@ export class MacMenubar { * its own defaults domain. A concrete Apple tag (en/ja/ko/fr, or zh-Hans/zh-Hant) * overrides; null (System) clears the override so the OS language decides. The * menu bar ships en + zh-Hans and falls back to English for the rest, so this is - * correct with no Swift change. AppKit reads AppleLanguages once, at launch, so a - * running copy is quit first — `open` then relaunches it into the new locale. + * correct with no Swift change. AppKit reads AppleLanguages once, at launch, so the + * menu bar has to come back up for the switch to show. + * + * It restarts *itself*, asked through the remote-command key. Quitting it and + * reopening it from here made the desktop app the new process's responsible + * process, and macOS then re-asked for "access data from other apps" on every + * single language change. An older menubar falls back to the quit-and-open below + * only because {@link OLDEST_ASKABLE} is the first version that watches the + * remote-command key at all. That is not a gate any later command inherits: a + * menubar that watches the key but does not know the command consumes it and + * drops it, so a command added here later needs a version floor of its own. */ async setLanguage(appleLang: string | null): Promise { if (appleLang) await this.run('/usr/bin/defaults', ['write', MENUBAR_BUNDLE_ID, 'AppleLanguages', '-array', appleLang]) @@ -288,6 +311,16 @@ export class MacMenubar { if (!path) return this.open() const executable = join(path, 'Contents', 'MacOS', 'CodeBurnMenubar') if ((await this.status()).running) { + const before = await this.runningPids(executable) + await this.run('/usr/bin/defaults', ['write', MENUBAR_BUNDLE_ID, REMOTE_COMMAND_KEY, '-string', 'relaunch']) + if (await this.waitForConsumed(EXIT_TIMEOUT_MS)) { + // It took the command but never came back up: open it ourselves rather than leave + // the menu bar gone for the sake of the permission prompt. + if (!(await this.waitForReplacement(executable, before, RELAUNCH_TIMEOUT_MS))) return this.open() + return this.status() + } + // Nobody consumed it, so it would relaunch the next launch instead. + await this.run('/usr/bin/defaults', ['delete', MENUBAR_BUNDLE_ID, REMOTE_COMMAND_KEY]) await this.run('/usr/bin/osascript', ['-e', 'quit app "CodeBurnMenubar"']) await this.waitForExit(executable, EXIT_TIMEOUT_MS) } @@ -417,6 +450,26 @@ export class MacMenubar { } } + /** The pids running from this bundle, as pgrep reports them. */ + private async runningPids(executable: string): Promise> { + const found = await this.run('/usr/bin/pgrep', ['-f', executable]) + return new Set((found ?? '').split('\n').map(line => line.trim()).filter(Boolean)) + } + + /** True once a menubar process appears that is not one of `before`. A self-relaunch is + * only done when the *replacement* is up: the old process still matches pgrep while it + * tears itself down, so "something is running" would pass instantly and every relaunch + * that silently failed would look like it worked. */ + private async waitForReplacement(executable: string, before: Set, timeoutMs: number): Promise { + const deadline = this.now() + timeoutMs + for (;;) { + const pids = await this.runningPids(executable) + if ([...pids].some(pid => !before.has(pid))) return true + if (this.now() >= deadline) return false + await new Promise(resolve => setTimeout(resolve, EXIT_POLL_MS)) + } + } + /** True once the menubar process is up, so a relaunch can confirm it took. */ private async waitForRunning(executable: string, timeoutMs: number): Promise { const deadline = this.now() + timeoutMs diff --git a/app/electron/main.test.ts b/app/electron/main.test.ts index 6b15bbd8..a769f3a9 100644 --- a/app/electron/main.test.ts +++ b/app/electron/main.test.ts @@ -36,6 +36,8 @@ function fakeSpawn(result: unknown = { current: { cost: 12.34 } }) { // must spawn. cliStatus is the one channel that resolves without spawning. const CHANNELS = [ 'codeburn:getOverview', + 'codeburn:getOptimizeSnapshot', + 'codeburn:powerStatus', 'codeburn:getTimeline', 'codeburn:getQuota', 'codeburn:getPlans', @@ -110,8 +112,8 @@ const CHANNELS = [ ] as const const ARGV_CASES: Array<{ channel: string; args: unknown[]; argv: string[] }> = [ - { channel: 'codeburn:getOverview', args: ['30days', 'claude'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--provider', 'claude'] }, - { channel: 'codeburn:getOverview', args: ['30days', 'all'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline'] }, + { channel: 'codeburn:getOverview', args: ['30days', 'claude'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--no-optimize', '--provider', 'claude'] }, + { channel: 'codeburn:getOverview', args: ['30days', 'all'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--no-optimize'] }, { channel: 'codeburn:getPlans', args: ['week'], argv: ['status', '--format', 'json', '--period', 'week'] }, { channel: 'codeburn:getActReport', args: [], argv: ['act', 'report', '--json'] }, { channel: 'codeburn:getModels', args: ['week', 'claude', true], argv: ['models', '--format', 'json', '--period', 'week', '--min-cost', '0', '--provider', 'claude', '--by-task'] }, @@ -135,15 +137,15 @@ const ARGV_CASES: Array<{ channel: string; args: unknown[]; argv: string[] }> = { channel: 'codeburn:getYield', args: ['today', 'claude'], argv: ['yield', '--format', 'json', '--period', 'today', '--provider', 'claude'] }, { channel: 'codeburn:getSpendFlow', args: ['month', 'openai'], argv: ['spend', '--format', 'flow-json', '--period', 'month', '--provider', 'openai'] }, { channel: 'codeburn:getOptimizeReport', args: ['month', 'openai'], argv: ['optimize', '--format', 'json', '--period', 'month', '--provider', 'openai'] }, - { channel: 'codeburn:getOverview', args: ['30days', 'all', { from: '2026-07-01', to: '2026-07-11' }], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--from', '2026-07-01', '--to', '2026-07-11'] }, - { channel: 'codeburn:getOverview', args: ['30days', 'all', undefined, 'claude-config:91dda17e8cf35193'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--claude-config-source', 'claude-config:91dda17e8cf35193'] }, - { channel: 'codeburn:getOverview', args: ['month', 'claude', { from: '2026-07-01', to: '2026-07-11' }, 'claude-desktop:980e1e488a654830'], argv: ['status', '--format', 'menubar-json', '--period', 'month', '--no-timeline', '--provider', 'claude', '--from', '2026-07-01', '--to', '2026-07-11', '--claude-config-source', 'claude-desktop:980e1e488a654830'] }, + { channel: 'codeburn:getOverview', args: ['30days', 'all', { from: '2026-07-01', to: '2026-07-11' }], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--no-optimize', '--from', '2026-07-01', '--to', '2026-07-11'] }, + { channel: 'codeburn:getOverview', args: ['30days', 'all', undefined, 'claude-config:91dda17e8cf35193'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--no-optimize', '--claude-config-source', 'claude-config:91dda17e8cf35193'] }, + { channel: 'codeburn:getOverview', args: ['month', 'claude', { from: '2026-07-01', to: '2026-07-11' }, 'claude-desktop:980e1e488a654830'], argv: ['status', '--format', 'menubar-json', '--period', 'month', '--no-timeline', '--no-optimize', '--provider', 'claude', '--from', '2026-07-01', '--to', '2026-07-11', '--claude-config-source', 'claude-desktop:980e1e488a654830'] }, // Combined scope emits --scope combined; an explicit local scope is identical // to the default (no flag). The CLI rejects --scope with --provider, so a // provider passed alongside combined is dropped (the renderer forces 'all'). - { channel: 'codeburn:getOverview', args: ['30days', 'all', undefined, undefined, undefined, 'combined'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--scope', 'combined'] }, - { channel: 'codeburn:getOverview', args: ['30days', 'claude', undefined, undefined, undefined, 'combined'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--scope', 'combined'] }, - { channel: 'codeburn:getOverview', args: ['30days', 'claude', undefined, undefined, undefined, 'local'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--provider', 'claude'] }, + { channel: 'codeburn:getOverview', args: ['30days', 'all', undefined, undefined, undefined, 'combined'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--no-optimize', '--scope', 'combined'] }, + { channel: 'codeburn:getOverview', args: ['30days', 'claude', undefined, undefined, undefined, 'combined'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--no-optimize', '--scope', 'combined'] }, + { channel: 'codeburn:getOverview', args: ['30days', 'claude', undefined, undefined, undefined, 'local'], argv: ['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--no-optimize', '--provider', 'claude'] }, { channel: 'codeburn:getModels', args: ['week', 'claude', true, { from: '2026-07-01', to: '2026-07-11' }], argv: ['models', '--format', 'json', '--period', 'week', '--min-cost', '0', '--provider', 'claude', '--by-task', '--from', '2026-07-01', '--to', '2026-07-11'] }, { channel: 'codeburn:getYield', args: ['today', 'all', { from: '2026-07-01', to: '2026-07-11' }], argv: ['yield', '--format', 'json', '--period', 'today', '--from', '2026-07-01', '--to', '2026-07-11'] }, { channel: 'codeburn:getSpendFlow', args: ['month', 'all', { from: '2026-07-01', to: '2026-07-11' }], argv: ['spend', '--format', 'flow-json', '--period', 'month', '--from', '2026-07-01', '--to', '2026-07-11'] }, @@ -235,7 +237,7 @@ describe('createBridgeHandlers (IPC wiring)', () => { const { spawnCli, spawnCliAction, calls } = fakeSpawn() const handlers = createBridgeHandlers(withQuota({ spawnCli, spawnCliAction, resolveCodeburnPath: () => '/bin/codeburn' })) const res = await handlers['codeburn:getOverview']!('30days', 'all') - expect(calls[0]).toEqual(['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline']) + expect(calls[0]).toEqual(['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--no-optimize']) expect(res).toEqual({ ok: true, value: { current: { cost: 12.34 } } }) }) @@ -913,7 +915,7 @@ describe('project filter', () => { const handlers = createBridgeHandlers(deps({ spawnCli, spawnCliAction, resolveCodeburnPath: () => '/bin/codeburn' })) await handlers['codeburn:getOverview']!('30days', 'all', undefined, undefined, undefined, 'combined') // No --scope combined: the CLI rejects it next to --exclude. - expect(calls[0]).toEqual(['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--exclude=my-company']) + expect(calls[0]).toEqual(['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--no-optimize', '--exclude=my-company']) }) }) @@ -923,7 +925,7 @@ describe('project filter', () => { const { spawnCli, spawnCliAction, calls } = fakeSpawn() const handlers = createBridgeHandlers(deps({ spawnCli, spawnCliAction, resolveCodeburnPath: () => '/bin/codeburn' })) await handlers['codeburn:getOverview']!('30days', 'all', undefined, undefined, undefined, 'combined') - expect(calls[0]).toEqual(['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--scope', 'combined']) + expect(calls[0]).toEqual(['status', '--format', 'menubar-json', '--period', '30days', '--no-timeline', '--no-optimize', '--scope', 'combined']) }) }) @@ -1114,15 +1116,28 @@ describe('project filter', () => { const handlers = createBridgeHandlers(deps({ spawnCli: vi.fn(), spawnCliAction, resolveCodeburnPath: () => '/bin/codeburn' })) const res = await handlers['codeburn:exportData']!('csv', 'all', '/tmp/out') expect(res).toMatchObject({ ok: true, value: { ok: false, stderr: expect.stringMatching(/Nothing to export/) } }) + expect((res as { value: { savedPath?: string } }).value.savedPath).toBeUndefined() }) }) - it('keeps an export that named a saved path successful', async () => { + it('keeps an export that named a saved path successful, and reports where it landed', async () => { await withFilterFile(async () => { - const spawnCliAction = vi.fn(async () => ({ ok: true, stdout: '\n Exported (Today + 7 Days + 30 Days) to: /tmp/out\n', stderr: '', code: 0 })) + // CSV nests a dated folder inside the picked destination, so the toast + // must name the CLI's path, not the argument it was given. + const spawnCliAction = vi.fn(async () => ({ ok: true, stdout: '\n Exported (Today + 7 Days + 30 Days) to: /tmp/out/codeburn-export-2026-09-19\n', stderr: '', code: 0 })) const handlers = createBridgeHandlers(deps({ spawnCli: vi.fn(), spawnCliAction, resolveCodeburnPath: () => '/bin/codeburn' })) const res = await handlers['codeburn:exportData']!('csv', 'all', '/tmp/out') - expect(res).toMatchObject({ ok: true, value: { ok: true } }) + expect(res).toMatchObject({ ok: true, value: { ok: true, savedPath: '/tmp/out/codeburn-export-2026-09-19' } }) + }) + }) + + it('reports the JSON export path the CLI chose, extension and all', async () => { + await withFilterFile(async () => { + // JSON lands inside the picked folder too, as a dated file. + const spawnCliAction = vi.fn(async () => ({ ok: true, stdout: '\n Exported (Today + 7 Days + 30 Days) to: /tmp/out/codeburn-export-2026-09-19.json\n', stderr: '', code: 0 })) + const handlers = createBridgeHandlers(deps({ spawnCli: vi.fn(), spawnCliAction, resolveCodeburnPath: () => '/bin/codeburn' })) + const res = await handlers['codeburn:exportData']!('json', 'all', '/tmp/out') + expect(res).toMatchObject({ ok: true, value: { ok: true, savedPath: '/tmp/out/codeburn-export-2026-09-19.json' } }) }) }) diff --git a/app/electron/main.ts b/app/electron/main.ts index 4d9c2303..162e8c39 100644 --- a/app/electron/main.ts +++ b/app/electron/main.ts @@ -1,12 +1,13 @@ -import { app, BrowserWindow, dialog, ipcMain, Menu, nativeTheme, shell, type MenuItemConstructorOptions } from 'electron' +import { app, BrowserWindow, dialog, ipcMain, Menu, nativeTheme, powerMonitor, shell, type MenuItemConstructorOptions } from 'electron' import { randomBytes } from 'node:crypto' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import { CliError, DESKTOP_COLD_TIMEOUT_MS, PROGRESS_LINE_PREFIX, reapOrphanServe, resolveCodeburnPath, shutdownAll, spawnCli, spawnCliAction, startServe, type ActionResult, type SpawnPriority } from './cli' +import { CliError, DESKTOP_COLD_TIMEOUT_MS, PROGRESS_LINE_PREFIX, reapOrphanServe, resolveCodeburnPath, serveUsage, shutdownAll, spawnCli, spawnCliAction, startServe, type ActionResult, type SpawnPriority } from './cli' import { MenubarCompanion, readDockEnabled, STARTUP_APPS_SETTINGS_URL, type CompanionStatus } from './menubar' import { MacMenubar, NO_MAC_MENUBAR, type InstallPhase } from './mac-menubar' +import { readOptimizeSnapshot, sameLocalDay, writeOptimizeSnapshot, type OptimizeBlock, type OptimizeSnapshot } from './optimize-store' import { getQuota, sanitizeError } from './quota' import { Telemetry } from './telemetry' import { createUpdateChecker, type UpdateChecker, type UpdateStatus } from './updates' @@ -482,6 +483,13 @@ type Deps = { > | null /** The macOS menubar app, as the Plugins page sees it; absent off darwin and under tests. */ macMenubar?: Pick | null + /** Where the daily optimize scan is cached (app userData). Absent = no cache. */ + stateDir?: string + /** Stamped into a cached scan so a build whose finding shapes changed never + * reads the previous build's cache. */ + appVersion?: string + /** Electron's powerMonitor, for the on-battery live cadence. */ + isOnBatteryPower?: () => boolean } type Handler = (...args: any[]) => Promise @@ -498,9 +506,24 @@ type Handler = (...args: any[]) => Promise * cannot tell the two apart. */ const EXPORT_SAVED_MARKER = 'Exported (' +const EXPORT_PATH_SEPARATOR = ') to: ' const EXPORT_NOTHING_WRITTEN = 'Nothing to export: no usage in the export window, or the project filter hides all of it.' -export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, resolveCodeburnPath, getQuota, emitProgress: broadcastProgress, telemetry: telemetryInstance, getUpdateStatus: () => updateChecker ? updateChecker.getStatus() : Promise.resolve(NO_UPDATE_STATUS), companion: companion, macMenubar: macMenubar }): Record { +/** The path the CLI actually wrote, which is not the destination the user picked: inside + * the chosen folder an export is a dated folder (CSV) or a dated file (JSON). */ +export function exportedPath(stdout: string): string | null { + for (const line of stdout.split('\n')) { + const marker = line.indexOf(EXPORT_SAVED_MARKER) + if (marker < 0) continue + const sep = line.indexOf(EXPORT_PATH_SEPARATOR, marker) + if (sep < 0) continue + const saved = line.slice(sep + EXPORT_PATH_SEPARATOR.length).trim() + if (saved) return saved + } + return null +} + +export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, resolveCodeburnPath, getQuota, emitProgress: broadcastProgress, telemetry: telemetryInstance, getUpdateStatus: () => updateChecker ? updateChecker.getStatus() : Promise.resolve(NO_UPDATE_STATUS), companion: companion, macMenubar: macMenubar, stateDir: app.getPath('userData'), appVersion: app.getVersion(), isOnBatteryPower: () => powerMonitor.isOnBatteryPower() }): Record { const emitProgress = deps.emitProgress ?? (() => {}) const telemetry = deps.telemetry ?? null // Flips true after the first overview fetch succeeds. Until then, every @@ -574,18 +597,69 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re // A project filter cannot be dropped the same way: the hidden projects would // come back inside the combined total. The renderer already picks local while // a filter is set; this keeps a stale caller off the rejected argv. - const buildOverviewArgs = (period: string, provider: string, range?: DateRange, configSource?: string | null, scope?: string): string[] => { + // + // The optimize scan is OFF this argv (`--no-optimize`): it is the one part of + // the payload that reads mutable project files, so it defeats the snapshot + // fast path (src/main.ts `useSnapshot = !queryScope.optimize`) and costs a + // fresh ~0.2s scan on every poll. The three figures the UI takes from it come + // from the once-a-day cache below (`codeburn:getOptimizeSnapshot`), which + // runs this same argv WITHOUT the flag, so no displayed number changes value. + const buildOverviewArgs = (period: string, provider: string, range?: DateRange, configSource?: string | null, scope?: string, optimize = false): string[] => { const vScopeValue = vScope(scope) const filterArgs = projectArgs() const combined = vScopeValue === 'combined' && filterArgs.length === 0 return [ 'status', '--format', 'menubar-json', '--period', vPeriod(period), '--no-timeline', + ...(optimize ? [] : ['--no-optimize']), ...(combined ? ['--scope', 'combined'] : providerArgs(vProvider(provider))), ...filterArgs, ...rangeArgs(vRange(range)), ...configSourceArgs(vConfigSource(configSource)), ] } + // The optimize scan is a DAILY figure: recomputed when nothing is cached for + // this scope, when the cache is older than `maxAgeMs` (24h by default) OR was + // computed on an earlier local day, or when the renderer forces it (the + // Optimize page, manual refresh). Never on a poll tick. The cache key is the + // full argv, so a period/provider/project/config/scope change is a different + // entry and one scope's savings can never be served for another. + // + // The same-day rule is what makes the key honest: the key says + // `--period today` (or week/30days/month), which names a window anchored to + // the LOCAL day, not a fixed date. Without it a scan taken at 23:50 would be + // served at 00:10 as today's, and every rolling window would be a day stale. + const OPTIMIZE_MAX_AGE_MS = 24 * 60 * 60 * 1000 + const getOptimizeSnapshot: Handler = async (period: string, provider: string, range?: DateRange, configSource?: string | null, scope?: string, maxAgeMs?: number) => { + const argv = buildOverviewArgs(period, provider, range, configSource, scope, true) + const key = argv.join(' ') + const appVersion = deps.appVersion ?? '0' + const maxAge = typeof maxAgeMs === 'number' && maxAgeMs >= 0 ? maxAgeMs : OPTIMIZE_MAX_AGE_MS + if (deps.stateDir) { + const cached = readOptimizeSnapshot(deps.stateDir, key, appVersion) + // An unparseable computedAt yields NaN, which fails both tests and + // recomputes — the safe direction. + const computedAt = cached ? Date.parse(cached.computedAt) : NaN + const now = Date.now() + if (cached && now - computedAt < maxAge && sameLocalDay(computedAt, now)) return { ok: true, value: cached } + } + try { + // Background priority: this must never take a CLI slot from the live + // headline poll or a click. + const payload = await deps.spawnCli(argv, { ...(readOpts() ?? {}), priority: 'background' }) + const optimize = (payload as { optimize?: OptimizeBlock } | null)?.optimize + if (!optimize || !Array.isArray(optimize.topFindings)) { + return { ok: false, error: { kind: 'nonzero', message: 'No optimize findings in the payload.' } } + } + const snapshot: OptimizeSnapshot = { scope: key, computedAt: new Date().toISOString(), appVersion, optimize } + if (deps.stateDir) writeOptimizeSnapshot(deps.stateDir, snapshot) + return { ok: true, value: snapshot } + } catch (err) { + const error = coldError(err) + telemetry?.track('cli_error', cliErrorProps(err, 'status')) + return { ok: false, error } + } + } + // `background` (renderer prefetch only) drops this fetch to background priority // so it yields the CLI's run slots to any interactive poll or click. Optional // and defaulting to interactive, so an older preload that omits it is unchanged. @@ -627,6 +701,11 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re catch (error) { return { ok: false, error: { kind: 'nonzero', message: sanitizeError(error) } } } }, 'codeburn:getOverview': getOverview, + 'codeburn:getOptimizeSnapshot': getOptimizeSnapshot, + 'codeburn:powerStatus': async () => { + try { return { ok: true, value: deps.isOnBatteryPower ? deps.isOnBatteryPower() : false } } + catch { return { ok: true, value: false } } + }, // Timeline variant for the Spend punchcard only: identical payload WITH // history.timeline (every other fetch keeps --no-timeline lean). 'codeburn:getTimeline': run((period: string, provider: string, range?: DateRange) => [ @@ -798,10 +877,11 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re 'export', '-f', vToken(format), '-o', vOutPath(outPath), '--provider', vProvider(provider), ...projectArgs(), ]) - if (result.ok && !result.stdout.includes(EXPORT_SAVED_MARKER)) { + const savedPath = exportedPath(result.stdout) + if (result.ok && savedPath === null) { return { ok: true, value: { ...result, ok: false, stderr: EXPORT_NOTHING_WRITTEN } } } - return { ok: true, value: { ...result, stderr: sanitizeError(result.stderr) } } + return { ok: true, value: { ...result, stderr: sanitizeError(result.stderr), ...(savedPath ? { savedPath } : {}) } } } catch (err) { return { ok: false, error: toEnvelopeError(err) } } @@ -1092,6 +1172,8 @@ function bootstrap(): void { country: app.getLocaleCountryCode() || null, isPackaged: app.isPackaged, appVersion: app.getVersion(), + getAppMetrics: () => app.getAppMetrics(), + getServeUsage: serveUsage, }) // completeOnboarding tracks the first app_open itself; only already- // onboarded installs record subsequent opens here. app_open carries the @@ -1100,7 +1182,10 @@ function bootstrap(): void { const dockPref = readDockEnabled() telemetryInstance.track('app_open', { dock: dockPref === undefined ? 'none' : dockPref ? 'on' : 'off' }) } - setInterval(() => { void telemetryInstance?.flush() }, 5 * 60_000) + setInterval(() => { + telemetryInstance?.sampleResources() + void telemetryInstance?.flush() + }, 5 * 60_000) } catch (err) { console.error('telemetry init failed (continuing without):', err) } @@ -1137,6 +1222,16 @@ function bootstrap(): void { }, }) registerHandlers() + // Power source, pushed to the renderer so the live cadence halves on + // battery and restores on AC. + const broadcastPower = () => { + const onBattery = powerMonitor.isOnBatteryPower() + for (const win of BrowserWindow.getAllWindows()) { + if (!win.isDestroyed()) win.webContents.send('codeburn:power', onBattery) + } + } + powerMonitor.on('on-battery', broadcastPower) + powerMonitor.on('on-ac', broadcastPower) installApplicationMenu() // Seed the preload-readable app locale before any window loads. app.getLocale() // needs the ready state, so this runs inside bootstrap's whenReady. diff --git a/app/electron/optimize-store.test.ts b/app/electron/optimize-store.test.ts new file mode 100644 index 00000000..68e7b817 --- /dev/null +++ b/app/electron/optimize-store.test.ts @@ -0,0 +1,245 @@ +// @vitest-environment node +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +// Stub electron so importing main.ts does not require an Electron runtime. +vi.mock('electron', () => ({ + app: { name: 'CodeBurn', whenReady: () => Promise.resolve(), on: () => {}, quit: () => {} }, + BrowserWindow: class {}, + dialog: { showOpenDialog: vi.fn() }, + ipcMain: { handle: () => {} }, + Menu: { buildFromTemplate: (template: unknown) => template, setApplicationMenu: () => {} }, + shell: { openExternal: vi.fn() }, +})) + +import { createBridgeHandlers } from './main' +import { readOptimizeSnapshots, readOptimizeSnapshot, sameLocalDay, writeOptimizeSnapshot, type OptimizeSnapshot } from './optimize-store' + +const DAY_MS = 24 * 60 * 60 * 1000 +const STORE = 'optimize-snapshots.json' + +const dirs: string[] = [] +function tempDir(): string { + const dir = mkdtempSync(join(tmpdir(), 'codeburn-optimize-')) + dirs.push(dir) + return dir +} +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) + vi.useRealTimers() +}) + +function block(savingsUSD: number) { + return { findingCount: 1, savingsUSD, topFindings: [{ title: 'Trim preamble', impact: 'high' as const, savingsUSD }] } +} + +function handlers(stateDir: string, payloadSavings = 12) { + const calls: string[][] = [] + const spawnCli = vi.fn(async (args: string[]) => { + calls.push(args) + return { optimize: block(payloadSavings) } + }) + const bridge = createBridgeHandlers({ + spawnCli, + spawnCliAction: vi.fn(), + resolveCodeburnPath: () => '/usr/local/bin/codeburn', + getQuota: vi.fn(), + stateDir, + appVersion: '1.2.3', + } as unknown as Parameters[0]) + return { snapshot: bridge['codeburn:getOptimizeSnapshot']!, calls } +} + +describe('optimize snapshot store', () => { + it('computes with optimize ON (the poll argv runs --no-optimize) and writes the result', async () => { + const dir = tempDir() + const { snapshot, calls } = handlers(dir) + + const res = await snapshot('today', 'all') as { ok: true; value: OptimizeSnapshot } + + expect(res.ok).toBe(true) + expect(calls[0]).not.toContain('--no-optimize') + expect(calls[0]).toEqual(['status', '--format', 'menubar-json', '--period', 'today', '--no-timeline']) + expect(res.value.optimize.savingsUSD).toBe(12) + expect(res.value.appVersion).toBe('1.2.3') + // Persisted for the next launch, keyed by the argv it was computed for. + const stored = JSON.parse(readFileSync(join(dir, STORE), 'utf8')) as OptimizeSnapshot[] + expect(stored).toHaveLength(1) + expect(stored[0]!.scope).toBe(calls[0]!.join(' ')) + }) + + it('serves a stored result younger than a day without spawning', async () => { + const dir = tempDir() + const first = handlers(dir) + const written = await first.snapshot('today', 'all') as { value: OptimizeSnapshot } + + const second = handlers(dir, 99) + const res = await second.snapshot('today', 'all') as { ok: true; value: OptimizeSnapshot } + + expect(second.calls).toHaveLength(0) + expect(res.value.computedAt).toBe(written.value.computedAt) + expect(res.value.optimize.savingsUSD).toBe(12) + }) + + it('recomputes a stored result older than a day', async () => { + const dir = tempDir() + writeOptimizeSnapshot(dir, { + scope: ['status', '--format', 'menubar-json', '--period', 'today', '--no-timeline'].join(' '), + computedAt: new Date(Date.now() - DAY_MS - 60_000).toISOString(), + appVersion: '1.2.3', + optimize: block(5), + }) + + const { snapshot, calls } = handlers(dir, 42) + const res = await snapshot('today', 'all') as { value: OptimizeSnapshot } + + expect(calls).toHaveLength(1) + expect(res.value.optimize.savingsUSD).toBe(42) + }) + + it('recomputes on demand (maxAgeMs 0) even with a fresh stored result', async () => { + const dir = tempDir() + const first = handlers(dir) + await first.snapshot('today', 'all') + + const second = handlers(dir, 77) + const res = await second.snapshot('today', 'all', undefined, null, undefined, 0) as { value: OptimizeSnapshot } + + expect(second.calls).toHaveLength(1) + expect(res.value.optimize.savingsUSD).toBe(77) + }) + + it("never serves one scope's savings for another", async () => { + const dir = tempDir() + const today = handlers(dir, 12) + await today.snapshot('today', 'all') + + // Different period, different provider, different config source: each is a + // distinct scope, so each recomputes instead of reading the other's figure. + for (const args of [['week', 'all'], ['today', 'claude'], ['today', 'all', undefined, 'claude-config:abc']]) { + const other = handlers(dir, 500) + const res = await other.snapshot(...args) as { value: OptimizeSnapshot } + expect(other.calls).toHaveLength(1) + expect(res.value.optimize.savingsUSD).toBe(500) + } + + // The original scope is still served from disk, unchanged. + const again = handlers(dir, 999) + const res = await again.snapshot('today', 'all') as { value: OptimizeSnapshot } + expect(again.calls).toHaveLength(0) + expect(res.value.optimize.savingsUSD).toBe(12) + }) + + it('recomputes across local midnight even though the scan is minutes old', async () => { + const dir = tempDir() + vi.useFakeTimers() + // 23:50 local. The argv says `--period today`, which names a window that + // moves at midnight, so age alone is not freshness. + vi.setSystemTime(new Date(2026, 8, 18, 23, 50, 0)) + const evening = handlers(dir, 12) + await evening.snapshot('today', 'all') + expect(evening.calls).toHaveLength(1) + + // 00:10 the next day: 20 minutes old, well inside the 24h bound, but a + // different local day → recompute. + vi.setSystemTime(new Date(2026, 8, 19, 0, 10, 0)) + const after = handlers(dir, 42) + const res = await after.snapshot('today', 'all') as { value: OptimizeSnapshot } + expect(after.calls).toHaveLength(1) + expect(res.value.optimize.savingsUSD).toBe(42) + + // Later the same day the fresh scan is reused, no spawn. + vi.setSystemTime(new Date(2026, 8, 19, 9, 30, 0)) + const sameDay = handlers(dir, 999) + const reused = await sameDay.snapshot('today', 'all') as { value: OptimizeSnapshot } + expect(sameDay.calls).toHaveLength(0) + expect(reused.value.optimize.savingsUSD).toBe(42) + }) + + it('applies the same-day rule to rolling windows and pinned custom ranges alike', async () => { + vi.useFakeTimers() + vi.setSystemTime(new Date(2026, 8, 18, 23, 50, 0)) + for (const args of [['week', 'all'], ['30days', 'all'], ['month', 'all'], ['today', 'all', { from: '2026-09-01', to: '2026-09-18' }]]) { + const dir = tempDir() + const evening = handlers(dir, 12) + await evening.snapshot(...args) + vi.setSystemTime(new Date(2026, 8, 19, 0, 10, 0)) + const after = handlers(dir, 42) + const res = await after.snapshot(...args) as { value: OptimizeSnapshot } + expect(after.calls).toHaveLength(1) + expect(res.value.optimize.savingsUSD).toBe(42) + vi.setSystemTime(new Date(2026, 8, 18, 23, 50, 0)) + } + }) + + it('sameLocalDay compares calendar days, not elapsed time', () => { + const lateNight = new Date(2026, 8, 18, 23, 50).getTime() + expect(sameLocalDay(lateNight, new Date(2026, 8, 18, 0, 1).getTime())).toBe(true) + expect(sameLocalDay(lateNight, new Date(2026, 8, 19, 0, 10).getTime())).toBe(false) + expect(sameLocalDay(lateNight, new Date(2025, 8, 18, 23, 50).getTime())).toBe(false) + expect(sameLocalDay(lateNight, NaN)).toBe(false) + }) + + it('drops rows from other app versions on write instead of letting them fill the cap', () => { + const dir = tempDir() + for (let i = 0; i < 8; i++) { + writeOptimizeSnapshot(dir, { + scope: `old-${i}`, + computedAt: new Date().toISOString(), + appVersion: '0.0.1', + optimize: block(i), + }) + } + expect(readOptimizeSnapshots(dir)).toHaveLength(8) + + writeOptimizeSnapshot(dir, { + scope: 'current', + computedAt: new Date().toISOString(), + appVersion: '1.2.3', + optimize: block(7), + }) + + // The unservable rows are gone, so the cap belongs to rows that can be used. + const rows = readOptimizeSnapshots(dir) + expect(rows).toHaveLength(1) + expect(rows[0]!.scope).toBe('current') + }) + + it('ignores a store written by a different app version', async () => { + const dir = tempDir() + writeOptimizeSnapshot(dir, { + scope: ['status', '--format', 'menubar-json', '--period', 'today', '--no-timeline'].join(' '), + computedAt: new Date().toISOString(), + appVersion: '0.0.1', + optimize: block(5), + }) + + const { snapshot, calls } = handlers(dir, 42) + const res = await snapshot('today', 'all') as { value: OptimizeSnapshot } + + expect(calls).toHaveLength(1) + expect(res.value.optimize.savingsUSD).toBe(42) + }) + + it('ignores a corrupt or truncated store file instead of throwing', async () => { + const dir = tempDir() + writeFileSync(join(dir, STORE), '{"scope": "today", trunc', 'utf8') + expect(readOptimizeSnapshot(dir, 'anything', '1.2.3')).toBeNull() + + const { snapshot, calls } = handlers(dir, 42) + const res = await snapshot('today', 'all') as { ok: true; value: OptimizeSnapshot } + + expect(res.ok).toBe(true) + expect(calls).toHaveLength(1) + // The corrupt file is replaced by a valid one. + expect(readOptimizeSnapshot(dir, calls[0]!.join(' '), '1.2.3')?.optimize.savingsUSD).toBe(42) + }) + + it('drops rows that are not snapshots rather than serving them', () => { + const dir = tempDir() + writeFileSync(join(dir, STORE), JSON.stringify([{ scope: 's', computedAt: 'x' }, 7, null]), 'utf8') + expect(readOptimizeSnapshot(dir, 's', '1.2.3')).toBeNull() + }) +}) diff --git a/app/electron/optimize-store.ts b/app/electron/optimize-store.ts new file mode 100644 index 00000000..469dbe73 --- /dev/null +++ b/app/electron/optimize-store.ts @@ -0,0 +1,93 @@ +import fs from 'node:fs' +import path from 'node:path' + +/** The `optimize` block of a menubar-json payload — the only part of the scan + * the Overview and Optimize pages read. */ +export type OptimizeBlock = { + findingCount: number + savingsUSD: number + topFindings: Array<{ title: string; impact: 'high' | 'medium' | 'low'; savingsUSD: number }> +} + +export type OptimizeSnapshot = { + /** The exact argv this scan was computed for (period, provider, project + * filter, config source, scope). A result is only ever served back for the + * identical scope, so one period's savings can never surface under another. */ + scope: string + computedAt: string + appVersion: string + optimize: OptimizeBlock +} + +const FILE = 'optimize-snapshots.json' +// A handful of scopes (the period picker, a provider switch) is all a user +// cycles through; past that the oldest entry is dropped. +const MAX_ENTRIES = 8 + +function storePath(dir: string): string { + return path.join(dir, FILE) +} + +function isSnapshot(value: unknown): value is OptimizeSnapshot { + if (!value || typeof value !== 'object') return false + const row = value as Partial + const block = row.optimize as Partial | undefined + return typeof row.scope === 'string' + && typeof row.computedAt === 'string' + && typeof row.appVersion === 'string' + && !!block + && typeof block.findingCount === 'number' + && typeof block.savingsUSD === 'number' + && Array.isArray(block.topFindings) +} + +/** + * Whether two instants fall on the same LOCAL calendar day. + * + * Age alone is not freshness here. Every period the scan is computed for + * ('today', 'week', '30days', 'month', …) is anchored to the local day, so a + * scan taken at 23:50 describes a different window than a request at 00:10 even + * though it is 20 minutes old. A cached scan is only ever served on the day it + * was computed. + */ +export function sameLocalDay(a: number, b: number): boolean { + const left = new Date(a) + const right = new Date(b) + return left.getFullYear() === right.getFullYear() + && left.getMonth() === right.getMonth() + && left.getDate() === right.getDate() +} + +/** Every stored scan, newest first. A missing, unreadable or corrupt file reads + * as empty: the caller then recomputes, which is always safe. */ +export function readOptimizeSnapshots(dir: string): OptimizeSnapshot[] { + try { + const parsed: unknown = JSON.parse(fs.readFileSync(storePath(dir), 'utf8')) + return Array.isArray(parsed) ? parsed.filter(isSnapshot) : [] + } catch { + return [] + } +} + +/** The stored scan for exactly this scope and app version, or null. */ +export function readOptimizeSnapshot(dir: string, scope: string, appVersion: string): OptimizeSnapshot | null { + return readOptimizeSnapshots(dir).find(row => row.scope === scope && row.appVersion === appVersion) ?? null +} + +export function writeOptimizeSnapshot(dir: string, snapshot: OptimizeSnapshot): void { + try { + // A row from another app version can never be served, so it only takes up a + // slot under the cap. Drop those before capping. + const rows = [snapshot, ...readOptimizeSnapshots(dir) + .filter(row => row.scope !== snapshot.scope && row.appVersion === snapshot.appVersion)] + .slice(0, MAX_ENTRIES) + fs.mkdirSync(dir, { recursive: true }) + const target = storePath(dir) + const tmp = `${target}.tmp` + fs.writeFileSync(tmp, JSON.stringify(rows), 'utf8') + fs.renameSync(tmp, target) + } catch { + // A cache that cannot be written is not an error the user needs: the next + // open recomputes. + } +} diff --git a/app/electron/preload.ts b/app/electron/preload.ts index 59907ee6..e28b68f0 100644 --- a/app/electron/preload.ts +++ b/app/electron/preload.ts @@ -44,6 +44,17 @@ const bridge = { getSpendFlow: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getSpendFlow', period, provider, range, background), getBranchSpend: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getBranchSpend', period, provider, range, background), getOptimizeReport: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getOptimizeReport', period, provider, range, background), + // The once-a-day optimize scan, cached on disk per query scope. `maxAgeMs` 0 + // forces a recompute (Optimize page, manual refresh). + getOptimizeSnapshot: (period: string, provider: string, range?: DateRange, configSource?: string | null, scope?: string, maxAgeMs?: number) => + invoke('codeburn:getOptimizeSnapshot', period, provider, range, configSource, scope, maxAgeMs), + // Power source for the battery-aware live cadence: one read plus a push. + powerStatus: () => invoke('codeburn:powerStatus'), + onPowerStatus: (cb: (onBattery: boolean) => void) => { + const listener = (_e: unknown, onBattery: boolean) => cb(onBattery) + ipcRenderer.on('codeburn:power', listener) + return () => { ipcRenderer.removeListener('codeburn:power', listener) } + }, getDevices: (period: string) => invoke('codeburn:getDevices', period), getDevicesScan: () => invoke('codeburn:getDevicesScan'), getShareStatus: () => invoke('codeburn:getShareStatus'), diff --git a/app/electron/telemetry.test.ts b/app/electron/telemetry.test.ts index 305ac314..91461f80 100644 --- a/app/electron/telemetry.test.ts +++ b/app/electron/telemetry.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { defaultEnabledFor, Telemetry } from './telemetry' +import { cpuBucket, defaultEnabledFor, memBucket, Telemetry } from './telemetry' let dir: string @@ -298,3 +298,106 @@ describe('events', () => { expect(Array.isArray(body.events)).toBe(true) }) }) + +describe('resource usage buckets', () => { + it('places every CPU boundary in the higher bucket', () => { + expect(cpuBucket(0)).toBe('<1') + expect(cpuBucket(0.99)).toBe('<1') + expect(cpuBucket(1)).toBe('1-5') + expect(cpuBucket(4.99)).toBe('1-5') + expect(cpuBucket(5)).toBe('5-15') + expect(cpuBucket(14.99)).toBe('5-15') + expect(cpuBucket(15)).toBe('15-40') + expect(cpuBucket(39.99)).toBe('15-40') + expect(cpuBucket(40)).toBe('40+') + expect(cpuBucket(1200)).toBe('40+') + // Unmeasurable reads as the lowest bucket, never as a thrown close. + expect(cpuBucket(Number.NaN)).toBe('<1') + expect(cpuBucket(-5)).toBe('<1') + }) + + it('places every memory boundary in the higher bucket', () => { + expect(memBucket(0)).toBe('<250') + expect(memBucket(249.9)).toBe('<250') + expect(memBucket(250)).toBe('250-500') + expect(memBucket(499.9)).toBe('250-500') + expect(memBucket(500)).toBe('500-1k') + expect(memBucket(999.9)).toBe('500-1k') + expect(memBucket(1000)).toBe('1-3k') + expect(memBucket(2999.9)).toBe('1-3k') + expect(memBucket(3000)).toBe('3k+') + expect(memBucket(Number.NaN)).toBe('<250') + }) +}) + +describe('app_close resource usage', () => { + const SESSION_MS = 10 * 60_000 + const OPENED_AT = Date.parse('2026-09-19T09:00:00Z') + /// Both counters are cumulative since their own process started, so the mocks below grow + /// with the clock and carry a head start from before telemetry was constructed. + const elapsedSec = () => (Date.now() - OPENED_AT) / 1000 + + afterEach(() => { vi.useRealTimers() }) + + async function closeWith(over: Partial[0]>, sample = false, sessionMs = SESSION_MS) { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-09-19T09:00:00Z')) + const { telemetry, posts } = make(over) + telemetry.completeOnboarding(true) + vi.setSystemTime(new Date(Date.now() + sessionMs)) + if (sample) telemetry.sampleResources() + telemetry.trackClose() + await telemetry.flush() + const body = posts[0]!.body as { events: Array<{ name: string; props: Record }> } + return body.events.find(event => event.name === 'app_close')!.props + } + + it('carries app and serve buckets when both report metrics', async () => { + const props = await closeWith({ + // 30 CPU-seconds over a 600s session is 5% of one core; 600MB of working set. The + // 400 and 100 already on the clocks belong to the time before this session. + getAppMetrics: () => [ + { cpu: { cumulativeCPUUsage: 400 + elapsedSec() * 0.03, percentCPUUsage: 0 }, memory: { workingSetSize: 400 * 1024 } }, + { cpu: { cumulativeCPUUsage: 100 + elapsedSec() * 0.02, percentCPUUsage: 0 }, memory: { workingSetSize: 200 * 1024 } }, + ], + getServeUsage: () => ({ cpuSec: 900 + elapsedSec() * 0.2, rssMb: 1200 }), + }) + expect(props).toEqual({ sessionMinutes: 10, cpu: '5-15', mem: '500-1k', serveCpu: '15-40', serveMem: '1-3k' }) + }) + + // The counters run from each process's own start, the wall clock from telemetry's: a + // desktop app that had been open for hours read as pinned CPU for a session that did + // nothing at all. + it('reports the CPU spent during the session, not what was already on the clock', async () => { + const props = await closeWith({ + getAppMetrics: () => [{ cpu: { cumulativeCPUUsage: 500, percentCPUUsage: 0 }, memory: { workingSetSize: 300 * 1024 } }], + getServeUsage: () => ({ cpuSec: 900, rssMb: 300 }), + }) + expect(props).toMatchObject({ cpu: '<1', serveCpu: '<1' }) + }) + + it('averages sampled percentages when the platform reports no cumulative CPU', async () => { + const props = await closeWith({ + getAppMetrics: () => [{ cpu: { percentCPUUsage: 8 }, memory: { workingSetSize: 300 * 1024 } }], + getServeUsage: () => null, + }, true) + expect(props).toMatchObject({ cpu: '5-15', mem: '250-500' }) + expect(props.serveCpu).toBeUndefined() + expect(props.serveMem).toBeUndefined() + }) + + // CPU seconds count from process start, the wall clock from telemetry init, so a + // ten-second session read '40+' however idle the app was. Memory is unaffected. + it('omits both CPU figures on a session too short to divide by', async () => { + const props = await closeWith({ + getAppMetrics: () => [{ cpu: { cumulativeCPUUsage: 20, percentCPUUsage: 0 }, memory: { workingSetSize: 400 * 1024 } }], + getServeUsage: () => ({ cpuSec: 120, rssMb: 1200 }), + }, false, 10_000) + expect(props).toEqual({ sessionMinutes: 0, mem: '250-500', serveMem: '1-3k' }) + }) + + it('omits every field it could not measure rather than sending zeros', async () => { + const props = await closeWith({}) + expect(props).toEqual({ sessionMinutes: 10 }) + }) +}) diff --git a/app/electron/telemetry.ts b/app/electron/telemetry.ts index fbf82022..e14def53 100644 --- a/app/electron/telemetry.ts +++ b/app/electron/telemetry.ts @@ -38,6 +38,28 @@ export function defaultEnabledFor(country: string | null | undefined): boolean { return !DEFAULT_OFF_COUNTRIES.has(country.toUpperCase()) } +/// Average CPU of the app over a session, as a percent of one core. Coarse +/// enough that a session is never recognisable from it; the point is only +/// whether a build runs light, warm or hot. +/// Buckets: `<1`, `1-5`, `5-15`, `15-40`, `40+`. +export function cpuBucket(percent: number): string { + if (!Number.isFinite(percent) || percent < 1) return '<1' + if (percent < 5) return '1-5' + if (percent < 15) return '5-15' + if (percent < 40) return '15-40' + return '40+' +} + +/// Peak resident memory in MB, same treatment. +/// Buckets: `<250`, `250-500`, `500-1k`, `1-3k`, `3k+`. +export function memBucket(mb: number): string { + if (!Number.isFinite(mb) || mb < 250) return '<250' + if (mb < 500) return '250-500' + if (mb < 1000) return '500-1k' + if (mb < 3000) return '1-3k' + return '3k+' +} + export const EVENT_NAMES = new Set([ 'app_open', 'app_close', @@ -54,6 +76,11 @@ export const EVENT_NAMES = new Set([ 'settings_change', ]) +/// A few seconds of wall time is too short a base for a percent: one burst of startup work +/// lands the whole session in a top bucket that says nothing about how the build runs. Under +/// the floor the figure is omitted rather than sent as noise. +const MIN_CPU_WALL_SECONDS = 30 + const MAX_QUEUE = 200 const MAX_CLI_ERRORS_PER_KIND_PER_DAY = 20 const MAX_STRING = 64 @@ -86,6 +113,14 @@ type PersistedState = { cliErrorCounts?: Record } +/** The slice of Electron's ProcessMetric this module reads. Injected, because + * telemetry.ts must not import electron. workingSetSize is in KB, + * cumulativeCPUUsage in seconds of CPU time. */ +export type ProcessMetricSample = { + cpu?: { percentCPUUsage?: number; cumulativeCPUUsage?: number } + memory?: { workingSetSize?: number } +} + type Deps = { /** Directory for the consent/state file (Electron userData in production). */ stateDir: string @@ -99,6 +134,11 @@ type Deps = { endpoint?: string fetchFn?: typeof fetch now?: () => Date + /** Electron `app.getAppMetrics()`. Covers the Electron processes only. */ + getAppMetrics?: () => ProcessMetricSample[] + /** The resident `codeburn serve` child's own totals (app/electron/cli.ts), + * which getAppMetrics cannot see. Null while it has not answered. */ + getServeUsage?: () => { cpuSec: number; rssMb: number } | null } type QueuedEvent = { name: string; day: string; props: Record } @@ -171,11 +211,22 @@ export class Telemetry { private state: PersistedState private queue: QueuedEvent[] = [] private openedAt: number + /** Total CPU seconds across the Electron processes, when the platform reports + * it cumulatively. Null on a build that only reports instantaneous percent. */ + private cpuSeconds: number | null = null + /** What the counters already stood at when this session's clock started. Both are + * cumulative since their process began, and the wall time below is measured from here, + * so only the growth since this point can be divided by it. */ + private cpuSecondsAtOpen: number | null = null + private serveCpuSecAtOpen: number | null = null + private cpuPercentSamples: number[] = [] + private peakMemMb = 0 constructor(deps: Deps) { this.deps = deps this.state = this.load() this.openedAt = Date.now() + this.sampleResources() } private stateFile(): string { @@ -273,9 +324,75 @@ export class Telemetry { this.queue.push({ name, day, props: sanitizedProps }) } - /** Record session duration; queued for the next (final) flush. */ + /** One cheap read of how heavy this app run is. Called on the existing flush + * beat and once at close, never on a timer of its own. */ + sampleResources(): void { + try { + let cumulativeSec = 0 + let hasCumulative = false + let percent = 0 + let hasPercent = false + let workingSetKb = 0 + for (const metric of this.deps.getAppMetrics?.() ?? []) { + const cumulative = metric.cpu?.cumulativeCPUUsage + if (typeof cumulative === 'number' && Number.isFinite(cumulative)) { + cumulativeSec += cumulative + hasCumulative = true + } + const share = metric.cpu?.percentCPUUsage + if (typeof share === 'number' && Number.isFinite(share)) { + percent += share + hasPercent = true + } + const workingSet = metric.memory?.workingSetSize + if (typeof workingSet === 'number' && Number.isFinite(workingSet)) workingSetKb += workingSet + } + if (hasCumulative) { + this.cpuSeconds = cumulativeSec + this.cpuSecondsAtOpen ??= cumulativeSec + } else if (hasPercent) this.cpuPercentSamples.push(percent) + this.peakMemMb = Math.max(this.peakMemMb, workingSetKb / 1024) + // Sampled here, not at close, because close is the only place the figure is read and + // a baseline taken then would be the reading itself. A serve child that restarted + // counts from zero again, so a reading below the baseline rebases to it. + const serveCpuSec = this.deps.getServeUsage?.()?.cpuSec + if (typeof serveCpuSec === 'number' && Number.isFinite(serveCpuSec)) { + if (this.serveCpuSecAtOpen === null || serveCpuSec < this.serveCpuSecAtOpen) this.serveCpuSecAtOpen = serveCpuSec + } + } catch { /* resource metrics are never worth a thrown quit */ } + } + + /** Bucket labels only: how much CPU and memory this run cost, in the app and + * in the serve child that does the parsing. A figure we could not measure is + * omitted rather than sent as a zero, which would read as "free". */ + private resourceProps(): Record { + const props: Record = {} + try { + this.sampleResources() + const wallSeconds = (Date.now() - this.openedAt) / 1000 + const cpuMeasurable = wallSeconds >= MIN_CPU_WALL_SECONDS + if (cpuMeasurable) { + if (this.cpuSeconds !== null && this.cpuSecondsAtOpen !== null) { + props.cpu = cpuBucket(((this.cpuSeconds - this.cpuSecondsAtOpen) / wallSeconds) * 100) + } else if (this.cpuPercentSamples.length > 0) { + props.cpu = cpuBucket(this.cpuPercentSamples.reduce((a, b) => a + b, 0) / this.cpuPercentSamples.length) + } + } + if (this.peakMemMb > 0) props.mem = memBucket(this.peakMemMb) + const serve = this.deps.getServeUsage?.() ?? null + if (serve) { + if (cpuMeasurable && Number.isFinite(serve.cpuSec)) { + props.serveCpu = cpuBucket(((serve.cpuSec - (this.serveCpuSecAtOpen ?? serve.cpuSec)) / wallSeconds) * 100) + } + if (serve.rssMb > 0) props.serveMem = memBucket(serve.rssMb) + } + } catch { /* best effort: a partial answer beats none, and none beats a throw */ } + return props + } + + /** Record session duration and resource cost; queued for the next (final) flush. */ trackClose(): void { - this.track('app_close', { sessionMinutes: Math.round((Date.now() - this.openedAt) / 60_000) }) + this.track('app_close', { sessionMinutes: Math.round((Date.now() - this.openedAt) / 60_000), ...this.resourceProps() }) } /** Best-effort batch POST. Keeps the queue on failure, clears on success. */ diff --git a/app/renderer/App.test.tsx b/app/renderer/App.test.tsx index b69d457d..6ff7984b 100644 --- a/app/renderer/App.test.tsx +++ b/app/renderer/App.test.tsx @@ -1039,33 +1039,39 @@ describe('freshness: hidden-window polling', () => { // the only remaining source of yield calls is the visible usePolled // interval. Then measure its steady per-cadence rate as the baseline. await act(async () => { await vi.advanceTimersByTimeAsync(30_000 * 8) }) - const beforeCadence = mocks.getYield.mock.calls.length + // The overview headline is the LIVE tier; yield is a slow tier and must + // not move on a live tick. + const beforeCadence = mocks.getOverview.mock.calls.length + const beforeYield = mocks.getYield.mock.calls.length await act(async () => { await vi.advanceTimersByTimeAsync(30_000) }) - const perCadence = mocks.getYield.mock.calls.length - beforeCadence + const perCadence = mocks.getOverview.mock.calls.length - beforeCadence expect(perCadence).toBeGreaterThan(0) // polling while visible + expect(mocks.getYield.mock.calls.length).toBe(beforeYield) // Hidden: the interval stops, so no CLI re-parse fires while unwatched. setVisibility('hidden') await act(async () => { document.dispatchEvent(new Event('visibilitychange')) }) const atHideYield = mocks.getYield.mock.calls.length const atHideOverview = mocks.getOverview.mock.calls.length - await act(async () => { await vi.advanceTimersByTimeAsync(30_000 * 5) }) + await act(async () => { await vi.advanceTimersByTimeAsync(30_000 * 12) }) expect(mocks.getYield.mock.calls.length).toBe(atHideYield) expect(mocks.getOverview.mock.calls.length).toBe(atHideOverview) // Back to visible after well over one cadence hidden: an immediate catch-up - // refresh fires so the returning view is never stale. + // refresh fires so the returning view is never stale. The slow yield tier + // came due while hidden, so it catches up exactly ONCE, not once per + // missed slow interval. setVisibility('visible') await act(async () => { document.dispatchEvent(new Event('visibilitychange')) }) await act(async () => { await vi.advanceTimersByTimeAsync(0) }) - expect(mocks.getYield.mock.calls.length).toBeGreaterThan(atHideYield) + expect(mocks.getYield.mock.calls.length).toBe(atHideYield + 1) expect(mocks.getOverview.mock.calls.length).toBeGreaterThan(atHideOverview) // The resumed timer is single: one cadence adds exactly the baseline count, // proving the hide/show cycle did not stack a second interval. - const afterCatchup = mocks.getYield.mock.calls.length + const afterCatchup = mocks.getOverview.mock.calls.length await act(async () => { await vi.advanceTimersByTimeAsync(30_000) }) - expect(mocks.getYield.mock.calls.length - afterCatchup).toBe(perCadence) + expect(mocks.getOverview.mock.calls.length - afterCatchup).toBe(perCadence) } finally { setVisibility('visible') vi.useRealTimers() diff --git a/app/renderer/App.tsx b/app/renderer/App.tsx index 59d576d4..67815464 100644 --- a/app/renderer/App.tsx +++ b/app/renderer/App.tsx @@ -42,7 +42,7 @@ import { localDateKey, PERIOD_LABELS } from './lib/period' import { generationAt } from './lib/generation' import { detectedProviders as detectedProviderList, providerLabel, readDisabledProviders, type DetectedProvider } from './lib/providers' import { reportMemoKey } from './lib/reportMemoKey' -import { persistRefreshValue, readRefreshValue, refreshValueToMs, RefreshCadenceContext, type RefreshCadence } from './lib/refreshCadence' +import { persistRefreshValue, readRefreshValue, resolveCadenceMs, useOnBattery, RefreshCadenceContext, type RefreshCadence } from './lib/refreshCadence' import { OverviewContent, type InvestigateRequest } from './sections/Overview' import { OptimizeContent } from './sections/Optimize' import { Models } from './sections/Models' @@ -276,9 +276,12 @@ export function App() { setRefreshValue(value) persistRefreshValue(value) }, []) + // On battery the live tier runs half as often; the user's chosen value is + // still the base, and AC restores it. + const onBattery = useOnBattery() const cadence = useMemo( - () => ({ value: refreshValue, intervalMs: refreshValueToMs(refreshValue), setValue }), - [refreshValue, setValue], + () => ({ value: refreshValue, intervalMs: resolveCadenceMs(refreshValue, onBattery), setValue }), + [refreshValue, onBattery, setValue], ) return ( @@ -971,7 +974,7 @@ function AppMain() { />
{section === 'overview' ? ( - + ) : section === 'sessions' ? ( // A new sort or a changed selection reorders the whole list, so // the pagination depth resets IN THE SAME commit — one history @@ -983,7 +986,7 @@ function AppMain() { ) : section === 'spend' ? ( ) : section === 'optimize' ? ( - + ) : section === 'models' ? ( ) : section === 'compare' ? ( diff --git a/app/renderer/assets/onboarding-flame.png b/app/renderer/assets/onboarding-flame.png index e4cbbce1..9c30c4fb 100644 Binary files a/app/renderer/assets/onboarding-flame.png and b/app/renderer/assets/onboarding-flame.png differ diff --git a/app/renderer/components/Onboarding.test.tsx b/app/renderer/components/Onboarding.test.tsx index cbda0f1c..663a6f50 100644 --- a/app/renderer/components/Onboarding.test.tsx +++ b/app/renderer/components/Onboarding.test.tsx @@ -64,7 +64,7 @@ describe('Onboarding', () => { next(); next(); next() // EU-style default: switch starts off. - const toggle = screen.getByRole('switch', { name: 'Anonymous telemetry' }) + const toggle = screen.getByRole('switch', { name: 'Anonymous usage statistics' }) expect(toggle).toHaveAttribute('aria-checked', 'false') // The user opts in, then finishes. diff --git a/app/renderer/components/Splash.tsx b/app/renderer/components/Splash.tsx index bf8d2273..709c5e1d 100644 --- a/app/renderer/components/Splash.tsx +++ b/app/renderer/components/Splash.tsx @@ -117,6 +117,7 @@ export function Splash({ hasData, hasError }: { hasData: boolean; hasError: bool const [reveal, setReveal] = useState(false) const shownAt = useRef(Date.now()) const done = useRef(false) + const videoRef = useRef(null) // Subscribe once to cold-start progress. `codeburn` is undefined outside the // Electron preload (e.g. unit tests); guard so the splash still renders. @@ -125,6 +126,21 @@ export function Splash({ hasData, hasError }: { hasData: boolean; hasError: bool return codeburn.onProgress(event => setProgress(prev => reduceProgress(prev, event))) }, []) + // The brand video plays once (no loop) and then holds no decoder. While the + // window is hidden, pause it so a minimized/occluded launch does not stack + // media decode on the cold hydration CPU spike; resume on show unless it has + // already ended. + useEffect(() => { + const video = videoRef.current + if (!video) return + const sync = () => { + if (document.visibilityState === 'hidden') video.pause() + else if (!video.ended) void video.play().catch(() => {}) + } + document.addEventListener('visibilitychange', sync) + return () => document.removeEventListener('visibilitychange', sync) + }, []) + // Only a genuine cold hydration reveals the indexing detail. Warm launches // never set `cold`, so the strip stays hidden and the flame dismisses fast. useEffect(() => { if (progress.cold) setReveal(true) }, [progress.cold]) @@ -163,7 +179,7 @@ export function Splash({ hasData, hasError }: { hasData: boolean; hasError: bool {motionEnabled() ? ( // The animated burn as VP9-with-alpha, floating directly on the splash // gradient while the first scan runs. Static mark under reduced motion. -