mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 02:39:13 +00:00
* 0.9.25: correctness + provider fixes, energy guard, logo, default DMG CLI/engine fixes: local-model savings count reasoning; ZCode reasoning billed; codex-credits version-boundary tiering; GLM alias repointed to z.ai discounted rate; openclaw/pi/qwen timestamp mtime fallback; hermes delta timestamp; sqlite/warp/hermes busy+permission reclassified as failed (no sealed empty); codex-cache dev+ino; cursor-cache WAL; antigravity server TTL; quota timeout+ grokbot footer+claude near-expiry; serve RSS guard env+hysteresis; CSV export subfolder; providers pane fixed window; Warp credit-based cost. Desktop/menubar: unified flame logo; default DMG; docs signed+notarized. * menubar: one running instance, self-relaunch on language change The single-instance guard only retired strictly older copies, so two login items starting in the same instant both survived, and a copy whose bundle identity did not survive install was never seen at all. The decision is now total (newest launch wins, ties break on pid) and peers are matched on bundle id or executable name. --keep-both opts one launch out. Language changes no longer have the desktop app quit and reopen the menu bar, which made macOS attribute the new process to the desktop app and re-ask for the data-access grant. The menu bar relaunches itself via the existing remote command key; older menu bars that do not watch the key fall back to the old path after 5s. * desktop: export toast shows the saved path; resource buckets on app_close The export toast showed the folder that was picked, not the dated subfolder the files land in. The handler already parsed the CLI's saved line; it now returns that path and the toast uses it. app_close carries cpu/mem (and serveCpu/serveMem when serve reported) as bucket labels, sampled on the existing flush interval. serve adds cpuSec and peak rssMb to its answer frames. Unmeasured figures are omitted, never sent as zero. * menubar guard never leaves zero instances; installer replaces in place; JSON export into folder Guard: an unreadable launch date on either side could make two copies retire each other. Unreadable peers now count only when their pid is lower, and a copy that cannot read its own date retires lower pids only, so a disagreement keeps at least one instance. Installer: an existing bundle in /Applications or ~/Applications is replaced where it lives instead of a second copy being added. The old bundle is moved aside and restored on any failure; a cross-volume move falls back to a copy that is re-verified with codesign. An unwritable location is never escalated: the install goes to ~/Applications and the leftover is named. Export: -o pointing at an existing folder writes the JSON inside it. Short sessions omit the cpu buckets. setLanguage reopens the menu bar if its own relaunch never comes back. AppRelaunch passes the bundle path as an argument. * menubar guard orders by kernel start time; installer opens the copy that exists and recovers a killed install Guard: launch dates could be unreadable and pid order can disagree with start order after pid reuse, so two copies could still retire each other. Ordering now uses the kernel-reported process start time, which both sides read identically. A copy whose start time cannot be read is left out, so the worst case is two menu bars, never none. Installer: with the only copy in an unwritable /Applications, a plain run tried to open a path that did not exist. It now opens the installed copy. A placement killed mid-way is recovered on the next run, a concurrent install is refused, and a failed restore names where the previous bundle is. Process matching uses the exact executable name. Export: a trailing separator names a folder. Telemetry cpu is measured from telemetry start. * installer: a recycled pid can no longer block installs; language change waits for the replacement process An aside left by an earlier install counted as an active install whenever its pid was live, so once that pid was reused every install was refused for good. It now also has to be recent (ctime within 10 minutes), a pid we may not signal is not ours, the refusal names the file, and an orphan that cannot be cleared is reported instead of aborting the install. setLanguage confirmed the relaunch with a matcher the dying process still satisfied, so the reopen fallback never fired. It now waits for a pid that was not running before. * desktop: only the headline refreshes live; act, yield and the optimize scan move to slower tiers An open window ran act report (a fresh CLI process each time), yield and an optimize scan on every refresh. The headline poll now passes --no-optimize and takes the snapshot path; act report refreshes on mount, on manual refresh and every 10 minutes, yield every 5. The optimize scan runs at most once a day per query scope, is stored in userData with its time, and is forced fresh by the Optimize page or a manual refresh. Figures that are not live show their age, and no stored scan means no savings clause rather than a zero. On battery the live interval doubles; the chosen cadence stays the base. * desktop: a stored optimize scan is only valid on the day it was computed; cadence changes no longer refetch The scan cache is keyed on the argv, which says 'today' or '30days', not a date, so yesterday's scan was served as today's. It is now reused only on the same local day. Stored findings in Signals carry their age, a failed scan shows the error instead of scanning forever, and the cold-boot label uses the time the app received the payload. usePolled fetched immediately whenever its interval changed, so every power transition (and launching on battery) refetched every live hook and could spawn an extra act report. Fetching and timer arming are now separate effects. Optimize's yield is on the same 5 minute tier as Overview. * desktop: re-ask for the optimize scan on the first render of a new local day An app left open across midnight kept yesterday's stored savings under Today, because the scan was only requested on mount, scope change or manual refresh. The local day is now one of the hook's triggers; the previous day's figure is dropped while the new scan runs. * serve: a menubar poll is never answered from the status snapshot Inside its settle window the status snapshot returns the pre-change payload on purpose. The resident serve process then memoized that answer as clean, so after a single write followed by quiet the headline stayed on the old figure until the next write or the five minute memo cap. The snapshot is for one-shot runs; the resident process already holds the parsed state, so it now skips it. * tests stop writing the real serve pid file; superseded caches are swept; installer notes reach the desktop card ServeConnection takes its pid file as a parameter, so the Swift tests no longer share ~/.cache/codeburn/menubar-serve.pid with a running menu bar, and the reaper only signals a record that is a serve --stdio command. Superseded session-cache, codex-results and cursor-results files (100MB+ each) are removed once untouched for 14 days, at most once a day. daily-cache and the hermes ledger are never swept: they carry sealed days a version bump adopts. The menu bar installer's leftover-copy advice is emitted as a marked line under CODEBURN_PROGRESS and shown on the desktop card. The skipped-refresh NSLog is debug only. The app's vitest workers turn off Node's built-in web storage. * menubar: anonymous usage statistics, under the same consent as the desktop and the Windows tray The Swift menu bar sent nothing, so every codeburn-menubar row was a Windows tray. It now follows the desktop's telemetry.v1.json when that exists (read only: same install id, same on/off, onboarded required) and otherwise keeps its own state with the same region default (off in EU/EEA/UK/CH and when the region is unknown). Settings gains one Privacy toggle, disabled when the desktop owns the choice. Events use the tray's names; the daily usage snapshot is the CLI's block passed through a sanitizer and is left to the desktop when it is the consent source. Debug builds never send. A resident CLI that gets disabled for the run now says so in the log. * menubar statistics: private network session, abandoned batch on opt-out, a desktop No survives the desktop going away The sender used URLSession.shared, so a server or CDN cookie and the default User-Agent rode along and would have outlived an opt-out. It now owns an ephemeral session with no cookies, no cache, a fixed agent string and no redirects. A batch that is out when the toggle goes off is dropped rather than re-queued under the fresh id. The desktop's answer is recorded locally, so a missing or damaged state file never falls back to the region default, and the standalone id is persisted when minted. The toggle stays usable as a local off switch under desktop consent. Copy states what this app actually sends. * vercel gateway spend is shown on its own row and kept out of totals by default The gateway reports daily aggregates per model, with nothing to match against the local tools that were pointed at it, so every headline counted that traffic twice. Totals now leave the gateway slice out when all providers are shown; the row keeps its full amount and is marked not in total, --provider vercel-gateway is unchanged, and codeburn gateway-totals include folds it back in. The daily cache still stores the slice, so the choice applies retroactively. Reports with no gateway credential are byte-identical. The gateway's request_count now feeds the call count instead of each daily row counting as one call. Hermes: a mid-session price change lands on the day it is observed and sealed days are never rewritten; stated in the code and changelog. * gateway exclusion applies to every report through the parse, and the detail panels follow the headline The first pass narrowed only the day totals, so By tool, top models, top projects, activities, status json projects and any project-filtered table still carried gateway spend next to a headline that did not, and By tool shares could pass 100%. The rule now lives in parseAllSessions: with all providers in scope and the opt-in off, aggregate-only sessions are dropped after the memo, and the callers that derive cached days opt out so stored slices are unchanged. day.projects is reduced like models. The gateway stays visible once, as a labelled not-in-total row with no share, and standalone reports note the excluded amount on stderr so machine output is unchanged. * dashboard: the background history index follows the gateway exclusion too The index keeps the whole corpus so it can fill the daily cache, but its per-period projection handed that unfiltered list to the project, model and activity panels, so they regained gateway spend once the index landed. * ci: a hung lock suite fails in 90s and retries once with a warning; slow Windows tests get measured limits The cache-lock step failed 6 of the last 60 runs with no output for five minutes after the vitest banner; passing runs take 12-18s on every Node version. Each attempt is now capped at 90s and retried once, with a warning whenever that happens. On windows-latest a single CLI spawn takes 1.4-12s, so the four-spawn status snapshot test and the c6 parser suite get limits taken from those runs, each with its reason. Both test jobs print their ten slowest cases. * desktop: Privacy & data uses the same rows as the rest of Settings The pane mixed two static claims with two controls in its own layout. It now uses the about-row pattern every other pane uses: title and hint on the left, one control on the right. The claims became the subtitle. Rows: anonymous usage statistics (toggle, link to what is sent), device sharing state with Manage, local report snapshots with Clear, export with Open export. * desktop: Privacy & data keeps one bounded column and rows that never squeeze The card stretched with the window, stranding each control hundreds of pixels from its text. This pane's heading, subtitle and card now share a 760px column and one text measure. Rows stack on their own width, because the window can never be narrow enough for the old viewport rule to fire; row buttons do not wrap. The what-is-sent link sits on its own line, and the snapshot and export descriptions fit their measure and say this machine. * menubar tests clean up their scratch defaults and leave the real Keychain alone Four test files never removed their UserDefaults suites and the rest removed the domain but left the plist, so thousands of files piled up in ~/Library/Preferences. A shared helper forgets a suite and deletes its file, and every test that makes a suite now uses it. cfprefsd still rewrites an empty plist when the test process exits, so a run leaves about a hundred 42-byte files with no test data in them. The real-Keychain round trip only runs with CODEBURN_TEST_REAL_KEYCHAIN=1. * desktop: the resident parser retires after 15 idle minutes and restarts on demand The renderer stops polling while the window is hidden, but the serve child stayed resident with its parsed cache, one to two GB on a large corpus. After 15 minutes without a request it is stopped the way a settings restart stops it, without spending the unexpected-death budget, and the next request starts a new resident through the existing lazy path, never a one-shot. CODEBURN_SERVE_IDLE_MS tunes or disables it. * desktop: every settings pane keeps a bounded column, and dark buttons have an edge Cards stretched with the window, so on a wide display controls sat up to 1300px from their labels and intro lines ran past 140 characters. All panes now share one left-aligned column (760px, 980px for projects, aliases and pricing, which hold wide rows) and one text measure. Rows stack on their own width instead of a viewport rule the 900px minimum window could never reach, and a long path in Projects no longer overflows the pane. In dark mode the secondary button matched or sat below its surface, and was invisible on the plugin install dialog. It gets a face and a border from two new tokens; light is unchanged. The onboarding consent label matches Settings. * desktop: this device shows its fingerprint on its own line The local name and the fingerprint are two adjacent inline spans, so they read as one run of text. * menubar: the resident parser retires after 15 idle minutes and restarts on demand The menu bar kept its serve child, and the parsed cache with it, for the whole run, even with the popover closed and nothing changing. After 15 minutes without a request the child is retired without counting as a death, and the next request starts a new resident through ensureStarted, never the one-shot fallback, whose snapshot settle window would make the figure lag a whole tick. The window sits above the longest gap between real requests, so a child stays warm while work is happening. CodeBurnServeIdleSeconds tunes or disables it. * serve: a poll re-checks only what the watcher saw change, and shard writes are coalesced With a session being written, every poll re-listed about 2,400 directories and re-fingerprinted about 6,000 transcripts, then rewrote the whole current-month shard (49MB on a large corpus) and read it back on the next poll. The resident process now reuses the previous listing and fingerprints for paths its root watcher proves untouched, and falls back to the full sweep whenever the watcher is missing, unhealthy, overflowed, armed after the sweep, does not cover the path, the memo is older than 4.5 minutes, or the process was suspended. Shard publication is held for up to 90s and flushed when stdin closes; a held write is dropped rather than written over something another process published. One-shot runs are unchanged. Active poll cost 0.71 to 0.33 CPU-s at a 30s cadence; time-to-reflect unchanged at about 1.2s across append, new dir, new file, delete, rename-over, in-flight, watcher overflow and unhealthy watcher. Changelog: state the telemetry default as it is in this version. * a retired parser gets to publish its held shards, and durable providers are never held Both apps retired the serve child with SIGTERM before its stdin-close flush could run, so every retire discarded the coalesced window. They now close stdin, give the child a bounded grace to publish and exit, and signal it only if it is still running; a settings restart does the same. Measured: flushed 0/5 before, 5/5 after, for both clients. copilot's cache entries are the only record once Copilot prunes its own files, so a held window that was dropped (retire, crash, kill -9) before the source was pruned lost that spend for good. A window that a durable provider dirtied is published on the poll that parsed it, as before coalescing existed. The RSS guard publishes a held window before it clears the caches instead of discarding it. * serve: release the lifetime parse after the fill, and make the collection real The RSS guard dropped its memos and then called globalThis.gc, which exists only under --expose-gc; no launcher passes it, so the collection had never run and the freed pages never went back. On a cold start the resident idled at 2.2GB with 364MB of live heap: clearing every memo moved RSS by 0MB, a collection alone by 700MB. After the background fill has sealed its summaries the process now publishes any held shard window, drops the memos it can re-read from disk (the cold start had loaded the cache with scope 'all', which then served every later poll), and collects; it collects again a minute later for as long as a pass returns 64MB, at most four times. Cold idle 2198MB to 700MB, warm 900MB to 781MB. Reports are leaf-identical cold and warm, time-to-reflect unchanged, a released month scope reloads in 0.3-0.5s. * warp: the billed cost reaches reports and survives the cache The provider derived a dollar cost from Warp's own billing record (provider cents, charged usage, or credits), but warp was missing from the reported-cost pass-through, so the cached call kept no cost and every report, cold or warm, priced the conversation from its tokens. A fixture billed at $1.22 reported $0.15. A call whose cost came from a billing record now keeps it; a call that only has the token floor stores none and is still re-priced when prices change. Warp entries re-parse once (provider parse version), and the daily cache moves to v34 so days whose Warp source still exists re-derive; call counts do not move, so nothing is double counted or dropped. * openclaw and pi: a reported cost survives the cache like every other reported cost Both providers read the cost their tool recorded for a message, and both were missing from the reported-cost pass-through, so reports priced every call from tokens instead. Fixtures reported $0.011 against $0.056 (openclaw) and $0.013 against $0.410 (pi). A call with a reported cost now keeps it; a call with none, or an explicit zero, stores none and is still re-priced when prices change. omp had been added to the list in #1150 and pi, the same parser, was never revisited. The provider list is one named set, the unreachable providerCallToTurn is gone, and both providers re-parse once; the v34 daily cache re-derives their days with call counts unchanged. * test: pin parse count per report and per resident poll
741 lines
36 KiB
TypeScript
741 lines
36 KiB
TypeScript
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
|
|
import { spawn, type ChildProcess } from 'child_process'
|
|
import { appendFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises'
|
|
import { tmpdir } from 'os'
|
|
import { join } from 'path'
|
|
import { classifyRootReuse, createOutputMemoEntry, fileDaySpan, outputMemoKey, servedDayRange } from '../src/serve.js'
|
|
|
|
it('timestamps a completed output memo before parsing begins', () => {
|
|
const parseStartedAt = 100
|
|
const rootEventDuringParseAt = 150
|
|
const parseCompletedAt = 200
|
|
const memo = createOutputMemoEntry(parseStartedAt, parseCompletedAt, 'output', 'config')
|
|
const rootsQuietSince = (sinceTs: number): boolean => rootEventDuringParseAt < sinceTs
|
|
|
|
// The old completion timestamp incorrectly made the in-parse event look
|
|
// older than the memo. The start timestamp keeps it visible to validation.
|
|
expect(rootsQuietSince(parseCompletedAt)).toBe(true)
|
|
expect(memo.createdAt).toBe(parseCompletedAt)
|
|
expect(memo.validatedFrom).toBe(parseStartedAt)
|
|
expect(rootsQuietSince(memo.validatedFrom)).toBe(false)
|
|
})
|
|
|
|
it('classifies watcher gaps as unknown without confusing them with dirty roots', () => {
|
|
expect(classifyRootReuse(100, { startedAt: 50, lastEventAt: 0, healthy: false })).toBe('unknown')
|
|
expect(classifyRootReuse(100, { startedAt: 150, lastEventAt: 0, healthy: true })).toBe('unknown')
|
|
expect(classifyRootReuse(100, { startedAt: 50, lastEventAt: 100, healthy: false })).toBe('dirty')
|
|
expect(classifyRootReuse(100, { startedAt: 50, lastEventAt: 100, healthy: true })).toBe('dirty')
|
|
expect(classifyRootReuse(100, { startedAt: 50, lastEventAt: 99, healthy: true })).toBe('clean')
|
|
})
|
|
|
|
describe('day-scoped invalidation', () => {
|
|
const day = (d: string): number => new Date(`${d}T12:00:00`).getTime()
|
|
const startOfDay = (ms: number): number => {
|
|
const x = new Date(ms)
|
|
return new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime()
|
|
}
|
|
const spanOf = (from: string, to: string) => fileDaySpan({ birthtimeMs: day(from), mtimeMs: day(to) }, startOfDay)
|
|
const august = { startMs: day('2026-08-20'), endMs: day('2026-08-20') + 3600_000 }
|
|
const dirty = { startedAt: 50, lastEventAt: 100, healthy: true }
|
|
|
|
it('covers every day between the creation of a file and its last write, plus a day of slack', () => {
|
|
const span = spanOf('2026-09-15', '2026-09-16')
|
|
expect(span.startMs).toBe(startOfDay(day('2026-09-14')))
|
|
expect(span.endMs).toBe(startOfDay(day('2026-09-17')) - 1)
|
|
})
|
|
|
|
it('keeps a finalized past range clean when only files from today changed', () => {
|
|
const state = { ...dirty, changedSince: () => ['/roots/today.jsonl'] }
|
|
expect(classifyRootReuse(100, state, august, () => spanOf('2026-09-16', '2026-09-16'))).toBe('clean')
|
|
})
|
|
|
|
it('dirties a range a changed file could have written into', () => {
|
|
const state = { ...dirty, changedSince: () => ['/roots/old.jsonl'] }
|
|
// Born before the queried day and still being appended: its own days reach
|
|
// into the range, so the range is not reusable.
|
|
expect(classifyRootReuse(100, state, august, () => spanOf('2026-08-19', '2026-09-16'))).toBe('dirty')
|
|
})
|
|
|
|
it('refuses to scope an event it cannot place', () => {
|
|
const unknownSpan = { ...dirty, changedSince: () => ['/roots/gone.jsonl'] }
|
|
expect(classifyRootReuse(100, unknownSpan, august, () => null)).toBe('dirty')
|
|
const unnamed = { ...dirty, changedSince: () => null }
|
|
expect(classifyRootReuse(100, unnamed, august, () => spanOf('2026-09-16', '2026-09-16'))).toBe('dirty')
|
|
// No range to scope against is the old, whole-corpus answer.
|
|
expect(classifyRootReuse(100, { ...dirty, changedSince: () => [] })).toBe('dirty')
|
|
})
|
|
|
|
it('still reports unknown coverage rather than clean', () => {
|
|
const state = { startedAt: 150, lastEventAt: 100, healthy: true, changedSince: () => ['/roots/today.jsonl'] }
|
|
expect(classifyRootReuse(100, state, august, () => spanOf('2026-09-16', '2026-09-16'))).toBe('unknown')
|
|
})
|
|
})
|
|
|
|
// End-to-end protocol test for `codeburn serve --stdio` (the desktop app's
|
|
// resident query server). Runs the real entry through tsx against the
|
|
// test-isolated env (env-isolation.ts points every provider at empty dirs),
|
|
// so requests answer fast and deterministically empty.
|
|
describe('codeburn serve --stdio', () => {
|
|
let child: ChildProcess
|
|
let buffer = ''
|
|
const waiters = new Map<number, (msg: Record<string, unknown>) => void>()
|
|
const progressFrames = new Map<number, Array<Record<string, unknown>>>()
|
|
let configPath = ''
|
|
let readyResolve: () => void
|
|
const ready = new Promise<void>(resolve => { readyResolve = resolve })
|
|
|
|
function request(id: number, args: string[]): Promise<Record<string, unknown>> {
|
|
return new Promise(resolve => {
|
|
waiters.set(id, resolve)
|
|
child.stdin!.write(JSON.stringify({ id, args }) + '\n')
|
|
})
|
|
}
|
|
|
|
function sendRaw(line: string): void {
|
|
child.stdin!.write(line + '\n')
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
const home = process.env['HOME']!
|
|
configPath = join(home, '.config', 'codeburn', 'config.json')
|
|
await mkdir(join(home, '.config', 'codeburn'), { recursive: true })
|
|
// Give the resident process one real provider root to arm. With no
|
|
// successfully armed roots, event-driven reuse correctly stays disabled.
|
|
await mkdir(join(home, '.claude', 'projects'), { recursive: true })
|
|
await writeFile(configPath, JSON.stringify({ currency: { code: 'USD' } }), 'utf8')
|
|
|
|
// Keep the EUR half of the config-freshness regression fully offline.
|
|
const cacheDir = join(home, '.cache', 'codeburn')
|
|
await mkdir(cacheDir, { recursive: true })
|
|
await writeFile(join(cacheDir, 'exchange-rate.json'), JSON.stringify({
|
|
timestamp: Date.now(),
|
|
code: 'EUR',
|
|
rate: 0.9,
|
|
}), 'utf8')
|
|
|
|
child = spawn(process.execPath, ['--import', 'tsx', join(__dirname, '..', 'src', 'cli.ts'), 'serve', '--stdio'], {
|
|
stdio: ['pipe', 'pipe', 'ignore'],
|
|
env: { ...process.env },
|
|
})
|
|
child.stdout!.setEncoding('utf8')
|
|
child.stdout!.on('data', (chunk: string) => {
|
|
buffer += chunk
|
|
let idx: number
|
|
while ((idx = buffer.indexOf('\n')) >= 0) {
|
|
const line = buffer.slice(0, idx).trim()
|
|
buffer = buffer.slice(idx + 1)
|
|
if (!line) continue
|
|
let msg: Record<string, unknown>
|
|
try { msg = JSON.parse(line) } catch { continue }
|
|
if (msg['ready']) { readyResolve(); continue }
|
|
if (typeof msg['progress'] === 'string' && !('ok' in msg)) {
|
|
const id = msg['id'] as number
|
|
const frames = progressFrames.get(id) ?? []
|
|
frames.push(msg)
|
|
progressFrames.set(id, frames)
|
|
continue
|
|
}
|
|
const waiter = waiters.get(msg['id'] as number)
|
|
if (waiter) { waiters.delete(msg['id'] as number); waiter(msg) }
|
|
}
|
|
})
|
|
await ready
|
|
}, 60_000)
|
|
|
|
afterAll(() => {
|
|
child?.kill('SIGKILL')
|
|
})
|
|
|
|
it('answers an allowed query with the command stdout', async () => {
|
|
const res = await request(1, ['status', '--format', 'menubar-json', '--period', 'today'])
|
|
expect(res['ok']).toBe(true)
|
|
const payload = JSON.parse(res['output'] as string) as { current: { label: string } }
|
|
expect(payload.current.label).toContain('Today')
|
|
}, 60_000)
|
|
|
|
it('isolates option state between requests (no sticky --period)', async () => {
|
|
// The whole reason serve rebuilds the program per request: commander
|
|
// option state is sticky, and a leaked --period would mislabel every
|
|
// later panel.
|
|
const month = await request(2, ['status', '--format', 'menubar-json', '--period', 'month'])
|
|
const today = await request(3, ['status', '--format', 'menubar-json', '--period', 'today'])
|
|
const monthLabel = (JSON.parse(month['output'] as string) as { current: { label: string } }).current.label
|
|
const todayLabel = (JSON.parse(today['output'] as string) as { current: { label: string } }).current.label
|
|
expect(monthLabel).not.toBe(todayLabel)
|
|
expect(todayLabel).toContain('Today')
|
|
}, 60_000)
|
|
|
|
it('stamps every answer with the generation it was derived in', async () => {
|
|
const first = await request(40, ['status', '--format', 'menubar-json', '--period', 'today'])
|
|
const second = await request(41, ['status', '--format', 'menubar-json', '--period', 'week'])
|
|
const firstGen = first['generation'] as { n: number; at: string }
|
|
const secondGen = second['generation'] as { n: number; at: string }
|
|
expect(firstGen.n).toBeGreaterThan(0)
|
|
// A distinct derivation advances the counter, and says when it happened.
|
|
expect(secondGen.n).toBeGreaterThan(firstGen.n)
|
|
expect(Number.isNaN(Date.parse(secondGen.at))).toBe(false)
|
|
expect(Date.parse(secondGen.at)).toBeGreaterThanOrEqual(Date.parse(firstGen.at))
|
|
|
|
// A repeat of the first query is either re-derived (a new counter) or
|
|
// served from the memo, in which case it carries the SAME stamp it was
|
|
// derived under rather than the moment it was handed over.
|
|
const repeat = await request(42, ['status', '--format', 'menubar-json', '--period', 'today'])
|
|
const repeatGen = repeat['generation'] as { n: number; at: string }
|
|
if (repeat['output'] === first['output']) {
|
|
expect([firstGen.n, secondGen.n + 1]).toContain(repeatGen.n)
|
|
}
|
|
expect(repeatGen.n).toBeGreaterThan(0)
|
|
}, 60_000)
|
|
|
|
// The desktop app buckets these into its consent-gated app_close event: serve
|
|
// is a plain CLI child, so Electron's own metrics cannot see this cost.
|
|
it('reports its own CPU seconds and peak RSS on an answer', async () => {
|
|
const res = await request(43, ['status', '--format', 'menubar-json', '--period', 'today'])
|
|
const usage = res['usage'] as { cpuSec: number; rssMb: number }
|
|
expect(usage.cpuSec).toBeGreaterThan(0)
|
|
expect(usage.rssMb).toBeGreaterThan(0)
|
|
}, 60_000)
|
|
|
|
it('refuses commands outside the read allowlist', async () => {
|
|
const res = await request(4, ['currency', 'EUR'])
|
|
expect(res['ok']).toBe(false)
|
|
expect(res['refused']).toBe(true)
|
|
})
|
|
|
|
it('refuses a smuggled positional on an allowed command', async () => {
|
|
const res = await request(5, ['sessions', 'positional-arg'])
|
|
expect(res['ok']).toBe(false)
|
|
expect(res['refused']).toBe(true)
|
|
})
|
|
|
|
it('refuses every optimize apply-only option without touching shell config or the action journal', async () => {
|
|
const home = process.env['HOME']!
|
|
const zshrc = join(home, '.zshrc')
|
|
const journal = join(home, '.config', 'codeburn', 'actions', 'journal.jsonl')
|
|
await writeFile(zshrc, '# user-owned\n', 'utf8')
|
|
|
|
// `optimize` is the only served command whose Commander definition also
|
|
// has mutation-capable options. The full request below used to execute a
|
|
// shell-config action inside the resident process.
|
|
const applied = await request(300, [
|
|
'optimize', '--apply', '--yes', '--only', 'bash-output-cap', '--period', 'today',
|
|
])
|
|
expect(applied).toMatchObject({ ok: false, refused: true })
|
|
|
|
// Keep the allowlist categorical: apply-only modifiers are not useful to
|
|
// a read query and must not become resident options on their own either.
|
|
for (const [id, args] of [
|
|
[301, ['optimize', '--yes']],
|
|
[302, ['optimize', '--dry-run']],
|
|
[303, ['optimize', '--only', 'bash-output-cap']],
|
|
] as const) {
|
|
expect(await request(id, [...args])).toMatchObject({ ok: false, refused: true })
|
|
}
|
|
|
|
expect(await readFile(zshrc, 'utf8')).toBe('# user-owned\n')
|
|
await expect(readFile(journal, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' })
|
|
}, 60_000)
|
|
|
|
it('accepts the reviewed read-only option surface for every served command', async () => {
|
|
const commands: Array<[number, string[]]> = [
|
|
[310, ['status', '--format', 'json', '--period', 'today']],
|
|
[311, ['overview', '--period', 'today', '--no-color']],
|
|
[312, ['models', '--format', 'json', '--period', 'today', '--no-totals']],
|
|
[313, ['sessions', '--format', 'json', '--period', 'today', '--no-pager']],
|
|
[314, ['compare', '--format', 'json', '--period', 'today']],
|
|
[315, ['yield', '--format', 'json', '--period', 'today']],
|
|
[316, ['spend', '--format', 'flow-json', '--period', 'today']],
|
|
[317, ['optimize', '--format', 'json', '--period', 'today']],
|
|
[318, ['audit', '--format', 'json', '--period', 'today']],
|
|
[319, ['report', '--format', 'json', '--period', 'today']],
|
|
]
|
|
for (const [id, args] of commands) {
|
|
expect(await request(id, args)).toMatchObject({ ok: true })
|
|
}
|
|
}, 60_000)
|
|
|
|
// SERVE_OPTIONS mirrors the Commander definitions: a command that declares
|
|
// --project/--exclude but is missing them here falls back to a cold spawn.
|
|
it('routes --project/--exclude for every command that declares them', async () => {
|
|
const commands: Array<[number, string[]]> = [
|
|
[330, ['status', '--format', 'json', '--period', 'today', '--project', '/nope']],
|
|
[331, ['overview', '--period', 'today', '--no-color', '--exclude', '/nope']],
|
|
[332, ['models', '--format', 'json', '--period', 'today', '--project', '/nope']],
|
|
[333, ['sessions', '--format', 'json', '--period', 'today', '--exclude', '/nope']],
|
|
[334, ['compare', '--format', 'json', '--period', 'today', '--project', '/nope']],
|
|
[335, ['yield', '--format', 'json', '--period', 'today', '--exclude', '/nope']],
|
|
[336, ['spend', '--format', 'flow-json', '--period', 'today', '--project', '/nope']],
|
|
[337, ['optimize', '--format', 'json', '--period', 'today', '--exclude', '/nope']],
|
|
[338, ['audit', '--format', 'json', '--period', 'today', '--project', '/nope']],
|
|
[339, ['report', '--format', 'json', '--period', 'today', '--exclude', '/nope']],
|
|
]
|
|
for (const [id, args] of commands) {
|
|
expect(await request(id, args)).toMatchObject({ ok: true })
|
|
}
|
|
}, 60_000)
|
|
|
|
// #1451: --route/--billing are call-level slicers on models/sessions/audit,
|
|
// the same shape as --project/--exclude, and must be servable the same way.
|
|
it('routes --route/--billing for every command that declares them', async () => {
|
|
const commands: Array<[number, string[]]> = [
|
|
[350, ['models', '--format', 'json', '--period', 'today', '--route', 'bedrock']],
|
|
[351, ['sessions', '--format', 'json', '--period', 'today', '--billing', 'metered']],
|
|
[352, ['audit', '--format', 'json', '--period', 'today', '--route', 'direct', '--billing', 'subscription']],
|
|
]
|
|
for (const [id, args] of commands) {
|
|
expect(await request(id, args)).toMatchObject({ ok: true })
|
|
}
|
|
}, 60_000)
|
|
|
|
// `report` is the interactive dashboard on every format but json, and a TUI
|
|
// inside a child whose stdout is the wire would write frames nobody can read.
|
|
// Only its JSON form is servable; the rest is refused and falls back to a
|
|
// one-shot spawn, which is where an interactive dashboard belongs.
|
|
it('serves the JSON report but refuses its interactive form', async () => {
|
|
expect(await request(340, ['report', '--format', 'json', '--period', 'today'])).toMatchObject({ ok: true })
|
|
expect(await request(341, ['report', '--period', 'today'])).toMatchObject({ ok: false, refused: true })
|
|
expect(await request(342, ['report', '--format', 'tui', '--period', 'today'])).toMatchObject({ ok: false, refused: true })
|
|
// --refresh only paces the dashboard, so it is not part of the served surface.
|
|
expect(await request(343, ['report', '--format', 'json', '--period', 'today', '--refresh', '60'])).toMatchObject({ ok: false, refused: true })
|
|
}, 60_000)
|
|
|
|
it('survives a malformed request line and keeps serving', async () => {
|
|
sendRaw('this is not json')
|
|
const res = await request(6, ['status', '--format', 'menubar-json', '--period', 'today'])
|
|
expect(res['ok']).toBe(true)
|
|
}, 60_000)
|
|
|
|
it('streams captured command stderr as protocol progress frames', async () => {
|
|
const res = await request(7, ['status', '--provider', 'definitely-not-a-real-provider'])
|
|
expect(res['ok']).toBe(false)
|
|
|
|
const frames = progressFrames.get(7) ?? []
|
|
expect(frames.length).toBeGreaterThan(0)
|
|
expect(frames.every(frame => Object.keys(frame).sort().join(',') === 'id,progress')).toBe(true)
|
|
expect(frames.map(frame => frame['progress']).join('')).toContain('unknown provider')
|
|
}, 60_000)
|
|
|
|
it('discovers a newly configured Claude root on identical resident argv', async () => {
|
|
const home = process.env['HOME']!
|
|
const rootA = join(home, 'claude-root-a')
|
|
const rootB = join(home, 'claude-root-b')
|
|
const slug = '-Users-test-shared-project'
|
|
const cwd = '/Users/test/shared-project'
|
|
|
|
const writeClaudeSession = async (root: string, sessionId: string, marker: string): Promise<void> => {
|
|
const projectDir = join(root, 'projects', slug)
|
|
await mkdir(projectDir, { recursive: true })
|
|
const lines = [
|
|
{
|
|
type: 'summary', summary: marker, leafUuid: `leaf-${marker}`, sessionId, cwd,
|
|
timestamp: '2026-08-12T10:00:00.000Z',
|
|
},
|
|
{
|
|
type: 'user', uuid: `user-${marker}`, sessionId, cwd,
|
|
timestamp: '2026-08-12T10:00:01.000Z', message: { role: 'user', content: marker },
|
|
},
|
|
{
|
|
type: 'assistant', uuid: `assistant-${marker}`, parentUuid: `user-${marker}`, sessionId, cwd,
|
|
timestamp: '2026-08-12T10:00:02.000Z',
|
|
message: {
|
|
id: `msg-${marker}`, type: 'message', role: 'assistant', model: 'claude-sonnet-4-6',
|
|
content: [{ type: 'text', text: 'reply' }], usage: { input_tokens: 100, output_tokens: 50 },
|
|
},
|
|
},
|
|
]
|
|
await writeFile(join(projectDir, `${sessionId}.jsonl`), lines.map(line => JSON.stringify(line)).join('\n'))
|
|
}
|
|
|
|
await writeClaudeSession(rootA, 'resident-session-a', 'a')
|
|
await writeClaudeSession(rootB, 'resident-session-b', 'b')
|
|
const args = ['sessions', '--period', 'lifetime', '--provider', 'claude', '--format', 'json', '--no-pager']
|
|
|
|
await writeFile(configPath, JSON.stringify({ claudeConfigDirs: [rootA] }), 'utf8')
|
|
const first = await request(200, args)
|
|
expect(first['ok']).toBe(true)
|
|
expect((JSON.parse(first['output'] as string) as Array<{ sessionId: string }>).map(row => row.sessionId)).toEqual([
|
|
'resident-session-a',
|
|
])
|
|
|
|
// Same command in the same process; only config.json adds root B.
|
|
await writeFile(configPath, JSON.stringify({ claudeConfigDirs: [rootA, rootB] }), 'utf8')
|
|
const second = await request(201, args)
|
|
expect(second['ok']).toBe(true)
|
|
expect((JSON.parse(second['output'] as string) as Array<{ sessionId: string }>).map(row => row.sessionId).sort()).toEqual([
|
|
'resident-session-a',
|
|
'resident-session-b',
|
|
])
|
|
|
|
// Keep the following currency-freshness regression self-contained.
|
|
await writeFile(configPath, JSON.stringify({ currency: { code: 'USD' } }), 'utf8')
|
|
}, 60_000)
|
|
|
|
it('invalidates identical-argv output memo immediately when config.json changes', async () => {
|
|
const args = ['status', '--format', 'menubar-json', '--period', 'week', '--no-optimize', '--no-timeline']
|
|
const usdConfig = JSON.stringify({ currency: { code: 'USD' } })
|
|
await writeFile(configPath, usdConfig, 'utf8')
|
|
|
|
let previous = await request(8, args)
|
|
expect(previous['ok']).toBe(true)
|
|
expect((JSON.parse(previous['output'] as string) as { currency: { code: string } }).currency.code).toBe('USD')
|
|
|
|
// Prove this argv is actually hitting the output memo before testing its
|
|
// invalidation. The root watchers arm asynchronously at serve startup, so
|
|
// allow a few requests until two byte-identical generated payloads arrive.
|
|
let memoized: Record<string, unknown> | null = null
|
|
for (let id = 9; id < 110; id++) {
|
|
await new Promise(resolve => setTimeout(resolve, 20))
|
|
const next = await request(id, args)
|
|
if (next['output'] === previous['output']) {
|
|
memoized = next
|
|
break
|
|
}
|
|
previous = next
|
|
}
|
|
expect(memoized).not.toBeNull()
|
|
|
|
// A byte-identical rewrite changes filesystem metadata but not effective
|
|
// configuration. The memo must survive it and return the exact generated
|
|
// payload, including the original volatile `generated` timestamp.
|
|
await new Promise(resolve => setTimeout(resolve, 20))
|
|
await writeFile(configPath, usdConfig, 'utf8')
|
|
const sameBytes = await request(110, args)
|
|
expect(sameBytes['ok']).toBe(true)
|
|
expect(sameBytes['output']).toBe(memoized!['output'])
|
|
// `generated` is minted per render, so an unchanged stamp is the proof
|
|
// that a memo hit returns the stored string instead of re-rendering.
|
|
const stamp = (res: Record<string, unknown>): string =>
|
|
(JSON.parse(res['output'] as string) as { generated: string }).generated
|
|
expect(stamp(sameBytes)).toBe(stamp(memoized!))
|
|
|
|
// Same byte length as USD: a size-only fingerprint would miss this.
|
|
await writeFile(configPath, JSON.stringify({ currency: { code: 'EUR' } }), 'utf8')
|
|
const fresh = await request(111, args)
|
|
expect(fresh['ok']).toBe(true)
|
|
expect((JSON.parse(fresh['output'] as string) as { currency: { code: string } }).currency.code).toBe('EUR')
|
|
expect(fresh['output']).not.toBe(memoized!['output'])
|
|
|
|
// Removing the configured currency is the USD reset contract. The serve
|
|
// process must reset its module-level currency state as well as invalidate
|
|
// the output memo, otherwise a long-lived child keeps rendering EUR.
|
|
await writeFile(configPath, '{}', 'utf8')
|
|
const reset = await request(112, args)
|
|
expect(reset['ok']).toBe(true)
|
|
expect((JSON.parse(reset['output'] as string) as {
|
|
currency: { code: string; rate: number }
|
|
}).currency).toMatchObject({ code: 'USD', rate: 1 })
|
|
}, 60_000)
|
|
|
|
it('exits on natural stdin EOF after arming a watcher for an existing Claude root', async () => {
|
|
const claudeRoot = join(process.env['HOME']!, 'claude-eof-root')
|
|
await mkdir(join(claudeRoot, 'projects'), { recursive: true })
|
|
|
|
const eofChild = spawn(process.execPath, ['--import', 'tsx', join(__dirname, '..', 'src', 'cli.ts'), 'serve', '--stdio'], {
|
|
stdio: ['pipe', 'pipe', 'ignore'],
|
|
env: { ...process.env, CLAUDE_CONFIG_DIR: claudeRoot },
|
|
})
|
|
let stdout = ''
|
|
const becameReady = new Promise<void>((resolve, reject) => {
|
|
eofChild.once('error', reject)
|
|
eofChild.stdout!.setEncoding('utf8')
|
|
eofChild.stdout!.on('data', (chunk: string) => {
|
|
stdout += chunk
|
|
if (stdout.split('\n').some(line => {
|
|
try { return (JSON.parse(line) as { ready?: boolean }).ready === true } catch { return false }
|
|
})) resolve()
|
|
})
|
|
eofChild.once('exit', (code, signal) => reject(new Error(`serve exited before ready: ${code ?? signal}`)))
|
|
})
|
|
const exited = new Promise<boolean>(resolve => eofChild.once('exit', () => resolve(true)))
|
|
|
|
let naturalExit = false
|
|
try {
|
|
await becameReady
|
|
// READY is intentionally emitted before provider probing; give the real
|
|
// watcher setup time to finish so the regression exercises its handle.
|
|
await new Promise(resolve => setTimeout(resolve, 500))
|
|
eofChild.stdin!.end()
|
|
naturalExit = await Promise.race([
|
|
exited,
|
|
new Promise<false>(resolve => setTimeout(() => resolve(false), 2_000)),
|
|
])
|
|
} finally {
|
|
if (!naturalExit) {
|
|
eofChild.kill('SIGKILL')
|
|
await exited
|
|
}
|
|
}
|
|
|
|
expect(naturalExit).toBe(true)
|
|
}, 10_000)
|
|
|
|
it('answers an in-flight request in full when stdin closes on the same tick', async () => {
|
|
// The transport closing does not cancel work already accepted. Returning
|
|
// before the queue drains loses the response frame outright, and because
|
|
// runCaptured() monkeypatches process.exit into a thrown ExitSignal it also
|
|
// turns the clean exit into a failure.
|
|
const raceChild = spawn(process.execPath, ['--import', 'tsx', join(__dirname, '..', 'src', 'cli.ts'), 'serve', '--stdio'], {
|
|
stdio: ['pipe', 'pipe', 'ignore'],
|
|
env: { ...process.env },
|
|
})
|
|
let stdout = ''
|
|
const lines = (): Array<Record<string, unknown>> => stdout.split('\n')
|
|
.map(line => { try { return JSON.parse(line) as Record<string, unknown> } catch { return null } })
|
|
.filter((v): v is Record<string, unknown> => v !== null)
|
|
|
|
const becameReady = new Promise<void>((resolve, reject) => {
|
|
raceChild.once('error', reject)
|
|
raceChild.stdout!.setEncoding('utf8')
|
|
raceChild.stdout!.on('data', (chunk: string) => {
|
|
stdout += chunk
|
|
if (lines().some(msg => msg['ready'] === true)) resolve()
|
|
})
|
|
raceChild.once('exit', (code, signal) => reject(new Error(`serve exited before ready: ${code ?? signal}`)))
|
|
})
|
|
const exited = new Promise<number | null>(resolve => raceChild.once('exit', code => resolve(code)))
|
|
|
|
await becameReady
|
|
// Request and EOF in the same tick: the request is accepted, then the
|
|
// transport is gone before it can possibly have finished.
|
|
raceChild.stdin!.write(JSON.stringify({ id: 77, args: ['status', '--format', 'json'] }) + '\n')
|
|
raceChild.stdin!.end()
|
|
|
|
const code = await Promise.race([
|
|
exited,
|
|
new Promise<'hung'>(resolve => setTimeout(() => resolve('hung'), 15_000)),
|
|
])
|
|
if (code === 'hung') { raceChild.kill('SIGKILL'); await exited }
|
|
|
|
expect(code).toBe(0)
|
|
const answer = lines().find(msg => msg['id'] === 77)
|
|
expect(answer).toBeDefined()
|
|
expect(answer!['ok']).toBe(true)
|
|
expect(typeof answer!['output']).toBe('string')
|
|
expect(() => JSON.parse(answer!['output'] as string)).not.toThrow()
|
|
}, 25_000)
|
|
|
|
it('gives up on an async-wedged request at the drain bound instead of lingering', async () => {
|
|
// The drain must not become the orphan it was added to prevent. A request
|
|
// that never settles releases the child at the bound (shortened here from
|
|
// its 45s default, which no legitimate request comes near).
|
|
const drainMs = 1_500
|
|
const wedgeChild = spawn(process.execPath, ['--import', 'tsx', join(__dirname, 'fixtures', 'serve-wedged-request.ts')], {
|
|
stdio: ['pipe', 'pipe', 'ignore'],
|
|
env: { ...process.env, CODEBURN_SERVE_DRAIN_MS: String(drainMs) },
|
|
})
|
|
let stdout = ''
|
|
const becameReady = new Promise<void>((resolve, reject) => {
|
|
wedgeChild.once('error', reject)
|
|
wedgeChild.stdout!.setEncoding('utf8')
|
|
wedgeChild.stdout!.on('data', (chunk: string) => {
|
|
stdout += chunk
|
|
if (stdout.includes('"ready"')) resolve()
|
|
})
|
|
wedgeChild.once('exit', () => reject(new Error('serve exited before ready')))
|
|
})
|
|
const exited = new Promise<number | null>(resolve => wedgeChild.once('exit', code => resolve(code)))
|
|
|
|
await becameReady
|
|
wedgeChild.stdin!.write(JSON.stringify({ id: 91, args: ['status', '--format', 'json'] }) + '\n')
|
|
wedgeChild.stdin!.end()
|
|
|
|
const began = Date.now()
|
|
const outcome = await Promise.race([
|
|
exited.then(() => 'exited' as const),
|
|
new Promise<'hung'>(resolve => setTimeout(() => resolve('hung'), drainMs + 12_000)),
|
|
])
|
|
const elapsed = Date.now() - began
|
|
if (outcome === 'hung') { wedgeChild.kill('SIGKILL'); await exited }
|
|
|
|
expect(outcome).toBe('exited')
|
|
// It waited for the request (not an instant return) but did not wait forever.
|
|
expect(elapsed).toBeGreaterThanOrEqual(drainMs - 250)
|
|
}, 30_000)
|
|
})
|
|
|
|
describe('output memo key', () => {
|
|
const args = ['status', '--format', 'menubar-json', '--period', 'today', '--no-timeline']
|
|
|
|
it('separates the same query asked on either side of local midnight', () => {
|
|
const before = outputMemoKey(args, new Date(2026, 8, 16, 23, 59))
|
|
const after = outputMemoKey(args, new Date(2026, 8, 17, 0, 1))
|
|
expect(before).not.toBe(after)
|
|
})
|
|
|
|
it('is stable for the same query within a day', () => {
|
|
expect(outputMemoKey(args, new Date(2026, 8, 16, 9, 0)))
|
|
.toBe(outputMemoKey(args, new Date(2026, 8, 16, 17, 30)))
|
|
})
|
|
|
|
it('separates queries whose resolved day range differs', () => {
|
|
const now = new Date(2026, 8, 16, 12, 0)
|
|
const day = ['report', '--format', 'json', '--day', '2026-08-20']
|
|
const otherDay = ['report', '--format', 'json', '--day', '2026-08-21']
|
|
expect(outputMemoKey(day, now)).not.toBe(outputMemoKey(otherDay, now))
|
|
})
|
|
})
|
|
|
|
describe('servedDayRange', () => {
|
|
const day = (d: Date): string => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
|
|
|
it('reads an explicit day', () => {
|
|
expect(servedDayRange(['report', '--format', 'json', '--day', '2026-08-20']))
|
|
.toEqual({ from: '2026-08-20', to: '2026-08-20' })
|
|
})
|
|
|
|
it('reads an explicit from/to window', () => {
|
|
expect(servedDayRange(['status', '--format', 'menubar-json', '--from', '2026-08-01', '--to', '2026-08-31']))
|
|
.toEqual({ from: '2026-08-01', to: '2026-08-31' })
|
|
})
|
|
|
|
it('resolves a named period against today', () => {
|
|
const today = day(new Date())
|
|
expect(servedDayRange(['status', '--format', 'menubar-json', '--period', 'today']))
|
|
.toEqual({ from: today, to: today })
|
|
const week = servedDayRange(['status', '--format', 'menubar-json', '--period', 'week'])
|
|
expect(week?.to).toBe(today)
|
|
expect(week!.from < today).toBe(true)
|
|
})
|
|
|
|
it('accepts the short period flag and the inline form', () => {
|
|
expect(servedDayRange(['models', '--format', 'json', '-p', 'today']))
|
|
.toEqual(servedDayRange(['models', '--format', 'json', '--period', 'today']))
|
|
expect(servedDayRange(['models', '--format', 'json', '--period=today']))
|
|
.toEqual(servedDayRange(['models', '--format', 'json', '--period', 'today']))
|
|
})
|
|
|
|
it('says nothing rather than guessing a default or a bad value', () => {
|
|
// The command's own default period lives in main.ts; guessing it here would
|
|
// stamp a range the answer may not have used.
|
|
expect(servedDayRange(['status', '--format', 'menubar-json'])).toBeNull()
|
|
expect(servedDayRange(['status', '--format', 'menubar-json', '--period', 'fortnight'])).toBeNull()
|
|
expect(servedDayRange(['report', '--format', 'json', '--day', 'not-a-day'])).toBeNull()
|
|
})
|
|
})
|
|
|
|
// Regression: the desktop polls `status --format menubar-json --no-optimize`,
|
|
// and `--no-optimize` used to route the resident child through the on-disk
|
|
// status snapshot. A poll landing inside that snapshot's settle window is
|
|
// answered with the deliberately deferred PRE-change payload, which serve then
|
|
// memoized; with the roots quiet again the memo stayed valid and replayed the
|
|
// stale payload until the next write or the 5-minute memo cap. Measured: the
|
|
// menubar stuck on the old cost for 40s+.
|
|
describe('codeburn serve --stdio never defers a menubar poll', () => {
|
|
let child: ChildProcess
|
|
let home = ''
|
|
let sessionFile = ''
|
|
const waiters = new Map<number, (msg: Record<string, unknown>) => void>()
|
|
let readyResolve: () => void
|
|
const ready = new Promise<void>(resolve => { readyResolve = resolve })
|
|
|
|
const calls = (res: Record<string, unknown>): number =>
|
|
(JSON.parse(res['output'] as string) as { current: { calls: number } }).current.calls
|
|
const cost = (res: Record<string, unknown>): number =>
|
|
(JSON.parse(res['output'] as string) as { current: { cost: number } }).current.cost
|
|
|
|
function request(id: number, args: string[]): Promise<Record<string, unknown>> {
|
|
return new Promise(resolve => {
|
|
waiters.set(id, resolve)
|
|
child.stdin!.write(JSON.stringify({ id, args }) + '\n')
|
|
})
|
|
}
|
|
|
|
// The corpus fixture is shaped like the ones in cli-status-menubar.test.ts:
|
|
// two hours back, clamped inside the current UTC day (TZ is pinned to UTC),
|
|
// so a run started just after midnight still lands inside "today".
|
|
const now = new Date()
|
|
const todayUtcMidnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
|
|
const base = new Date(Math.max(todayUtcMidnight, now.getTime() - 2 * 3600_000))
|
|
const ts = (offset: number): string => new Date(base.getTime() + offset).toISOString().replace(/\.\d+Z$/, 'Z')
|
|
const pricedCall = (n: number, offset: number): string => [
|
|
JSON.stringify({ type: 'user', sessionId: 's1', timestamp: ts(offset), message: { role: 'user', content: 'go' } }),
|
|
JSON.stringify({
|
|
type: 'assistant', sessionId: 's1', timestamp: ts(offset + 60_000),
|
|
message: {
|
|
id: `msg-${n}`, type: 'message', role: 'assistant', model: 'claude-sonnet-4-5',
|
|
content: [{ type: 'text', text: 'done' }],
|
|
usage: { input_tokens: 500, output_tokens: 50 },
|
|
},
|
|
}),
|
|
].join('\n')
|
|
|
|
beforeAll(async () => {
|
|
home = await mkdtemp(join(tmpdir(), 'codeburn-serve-freshness-'))
|
|
const projectDir = join(home, '.claude', 'projects', 'myapp')
|
|
await mkdir(projectDir, { recursive: true })
|
|
await mkdir(join(home, '.config', 'codeburn'), { recursive: true })
|
|
await writeFile(join(home, '.config', 'codeburn', 'config.json'), JSON.stringify({ currency: { code: 'USD' } }), 'utf8')
|
|
sessionFile = join(projectDir, 'session.jsonl')
|
|
await writeFile(sessionFile, pricedCall(1, 0) + '\n', 'utf8')
|
|
|
|
child = spawn(process.execPath, ['--import', 'tsx', join(__dirname, '..', 'src', 'cli.ts'), 'serve', '--stdio'], {
|
|
stdio: ['pipe', 'pipe', 'ignore'],
|
|
env: {
|
|
...process.env,
|
|
HOME: home, USERPROFILE: home,
|
|
CLAUDE_CONFIG_DIR: join(home, '.claude'),
|
|
CODEBURN_CACHE_DIR: join(home, '.cache', 'codeburn'),
|
|
// Force the snapshot settle window wide open. The real one is 2s, and
|
|
// racing a 2s wall clock from a CI runner is how this test would rot;
|
|
// a window this large makes "the deferral must not happen in serve"
|
|
// deterministic instead of timing-dependent.
|
|
CODEBURN_STATUS_SNAPSHOT_SETTLE_MS: '600000',
|
|
},
|
|
})
|
|
let buffer = ''
|
|
child.stdout!.setEncoding('utf8')
|
|
child.stdout!.on('data', (chunk: string) => {
|
|
buffer += chunk
|
|
let idx: number
|
|
while ((idx = buffer.indexOf('\n')) >= 0) {
|
|
const line = buffer.slice(0, idx).trim()
|
|
buffer = buffer.slice(idx + 1)
|
|
if (!line) continue
|
|
let msg: Record<string, unknown>
|
|
try { msg = JSON.parse(line) } catch { continue }
|
|
if (msg['ready']) { readyResolve(); continue }
|
|
if (typeof msg['progress'] === 'string' && !('ok' in msg)) continue
|
|
const waiter = waiters.get(msg['id'] as number)
|
|
if (waiter) { waiters.delete(msg['id'] as number); waiter(msg) }
|
|
}
|
|
})
|
|
await ready
|
|
}, 120_000)
|
|
|
|
afterAll(async () => {
|
|
child?.kill('SIGKILL')
|
|
if (home) await rm(home, { recursive: true, force: true })
|
|
})
|
|
|
|
it('reflects a single appended call on the poll after it, and keeps reflecting it', async () => {
|
|
const args = ['status', '--format', 'menubar-json', '--period', 'today', '--no-timeline', '--no-optimize']
|
|
|
|
const first = await request(500, args)
|
|
expect(first['ok'], JSON.stringify(first)).toBe(true)
|
|
expect(calls(first)).toBe(1)
|
|
const firstCost = cost(first)
|
|
|
|
// One append, then nothing else touches the corpus for the rest of the
|
|
// test - exactly the protocol that pinned the menubar.
|
|
await appendFile(sessionFile, pricedCall(2, 120_000) + '\n', 'utf8')
|
|
// Let the root watcher observe the write before polling, so the poll below
|
|
// is the one that has to decide between deferring and answering. Generous
|
|
// rather than tight: nothing here races the settle window.
|
|
await new Promise(resolve => setTimeout(resolve, 3000))
|
|
|
|
// Inside the settle window: a one-shot CLI may debounce here, the resident
|
|
// process must not - it has the parse state and cannot be re-asked.
|
|
const inWindow = await request(501, args)
|
|
expect(inWindow['ok'], JSON.stringify(inWindow)).toBe(true)
|
|
expect(calls(inWindow)).toBe(2)
|
|
expect(cost(inWindow)).toBeGreaterThan(firstCost)
|
|
|
|
// The actual regression: with no further filesystem event the output memo
|
|
// stays valid, so whatever the previous poll answered is replayed. A
|
|
// deferred answer here is stale for the whole memo cap.
|
|
const memoed = await request(502, args)
|
|
expect(memoed['ok'], JSON.stringify(memoed)).toBe(true)
|
|
expect(calls(memoed)).toBe(2)
|
|
expect(cost(memoed)).toBeGreaterThan(firstCost)
|
|
}, 120_000)
|
|
})
|