From 3f14d95118d01af4ecd191d298b9f706fad50ef3 Mon Sep 17 00:00:00 2001 From: Resham Joshi <65915470+iamtoruk@users.noreply.github.com> Date: Thu, 24 Sep 2026 20:07:25 +0200 Subject: [PATCH] fix(menubar): older menubar apps load again, and in-app Update restarts the app (#1548) * fix(menubar): always emit avgCostPerSession for older menubar apps Menubar 0.9.14-0.9.24 decode topProjects[].avgCostPerSession as required, so omitting it for partial session counts broke Today with any 0.9.25 CLI. Emit the 0.9.24 value again and keep sessionCountBasis so 0.9.25+ hides a partial average. Add a test that checks the payload against the required keys of every released menubar app. * fix(menubar): restart the app after an in-app update The app runs `codeburn menubar --force` as its child, and pgrep/pkill skip their own ancestors, so the running app was never stopped and `open` re-activated the old copy. Find the app with pgrep -a; when it is an ancestor, swap the bundle while it runs, exit, and let a detached helper stop it and open the new bundle. The terminal path stops the app first as before. Reported in #1541, thanks @AleksandrLiadov. --- CHANGELOG.md | 2 + src/menubar-installer.ts | 123 ++- src/menubar-json.ts | 13 +- .../menubar-legacy-required-keys.json | 853 ++++++++++++++++++ tests/menubar-legacy-decode.test.ts | 79 ++ tests/menubar-relaunch.test.ts | 143 +++ tests/session-count-label.test.ts | 4 +- 7 files changed, 1179 insertions(+), 38 deletions(-) create mode 100644 tests/fixtures/menubar-legacy-required-keys.json create mode 100644 tests/menubar-legacy-decode.test.ts create mode 100644 tests/menubar-relaunch.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4325cd6e..c667da83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ### Fixed - **Windows Store installs: no update offer the Store cannot deliver, and `codeburn menubar` opens the Store copy.** The desktop app read GitHub releases for its update banner, so a Store copy was told about a version still waiting on Store certification and sent to a Store page that did not have it. Store installs now skip the GitHub check and the About update button, like the tray app already did; the Store updates them. `codeburn menubar` spawned the tray exe inside `WindowsApps`, which Windows refuses from outside the package (`spawn EPERM`); it now opens the Store app by its app id, and the desktop app starts the tray. Reported in #1520, thanks @Brandin. +- **Menu bar apps 0.9.14 to 0.9.24 load Today again with a 0.9.25 CLI.** Homebrew and npm update the CLI on their own, and 0.9.25 left `avgCostPerSession` out of a project row whose session count is a lower bound, a key those apps require, so the popover showed "Couldn't load Today". The payload always carries it again, with `sessionCountBasis` still telling 0.9.25 and later not to show a partial average. A new test checks the payload against the keys every released menu bar app requires. Reported in #1541, thanks @AleksandrLiadov. +- **Update in the menu bar app restarts it into the new version.** The app runs `codeburn menubar --force` as its own child, and `pkill`/`pgrep` skip their own ancestors unless told otherwise, so the running app was never stopped: the bundle was replaced and `open` re-activated the old copy. The CLI now finds the app among its ancestors, swaps the bundle, exits, and a detached helper stops the old copy and opens the new one. Run from a terminal, it stops the app first as before. Because the fix is in the CLI, older menu bar apps update correctly once the CLI is current. Reported in #1541, thanks @AleksandrLiadov. - **OpenCode 2.x: upgraded history is no longer lost and v2 turns price like 1.x ones.** OpenCode 2 copies 1.x sessions into new tables on first start, but the copy drops compaction summary and task-tool turns, skips messages it cannot decode, and can stop partway. CodeBurn read only the copy for any migrated session, so on one real upgraded database more than half the sessions and three quarters of the all-time OpenCode cost disappeared. A session present in both generations now reads its legacy turns first and adds only the turns written after the upgrade, so pre-upgrade figures match 1.x exactly. v2 turns also carried a `provider/model` id that failed pricing for ids like `opencode/claude-haiku-4-5` or `github-copilot/gpt-5` so they showed as $0 in reports; they now use the bare id 1.x used. OpenCode sessions re-parse once. Users on CodeBurn 0.9.24 or older see no OpenCode 2 usage at all and need 0.9.25 or later. Reported by a user. - **`overview`, `status` and the menu bar load only the part of the session cache a date range can use.** Cached sessions outside the range stay on disk and are held in memory as small stubs that still take part in duplicate checks and clean-up, so figures are unchanged. Shards are written one session per line, so a month past 512 MB is saved instead of silently re-parsed on every run, and Codex project names come from a small index instead of the whole results cache. On a heavy corpus `overview -p today` drops from about 3.4 GB to 1.2 GB and runs under a 1 GB heap where it used to crash; on a normal one it drops from about 970 MB to 280 MB and gets faster. Closes #1504. - **An expired Claude Code login is recovered from the Keychain, and `codeburn quota` and the desktop app say so when it cannot be.** Both providers read the OAuth credential from `~/.claude/.credentials.json` and fall back to the macOS Keychain, which is where Claude Code keeps it on a normal Mac. After a 401 the retry re-read the file whatever the credential had come from, so a Keychain user got `Temporarily unavailable.` until Claude Code was run again, and the desktop Plans card kept showing the last percentage it had fetched. A 401 now re-reads the store the credential came from, which picks up a login Claude Code has since renewed. When nothing newer is there and the credential's `expiresAt` has passed, the row reports a terminal failure with a line telling you to run Claude Code once. The desktop app still reads the Keychain only on Check now or a forced refresh, and a background poll keeps that reconnect prompt instead of falling back to Check now. A 401 on a credential still within its life stays transient with its backoff. (#1516, thanks @ozymandiashh) diff --git a/src/menubar-installer.ts b/src/menubar-installer.ts index d565a560..864c7e51 100644 --- a/src/menubar-installer.ts +++ b/src/menubar-installer.ts @@ -1,5 +1,6 @@ import { spawn } from 'node:child_process' import { createHash } from 'node:crypto' +import { once } from 'node:events' import { createWriteStream, constants as fsConstants } from 'node:fs' import { access, chmod, cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises' import { homedir, platform, tmpdir } from 'node:os' @@ -754,28 +755,102 @@ export async function hasRunnableRecordedCli(recordPath: string = PERSISTED_CLI_ /// `-x`, not `-f`: the executable inside the bundle is named exactly CodeBurnMenubar, and /// matching the whole command line instead would also hit an editor with the bundle's /// Info.plist open, or a tail on a log path. The name is the same from either Applications -/// folder, so a copy running from the other one is still matched. killRunningApp must use -/// the same matcher, or this reports a process that was never signalled. -async function isAppRunning(): Promise { - return new Promise((resolve) => { - const proc = spawn('/usr/bin/pgrep', ['-x', APP_PROCESS_NAME]) - proc.on('close', (code) => resolve(code === 0)) - proc.on('error', () => resolve(false)) - }) +/// folder, so a copy running from the other one is still matched. `-a`: pgrep leaves out its +/// own ancestors by default, and the app's Update button runs this install as the app's +/// child, so without it the app asking for the update is never seen (#1541). +export async function runningAppPids(name: string = APP_PROCESS_NAME): Promise { + const out = await captureCommand('/usr/bin/pgrep', ['-a', '-x', name]).catch(() => '') + return out.split('\n').map(Number).filter(pid => Number.isInteger(pid) && pid > 0) } -async function killRunningApp(): Promise { - await new Promise((resolve) => { - const proc = spawn('/usr/bin/pkill', ['-x', APP_PROCESS_NAME]) - proc.on('close', () => resolve()) - proc.on('error', () => resolve()) - }) - for (let i = 0; i < 10; i++) { - if (!(await isAppRunning())) return +async function isAppRunning(): Promise { + return (await runningAppPids()).length > 0 +} + +/// Every ancestor of `pid` in `ps -A -o pid= -o ppid=` output, nearest first, stopping at +/// launchd. +export function ancestorsOf(pid: number, psOutput: string): Set { + const parent = new Map() + for (const line of psOutput.split('\n')) { + const [child, ppid] = line.trim().split(/\s+/).map(Number) + if (child && ppid !== undefined && Number.isInteger(ppid)) parent.set(child, ppid) + } + const ancestors = new Set() + for (let p = parent.get(pid); p !== undefined && p > 1 && !ancestors.has(p); p = parent.get(p)) ancestors.add(p) + return ancestors +} + +async function killRunningApp(pids: number[]): Promise { + for (const pid of pids) { + try { process.kill(pid, 'SIGTERM') } catch {} + } + for (let i = 0; i < 10 && pids.some(pidIsLive); i++) { await new Promise(r => setTimeout(r, 500)) } } +/// Runs detached in its own session, so nothing that happens to the app or to this CLI +/// reaches it. Waits for the CLI ($1) to exit first: the app reads the CLI's stderr and waits +/// on its exit status, so the app must outlive it. Then asks the app ($2) to go, forces it +/// after 5s, and launches the new bundle only once no old copy is left for `open` to +/// re-activate instead. +const RELAUNCH_SCRIPT = `cli=$1 pids=$2; shift 2 +alive() { for p in $pids; do kill -0 "$p" 2>/dev/null && return 0; done; return 1; } +i=0; while kill -0 "$cli" 2>/dev/null && [ $i -lt 100 ]; do sleep 0.1; i=$((i+1)); done +kill -TERM $pids 2>/dev/null +i=0; while alive && [ $i -lt 50 ]; do sleep 0.1; i=$((i+1)); done +kill -KILL $pids 2>/dev/null +i=0; while alive && [ $i -lt 20 ]; do sleep 0.1; i=$((i+1)); done +exec "$@"` + +async function relaunchAfterExit(appPids: number[], launch: string[]): Promise { + const child = spawn('/bin/sh', ['-c', RELAUNCH_SCRIPT, 'codeburn-relaunch', String(process.pid), appPids.join(' '), ...launch], { + detached: true, + stdio: 'ignore', + }) + await once(child, 'spawn') + child.unref() +} + +export type RelaunchHooks = { + processName?: string + /// Replaces `open` (and `open -n`); the target path is appended. + launchCommand?: string[] +} + +/// Put the staged bundle in place and restart the app into it. From a terminal the running +/// copy is stopped first, as it always was. From the app's own Update button the running copy +/// is this process's ancestor: stopping it here would take down the reader of this process's +/// stderr, so the bundle is swapped while it runs (it keeps running from the unlinked copy) +/// and a detached helper stops and relaunches it after this process has exited. +export async function replaceAndRelaunch( + unpackedApp: string, + targetPath: string, + stopRunning: boolean, + hooks: RelaunchHooks = {}, +): Promise { + const running = stopRunning ? await runningAppPids(hooks.processName) : [] + if (running.length > 0) { + const ancestors = ancestorsOf(process.pid, await captureCommand('/bin/ps', ['-A', '-o', 'pid=', '-o', 'ppid=']).catch(() => '')) + if (running.some(pid => ancestors.has(pid))) { + await placeMenubarBundle(unpackedApp, targetPath) + // -n: the old copy is gone by now, but Launch Services can take a moment to notice, + // and a plain `open` in that window re-activates it instead of launching anything. + await relaunchAfterExit(running, [...(hooks.launchCommand ?? ['/usr/bin/open', '-n']), targetPath]) + console.log('CodeBurn Menubar will restart into the new version.') + return + } + } + await killRunningApp(running) + // Only now, with the new bundle downloaded, checksummed and its identity verified, is + // the installed copy touched at all — and it is moved aside, not deleted, until this + // returns. + await placeMenubarBundle(unpackedApp, targetPath) + console.log('Launching CodeBurn Menubar...') + const [command, ...args] = hooks.launchCommand ?? ['/usr/bin/open'] + await runCommand(command!, [...args, targetPath]) +} + /// Windows mirror of the mac install below: pin the release to the CLI's own version, fall back /// to the newest windows-v* release, verify the sha256 before anything executes the file, hand /// the .msi to msiexec, then launch what it installed. Two routes come before that one: an .msi @@ -1581,19 +1656,9 @@ export async function installMenubarApp(options: InstallOptions = {}): Promise 0. - /// Omitted for lower-bound counts so clients cannot treat cost/count as exact. - avgCostPerSession?: number + /// Always present: menubar 0.9.14-0.9.24 decode it as required (#1541). + /// Exact only when `sessionCountBasis` is `identity`; a client must not + /// show it for any other basis. + avgCostPerSession: number /// How `sessions` was derived. Omitted on older producers. `identity` is /// an exact unique count from surviving source files; `partial` is a lower bound. sessionCountBasis?: SessionCountBasis @@ -687,9 +688,7 @@ function buildTopProjects(projects: PeriodData['projects']): MenubarPayload['cur cost: p.cost, savingsUSD: p.savingsUSD, sessions: p.sessions, - ...(sessionCountIsExact(p.sessionCountBasis) && p.sessions > 0 - ? { avgCostPerSession: p.cost / p.sessions } - : {}), + avgCostPerSession: p.sessions > 0 ? p.cost / p.sessions : 0, ...(p.sessionCountBasis ? { sessionCountBasis: p.sessionCountBasis } : {}), sessionDetails: (p.sessionDetails ?? []).map(s => ({ cost: s.cost, diff --git a/tests/fixtures/menubar-legacy-required-keys.json b/tests/fixtures/menubar-legacy-required-keys.json new file mode 100644 index 00000000..c605b049 --- /dev/null +++ b/tests/fixtures/menubar-legacy-required-keys.json @@ -0,0 +1,853 @@ +{ + "mac-v0.9.14": [ + "current", + "current.calls", + "current.cost", + "current.inputTokens", + "current.label", + "current.localModelSavings.byModel", + "current.localModelSavings.byModel[].actualUSD", + "current.localModelSavings.byModel[].baselineModel", + "current.localModelSavings.byModel[].calls", + "current.localModelSavings.byModel[].inputTokens", + "current.localModelSavings.byModel[].name", + "current.localModelSavings.byModel[].outputTokens", + "current.localModelSavings.byModel[].savingsUSD", + "current.localModelSavings.byProvider", + "current.localModelSavings.byProvider[].calls", + "current.localModelSavings.byProvider[].name", + "current.localModelSavings.byProvider[].savingsUSD", + "current.localModelSavings.calls", + "current.localModelSavings.totalUSD", + "current.mcpServers[].calls", + "current.mcpServers[].name", + "current.modelEfficiency[].name", + "current.outputTokens", + "current.retryTax.byModel", + "current.retryTax.byModel[].name", + "current.retryTax.byModel[].retries", + "current.retryTax.byModel[].taxUSD", + "current.retryTax.editTurns", + "current.retryTax.retries", + "current.retryTax.totalUSD", + "current.routingWaste.baselineCostPerEdit", + "current.routingWaste.baselineModel", + "current.routingWaste.byModel", + "current.routingWaste.byModel[].actualUSD", + "current.routingWaste.byModel[].costPerEdit", + "current.routingWaste.byModel[].counterfactualUSD", + "current.routingWaste.byModel[].editTurns", + "current.routingWaste.byModel[].name", + "current.routingWaste.byModel[].savingsUSD", + "current.routingWaste.totalSavingsUSD", + "current.sessions", + "current.skills[].cost", + "current.skills[].name", + "current.skills[].turns", + "current.subagents[].calls", + "current.subagents[].cost", + "current.subagents[].name", + "current.tools[].calls", + "current.tools[].name", + "current.topActivities[].cost", + "current.topActivities[].name", + "current.topActivities[].turns", + "current.topModels[].calls", + "current.topModels[].cost", + "current.topModels[].name", + "current.topProjects[].avgCostPerSession", + "current.topProjects[].cost", + "current.topProjects[].name", + "current.topProjects[].sessionDetails[].calls", + "current.topProjects[].sessionDetails[].cost", + "current.topProjects[].sessionDetails[].date", + "current.topProjects[].sessionDetails[].inputTokens", + "current.topProjects[].sessionDetails[].models[].cost", + "current.topProjects[].sessionDetails[].models[].name", + "current.topProjects[].sessionDetails[].outputTokens", + "current.topProjects[].sessions", + "current.topSessions[].calls", + "current.topSessions[].cost", + "current.topSessions[].date", + "current.topSessions[].project", + "generated", + "history", + "history.daily", + "history.daily[].cacheReadTokens", + "history.daily[].cacheWriteTokens", + "history.daily[].calls", + "history.daily[].cost", + "history.daily[].date", + "history.daily[].inputTokens", + "history.daily[].outputTokens", + "history.daily[].topModels[].calls", + "history.daily[].topModels[].cost", + "history.daily[].topModels[].inputTokens", + "history.daily[].topModels[].name", + "history.daily[].topModels[].outputTokens", + "optimize", + "optimize.findingCount", + "optimize.savingsUSD", + "optimize.topFindings", + "optimize.topFindings[].impact", + "optimize.topFindings[].savingsUSD", + "optimize.topFindings[].title" + ], + "mac-v0.9.15": [ + "combined.combined", + "combined.combined.cacheCreateTokens", + "combined.combined.cacheReadTokens", + "combined.combined.calls", + "combined.combined.cost", + "combined.combined.deviceCount", + "combined.combined.inputTokens", + "combined.combined.outputTokens", + "combined.combined.reachableCount", + "combined.combined.sessions", + "combined.combined.totalTokens", + "combined.perDevice", + "combined.perDevice[].cacheCreateTokens", + "combined.perDevice[].cacheReadTokens", + "combined.perDevice[].calls", + "combined.perDevice[].cost", + "combined.perDevice[].id", + "combined.perDevice[].inputTokens", + "combined.perDevice[].local", + "combined.perDevice[].name", + "combined.perDevice[].outputTokens", + "combined.perDevice[].sessions", + "combined.perDevice[].totalTokens", + "current", + "current.calls", + "current.cost", + "current.inputTokens", + "current.label", + "current.localModelSavings.byModel", + "current.localModelSavings.byModel[].actualUSD", + "current.localModelSavings.byModel[].baselineModel", + "current.localModelSavings.byModel[].calls", + "current.localModelSavings.byModel[].inputTokens", + "current.localModelSavings.byModel[].name", + "current.localModelSavings.byModel[].outputTokens", + "current.localModelSavings.byModel[].savingsUSD", + "current.localModelSavings.byProvider", + "current.localModelSavings.byProvider[].calls", + "current.localModelSavings.byProvider[].name", + "current.localModelSavings.byProvider[].savingsUSD", + "current.localModelSavings.calls", + "current.localModelSavings.totalUSD", + "current.mcpServers[].calls", + "current.mcpServers[].name", + "current.modelEfficiency[].name", + "current.outputTokens", + "current.retryTax.byModel", + "current.retryTax.byModel[].name", + "current.retryTax.byModel[].retries", + "current.retryTax.byModel[].taxUSD", + "current.retryTax.editTurns", + "current.retryTax.retries", + "current.retryTax.totalUSD", + "current.routingWaste.baselineCostPerEdit", + "current.routingWaste.baselineModel", + "current.routingWaste.byModel", + "current.routingWaste.byModel[].actualUSD", + "current.routingWaste.byModel[].costPerEdit", + "current.routingWaste.byModel[].counterfactualUSD", + "current.routingWaste.byModel[].editTurns", + "current.routingWaste.byModel[].name", + "current.routingWaste.byModel[].savingsUSD", + "current.routingWaste.totalSavingsUSD", + "current.sessions", + "current.skills[].cost", + "current.skills[].name", + "current.skills[].turns", + "current.subagents[].calls", + "current.subagents[].cost", + "current.subagents[].name", + "current.tools[].calls", + "current.tools[].name", + "current.topActivities[].cost", + "current.topActivities[].name", + "current.topActivities[].turns", + "current.topModels[].calls", + "current.topModels[].cost", + "current.topModels[].name", + "current.topProjects[].avgCostPerSession", + "current.topProjects[].cost", + "current.topProjects[].name", + "current.topProjects[].sessionDetails[].calls", + "current.topProjects[].sessionDetails[].cost", + "current.topProjects[].sessionDetails[].date", + "current.topProjects[].sessionDetails[].inputTokens", + "current.topProjects[].sessionDetails[].models[].cost", + "current.topProjects[].sessionDetails[].models[].name", + "current.topProjects[].sessionDetails[].outputTokens", + "current.topProjects[].sessions", + "current.topSessions[].calls", + "current.topSessions[].cost", + "current.topSessions[].date", + "current.topSessions[].project", + "generated", + "history", + "history.daily", + "history.daily[].cacheReadTokens", + "history.daily[].cacheWriteTokens", + "history.daily[].calls", + "history.daily[].cost", + "history.daily[].date", + "history.daily[].inputTokens", + "history.daily[].outputTokens", + "history.daily[].topModels[].calls", + "history.daily[].topModels[].cost", + "history.daily[].topModels[].inputTokens", + "history.daily[].topModels[].name", + "history.daily[].topModels[].outputTokens", + "optimize", + "optimize.findingCount", + "optimize.savingsUSD", + "optimize.topFindings", + "optimize.topFindings[].impact", + "optimize.topFindings[].savingsUSD", + "optimize.topFindings[].title" + ], + "mac-v0.9.16 mac-v0.9.18 mac-v0.9.19": [ + "claudeConfigs.options", + "claudeConfigs.options[].id", + "claudeConfigs.options[].label", + "claudeConfigs.options[].path", + "combined.combined", + "combined.combined.cacheCreateTokens", + "combined.combined.cacheReadTokens", + "combined.combined.calls", + "combined.combined.cost", + "combined.combined.deviceCount", + "combined.combined.inputTokens", + "combined.combined.outputTokens", + "combined.combined.reachableCount", + "combined.combined.sessions", + "combined.combined.totalTokens", + "combined.perDevice", + "combined.perDevice[].cacheCreateTokens", + "combined.perDevice[].cacheReadTokens", + "combined.perDevice[].calls", + "combined.perDevice[].cost", + "combined.perDevice[].id", + "combined.perDevice[].inputTokens", + "combined.perDevice[].local", + "combined.perDevice[].name", + "combined.perDevice[].outputTokens", + "combined.perDevice[].sessions", + "combined.perDevice[].totalTokens", + "current", + "current.calls", + "current.cost", + "current.inputTokens", + "current.label", + "current.localModelSavings.byModel", + "current.localModelSavings.byModel[].actualUSD", + "current.localModelSavings.byModel[].baselineModel", + "current.localModelSavings.byModel[].calls", + "current.localModelSavings.byModel[].inputTokens", + "current.localModelSavings.byModel[].name", + "current.localModelSavings.byModel[].outputTokens", + "current.localModelSavings.byModel[].savingsUSD", + "current.localModelSavings.byProvider", + "current.localModelSavings.byProvider[].calls", + "current.localModelSavings.byProvider[].name", + "current.localModelSavings.byProvider[].savingsUSD", + "current.localModelSavings.calls", + "current.localModelSavings.totalUSD", + "current.mcpServers[].calls", + "current.mcpServers[].name", + "current.modelEfficiency[].name", + "current.outputTokens", + "current.retryTax.byModel", + "current.retryTax.byModel[].name", + "current.retryTax.byModel[].retries", + "current.retryTax.byModel[].taxUSD", + "current.retryTax.editTurns", + "current.retryTax.retries", + "current.retryTax.totalUSD", + "current.routingWaste.baselineCostPerEdit", + "current.routingWaste.baselineModel", + "current.routingWaste.byModel", + "current.routingWaste.byModel[].actualUSD", + "current.routingWaste.byModel[].costPerEdit", + "current.routingWaste.byModel[].counterfactualUSD", + "current.routingWaste.byModel[].editTurns", + "current.routingWaste.byModel[].name", + "current.routingWaste.byModel[].savingsUSD", + "current.routingWaste.totalSavingsUSD", + "current.sessions", + "current.skills[].cost", + "current.skills[].name", + "current.skills[].turns", + "current.subagents[].calls", + "current.subagents[].cost", + "current.subagents[].name", + "current.tools[].calls", + "current.tools[].name", + "current.topActivities[].cost", + "current.topActivities[].name", + "current.topActivities[].turns", + "current.topModels[].calls", + "current.topModels[].cost", + "current.topModels[].name", + "current.topProjects[].avgCostPerSession", + "current.topProjects[].cost", + "current.topProjects[].name", + "current.topProjects[].sessionDetails[].calls", + "current.topProjects[].sessionDetails[].cost", + "current.topProjects[].sessionDetails[].date", + "current.topProjects[].sessionDetails[].inputTokens", + "current.topProjects[].sessionDetails[].models[].cost", + "current.topProjects[].sessionDetails[].models[].name", + "current.topProjects[].sessionDetails[].outputTokens", + "current.topProjects[].sessions", + "current.topSessions[].calls", + "current.topSessions[].cost", + "current.topSessions[].date", + "current.topSessions[].project", + "generated", + "history", + "history.daily", + "history.daily[].cacheReadTokens", + "history.daily[].cacheWriteTokens", + "history.daily[].calls", + "history.daily[].cost", + "history.daily[].date", + "history.daily[].inputTokens", + "history.daily[].outputTokens", + "history.daily[].topModels[].calls", + "history.daily[].topModels[].cost", + "history.daily[].topModels[].inputTokens", + "history.daily[].topModels[].name", + "history.daily[].topModels[].outputTokens", + "optimize", + "optimize.findingCount", + "optimize.savingsUSD", + "optimize.topFindings", + "optimize.topFindings[].impact", + "optimize.topFindings[].savingsUSD", + "optimize.topFindings[].title" + ], + "mac-v0.9.20": [ + "claudeConfigs.options", + "claudeConfigs.options[].id", + "claudeConfigs.options[].label", + "claudeConfigs.options[].path", + "combined.combined", + "combined.combined.cacheCreateTokens", + "combined.combined.cacheReadTokens", + "combined.combined.calls", + "combined.combined.cost", + "combined.combined.deviceCount", + "combined.combined.inputTokens", + "combined.combined.outputTokens", + "combined.combined.reachableCount", + "combined.combined.sessions", + "combined.combined.totalTokens", + "combined.perDevice", + "combined.perDevice[].cacheCreateTokens", + "combined.perDevice[].cacheReadTokens", + "combined.perDevice[].calls", + "combined.perDevice[].cost", + "combined.perDevice[].id", + "combined.perDevice[].inputTokens", + "combined.perDevice[].local", + "combined.perDevice[].name", + "combined.perDevice[].outputTokens", + "combined.perDevice[].sessions", + "combined.perDevice[].totalTokens", + "current", + "current.calls", + "current.cost", + "current.inputTokens", + "current.label", + "current.localModelSavings.byModel", + "current.localModelSavings.byModel[].actualUSD", + "current.localModelSavings.byModel[].baselineModel", + "current.localModelSavings.byModel[].calls", + "current.localModelSavings.byModel[].inputTokens", + "current.localModelSavings.byModel[].name", + "current.localModelSavings.byModel[].outputTokens", + "current.localModelSavings.byModel[].savingsUSD", + "current.localModelSavings.byProvider", + "current.localModelSavings.byProvider[].calls", + "current.localModelSavings.byProvider[].name", + "current.localModelSavings.byProvider[].savingsUSD", + "current.localModelSavings.calls", + "current.localModelSavings.totalUSD", + "current.mcpServers[].calls", + "current.mcpServers[].name", + "current.modelEfficiency[].name", + "current.outputTokens", + "current.retryTax.byModel", + "current.retryTax.byModel[].name", + "current.retryTax.byModel[].retries", + "current.retryTax.byModel[].taxUSD", + "current.retryTax.editTurns", + "current.retryTax.retries", + "current.retryTax.totalUSD", + "current.routingWaste.baselineCostPerEdit", + "current.routingWaste.baselineModel", + "current.routingWaste.byModel", + "current.routingWaste.byModel[].actualUSD", + "current.routingWaste.byModel[].costPerEdit", + "current.routingWaste.byModel[].counterfactualUSD", + "current.routingWaste.byModel[].editTurns", + "current.routingWaste.byModel[].name", + "current.routingWaste.byModel[].savingsUSD", + "current.routingWaste.totalSavingsUSD", + "current.sessions", + "current.skills[].cost", + "current.skills[].name", + "current.skills[].turns", + "current.subagents[].calls", + "current.subagents[].cost", + "current.subagents[].name", + "current.tools[].calls", + "current.tools[].name", + "current.topActivities[].cost", + "current.topActivities[].name", + "current.topActivities[].turns", + "current.topModels[].calls", + "current.topModels[].cost", + "current.topModels[].name", + "current.topProjects[].avgCostPerSession", + "current.topProjects[].cost", + "current.topProjects[].name", + "current.topProjects[].sessionDetails[].calls", + "current.topProjects[].sessionDetails[].cost", + "current.topProjects[].sessionDetails[].date", + "current.topProjects[].sessionDetails[].inputTokens", + "current.topProjects[].sessionDetails[].models[].cost", + "current.topProjects[].sessionDetails[].models[].name", + "current.topProjects[].sessionDetails[].outputTokens", + "current.topProjects[].sessions", + "current.topReworkedFiles[].edits", + "current.topReworkedFiles[].path", + "current.topReworkedFiles[].sessions", + "current.topSessions[].calls", + "current.topSessions[].cost", + "current.topSessions[].date", + "current.topSessions[].project", + "current.workflow.corrections", + "generated", + "history", + "history.daily", + "history.daily[].cacheReadTokens", + "history.daily[].cacheWriteTokens", + "history.daily[].calls", + "history.daily[].cost", + "history.daily[].date", + "history.daily[].inputTokens", + "history.daily[].outputTokens", + "history.daily[].topModels[].calls", + "history.daily[].topModels[].cost", + "history.daily[].topModels[].inputTokens", + "history.daily[].topModels[].name", + "history.daily[].topModels[].outputTokens", + "optimize", + "optimize.findingCount", + "optimize.savingsUSD", + "optimize.topFindings", + "optimize.topFindings[].impact", + "optimize.topFindings[].savingsUSD", + "optimize.topFindings[].title" + ], + "mac-v0.9.21 mac-v0.9.22 mac-v0.9.23": [ + "claudeConfigs.options", + "claudeConfigs.options[].id", + "claudeConfigs.options[].label", + "claudeConfigs.options[].path", + "combined.combined", + "combined.combined.cacheCreateTokens", + "combined.combined.cacheReadTokens", + "combined.combined.calls", + "combined.combined.cost", + "combined.combined.deviceCount", + "combined.combined.inputTokens", + "combined.combined.outputTokens", + "combined.combined.reachableCount", + "combined.combined.sessions", + "combined.combined.totalTokens", + "combined.perDevice", + "combined.perDevice[].cacheCreateTokens", + "combined.perDevice[].cacheReadTokens", + "combined.perDevice[].calls", + "combined.perDevice[].cost", + "combined.perDevice[].id", + "combined.perDevice[].inputTokens", + "combined.perDevice[].local", + "combined.perDevice[].name", + "combined.perDevice[].outputTokens", + "combined.perDevice[].sessions", + "combined.perDevice[].totalTokens", + "current", + "current.calls", + "current.cost", + "current.inputTokens", + "current.label", + "current.localModelSavings.byModel", + "current.localModelSavings.byModel[].actualUSD", + "current.localModelSavings.byModel[].baselineModel", + "current.localModelSavings.byModel[].calls", + "current.localModelSavings.byModel[].inputTokens", + "current.localModelSavings.byModel[].name", + "current.localModelSavings.byModel[].outputTokens", + "current.localModelSavings.byModel[].savingsUSD", + "current.localModelSavings.byProvider", + "current.localModelSavings.byProvider[].calls", + "current.localModelSavings.byProvider[].name", + "current.localModelSavings.byProvider[].savingsUSD", + "current.localModelSavings.calls", + "current.localModelSavings.totalUSD", + "current.mcpServers[].calls", + "current.mcpServers[].name", + "current.modelEfficiency[].name", + "current.outputTokens", + "current.retryTax.byModel", + "current.retryTax.byModel[].name", + "current.retryTax.byModel[].retries", + "current.retryTax.byModel[].taxUSD", + "current.retryTax.editTurns", + "current.retryTax.retries", + "current.retryTax.totalUSD", + "current.routingWaste.baselineCostPerEdit", + "current.routingWaste.baselineModel", + "current.routingWaste.byModel", + "current.routingWaste.byModel[].actualUSD", + "current.routingWaste.byModel[].costPerEdit", + "current.routingWaste.byModel[].counterfactualUSD", + "current.routingWaste.byModel[].editTurns", + "current.routingWaste.byModel[].name", + "current.routingWaste.byModel[].savingsUSD", + "current.routingWaste.totalSavingsUSD", + "current.sessions", + "current.skills[].cost", + "current.skills[].name", + "current.skills[].turns", + "current.subagents[].calls", + "current.subagents[].cost", + "current.subagents[].name", + "current.tools[].calls", + "current.tools[].name", + "current.topActivities[].cost", + "current.topActivities[].name", + "current.topActivities[].turns", + "current.topModels[].calls", + "current.topModels[].cost", + "current.topModels[].name", + "current.topProjects[].avgCostPerSession", + "current.topProjects[].cost", + "current.topProjects[].name", + "current.topProjects[].sessionDetails[].calls", + "current.topProjects[].sessionDetails[].cost", + "current.topProjects[].sessionDetails[].date", + "current.topProjects[].sessionDetails[].inputTokens", + "current.topProjects[].sessionDetails[].models[].cost", + "current.topProjects[].sessionDetails[].models[].name", + "current.topProjects[].sessionDetails[].outputTokens", + "current.topProjects[].sessions", + "current.topReworkedFiles[].edits", + "current.topReworkedFiles[].path", + "current.topReworkedFiles[].sessions", + "current.topSessions[].calls", + "current.topSessions[].cost", + "current.topSessions[].date", + "current.topSessions[].project", + "current.workflow.corrections", + "generated", + "history", + "history.daily", + "history.daily[].cacheReadTokens", + "history.daily[].cacheWriteTokens", + "history.daily[].calls", + "history.daily[].cost", + "history.daily[].date", + "history.daily[].inputTokens", + "history.daily[].outputTokens", + "history.daily[].topModels[].calls", + "history.daily[].topModels[].cost", + "history.daily[].topModels[].inputTokens", + "history.daily[].topModels[].name", + "history.daily[].topModels[].outputTokens", + "optimize", + "optimize.findingCount", + "optimize.savingsUSD", + "optimize.topFindings", + "optimize.topFindings[].impact", + "optimize.topFindings[].savingsUSD", + "optimize.topFindings[].title" + ], + "mac-v0.9.24": [ + "claudeConfigs.options", + "claudeConfigs.options[].id", + "claudeConfigs.options[].label", + "claudeConfigs.options[].path", + "combined.combined", + "combined.combined.cacheCreateTokens", + "combined.combined.cacheReadTokens", + "combined.combined.calls", + "combined.combined.cost", + "combined.combined.deviceCount", + "combined.combined.inputTokens", + "combined.combined.outputTokens", + "combined.combined.reachableCount", + "combined.combined.sessions", + "combined.combined.totalTokens", + "combined.perDevice", + "combined.perDevice[].cacheCreateTokens", + "combined.perDevice[].cacheReadTokens", + "combined.perDevice[].calls", + "combined.perDevice[].cost", + "combined.perDevice[].id", + "combined.perDevice[].inputTokens", + "combined.perDevice[].local", + "combined.perDevice[].name", + "combined.perDevice[].outputTokens", + "combined.perDevice[].sessions", + "combined.perDevice[].totalTokens", + "current", + "current.calls", + "current.cost", + "current.inputTokens", + "current.label", + "current.localModelSavings.byModel", + "current.localModelSavings.byModel[].actualUSD", + "current.localModelSavings.byModel[].baselineModel", + "current.localModelSavings.byModel[].calls", + "current.localModelSavings.byModel[].inputTokens", + "current.localModelSavings.byModel[].name", + "current.localModelSavings.byModel[].outputTokens", + "current.localModelSavings.byModel[].savingsUSD", + "current.localModelSavings.byProvider", + "current.localModelSavings.byProvider[].calls", + "current.localModelSavings.byProvider[].name", + "current.localModelSavings.byProvider[].savingsUSD", + "current.localModelSavings.calls", + "current.localModelSavings.totalUSD", + "current.mcpServers[].calls", + "current.mcpServers[].name", + "current.modelEfficiency[].name", + "current.outputTokens", + "current.providerDetails[].cost", + "current.providerDetails[].id", + "current.providerDetails[].label", + "current.retryTax.byModel", + "current.retryTax.byModel[].name", + "current.retryTax.byModel[].retries", + "current.retryTax.byModel[].taxUSD", + "current.retryTax.editTurns", + "current.retryTax.retries", + "current.retryTax.totalUSD", + "current.routingWaste.baselineCostPerEdit", + "current.routingWaste.baselineModel", + "current.routingWaste.byModel", + "current.routingWaste.byModel[].actualUSD", + "current.routingWaste.byModel[].costPerEdit", + "current.routingWaste.byModel[].counterfactualUSD", + "current.routingWaste.byModel[].editTurns", + "current.routingWaste.byModel[].name", + "current.routingWaste.byModel[].savingsUSD", + "current.routingWaste.totalSavingsUSD", + "current.sessions", + "current.skills[].cost", + "current.skills[].name", + "current.skills[].turns", + "current.subagents[].calls", + "current.subagents[].cost", + "current.subagents[].name", + "current.tools[].calls", + "current.tools[].name", + "current.topActivities[].cost", + "current.topActivities[].name", + "current.topActivities[].turns", + "current.topModels[].calls", + "current.topModels[].cost", + "current.topModels[].name", + "current.topProjects[].avgCostPerSession", + "current.topProjects[].cost", + "current.topProjects[].name", + "current.topProjects[].sessionDetails[].calls", + "current.topProjects[].sessionDetails[].cost", + "current.topProjects[].sessionDetails[].date", + "current.topProjects[].sessionDetails[].inputTokens", + "current.topProjects[].sessionDetails[].models[].cost", + "current.topProjects[].sessionDetails[].models[].name", + "current.topProjects[].sessionDetails[].outputTokens", + "current.topProjects[].sessions", + "current.topReworkedFiles[].edits", + "current.topReworkedFiles[].path", + "current.topReworkedFiles[].sessions", + "current.topSessions[].calls", + "current.topSessions[].cost", + "current.topSessions[].date", + "current.topSessions[].project", + "current.workflow.corrections", + "generated", + "history", + "history.daily", + "history.daily[].cacheReadTokens", + "history.daily[].cacheWriteTokens", + "history.daily[].calls", + "history.daily[].cost", + "history.daily[].date", + "history.daily[].inputTokens", + "history.daily[].outputTokens", + "history.daily[].topModels[].calls", + "history.daily[].topModels[].cost", + "history.daily[].topModels[].inputTokens", + "history.daily[].topModels[].name", + "history.daily[].topModels[].outputTokens", + "liveSessions.sessions", + "liveSessions.sessions[].id", + "liveSessions.sessions[].lastActivityAt", + "liveSessions.sessions[].project", + "liveSessions.sessions[].provider", + "liveSessions.sessions[].startedAt", + "liveSessions.windowSeconds", + "optimize", + "optimize.findingCount", + "optimize.savingsUSD", + "optimize.topFindings", + "optimize.topFindings[].impact", + "optimize.topFindings[].savingsUSD", + "optimize.topFindings[].title" + ], + "mac-v0.9.25": [ + "claudeConfigs.options", + "claudeConfigs.options[].id", + "claudeConfigs.options[].label", + "claudeConfigs.options[].path", + "combined.combined", + "combined.combined.cacheCreateTokens", + "combined.combined.cacheReadTokens", + "combined.combined.calls", + "combined.combined.cost", + "combined.combined.deviceCount", + "combined.combined.inputTokens", + "combined.combined.outputTokens", + "combined.combined.reachableCount", + "combined.combined.sessions", + "combined.combined.totalTokens", + "combined.perDevice", + "combined.perDevice[].cacheCreateTokens", + "combined.perDevice[].cacheReadTokens", + "combined.perDevice[].calls", + "combined.perDevice[].cost", + "combined.perDevice[].id", + "combined.perDevice[].inputTokens", + "combined.perDevice[].local", + "combined.perDevice[].name", + "combined.perDevice[].outputTokens", + "combined.perDevice[].sessions", + "combined.perDevice[].totalTokens", + "current", + "current.calls", + "current.cost", + "current.inputTokens", + "current.label", + "current.localModelSavings.byModel", + "current.localModelSavings.byModel[].actualUSD", + "current.localModelSavings.byModel[].baselineModel", + "current.localModelSavings.byModel[].calls", + "current.localModelSavings.byModel[].inputTokens", + "current.localModelSavings.byModel[].name", + "current.localModelSavings.byModel[].outputTokens", + "current.localModelSavings.byModel[].savingsUSD", + "current.localModelSavings.byProvider", + "current.localModelSavings.byProvider[].calls", + "current.localModelSavings.byProvider[].name", + "current.localModelSavings.byProvider[].savingsUSD", + "current.localModelSavings.calls", + "current.localModelSavings.totalUSD", + "current.mcpServers[].calls", + "current.mcpServers[].name", + "current.modelEfficiency[].name", + "current.outputTokens", + "current.providerDetails[].cost", + "current.providerDetails[].id", + "current.providerDetails[].label", + "current.retryTax.byModel", + "current.retryTax.byModel[].name", + "current.retryTax.byModel[].retries", + "current.retryTax.byModel[].taxUSD", + "current.retryTax.editTurns", + "current.retryTax.retries", + "current.retryTax.totalUSD", + "current.routingWaste.baselineCostPerEdit", + "current.routingWaste.baselineModel", + "current.routingWaste.byModel", + "current.routingWaste.byModel[].actualUSD", + "current.routingWaste.byModel[].costPerEdit", + "current.routingWaste.byModel[].counterfactualUSD", + "current.routingWaste.byModel[].editTurns", + "current.routingWaste.byModel[].name", + "current.routingWaste.byModel[].savingsUSD", + "current.routingWaste.totalSavingsUSD", + "current.sessions", + "current.skills[].cost", + "current.skills[].name", + "current.skills[].turns", + "current.subagents[].calls", + "current.subagents[].cost", + "current.subagents[].name", + "current.tools[].calls", + "current.tools[].name", + "current.topActivities[].cost", + "current.topActivities[].name", + "current.topActivities[].turns", + "current.topModels[].calls", + "current.topModels[].cost", + "current.topModels[].name", + "current.topProjects[].cost", + "current.topProjects[].name", + "current.topProjects[].sessionDetails[].calls", + "current.topProjects[].sessionDetails[].cost", + "current.topProjects[].sessionDetails[].date", + "current.topProjects[].sessionDetails[].inputTokens", + "current.topProjects[].sessionDetails[].models[].cost", + "current.topProjects[].sessionDetails[].models[].name", + "current.topProjects[].sessionDetails[].outputTokens", + "current.topProjects[].sessions", + "current.topReworkedFiles[].edits", + "current.topReworkedFiles[].path", + "current.topReworkedFiles[].sessions", + "current.topSessions[].calls", + "current.topSessions[].cost", + "current.topSessions[].date", + "current.topSessions[].project", + "current.workflow.corrections", + "generated", + "history", + "history.daily", + "history.daily[].cacheReadTokens", + "history.daily[].cacheWriteTokens", + "history.daily[].calls", + "history.daily[].cost", + "history.daily[].date", + "history.daily[].inputTokens", + "history.daily[].outputTokens", + "history.daily[].topModels[].calls", + "history.daily[].topModels[].cost", + "history.daily[].topModels[].inputTokens", + "history.daily[].topModels[].name", + "history.daily[].topModels[].outputTokens", + "liveSessions.sessions", + "liveSessions.sessions[].id", + "liveSessions.sessions[].lastActivityAt", + "liveSessions.sessions[].project", + "liveSessions.sessions[].provider", + "liveSessions.sessions[].startedAt", + "liveSessions.windowSeconds", + "optimize", + "optimize.findingCount", + "optimize.savingsUSD", + "optimize.topFindings", + "optimize.topFindings[].impact", + "optimize.topFindings[].savingsUSD", + "optimize.topFindings[].title" + ] +} diff --git a/tests/menubar-legacy-decode.test.ts b/tests/menubar-legacy-decode.test.ts new file mode 100644 index 00000000..f83b1ab6 --- /dev/null +++ b/tests/menubar-legacy-decode.test.ts @@ -0,0 +1,79 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' + +import { buildMenubarPayload, type PeriodData } from '../src/menubar-json.js' +import { buildLiveSessions } from '../src/live-sessions.js' +import { summarizeDeviceUsage } from '../src/sharing/host.js' + +// Keys each released menubar app decodes as required, per tag. Derived by +// compiling that tag's MenubarPayload.swift and deleting each key from a full +// payload in turn: a key is listed when its absence makes the decode throw. +// Released apps never change, so this table is frozen history. The Homebrew +// and npm CLI updates independently of the app, so every newer CLI must keep +// emitting these (#1541). +const REQUIRED = JSON.parse(readFileSync(new URL('./fixtures/menubar-legacy-required-keys.json', import.meta.url), 'utf-8')) as Record + +// Worst case for conditional keys: lower-bound session counts, no ids, no +// optional token counts, nulls wherever the payload allows them. +function fullPayload() { + const period: PeriodData = { + label: 'Today', cost: 4, savingsUSD: 0, calls: 4, sessions: 2, sessionCountBasis: 'partial', + inputTokens: 10, outputTokens: 5, cacheReadTokens: 0, cacheWriteTokens: 0, + categories: [{ name: 'Coding', cost: 4, savingsUSD: 0, turns: 2, editTurns: 0, oneShotTurns: 0 }], + models: [{ name: 'claude-sonnet-4-5', cost: 4, savingsUSD: 0, calls: 4 }], + projects: [{ + name: 'vault', cost: 4, savingsUSD: 0, sessions: 2, sessionCountBasis: 'partial', + sessionDetails: [{ cost: 4, savingsUSD: 0, calls: 4, inputTokens: 10, outputTokens: 5, date: '2026-09-24', models: [{ name: 'Sonnet 4.5', cost: 4, savingsUSD: 0 }] }], + }], + modelEfficiency: [{ name: 'Sonnet 4.5', costPerEdit: 1, oneShotRate: null }], + topSessions: [{ project: 'vault', cost: 4, savingsUSD: 0, calls: 4, date: '2026-09-24' }], + workflow: { corrections: 0, correctionRate: null, medianTimeToFirstEditMs: null }, + topReworkedFiles: [{ path: 'a/b.ts', sessions: 1, edits: 2 }], + } + const payload = buildMenubarPayload( + period, + [{ name: 'claude', displayName: 'Claude', cost: 4 }], + { findings: [{ id: 'x', title: 'T', explanation: 'E', impact: 'high', tokensSaved: 1000 }], costRate: 0.000001, healthScore: 90, healthGrade: 'A' } as never, + [{ date: '2026-09-24', cost: 4, savingsUSD: 0, calls: 4, inputTokens: 10, outputTokens: 5, cacheReadTokens: 0, cacheWriteTokens: 0, topModels: [{ name: 'Sonnet 4.5', cost: 4, savingsUSD: 0, calls: 4, inputTokens: 10, outputTokens: 5 }] }], + { totalUSD: 0, retries: 0, editTurns: 0, byModel: [{ name: 'Sonnet 4.5', taxUSD: 0, retries: 0, retriesPerEdit: null }] }, + { totalSavingsUSD: 0, baselineModel: 'Sonnet 4.5', baselineCostPerEdit: 1, byModel: [{ name: 'Sonnet 4.5', costPerEdit: 1, editTurns: 1, actualUSD: 1, counterfactualUSD: 1, savingsUSD: 0 }] }, + { + tools: [{ name: 'Edit', calls: 1 }], + skills: [{ name: 's', turns: 1, cost: 0 }], + subagents: [{ name: 'a', calls: 1, cost: 0 }], + mcpServers: [{ name: 'm', calls: 1 }], + localModelSavings: { totalUSD: 0, calls: 1, byModel: [{ name: 'q', calls: 1, actualUSD: 0, savingsUSD: 0, baselineModel: 'b', inputTokens: 1, outputTokens: 1 }], byProvider: [{ name: 'ollama', calls: 1, savingsUSD: 0 }] }, + }, + { selectedId: null, options: [{ id: 'a', label: 'A', path: '/a' }, { id: 'b', label: 'B', path: '/b' }] }, + ) + payload.combined = summarizeDeviceUsage([ + { id: 'local', name: 'Mac', local: true, payload: payload as never }, + { id: 'peer', name: 'Peer', local: false, error: 'unreachable' }, + ]) + const now = Date.now() + payload.liveSessions = buildLiveSessions([{ id: 's', provider: 'claude', project: 'vault', branch: null, model: null, contextTokens: null, contextWindow: null, startedMs: now - 60_000, lastActivityMs: now, subagentActivityMs: [] }], now) + return JSON.parse(JSON.stringify(payload)) as unknown +} + +function missing(value: unknown, parts: string[], at: string): string[] { + if (parts.length === 0) return [] + const [head, ...rest] = parts + const isArray = head!.endsWith('[]') + const key = isArray ? head!.slice(0, -2) : head! + const obj = value as Record + if (!(key in obj)) return [`${at}${key}`] + if (!isArray) return missing(obj[key], rest, `${at}${key}.`) + const items = obj[key] as unknown[] + // An empty array would pass vacuously and hide a missing nested key. + if (items.length === 0) return [`${at}${key}[] (empty in fixture)`] + return items.flatMap((item, i) => missing(item, rest, `${at}${key}[${i}].`)) +} + +describe('menubar payload stays decodable by released menubar apps', () => { + const payload = fullPayload() + for (const [tags, paths] of Object.entries(REQUIRED)) { + it(tags, () => { + expect(paths.flatMap(p => missing(payload, p.split('.'), ''))).toEqual([]) + }) + } +}) diff --git a/tests/menubar-relaunch.test.ts b/tests/menubar-relaunch.test.ts new file mode 100644 index 00000000..921552c9 --- /dev/null +++ b/tests/menubar-relaunch.test.ts @@ -0,0 +1,143 @@ +import { spawn, spawnSync, type ChildProcess } from 'node:child_process' +import { once } from 'node:events' +import { existsSync } from 'node:fs' +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { ancestorsOf, replaceAndRelaunch, runningAppPids } from '../src/menubar-installer.js' + +describe('ancestorsOf', () => { + const ps = [' 1 0', ' 50 1', ' 60 50', ' 70 60', ' 80 1', ''].join('\n') + + it('walks the parent chain up to launchd', () => { + expect([...ancestorsOf(70, ps)]).toEqual([60, 50]) + }) + + it('does not count unrelated processes', () => { + expect(ancestorsOf(70, ps).has(80)).toBe(false) + expect(ancestorsOf(80, ps).size).toBe(0) + }) + + it('stops on a cycle and on an unknown pid', () => { + expect([...ancestorsOf(2, ' 2 3\n 3 2\n')]).toEqual([3, 2]) + expect(ancestorsOf(999, ps).size).toBe(0) + }) +}) + +// A stand-in for the menubar app: a real process with a unique name, so the pgrep, kill and +// ancestry code runs for real without going near the installed CodeBurnMenubar. It runs an +// optional command as its child (the Update button's `codeburn menubar --force`), records the +// exit status, then idles until signalled. +const DUMMY_C = `#include +#include +#include +#include +int main(int argc, char **argv) { + if (argc > 2) { + int status = system(argv[2]); + FILE *f = fopen(argv[1], "w"); + fprintf(f, "%d", WEXITSTATUS(status)); + fclose(f); + } + for (;;) pause(); +} +` + +const canRun = process.platform === 'darwin' && spawnSync('cc', ['--version']).status === 0 + +describe.skipIf(!canRun)('replaceAndRelaunch with a stand-in app', () => { + vi.setConfig({ testTimeout: 60_000 }) + const cleanup: Array<() => Promise> = [] + afterEach(async () => { + for (const fn of cleanup.splice(0)) await fn() + }) + + async function setup() { + const dir = await mkdtemp(join(tmpdir(), 'codeburn-relaunch-')) + const name = `cbRl${Math.random().toString(16).slice(2, 8)}` + const bin = join(dir, name) + await writeFile(join(dir, 'dummy.c'), DUMMY_C) + expect(spawnSync('cc', ['-o', bin, join(dir, 'dummy.c')]).status).toBe(0) + const staged = join(dir, 'staged', 'CodeBurnMenubar.app') + const target = join(dir, 'apps', 'CodeBurnMenubar.app') + await mkdir(staged, { recursive: true }) + await mkdir(target, { recursive: true }) + await writeFile(join(staged, 'v'), 'new') + await writeFile(join(target, 'v'), 'old') + const procs: ChildProcess[] = [] + cleanup.push(async () => { + for (const p of procs) if (p.exitCode === null && p.signalCode === null) p.kill('SIGKILL') + await rm(dir, { recursive: true, force: true }) + }) + const start = async (args: string[]) => { + const p = spawn(bin, args, { stdio: 'ignore' }) + procs.push(p) + await once(p, 'spawn') + return p + } + const marker = join(dir, 'launched') + // Stands in for `open`: records whether the app was still alive and which bundle was in + // place at the moment of the launch. + const launchCommand = (pid: number) => ['/bin/sh', '-c', 'kill -0 "$1" 2>/dev/null && s=alive || s=dead; echo "$s $(cat "$3/v")" > "$2"', 'launch', String(pid), marker] + return { dir, name, staged, target, marker, start, launchCommand } + } + + async function waitFor(path: string, ms = 30_000): Promise { + const until = Date.now() + ms + while (!existsSync(path)) { + if (Date.now() > until) throw new Error(`timed out waiting for ${path}`) + await new Promise(r => setTimeout(r, 100)) + } + await new Promise(r => setTimeout(r, 100)) + return (await readFile(path, 'utf-8')).trim() + } + + it('from a terminal: stops the app, swaps, then launches, before returning', async () => { + const t = await setup() + const app = await t.start([]) + expect(await runningAppPids(t.name)).toEqual([app.pid]) + const exited = once(app, 'exit') + + await replaceAndRelaunch(t.staged, t.target, true, { processName: t.name, launchCommand: t.launchCommand(app.pid!) }) + + expect(await readFile(t.marker, 'utf-8')).toBe('dead new\n') + expect((await exited)[1]).toBe('SIGTERM') + }) + + it('from the app itself: finds its ancestor, swaps while it runs, exits, then the helper stops and relaunches it', async () => { + const t = await setup() + const installer = pathToFileURL(join(process.cwd(), 'src', 'menubar-installer.ts')).href + const swapped = join(t.dir, 'swapped') + const child = join(t.dir, 'child.mts') + const status = join(t.dir, 'status') + const appPid = join(t.dir, 'apppid') + // The dummy's pid is only known once it runs, so the child reads it from its parent. + await writeFile(child, ` +import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { replaceAndRelaunch } from ${JSON.stringify(installer)} +while (!existsSync(${JSON.stringify(appPid)})) await new Promise(r => setTimeout(r, 50)) +const app = Number(readFileSync(${JSON.stringify(appPid)}, 'utf-8')) +await replaceAndRelaunch(${JSON.stringify(t.staged)}, ${JSON.stringify(t.target)}, true, { + processName: ${JSON.stringify(t.name)}, + launchCommand: ${JSON.stringify(t.launchCommand(0).slice(0, 3))}.concat(['launch', String(app), ${JSON.stringify(t.marker)}]), +}) +let alive = true +try { process.kill(app, 0) } catch { alive = false } +writeFileSync(${JSON.stringify(swapped)}, (alive ? 'alive ' : 'dead ') + readFileSync(${JSON.stringify(join(t.target, 'v'))}, 'utf-8')) +`) + const cmd = `exec "${process.execPath}" --import tsx "${child}"` + const app = await t.start([status, cmd]) + await writeFile(appPid, String(app.pid)) + const exited = once(app, 'exit') + + expect(await waitFor(t.marker)).toBe('dead new') + // The CLI finished, successfully, with the app still alive to read its exit status... + expect(await readFile(status, 'utf-8')).toBe('0') + // ...and the bundle was already swapped while the app was running. + expect(await readFile(swapped, 'utf-8')).toBe('alive new') + expect((await exited)[1]).toBe('SIGTERM') + }) +}) diff --git a/tests/session-count-label.test.ts b/tests/session-count-label.test.ts index 4bb5c6a4..d37049fa 100644 --- a/tests/session-count-label.test.ts +++ b/tests/session-count-label.test.ts @@ -41,7 +41,7 @@ describe('payload serialization', () => { }], }) - it('omits average when the count is a bound and keeps numeric sessions', () => { + it('keeps the average numeric for a bound count and labels it partial', () => { const payload = buildMenubarPayload(emptyPeriod(), [], null) const json = JSON.parse(JSON.stringify(payload)) as { current: { sessions: number, sessionCountBasis?: string, topProjects: Array<{ sessions: number, avgCostPerSession?: number, sessionCountBasis?: string }> } @@ -50,7 +50,7 @@ describe('payload serialization', () => { expect(json.current.sessionCountBasis).toBe('partial') expect(json.current.topProjects[0]!.sessions).toBe(3) expect(json.current.topProjects[0]!.sessionCountBasis).toBe('partial') - expect(json.current.topProjects[0]!.avgCostPerSession).toBeUndefined() + expect(json.current.topProjects[0]!.avgCostPerSession).toBeCloseTo(4 / 3) expect(sessionCountIsExact('partial')).toBe(false) })