mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
Merge pull request #699 from getagentseal/feat/cadence-and-coherence
Desktop: refresh cadence, instant switching, cache coherence, telemetry v1
This commit is contained in:
commit
4d8d81a714
39 changed files with 1630 additions and 91 deletions
|
|
@ -60,6 +60,10 @@ const CHANNELS = [
|
|||
'codeburn:resetPlan',
|
||||
'codeburn:exportData',
|
||||
'codeburn:cliStatus',
|
||||
'codeburn:telemetryStatus',
|
||||
'codeburn:telemetrySetEnabled',
|
||||
'codeburn:telemetryOnboarded',
|
||||
'codeburn:telemetryTrack',
|
||||
] as const
|
||||
|
||||
const ARGV_CASES: Array<{ channel: string; args: unknown[]; argv: string[] }> = [
|
||||
|
|
@ -320,3 +324,61 @@ describe('createBridgeHandlers (cold-start warmup)', () => {
|
|||
expect(emitProgress).toHaveBeenCalledWith({ kind: 'tick', provider: 'claude', done: 5, total: 10 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('createBridgeHandlers (telemetry wiring)', () => {
|
||||
const fakeTelemetry = () => ({
|
||||
status: vi.fn(() => ({ installId: 'id-1', country: 'US', enabled: true, defaultEnabled: true, onboarded: false })),
|
||||
setEnabled: vi.fn((enabled: boolean) => ({ installId: 'id-2', country: 'US', enabled, defaultEnabled: true, onboarded: false })),
|
||||
completeOnboarding: vi.fn((enabled: boolean) => ({ installId: 'id-1', country: 'US', enabled, defaultEnabled: true, onboarded: true })),
|
||||
track: vi.fn(),
|
||||
})
|
||||
const deps = (telemetry: ReturnType<typeof fakeTelemetry> | null) => ({
|
||||
spawnCli: vi.fn(async () => ({ current: { cost: 1 } })),
|
||||
spawnCliAction: vi.fn(),
|
||||
resolveCodeburnPath: () => '/bin/codeburn',
|
||||
getQuota: vi.fn(async () => []),
|
||||
emitProgress: vi.fn(),
|
||||
telemetry,
|
||||
})
|
||||
|
||||
it('exposes status/consent/track channels and forwards to the telemetry service', async () => {
|
||||
const telemetry = fakeTelemetry()
|
||||
const handlers = createBridgeHandlers(deps(telemetry))
|
||||
|
||||
expect(await handlers['codeburn:telemetryStatus']!()).toMatchObject({ ok: true, value: { installId: 'id-1', onboarded: false } })
|
||||
expect(await handlers['codeburn:telemetrySetEnabled']!(false)).toMatchObject({ ok: true, value: { enabled: false } })
|
||||
expect(telemetry.setEnabled).toHaveBeenCalledWith(false)
|
||||
expect(await handlers['codeburn:telemetryOnboarded']!(true)).toMatchObject({ ok: true, value: { onboarded: true } })
|
||||
expect(telemetry.completeOnboarding).toHaveBeenCalledWith(true)
|
||||
await handlers['codeburn:telemetryTrack']!('section_view', { section: 'spend' })
|
||||
expect(telemetry.track).toHaveBeenCalledWith('section_view', { section: 'spend' })
|
||||
})
|
||||
|
||||
it('returns null (not an error) when telemetry is unavailable', async () => {
|
||||
const handlers = createBridgeHandlers(deps(null))
|
||||
expect(await handlers['codeburn:telemetryStatus']!()).toEqual({ ok: true, value: null })
|
||||
expect(await handlers['codeburn:telemetryTrack']!('section_view', {})).toEqual({ ok: true, value: true })
|
||||
})
|
||||
|
||||
it('tracks cold_start once on the first overview success, with duration', async () => {
|
||||
const telemetry = fakeTelemetry()
|
||||
const handlers = createBridgeHandlers(deps(telemetry))
|
||||
await handlers['codeburn:getOverview']!('30days', 'all')
|
||||
await handlers['codeburn:getOverview']!('30days', 'all')
|
||||
const coldStarts = telemetry.track.mock.calls.filter(([name]) => name === 'cold_start')
|
||||
expect(coldStarts.length).toBe(1)
|
||||
expect(coldStarts[0]![1]).toMatchObject({ timedOut: false })
|
||||
expect(typeof (coldStarts[0]![1] as { ms: number }).ms).toBe('number')
|
||||
})
|
||||
|
||||
it('tracks cli_error kinds from failing handlers', async () => {
|
||||
const telemetry = fakeTelemetry()
|
||||
const failing = {
|
||||
...deps(telemetry),
|
||||
spawnCli: vi.fn(async () => { throw new CliError('timeout', 'timed out') }),
|
||||
}
|
||||
const handlers = createBridgeHandlers(failing)
|
||||
await handlers['codeburn:getSessions']!('week', 'all')
|
||||
expect(telemetry.track).toHaveBeenCalledWith('cli_error', { kind: 'timeout' })
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -3,6 +3,13 @@ import path from 'node:path'
|
|||
|
||||
import { CliError, killAll, resolveCodeburnPath, spawnCli, spawnCliAction, type ActionResult } from './cli'
|
||||
import { getQuota, sanitizeError } from './quota'
|
||||
import { Telemetry } from './telemetry'
|
||||
|
||||
// Initialized in bootstrap() once Electron paths exist; stays null under tests.
|
||||
let telemetryInstance: Telemetry | null = null
|
||||
|
||||
/** The slice of Telemetry the bridge handlers use — injectable for tests. */
|
||||
export type TelemetryBridge = Pick<Telemetry, 'status' | 'setEnabled' | 'completeOnboarding' | 'track'>
|
||||
|
||||
// Result envelope: handlers never throw across IPC so the structured error
|
||||
// `kind` survives contextBridge serialization. preload.ts unwraps it.
|
||||
|
|
@ -127,6 +134,8 @@ type Deps = {
|
|||
getQuota: typeof getQuota
|
||||
/** Forward cold-start scan-progress events to the renderer splash. */
|
||||
emitProgress?: (event: unknown) => void
|
||||
/** Consent-gated anonymous telemetry; absent under tests unless injected. */
|
||||
telemetry?: TelemetryBridge | null
|
||||
}
|
||||
|
||||
type Handler = (...args: any[]) => Promise<Envelope>
|
||||
|
|
@ -136,8 +145,9 @@ type Handler = (...args: any[]) => Promise<Envelope>
|
|||
* shell) and returns a result envelope. Pure + injectable so the wiring is
|
||||
* unit-testable without launching Electron.
|
||||
*/
|
||||
export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, resolveCodeburnPath, getQuota, emitProgress: broadcastProgress }): Record<string, Handler> {
|
||||
export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, resolveCodeburnPath, getQuota, emitProgress: broadcastProgress, telemetry: telemetryInstance }): Record<string, Handler> {
|
||||
const emitProgress = deps.emitProgress ?? (() => {})
|
||||
const telemetry = deps.telemetry ?? null
|
||||
// Flips true after the first overview fetch succeeds. Until then, every
|
||||
// overview fetch runs cold (long timeout + progress streaming); the shared
|
||||
// spawnCli coalescing means concurrent same-arg re-polls join one child.
|
||||
|
|
@ -147,7 +157,9 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re
|
|||
try {
|
||||
return { ok: true, value: await deps.spawnCli(build(...args)) }
|
||||
} catch (err) {
|
||||
return { ok: false, error: toEnvelopeError(err) }
|
||||
const error = toEnvelopeError(err)
|
||||
telemetry?.track('cli_error', { kind: error.kind })
|
||||
return { ok: false, error }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -160,6 +172,7 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re
|
|||
]
|
||||
|
||||
const getOverview: Handler = async (period: string, provider: string, range?: DateRange, configSource?: string | null) => {
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const args = buildOverviewArgs(period, provider, range, configSource)
|
||||
if (overviewWarmed) return { ok: true, value: await deps.spawnCli(args) }
|
||||
|
|
@ -170,9 +183,13 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re
|
|||
})
|
||||
overviewWarmed = true
|
||||
emitProgress({ kind: 'done' })
|
||||
telemetry?.track('cold_start', { ms: Date.now() - startedAt, timedOut: false })
|
||||
return { ok: true, value }
|
||||
} catch (err) {
|
||||
return { ok: false, error: toEnvelopeError(err) }
|
||||
const error = toEnvelopeError(err)
|
||||
if (!overviewWarmed) telemetry?.track('cold_start', { ms: Date.now() - startedAt, timedOut: error.kind === 'timeout' })
|
||||
telemetry?.track('cli_error', { kind: error.kind })
|
||||
return { ok: false, error }
|
||||
}
|
||||
}
|
||||
const runAction = (build: (...args: any[]) => string[]): Handler => async (...args: any[]) => {
|
||||
|
|
@ -239,6 +256,15 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re
|
|||
const p = deps.resolveCodeburnPath()
|
||||
return { ok: true, value: { found: p !== null, path: p } }
|
||||
},
|
||||
// Telemetry consent + events. Value is null when telemetry is unavailable
|
||||
// (tests, or init failure) — the renderer treats null as "no onboarding".
|
||||
'codeburn:telemetryStatus': async () => ({ ok: true, value: telemetry ? telemetry.status() : null }),
|
||||
'codeburn:telemetrySetEnabled': async (enabled?: boolean) => ({ ok: true, value: telemetry ? telemetry.setEnabled(Boolean(enabled)) : null }),
|
||||
'codeburn:telemetryOnboarded': async (enabled?: boolean) => ({ ok: true, value: telemetry ? telemetry.completeOnboarding(Boolean(enabled)) : null }),
|
||||
'codeburn:telemetryTrack': async (name?: string, props?: unknown) => {
|
||||
telemetry?.track(String(name ?? ''), props)
|
||||
return { ok: true, value: true }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -400,9 +426,31 @@ function bootstrap(): void {
|
|||
win.focus()
|
||||
})
|
||||
|
||||
app.on('before-quit', () => killAll())
|
||||
app.on('before-quit', () => {
|
||||
killAll()
|
||||
// Best-effort final beat: session duration + whatever is still queued.
|
||||
telemetryInstance?.trackClose()
|
||||
void telemetryInstance?.flush()
|
||||
})
|
||||
|
||||
void app.whenReady().then(() => {
|
||||
// Consent-gated anonymous telemetry (desktop only). Nothing transmits until
|
||||
// the onboarding consent screen is completed and the toggle is on; EU/EEA/
|
||||
// UK/CH installs default the toggle off. Dev builds never send.
|
||||
try {
|
||||
telemetryInstance = new Telemetry({
|
||||
stateDir: app.getPath('userData'),
|
||||
country: app.getLocaleCountryCode() || null,
|
||||
isPackaged: app.isPackaged,
|
||||
appVersion: app.getVersion(),
|
||||
})
|
||||
// completeOnboarding tracks the first app_open itself; only already-
|
||||
// onboarded installs record subsequent opens here.
|
||||
if (telemetryInstance.status().onboarded) telemetryInstance.track('app_open', {})
|
||||
setInterval(() => { void telemetryInstance?.flush() }, 5 * 60_000)
|
||||
} catch (err) {
|
||||
console.error('telemetry init failed (continuing without):', err)
|
||||
}
|
||||
registerHandlers()
|
||||
installApplicationMenu()
|
||||
createWindow()
|
||||
|
|
|
|||
|
|
@ -50,6 +50,10 @@ const bridge = {
|
|||
exportData: (format: string, provider: string, outPath: string) => invoke('codeburn:exportData', format, provider, outPath),
|
||||
chooseDirectory: () => invoke('codeburn:chooseDirectory'),
|
||||
cliStatus: () => invoke('codeburn:cliStatus'),
|
||||
telemetryStatus: () => invoke('codeburn:telemetryStatus'),
|
||||
setTelemetryEnabled: (enabled: boolean) => invoke('codeburn:telemetrySetEnabled', enabled),
|
||||
completeOnboarding: (enabled: boolean) => invoke('codeburn:telemetryOnboarded', enabled),
|
||||
telemetryTrack: (name: string, props?: Record<string, unknown>) => invoke('codeburn:telemetryTrack', name, props),
|
||||
openExternal: (url: string) => ipcRenderer.invoke('open-external', url),
|
||||
// Cold-start scan progress (main → renderer). Returns an unsubscribe fn.
|
||||
onProgress: (cb: (event: unknown) => void) => {
|
||||
|
|
|
|||
|
|
@ -28,7 +28,9 @@ const defaultDeps: QuotaDeps = {
|
|||
readFile: readSecureFile,
|
||||
writeFile: atomicWriteSecureFile,
|
||||
now: Date.now,
|
||||
refreshMs: 2 * 60_000,
|
||||
// Politeness floor: quota stays gentle regardless of the app refresh cadence.
|
||||
// A user-initiated force refresh still bypasses this (invalidate()).
|
||||
refreshMs: 5 * 60_000,
|
||||
}
|
||||
|
||||
function unavailable(provider: ProviderName, connection: QuotaProvider['connection']): QuotaProvider {
|
||||
|
|
@ -89,11 +91,11 @@ export class QuotaService {
|
|||
// poll; keep showing the live connection rather than flapping to
|
||||
// disconnected. A forced refresh re-reads the keychain and reveals truth.
|
||||
if (!allowKeychain && (next.connection === 'disconnected' || next.connection === 'accessDenied')) return previous
|
||||
if (next.connection === 'transientFailure') return { ...previous, connection: 'transientFailure' }
|
||||
if (next.connection === 'transientFailure') return { ...previous, connection: 'transientFailure', rateLimited: next.rateLimited }
|
||||
return next
|
||||
}
|
||||
const until = blocked[provider] ? Date.parse(blocked[provider]!) : NaN
|
||||
if (Number.isFinite(until) && until > this.deps.now()) return retainOnFailure(unavailable(provider, 'transientFailure'))
|
||||
if (Number.isFinite(until) && until > this.deps.now()) return retainOnFailure({ ...unavailable(provider, 'transientFailure'), rateLimited: true })
|
||||
const generation = this.generations[provider]
|
||||
const controller = new AbortController()
|
||||
this.controllers[provider] = controller
|
||||
|
|
@ -104,6 +106,8 @@ export class QuotaService {
|
|||
if (result.retryAfterSeconds !== undefined) {
|
||||
blocked[provider] = new Date(this.deps.now() + result.retryAfterSeconds * 1000).toISOString()
|
||||
await this.writeBlocked(blocked)
|
||||
if (this.controllers[provider] === controller) this.controllers[provider] = undefined
|
||||
return retainOnFailure({ ...result.quota, rateLimited: true })
|
||||
} else if (blocked[provider]) {
|
||||
delete blocked[provider]
|
||||
await this.writeBlocked(blocked)
|
||||
|
|
|
|||
|
|
@ -11,6 +11,10 @@ export type QuotaProvider = {
|
|||
details: QuotaWindow[]
|
||||
planLabel: string | null
|
||||
footerLines: string[]
|
||||
/** Set when the provider is in a 429 backoff window (rate limited by the
|
||||
* upstream quota endpoint), so the UI can say so honestly instead of the
|
||||
* generic "waiting" copy. */
|
||||
rateLimited?: boolean
|
||||
}
|
||||
|
||||
export type ProviderName = QuotaProvider['provider']
|
||||
|
|
|
|||
162
app/electron/telemetry.test.ts
Normal file
162
app/electron/telemetry.test.ts
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
// @vitest-environment node
|
||||
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { defaultEnabledFor, Telemetry } from './telemetry'
|
||||
|
||||
let dir: string
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'cb-telemetry-'))
|
||||
delete process.env.CODEBURN_TELEMETRY_DEV
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
delete process.env.CODEBURN_TELEMETRY_DEV
|
||||
})
|
||||
|
||||
function make(over: Partial<ConstructorParameters<typeof Telemetry>[0]> = {}) {
|
||||
const posts: Array<{ url: string; body: unknown }> = []
|
||||
const fetchFn = vi.fn(async (url: unknown, init?: { body?: unknown }) => {
|
||||
posts.push({ url: String(url), body: JSON.parse(String(init?.body)) })
|
||||
return { ok: true } as Response
|
||||
}) as unknown as typeof fetch
|
||||
const telemetry = new Telemetry({
|
||||
stateDir: dir,
|
||||
country: 'US',
|
||||
isPackaged: true,
|
||||
appVersion: '1.0.0',
|
||||
fetchFn,
|
||||
...over,
|
||||
})
|
||||
return { telemetry, posts, fetchFn }
|
||||
}
|
||||
|
||||
describe('regional consent defaults', () => {
|
||||
it('defaults OFF in the EU/EEA/UK/CH and for unknown regions, ON elsewhere', () => {
|
||||
for (const c of ['DE', 'FR', 'NL', 'SE', 'GB', 'CH', 'NO', 'IS']) expect(defaultEnabledFor(c), c).toBe(false)
|
||||
for (const c of ['US', 'CA', 'JP', 'AU', 'BR', 'IN']) expect(defaultEnabledFor(c), c).toBe(true)
|
||||
expect(defaultEnabledFor(null)).toBe(false)
|
||||
expect(defaultEnabledFor(undefined)).toBe(false)
|
||||
})
|
||||
|
||||
it('a fresh EU install starts disabled; a fresh US install starts enabled', () => {
|
||||
const eu = new Telemetry({ stateDir: join(dir, 'eu'), country: 'DE', isPackaged: true, appVersion: '1' })
|
||||
expect(eu.status()).toMatchObject({ enabled: false, defaultEnabled: false, onboarded: false })
|
||||
const us = new Telemetry({ stateDir: join(dir, 'us'), country: 'US', isPackaged: true, appVersion: '1' })
|
||||
expect(us.status()).toMatchObject({ enabled: true, defaultEnabled: true, onboarded: false })
|
||||
})
|
||||
})
|
||||
|
||||
describe('consent gating', () => {
|
||||
it('never sends before onboarding completes, even when enabled', async () => {
|
||||
const { telemetry, posts } = make()
|
||||
telemetry.track('app_open', {})
|
||||
expect(await telemetry.flush()).toBe(false)
|
||||
expect(posts.length).toBe(0)
|
||||
})
|
||||
|
||||
it('sends after onboarding, and stops (dropping the queue) when disabled', async () => {
|
||||
const { telemetry, posts } = make()
|
||||
telemetry.completeOnboarding(true)
|
||||
telemetry.track('section_view', { section: 'spend' })
|
||||
expect(await telemetry.flush()).toBe(true)
|
||||
expect(posts.length).toBe(1)
|
||||
|
||||
telemetry.setEnabled(false)
|
||||
telemetry.track('section_view', { section: 'models' })
|
||||
expect(telemetry.queueLength).toBe(0)
|
||||
expect(await telemetry.flush()).toBe(false)
|
||||
expect(posts.length).toBe(1)
|
||||
})
|
||||
|
||||
it('opting out rotates the install id so history cannot be linked', () => {
|
||||
const { telemetry } = make()
|
||||
const before = telemetry.status().installId
|
||||
telemetry.setEnabled(false)
|
||||
const after = telemetry.status().installId
|
||||
expect(after).not.toBe(before)
|
||||
})
|
||||
|
||||
it('unpackaged (dev) builds never send unless CODEBURN_TELEMETRY_DEV=1', async () => {
|
||||
const { telemetry, posts } = make({ isPackaged: false })
|
||||
telemetry.completeOnboarding(true)
|
||||
expect(await telemetry.flush()).toBe(false)
|
||||
expect(posts.length).toBe(0)
|
||||
|
||||
process.env.CODEBURN_TELEMETRY_DEV = '1'
|
||||
telemetry.track('app_open', {})
|
||||
expect(await telemetry.flush()).toBe(true)
|
||||
expect(posts.length).toBe(1)
|
||||
})
|
||||
|
||||
it('persists consent + install id across instances', () => {
|
||||
const { telemetry } = make()
|
||||
const id = telemetry.completeOnboarding(true).installId
|
||||
const reloaded = new Telemetry({ stateDir: dir, country: 'US', isPackaged: true, appVersion: '1' })
|
||||
expect(reloaded.status()).toMatchObject({ installId: id, enabled: true, onboarded: true })
|
||||
const raw = JSON.parse(readFileSync(join(dir, 'telemetry.v1.json'), 'utf-8'))
|
||||
expect(raw.installId).toBe(id)
|
||||
})
|
||||
})
|
||||
|
||||
describe('events', () => {
|
||||
it('drops unknown event names and sanitizes props', async () => {
|
||||
const { telemetry, posts } = make()
|
||||
telemetry.completeOnboarding(true) // queues app_open
|
||||
telemetry.track('totally_made_up', { a: 1 })
|
||||
telemetry.track('section_view', {
|
||||
section: 'x'.repeat(500),
|
||||
junk: { nested: 'object' },
|
||||
fn: () => {},
|
||||
nan: NaN,
|
||||
ok: 42,
|
||||
})
|
||||
await telemetry.flush()
|
||||
const body = posts[0]!.body as { events: Array<{ name: string; day: string; props: Record<string, unknown> }> }
|
||||
expect(body.events.map(e => e.name)).toEqual(['app_open', 'section_view'])
|
||||
const props = body.events[1]!.props
|
||||
expect((props.section as string).length).toBe(64)
|
||||
expect(props.junk).toBeUndefined()
|
||||
expect(props.fn).toBeUndefined()
|
||||
expect(props.nan).toBeUndefined()
|
||||
expect(props.ok).toBe(42)
|
||||
// Day-granularity timestamps only.
|
||||
expect(body.events[0]!.day).toMatch(/^\d{4}-\d{2}-\d{2}$/)
|
||||
})
|
||||
|
||||
it('caps usage_snapshot at one per calendar day', () => {
|
||||
const { telemetry } = make()
|
||||
telemetry.completeOnboarding(true)
|
||||
const before = telemetry.queueLength
|
||||
telemetry.track('usage_snapshot', { costBucket: '1-10' })
|
||||
telemetry.track('usage_snapshot', { costBucket: '10-50' })
|
||||
expect(telemetry.queueLength).toBe(before + 1)
|
||||
})
|
||||
|
||||
it('keeps the queue on a failed POST and clears it on success', async () => {
|
||||
let ok = false
|
||||
const fetchFn = vi.fn(async () => ({ ok })) as unknown as typeof fetch
|
||||
const { telemetry } = make({ fetchFn })
|
||||
telemetry.completeOnboarding(true)
|
||||
expect(await telemetry.flush()).toBe(false)
|
||||
expect(telemetry.queueLength).toBe(1)
|
||||
ok = true
|
||||
expect(await telemetry.flush()).toBe(true)
|
||||
expect(telemetry.queueLength).toBe(0)
|
||||
})
|
||||
|
||||
it('batches with the wire contract: schema, installId, app block, events', async () => {
|
||||
const { telemetry, posts } = make()
|
||||
telemetry.completeOnboarding(true)
|
||||
await telemetry.flush()
|
||||
const body = posts[0]!.body as Record<string, unknown>
|
||||
expect(body.schema).toBe(1)
|
||||
expect(typeof body.installId).toBe('string')
|
||||
expect(body.app).toMatchObject({ name: 'codeburn-desktop', version: '1.0.0', country: 'US' })
|
||||
expect(Array.isArray(body.events)).toBe(true)
|
||||
})
|
||||
})
|
||||
260
app/electron/telemetry.ts
Normal file
260
app/electron/telemetry.ts
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
import { randomUUID } from 'node:crypto'
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
// Anonymous, consent-gated product telemetry for the desktop app ONLY.
|
||||
// Runs entirely in the Electron main process. Like cli.ts, this module must
|
||||
// NOT import `electron` so it stays unit-testable in plain node; main.ts
|
||||
// injects the electron-derived bits (userData path, country, isPackaged).
|
||||
//
|
||||
// Privacy invariants (enforced here, not by the caller):
|
||||
// - Nothing is ever sent before the user completes the onboarding consent
|
||||
// screen, and nothing is sent while the toggle is off.
|
||||
// - EU/EEA/UK/CH installs default the toggle OFF; everywhere else defaults ON.
|
||||
// Either way the user decides on the consent screen.
|
||||
// - The only identifier is a random UUID minted locally. No fingerprinting.
|
||||
// - Events carry day-granularity timestamps only, and props pass a whitelist
|
||||
// sanitizer (short strings / finite numbers / booleans, capped arrays).
|
||||
// - Dev / unpackaged builds never send (CODEBURN_TELEMETRY_DEV=1 overrides
|
||||
// for end-to-end testing).
|
||||
|
||||
export const TELEMETRY_ENDPOINT = 'https://api.codeburn.app/v1/telemetry'
|
||||
export const TELEMETRY_SCHEMA = 1
|
||||
|
||||
// EU-27 + EEA (IS, LI, NO) + UK + CH: conservative "default off" region.
|
||||
const DEFAULT_OFF_COUNTRIES = new Set([
|
||||
'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR',
|
||||
'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK',
|
||||
'SI', 'ES', 'SE', 'IS', 'LI', 'NO', 'GB', 'CH',
|
||||
])
|
||||
|
||||
export function defaultEnabledFor(country: string | null | undefined): boolean {
|
||||
if (!country) return false // unknown region: be conservative
|
||||
return !DEFAULT_OFF_COUNTRIES.has(country.toUpperCase())
|
||||
}
|
||||
|
||||
export const EVENT_NAMES = new Set([
|
||||
'app_open',
|
||||
'app_close',
|
||||
'section_view',
|
||||
'cold_start',
|
||||
'usage_snapshot',
|
||||
'cli_error',
|
||||
])
|
||||
|
||||
const MAX_QUEUE = 200
|
||||
const MAX_STRING = 64
|
||||
const MAX_ARRAY = 12
|
||||
const MAX_KEYS = 16
|
||||
|
||||
export type TelemetryStatus = {
|
||||
installId: string
|
||||
country: string | null
|
||||
enabled: boolean
|
||||
defaultEnabled: boolean
|
||||
/** True once the user has been through the onboarding consent screen. */
|
||||
onboarded: boolean
|
||||
}
|
||||
|
||||
type PersistedState = {
|
||||
version: 1
|
||||
installId: string
|
||||
enabled: boolean
|
||||
onboardedAt?: string
|
||||
lastSnapshotDay?: string
|
||||
}
|
||||
|
||||
type Deps = {
|
||||
/** Directory for the consent/state file (Electron userData in production). */
|
||||
stateDir: string
|
||||
/** ISO-3166 alpha-2 from the OS locale, or null when unknown. */
|
||||
country: string | null
|
||||
/** Only packaged builds send (unless CODEBURN_TELEMETRY_DEV=1). */
|
||||
isPackaged: boolean
|
||||
appVersion: string
|
||||
platform?: string
|
||||
arch?: string
|
||||
endpoint?: string
|
||||
fetchFn?: typeof fetch
|
||||
now?: () => Date
|
||||
}
|
||||
|
||||
type QueuedEvent = { name: string; day: string; props: Record<string, unknown> }
|
||||
|
||||
function dayKey(date: Date): string {
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
function sanitizeValue(value: unknown): unknown | undefined {
|
||||
if (typeof value === 'string') return value.slice(0, MAX_STRING)
|
||||
if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
|
||||
if (typeof value === 'boolean') return value
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Whitelist sanitizer: primitives, plus one level of arrays-of-flat-objects. */
|
||||
export function sanitizeProps(props: unknown): Record<string, unknown> {
|
||||
if (!props || typeof props !== 'object' || Array.isArray(props)) return {}
|
||||
const out: Record<string, unknown> = {}
|
||||
let keys = 0
|
||||
for (const [key, value] of Object.entries(props as Record<string, unknown>)) {
|
||||
if (keys >= MAX_KEYS) break
|
||||
const k = key.slice(0, MAX_STRING)
|
||||
if (Array.isArray(value)) {
|
||||
const items: Record<string, unknown>[] = []
|
||||
for (const entry of value.slice(0, MAX_ARRAY)) {
|
||||
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
|
||||
const flat: Record<string, unknown> = {}
|
||||
let inner = 0
|
||||
for (const [ik, iv] of Object.entries(entry as Record<string, unknown>)) {
|
||||
if (inner >= MAX_KEYS) break
|
||||
const sv = sanitizeValue(iv)
|
||||
if (sv === undefined) continue
|
||||
flat[ik.slice(0, MAX_STRING)] = sv
|
||||
inner++
|
||||
}
|
||||
if (Object.keys(flat).length > 0) items.push(flat)
|
||||
}
|
||||
if (items.length > 0) { out[k] = items; keys++ }
|
||||
continue
|
||||
}
|
||||
const sv = sanitizeValue(value)
|
||||
if (sv === undefined) continue
|
||||
out[k] = sv
|
||||
keys++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export class Telemetry {
|
||||
private readonly deps: Required<Pick<Deps, 'stateDir' | 'country' | 'isPackaged' | 'appVersion'>> & Deps
|
||||
private state: PersistedState
|
||||
private queue: QueuedEvent[] = []
|
||||
private openedAt: number
|
||||
|
||||
constructor(deps: Deps) {
|
||||
this.deps = deps
|
||||
this.state = this.load()
|
||||
this.openedAt = Date.now()
|
||||
}
|
||||
|
||||
private stateFile(): string {
|
||||
return join(this.deps.stateDir, 'telemetry.v1.json')
|
||||
}
|
||||
|
||||
private load(): PersistedState {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(this.stateFile(), 'utf-8')) as Partial<PersistedState>
|
||||
if (raw && raw.version === 1 && typeof raw.installId === 'string' && typeof raw.enabled === 'boolean') {
|
||||
return {
|
||||
version: 1,
|
||||
installId: raw.installId,
|
||||
enabled: raw.enabled,
|
||||
onboardedAt: typeof raw.onboardedAt === 'string' ? raw.onboardedAt : undefined,
|
||||
lastSnapshotDay: typeof raw.lastSnapshotDay === 'string' ? raw.lastSnapshotDay : undefined,
|
||||
}
|
||||
}
|
||||
} catch { /* first run or unreadable — start fresh */ }
|
||||
return { version: 1, installId: randomUUID(), enabled: defaultEnabledFor(this.deps.country) }
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
try {
|
||||
const file = this.stateFile()
|
||||
if (!existsSync(dirname(file))) mkdirSync(dirname(file), { recursive: true })
|
||||
writeFileSync(file, JSON.stringify(this.state), { mode: 0o600 })
|
||||
} catch { /* consent must still work in-memory */ }
|
||||
}
|
||||
|
||||
status(): TelemetryStatus {
|
||||
return {
|
||||
installId: this.state.installId,
|
||||
country: this.deps.country,
|
||||
enabled: this.state.enabled,
|
||||
defaultEnabled: defaultEnabledFor(this.deps.country),
|
||||
onboarded: this.state.onboardedAt !== undefined,
|
||||
}
|
||||
}
|
||||
|
||||
setEnabled(enabled: boolean): TelemetryStatus {
|
||||
this.state.enabled = enabled
|
||||
// Opting out mints a fresh id so past and future data cannot be linked.
|
||||
if (!enabled) {
|
||||
this.queue = []
|
||||
this.state.installId = randomUUID()
|
||||
}
|
||||
this.save()
|
||||
return this.status()
|
||||
}
|
||||
|
||||
/** The onboarding consent screen's final decision. Unlocks sending. */
|
||||
completeOnboarding(enabled: boolean): TelemetryStatus {
|
||||
this.state.onboardedAt = new Date().toISOString()
|
||||
const next = this.setEnabled(enabled)
|
||||
this.track('app_open', {})
|
||||
return next
|
||||
}
|
||||
|
||||
private get canSend(): boolean {
|
||||
if (!this.state.enabled || this.state.onboardedAt === undefined) return false
|
||||
return this.deps.isPackaged || process.env.CODEBURN_TELEMETRY_DEV === '1'
|
||||
}
|
||||
|
||||
/** Queue an event. Unknown names and junk props are dropped, never thrown. */
|
||||
track(name: string, props: unknown): void {
|
||||
if (!EVENT_NAMES.has(name)) return
|
||||
if (!this.state.enabled) return
|
||||
// usage_snapshot is an aggregate: at most one per calendar day.
|
||||
const now = (this.deps.now ?? (() => new Date()))()
|
||||
if (name === 'usage_snapshot') {
|
||||
const day = dayKey(now)
|
||||
if (this.state.lastSnapshotDay === day) return
|
||||
this.state.lastSnapshotDay = day
|
||||
this.save()
|
||||
}
|
||||
if (this.queue.length >= MAX_QUEUE) return
|
||||
this.queue.push({ name, day: dayKey(now), props: sanitizeProps(props) })
|
||||
}
|
||||
|
||||
/** Record session duration; queued for the next (final) flush. */
|
||||
trackClose(): void {
|
||||
this.track('app_close', { sessionMinutes: Math.round((Date.now() - this.openedAt) / 60_000) })
|
||||
}
|
||||
|
||||
/** Best-effort batch POST. Keeps the queue on failure, clears on success. */
|
||||
async flush(): Promise<boolean> {
|
||||
if (!this.canSend || this.queue.length === 0) return false
|
||||
const events = this.queue
|
||||
const body = JSON.stringify({
|
||||
schema: TELEMETRY_SCHEMA,
|
||||
installId: this.state.installId,
|
||||
app: {
|
||||
name: 'codeburn-desktop',
|
||||
version: this.deps.appVersion,
|
||||
platform: this.deps.platform ?? process.platform,
|
||||
arch: this.deps.arch ?? process.arch,
|
||||
country: this.deps.country,
|
||||
},
|
||||
events,
|
||||
})
|
||||
try {
|
||||
const fetchFn = this.deps.fetchFn ?? fetch
|
||||
const res = await fetchFn(this.deps.endpoint ?? TELEMETRY_ENDPOINT, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body,
|
||||
})
|
||||
if (!res.ok) return false
|
||||
// Only drop what was sent; events tracked mid-flight stay queued.
|
||||
this.queue = this.queue.filter(e => !events.includes(e))
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** Visible for tests. */
|
||||
get queueLength(): number {
|
||||
return this.queue.length
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
|
||||
import { EmptyNote } from './components/EmptyState'
|
||||
import { ErrorBoundary } from './components/ErrorBoundary'
|
||||
import { Hint } from './components/Hint'
|
||||
import { Onboarding } from './components/Onboarding'
|
||||
import { Panel } from './components/Panel'
|
||||
import { Sidebar, type Section } from './components/Sidebar'
|
||||
import { Splash } from './components/Splash'
|
||||
|
|
@ -15,6 +16,7 @@ import { formatCompact, formatUsd, setActiveCurrency } from './lib/format'
|
|||
import { motionClass } from './lib/motion'
|
||||
import { codeburn } from './lib/ipc'
|
||||
import { localDateKey } from './lib/period'
|
||||
import { persistRefreshValue, readRefreshValue, refreshValueToMs, RefreshCadenceContext, type RefreshCadence } from './lib/refreshCadence'
|
||||
import { OverviewContent } from './sections/Overview'
|
||||
import { OptimizeContent } from './sections/Optimize'
|
||||
import { Models } from './sections/Models'
|
||||
|
|
@ -23,7 +25,36 @@ import { Compare } from './sections/Compare'
|
|||
import { Plans } from './sections/Plans'
|
||||
import { Settings, type SettingsPane } from './sections/Settings'
|
||||
import { SpendContent } from './sections/Spend'
|
||||
import type { DateRange, MenubarPayload, Period } from './lib/types'
|
||||
import type { DateRange, MenubarPayload, Period, TelemetryStatus } from './lib/types'
|
||||
|
||||
// Bucket raw dollar amounts before they leave the machine: telemetry carries
|
||||
// coarse ranges, never exact spend.
|
||||
function costBucket(usd: number): string {
|
||||
if (usd < 1) return '<1'
|
||||
if (usd < 10) return '1-10'
|
||||
if (usd < 50) return '10-50'
|
||||
if (usd < 200) return '50-200'
|
||||
if (usd < 1000) return '200-1k'
|
||||
return '1k+'
|
||||
}
|
||||
|
||||
/** The once-per-day anonymous aggregate (main process dedups by calendar day). */
|
||||
function usageSnapshotProps(payload: MenubarPayload): Record<string, unknown> {
|
||||
return {
|
||||
period: payload.current.label,
|
||||
providerCount: Object.keys(payload.current.providers).length,
|
||||
costBucket: costBucket(payload.current.cost),
|
||||
models: (payload.current.topModels ?? []).slice(0, 8).map(model => ({
|
||||
name: model.name,
|
||||
costBucket: costBucket(model.cost),
|
||||
})),
|
||||
categories: (payload.current.topActivities ?? []).slice(0, 12).map(activity => ({
|
||||
name: activity.name,
|
||||
// Task-completion signal: share of turns resolved in one shot, 2dp.
|
||||
oneShotRate: activity.oneShotRate == null ? -1 : Math.round(activity.oneShotRate * 100) / 100,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
const SECTION_TITLES: Record<Section, string> = {
|
||||
overview: 'Overview',
|
||||
|
|
@ -88,7 +119,26 @@ function refreshedLabel(lastSuccessAt: number | null, loading: boolean, now: num
|
|||
return `refreshed ${minutes}m ago`
|
||||
}
|
||||
|
||||
/** Provides the app-wide refresh cadence (read persisted at boot, applied live)
|
||||
* so every usePolled below reads it as its default interval. */
|
||||
export function App() {
|
||||
const [refreshValue, setRefreshValue] = useState(readRefreshValue)
|
||||
const setValue = useCallback((value: string) => {
|
||||
setRefreshValue(value)
|
||||
persistRefreshValue(value)
|
||||
}, [])
|
||||
const cadence = useMemo<RefreshCadence>(
|
||||
() => ({ value: refreshValue, intervalMs: refreshValueToMs(refreshValue), setValue }),
|
||||
[refreshValue, setValue],
|
||||
)
|
||||
return (
|
||||
<RefreshCadenceContext.Provider value={cadence}>
|
||||
<AppMain />
|
||||
</RefreshCadenceContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function AppMain() {
|
||||
const [section, setSection] = useState<Section>('overview')
|
||||
const [settingsPane, setSettingsPane] = useState<SettingsPane>('general')
|
||||
const [period, setPeriod] = useState<Period>(initialPeriod)
|
||||
|
|
@ -109,6 +159,7 @@ export function App() {
|
|||
? codeburn.getOverview(period, provider, customRange)
|
||||
: codeburn.getOverview(period, provider),
|
||||
[period, provider, customRange?.from, customRange?.to, claudeConfigSource],
|
||||
{ memoKey: `overview|${provider}|${period}|${customRange?.from ?? ''}-${customRange?.to ?? ''}|${claudeConfigSource ?? ''}` },
|
||||
)
|
||||
const refreshOverview = overview.refresh
|
||||
|
||||
|
|
@ -119,6 +170,32 @@ export function App() {
|
|||
// (resolved) error; after that everything polls normally.
|
||||
const ready = overview.data != null || overview.error != null
|
||||
|
||||
// First-launch onboarding: shown until the telemetry consent screen has been
|
||||
// completed once. All telemetry bridge calls are typeof-guarded so an older
|
||||
// preload (or the test bridge mock) degrades to "no onboarding, no tracking".
|
||||
const [onboardingStatus, setOnboardingStatus] = useState<TelemetryStatus | null>(null)
|
||||
useEffect(() => {
|
||||
if (typeof codeburn.telemetryStatus !== 'function') return
|
||||
codeburn.telemetryStatus()
|
||||
.then(status => { if (status && !status.onboarded) setOnboardingStatus(status) })
|
||||
.catch(() => { /* telemetry unavailable — skip onboarding */ })
|
||||
}, [])
|
||||
const finishOnboarding = useCallback((enabled: boolean) => {
|
||||
setOnboardingStatus(null)
|
||||
if (typeof codeburn.completeOnboarding === 'function') void codeburn.completeOnboarding(enabled).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const trackEvent = useCallback((name: string, props?: Record<string, unknown>) => {
|
||||
if (typeof codeburn.telemetryTrack === 'function') void codeburn.telemetryTrack(name, props).catch(() => {})
|
||||
}, [])
|
||||
|
||||
// Once-per-day anonymous usage aggregate, only from the canonical view
|
||||
// (all providers, standard period, no config scope) so buckets are stable.
|
||||
useEffect(() => {
|
||||
if (!overview.data || provider !== 'all' || customRange || claudeConfigSource) return
|
||||
trackEvent('usage_snapshot', usageSnapshotProps(overview.data))
|
||||
}, [overview.data, provider, customRange, claudeConfigSource, trackEvent])
|
||||
|
||||
useEffect(() => {
|
||||
let saved: string | null = null
|
||||
try { saved = globalThis.localStorage?.getItem('codeburn.theme') ?? null } catch { /* storage can be unavailable */ }
|
||||
|
|
@ -172,7 +249,8 @@ export function App() {
|
|||
const navigate = useCallback((next: Section, pane: SettingsPane = 'general') => {
|
||||
setSettingsPane(pane)
|
||||
setSection(next)
|
||||
}, [])
|
||||
trackEvent('section_view', { section: next })
|
||||
}, [trackEvent])
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
|
|
@ -238,7 +316,9 @@ export function App() {
|
|||
<Sidebar active={section} onNavigate={navigate} status={<StatusLine polled={overview} />} />
|
||||
<ToastHost />
|
||||
<Splash hasData={overview.data != null} hasError={overview.error != null} />
|
||||
{onboardingStatus && <Onboarding defaultEnabled={onboardingStatus.defaultEnabled} onDone={finishOnboarding} />}
|
||||
<div className="ct">
|
||||
<div className={overview.switching ? 'switch-line on' : 'switch-line'} aria-hidden="true" />
|
||||
<DailyBudgetBanner payload={overview.data ?? null} provider={provider} />
|
||||
<ErrorBoundary key={section}>
|
||||
{section === 'plans' ? (
|
||||
|
|
|
|||
63
app/renderer/components/Onboarding.test.tsx
Normal file
63
app/renderer/components/Onboarding.test.tsx
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
// @vitest-environment jsdom
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
openExternal: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../lib/ipc', () => ({
|
||||
codeburn: { openExternal: mocks.openExternal },
|
||||
normalizeCliError: (err: unknown) => err,
|
||||
}))
|
||||
|
||||
import { Onboarding } from './Onboarding'
|
||||
|
||||
function next(): void {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next' }))
|
||||
}
|
||||
|
||||
describe('Onboarding', () => {
|
||||
it('walks three feature screens into the consent screen', () => {
|
||||
render(<Onboarding defaultEnabled onDone={() => {}} />)
|
||||
|
||||
expect(screen.getByText('Every agent. One dashboard.')).toBeInTheDocument()
|
||||
next()
|
||||
expect(screen.getByText('Local-first by design.')).toBeInTheDocument()
|
||||
next()
|
||||
expect(screen.getByText('Find the waste.')).toBeInTheDocument()
|
||||
next()
|
||||
expect(screen.getByText('Help improve CodeBurn')).toBeInTheDocument()
|
||||
// Back returns to the previous screen.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Back' }))
|
||||
expect(screen.getByText('Find the waste.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('seeds the toggle from the regional default and reports the final choice', () => {
|
||||
const onDone = vi.fn()
|
||||
render(<Onboarding defaultEnabled={false} onDone={onDone} />)
|
||||
next(); next(); next()
|
||||
|
||||
// EU-style default: switch starts off.
|
||||
const toggle = screen.getByRole('switch', { name: 'Anonymous telemetry' })
|
||||
expect(toggle).toHaveAttribute('aria-checked', 'false')
|
||||
|
||||
// The user opts in, then finishes.
|
||||
fireEvent.click(toggle)
|
||||
expect(toggle).toHaveAttribute('aria-checked', 'true')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Get started' }))
|
||||
expect(onDone).toHaveBeenCalledWith(true)
|
||||
})
|
||||
|
||||
it('keeps the regional default when untouched and links the data policy', () => {
|
||||
const onDone = vi.fn()
|
||||
render(<Onboarding defaultEnabled onDone={onDone} />)
|
||||
next(); next(); next()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'What data we collect' }))
|
||||
expect(mocks.openExternal).toHaveBeenCalledWith('https://www.codeburn.app/telemetry')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Get started' }))
|
||||
expect(onDone).toHaveBeenCalledWith(true)
|
||||
})
|
||||
})
|
||||
107
app/renderer/components/Onboarding.tsx
Normal file
107
app/renderer/components/Onboarding.tsx
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
import { useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
|
||||
import { FlameMark } from './FlameMark'
|
||||
import { codeburn } from '../lib/ipc'
|
||||
import { motionClass } from '../lib/motion'
|
||||
|
||||
const COLLECT_URL = 'https://www.codeburn.app/telemetry'
|
||||
|
||||
type Screen = {
|
||||
title: string
|
||||
body: string
|
||||
glyph: React.ReactNode
|
||||
}
|
||||
|
||||
const SCREENS: Screen[] = [
|
||||
{
|
||||
title: 'Every agent. One dashboard.',
|
||||
body: 'Claude Code, Codex, Cursor, Copilot and 20+ more: spend, sessions, models and quotas, side by side.',
|
||||
glyph: <><rect x="3" y="4" width="18" height="14" rx="2" /><path d="M7 14v-3M11 14V8M15 14v-5M3 18h18" /></>,
|
||||
},
|
||||
{
|
||||
title: 'Local-first by design.',
|
||||
body: 'Usage is read from files already on your machine. No accounts, no API keys, nothing leaves your device.',
|
||||
glyph: <><rect x="4.5" y="10" width="15" height="11" rx="2" /><path d="M8 10V7a4 4 0 0 1 8 0v3" /></>,
|
||||
},
|
||||
{
|
||||
title: 'Find the waste.',
|
||||
body: 'Retry tax, routing waste and task success by category: see what your agents actually deliver for the money.',
|
||||
glyph: <><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3.5 2" /></>,
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* First-launch overlay: three feature screens, then the telemetry consent
|
||||
* screen. The toggle's initial position comes from the region default (EU/EEA/
|
||||
* UK/CH off, elsewhere on) and nothing is transmitted until the user finishes
|
||||
* here. Rendered only while the main process reports `onboarded: false`.
|
||||
*/
|
||||
export function Onboarding({ defaultEnabled, onDone }: { defaultEnabled: boolean; onDone: (enabled: boolean) => void }) {
|
||||
const [step, setStep] = useState(0)
|
||||
const [enabled, setEnabled] = useState(defaultEnabled)
|
||||
const last = SCREENS.length // consent screen index
|
||||
const isConsent = step === last
|
||||
|
||||
if (typeof document === 'undefined') return null
|
||||
|
||||
return createPortal(
|
||||
<div className={motionClass('onboard', 'onboard-in')} role="dialog" aria-label="Welcome to CodeBurn">
|
||||
<div className="onboard-card">
|
||||
<div className="onboard-glyph" aria-hidden>
|
||||
{isConsent
|
||||
? <FlameMark size={40} />
|
||||
: <svg viewBox="0 0 24 24" width="40" height="40" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">{SCREENS[step].glyph}</svg>}
|
||||
</div>
|
||||
|
||||
{isConsent ? (
|
||||
<>
|
||||
<h2 className="onboard-title">Help improve CodeBurn</h2>
|
||||
<p className="onboard-body">
|
||||
Share anonymous usage statistics: model and provider mix, task success rates, performance and errors.
|
||||
Never your prompts, code, project names or anything that identifies you.
|
||||
</p>
|
||||
<div className="onboard-consent">
|
||||
<span id="onboard-consent-label">Anonymous telemetry</span>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={enabled}
|
||||
aria-labelledby="onboard-consent-label"
|
||||
className={enabled ? 'switch on' : 'switch'}
|
||||
onClick={() => setEnabled(value => !value)}
|
||||
>
|
||||
<span className="switch-knob" />
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" className="onboard-link" onClick={() => { void codeburn.openExternal?.(COLLECT_URL) }}>
|
||||
What data we collect
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h2 className="onboard-title">{SCREENS[step].title}</h2>
|
||||
<p className="onboard-body">{SCREENS[step].body}</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="onboard-controls">
|
||||
{step > 0 ? (
|
||||
<button type="button" className="onboard-btn" onClick={() => setStep(value => value - 1)}>Back</button>
|
||||
) : <span className="onboard-btn-ghost" />}
|
||||
<div className="onboard-dots" aria-hidden>
|
||||
{[...SCREENS, null].map((_, index) => (
|
||||
<span key={index} className={index === step ? 'onboard-dot on' : 'onboard-dot'} />
|
||||
))}
|
||||
</div>
|
||||
{isConsent ? (
|
||||
<button type="button" className="onboard-btn primary" onClick={() => onDone(enabled)}>Get started</button>
|
||||
) : (
|
||||
<button type="button" className="onboard-btn primary" onClick={() => setStep(value => value + 1)}>Next</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
|
|
@ -1,9 +1,16 @@
|
|||
// @vitest-environment jsdom
|
||||
import { createElement, type ReactNode } from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
|
||||
import { RefreshCadenceContext, type RefreshCadence } from '../lib/refreshCadence'
|
||||
import { usePolled } from './usePolled'
|
||||
|
||||
function cadenceWrapper(intervalMs: number | null) {
|
||||
const value: RefreshCadence = { value: 'x', intervalMs, setValue: () => {} }
|
||||
return ({ children }: { children: ReactNode }) => createElement(RefreshCadenceContext.Provider, { value }, children)
|
||||
}
|
||||
|
||||
describe('usePolled', () => {
|
||||
it('discards a stale in-flight fetch that resolves after a newer one (epoch guard)', async () => {
|
||||
// A fetcher we resolve by hand, one deferred per call, so we can force a
|
||||
|
|
@ -76,4 +83,69 @@ describe('usePolled', () => {
|
|||
expect(result.current.data).toBe('good')
|
||||
expect(result.current.error).toMatchObject({ kind: 'nonzero', message: 'boom' })
|
||||
})
|
||||
|
||||
it('serves last-good data instantly on switch-back and flags `switching` while it refreshes', async () => {
|
||||
const resolvers: Array<(v: string) => void> = []
|
||||
const fetcher = vi.fn(() => new Promise<string>(resolve => { resolvers.push(resolve) }))
|
||||
|
||||
// Mount on key kA, resolve to A0 → memoized under kA.
|
||||
const { result, rerender } = renderHook(
|
||||
({ k }: { k: string }) => usePolled(fetcher, [k], { memoKey: k }),
|
||||
{ initialProps: { k: 'kA' } },
|
||||
)
|
||||
await act(async () => { resolvers[0]!('A0') })
|
||||
expect(result.current.data).toBe('A0')
|
||||
expect(result.current.switching).toBe(false)
|
||||
|
||||
// Switch to a fresh key kB, resolve to B0 → memoized under kB.
|
||||
rerender({ k: 'kB' })
|
||||
await act(async () => { resolvers[1]!('B0') })
|
||||
expect(result.current.data).toBe('B0')
|
||||
|
||||
// Switch BACK to kA: the memoized A0 paints in the same commit (no blank, no
|
||||
// B0 freeze) and `switching` is true while the fresh fetch runs behind it.
|
||||
rerender({ k: 'kA' })
|
||||
expect(result.current.data).toBe('A0')
|
||||
expect(result.current.switching).toBe(true)
|
||||
expect(result.current.loading).toBe(true)
|
||||
|
||||
// The fresh fetch resolves → new data, switching clears.
|
||||
await act(async () => { resolvers[2]!('A1') })
|
||||
expect(result.current.data).toBe('A1')
|
||||
expect(result.current.switching).toBe(false)
|
||||
})
|
||||
|
||||
it('manual cadence (null interval) polls only on mount + refresh, never on a timer', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const fetcher = vi.fn().mockResolvedValue('x')
|
||||
const { result } = renderHook(() => usePolled(fetcher, [], { intervalMs: null }))
|
||||
expect(fetcher).toHaveBeenCalledTimes(1) // mount
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(600_000) })
|
||||
expect(fetcher).toHaveBeenCalledTimes(1) // no interval fired
|
||||
act(() => { result.current.refresh() })
|
||||
expect(fetcher).toHaveBeenCalledTimes(2) // manual refresh still works
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('defaults the interval to the RefreshCadence context, and Manual disables the timer', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const timed = vi.fn().mockResolvedValue('x')
|
||||
renderHook(() => usePolled(timed, []), { wrapper: cadenceWrapper(60_000) })
|
||||
expect(timed).toHaveBeenCalledTimes(1)
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(60_000) })
|
||||
expect(timed).toHaveBeenCalledTimes(2) // context interval fired
|
||||
|
||||
const manual = vi.fn().mockResolvedValue('x')
|
||||
renderHook(() => usePolled(manual, []), { wrapper: cadenceWrapper(null) })
|
||||
expect(manual).toHaveBeenCalledTimes(1)
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(600_000) })
|
||||
expect(manual).toHaveBeenCalledTimes(1) // Manual context → no timer
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,39 +1,85 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useCallback, useContext, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { normalizeCliError } from '../lib/ipc'
|
||||
import { RefreshCadenceContext } from '../lib/refreshCadence'
|
||||
import type { CliError } from '../lib/types'
|
||||
|
||||
export type Polled<T> = {
|
||||
data: T | null
|
||||
error: CliError | null
|
||||
loading: boolean
|
||||
/** True while a fresh fetch runs behind instantly-served memoized data (a
|
||||
* provider/period switch). Sections use it for a subtle in-flight indicator. */
|
||||
switching: boolean
|
||||
/** Wall-clock timestamp for the most recent successful fetch. */
|
||||
lastSuccessAt: number | null
|
||||
/** Re-run the fetcher immediately (period/provider change, manual refresh). */
|
||||
refresh: () => void
|
||||
}
|
||||
|
||||
// Module-level LRU of last-good results per memoKey. A section that switches deps
|
||||
// to a previously-seen key (e.g. a provider switch, or a switch-back) paints the
|
||||
// cached result in the same frame while a fresh fetch runs behind it — no blank,
|
||||
// no stale-freeze. ~8 entries is plenty for the handful of live (provider ×
|
||||
// period × range) combinations a user cycles through.
|
||||
const MEMO_MAX = 8
|
||||
const memoStore = new Map<string, unknown>()
|
||||
|
||||
function memoGet<T>(key: string): T | undefined {
|
||||
if (!memoStore.has(key)) return undefined
|
||||
const value = memoStore.get(key) as T
|
||||
// Touch recency.
|
||||
memoStore.delete(key)
|
||||
memoStore.set(key, value)
|
||||
return value
|
||||
}
|
||||
|
||||
function memoSet(key: string, value: unknown): void {
|
||||
if (memoStore.has(key)) memoStore.delete(key)
|
||||
memoStore.set(key, value)
|
||||
while (memoStore.size > MEMO_MAX) {
|
||||
const oldest = memoStore.keys().next().value
|
||||
if (oldest === undefined) break
|
||||
memoStore.delete(oldest)
|
||||
}
|
||||
}
|
||||
|
||||
/** Test-only: clear the module-level memo between renders so cached results from
|
||||
* one test never bleed into the next. */
|
||||
export function __resetPolledMemo(): void {
|
||||
memoStore.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic CLI-backed data hook: fetches on mount + whenever `deps` change, then
|
||||
* re-polls every `intervalMs`. Errors are normalized to the CliError shape so
|
||||
* sections can branch on `error.kind`. Last-good data is retained on error.
|
||||
*
|
||||
* `intervalMs` defaults to the app-wide refresh cadence (Settings > General) via
|
||||
* context; pass one explicitly to override. `null` cadence (Manual) means no
|
||||
* setInterval — the fetcher runs only on mount, deps change, and refresh().
|
||||
*
|
||||
* `enabled` (default true) gates fetching: while false the hook stays in its
|
||||
* initial loading state and issues no CLI spawn. The app boot flow sets it false
|
||||
* on every section poll until the first overview resolves, so the one-time cold
|
||||
* cache hydration happens ONCE (via overview) instead of fanning out into a
|
||||
* parallel full-history parse per section.
|
||||
*
|
||||
* `memoKey` opts into the instant-switch memo above.
|
||||
*/
|
||||
export function usePolled<T>(
|
||||
fetcher: () => Promise<T>,
|
||||
deps: unknown[],
|
||||
opts: { intervalMs?: number; enabled?: boolean } = {},
|
||||
opts: { intervalMs?: number | null; enabled?: boolean; memoKey?: string } = {},
|
||||
): Polled<T> {
|
||||
const intervalMs = opts.intervalMs ?? 30_000
|
||||
const cadence = useContext(RefreshCadenceContext)
|
||||
const intervalMs = opts.intervalMs !== undefined ? opts.intervalMs : cadence.intervalMs
|
||||
const enabled = opts.enabled ?? true
|
||||
const [data, setData] = useState<T | null>(null)
|
||||
const memoKey = opts.memoKey
|
||||
const [data, setData] = useState<T | null>(() => (memoKey ? memoGet<T>(memoKey) ?? null : null))
|
||||
const [error, setError] = useState<CliError | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [switching, setSwitching] = useState(false)
|
||||
const [lastSuccessAt, setLastSuccessAt] = useState<number | null>(null)
|
||||
// Generation counter: every load() (mount, deps change, interval, refresh)
|
||||
// claims the next epoch; a fetch applies its result only while its epoch is
|
||||
|
|
@ -44,7 +90,16 @@ export function usePolled<T>(
|
|||
const load = useCallback(() => {
|
||||
if (!enabled) return
|
||||
const epoch = ++epochRef.current
|
||||
// Instant paint: on a deps/key change, if a last-good result for the new key
|
||||
// is cached, show it immediately and flag `switching` while the fresh fetch
|
||||
// runs. Otherwise fall back to the normal loading state.
|
||||
let servedCached = false
|
||||
if (memoKey) {
|
||||
const cached = memoGet<T>(memoKey)
|
||||
if (cached !== undefined) { setData(cached); servedCached = true }
|
||||
}
|
||||
setLoading(true)
|
||||
setSwitching(servedCached)
|
||||
// Clear any prior error at the start of each attempt so a fresh poll never
|
||||
// shows a stale banner while it is still in flight; last-good `data` stays.
|
||||
setError(null)
|
||||
|
|
@ -54,6 +109,7 @@ export function usePolled<T>(
|
|||
setData(result)
|
||||
setError(null)
|
||||
setLastSuccessAt(Date.now())
|
||||
if (memoKey) memoSet(memoKey, result)
|
||||
})
|
||||
.catch(err => {
|
||||
if (epochRef.current !== epoch) return
|
||||
|
|
@ -62,17 +118,20 @@ export function usePolled<T>(
|
|||
.finally(() => {
|
||||
if (epochRef.current !== epoch) return
|
||||
setLoading(false)
|
||||
setSwitching(false)
|
||||
})
|
||||
// deps are intentionally the caller-provided dependency list; `enabled`
|
||||
// is prepended so flipping the gate re-creates load and fires immediately.
|
||||
// deps are intentionally the caller-provided dependency list; `enabled` and
|
||||
// `memoKey` are prepended so flipping the gate / key re-creates load and
|
||||
// fires immediately.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [enabled, ...deps])
|
||||
}, [enabled, memoKey, ...deps])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
const id = setInterval(() => load(), intervalMs)
|
||||
// Manual cadence (intervalMs == null) skips the interval entirely.
|
||||
const id = intervalMs != null ? setInterval(() => load(), intervalMs) : null
|
||||
return () => {
|
||||
clearInterval(id)
|
||||
if (id != null) clearInterval(id)
|
||||
// Retire this generation so an in-flight fetch can't resolve into state
|
||||
// after unmount or a deps change.
|
||||
epochRef.current++
|
||||
|
|
@ -83,5 +142,5 @@ export function usePolled<T>(
|
|||
load()
|
||||
}, [load])
|
||||
|
||||
return { data, error, loading, lastSuccessAt, refresh }
|
||||
return { data, error, loading, switching, lastSuccessAt, refresh }
|
||||
}
|
||||
|
|
|
|||
55
app/renderer/lib/refreshCadence.tsx
Normal file
55
app/renderer/lib/refreshCadence.tsx
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import { createContext, useContext } from 'react'
|
||||
|
||||
// The auto-refresh cadence, chosen in Settings > General and persisted at
|
||||
// localStorage `codeburn.refreshInterval`. usePolled reads the resolved
|
||||
// interval from context as its default when the caller passes none. `Manual`
|
||||
// means no setInterval — data refreshes only on deps change and ⌘R / refresh.
|
||||
export const REFRESH_OPTIONS: ReadonlyArray<{ value: string; label: string; ms: number | null }> = [
|
||||
{ value: 'manual', label: 'Manual', ms: null },
|
||||
{ value: '30s', label: '30 seconds', ms: 30_000 },
|
||||
{ value: '1m', label: '1 minute', ms: 60_000 },
|
||||
{ value: '3m', label: '3 minutes', ms: 180_000 },
|
||||
{ value: '5m', label: '5 minutes', ms: 300_000 },
|
||||
{ value: '10m', label: '10 minutes', ms: 600_000 },
|
||||
]
|
||||
|
||||
export const DEFAULT_REFRESH_VALUE = '30s'
|
||||
const DEFAULT_MS = 30_000
|
||||
const STORAGE_KEY = 'codeburn.refreshInterval'
|
||||
|
||||
export function refreshValueToMs(value: string): number | null {
|
||||
const option = REFRESH_OPTIONS.find(o => o.value === value)
|
||||
return option ? option.ms : DEFAULT_MS
|
||||
}
|
||||
|
||||
/** Persisted cadence at boot; falls back to the 30s default (prior behavior). */
|
||||
export function readRefreshValue(): string {
|
||||
try {
|
||||
const saved = globalThis.localStorage?.getItem(STORAGE_KEY)
|
||||
if (saved && REFRESH_OPTIONS.some(o => o.value === saved)) return saved
|
||||
} catch { /* storage can be unavailable */ }
|
||||
return DEFAULT_REFRESH_VALUE
|
||||
}
|
||||
|
||||
export function persistRefreshValue(value: string): void {
|
||||
try { globalThis.localStorage?.setItem(STORAGE_KEY, value) } catch { /* storage can be unavailable */ }
|
||||
}
|
||||
|
||||
export type RefreshCadence = {
|
||||
value: string
|
||||
/** Resolved poll interval in ms, or null for Manual (no auto-poll). */
|
||||
intervalMs: number | null
|
||||
setValue: (value: string) => void
|
||||
}
|
||||
|
||||
// Default matches the historical 30s hardcoded interval so any consumer rendered
|
||||
// without a provider (e.g. isolated hook/component tests) behaves as before.
|
||||
export const RefreshCadenceContext = createContext<RefreshCadence>({
|
||||
value: DEFAULT_REFRESH_VALUE,
|
||||
intervalMs: DEFAULT_MS,
|
||||
setValue: () => {},
|
||||
})
|
||||
|
||||
export function useRefreshCadence(): RefreshCadence {
|
||||
return useContext(RefreshCadenceContext)
|
||||
}
|
||||
|
|
@ -32,6 +32,8 @@ export type QuotaProvider = {
|
|||
details: QuotaWindow[]
|
||||
planLabel: string | null
|
||||
footerLines: string[]
|
||||
/** True when the provider is in a 429 backoff window (upstream rate limit). */
|
||||
rateLimited?: boolean
|
||||
}
|
||||
|
||||
// ————— src/menubar-json.ts —————
|
||||
|
|
@ -549,6 +551,16 @@ export type PriceRates = { input?: number; output?: number; cacheRead?: number;
|
|||
|
||||
// ————— IPC surface (preload contextBridge → window.codeburn) —————
|
||||
|
||||
/** Anonymous-telemetry consent state (app/electron/telemetry.ts). Null when
|
||||
* telemetry is unavailable in the main process. */
|
||||
export type TelemetryStatus = {
|
||||
installId: string
|
||||
country: string | null
|
||||
enabled: boolean
|
||||
defaultEnabled: boolean
|
||||
onboarded: boolean
|
||||
}
|
||||
|
||||
/** Cold-start scan progress streamed from the CLI warmup (src/parser.ts). */
|
||||
export type ScanProgressEvent =
|
||||
| { kind: 'providers'; providers: string[] }
|
||||
|
|
@ -591,5 +603,9 @@ export interface CodeburnBridge {
|
|||
exportData(format: string, provider: string, outPath: string): Promise<ActionResult>
|
||||
chooseDirectory(): Promise<string | null>
|
||||
cliStatus(): Promise<{ found: boolean; path: string | null; error?: string }>
|
||||
telemetryStatus(): Promise<TelemetryStatus | null>
|
||||
setTelemetryEnabled(enabled: boolean): Promise<TelemetryStatus | null>
|
||||
completeOnboarding(enabled: boolean): Promise<TelemetryStatus | null>
|
||||
telemetryTrack(name: string, props?: Record<string, unknown>): Promise<boolean>
|
||||
openExternal(url: string): Promise<void>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ export function Compare({
|
|||
const models = usePolled<ModelStats[]>(
|
||||
() => codeburn.getCompareModels(period, provider),
|
||||
[period, provider, refreshToken],
|
||||
{ enabled: ready },
|
||||
{ enabled: ready, memoKey: `comparemodels|${period}|${provider}` },
|
||||
)
|
||||
const [modelA, setModelA] = useState<string | null>(null)
|
||||
const [modelB, setModelB] = useState<string | null>(null)
|
||||
|
|
@ -136,6 +136,7 @@ function CompareReport({
|
|||
const report = usePolled<CompareJsonReport>(
|
||||
() => codeburn.getCompare(period, provider, modelA, modelB),
|
||||
[period, provider, modelA, modelB, refreshToken],
|
||||
{ memoKey: `compare|${period}|${provider}|${modelA}|${modelB}` },
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
|
|
|
|||
|
|
@ -95,7 +95,7 @@ function ModelsUsage({
|
|||
const report = usePolled<ModelReportRow[]>(
|
||||
() => range ? codeburn.getModels(period, provider, byTask, range) : codeburn.getModels(period, provider, byTask),
|
||||
[period, provider, byTask, range?.from, range?.to, refreshToken],
|
||||
{ enabled: ready },
|
||||
{ enabled: ready, memoKey: `models|${period}|${provider}|${byTask}|${range?.from ?? ''}-${range?.to ?? ''}` },
|
||||
)
|
||||
|
||||
if (!report.data) {
|
||||
|
|
@ -141,7 +141,7 @@ function AuditLens({
|
|||
const report = usePolled<AuditRow[]>(
|
||||
() => range ? codeburn.getAudit(period, provider, range) : codeburn.getAudit(period, provider),
|
||||
[period, provider, range?.from, range?.to, refreshToken],
|
||||
{ enabled: ready },
|
||||
{ enabled: ready, memoKey: `audit|${period}|${provider}|${range?.from ?? ''}-${range?.to ?? ''}` },
|
||||
)
|
||||
|
||||
if (!report.data) {
|
||||
|
|
|
|||
|
|
@ -236,7 +236,7 @@ describe('Optimize', () => {
|
|||
|
||||
it('keeps last-good yield totals and rows visible during revalidation', async () => {
|
||||
getYield.mockReset().mockResolvedValueOnce(makeYield()).mockImplementation(() => new Promise<YieldJsonReport>(() => {}))
|
||||
const overview = { data: makePayload(), error: null, loading: false, lastSuccessAt: Date.now(), refresh: vi.fn() }
|
||||
const overview = { data: makePayload(), error: null, loading: false, switching: false, lastSuccessAt: Date.now(), refresh: vi.fn() }
|
||||
const { rerender } = render(<OptimizeContent period="30days" overview={overview} refreshToken={0} />)
|
||||
|
||||
expect(await screen.findByRole('tab', { name: 'Reverts $107.00' })).toBeInTheDocument()
|
||||
|
|
|
|||
|
|
@ -41,12 +41,12 @@ export function OptimizeContent({
|
|||
const optimizeReport = usePolled<OptimizeJsonReport>(
|
||||
() => range ? codeburn.getOptimizeReport(period, provider, range) : codeburn.getOptimizeReport(period, provider),
|
||||
[period, provider, range?.from, range?.to, refreshToken],
|
||||
{ enabled: ready },
|
||||
{ enabled: ready, memoKey: `optimize|${period}|${provider}|${range?.from ?? ''}-${range?.to ?? ''}` },
|
||||
)
|
||||
const yieldReport = usePolled<YieldJsonReport>(
|
||||
() => range ? codeburn.getYield(period, provider, range) : codeburn.getYield(period, provider),
|
||||
[period, provider, range?.from, range?.to, refreshToken],
|
||||
{ enabled: ready },
|
||||
{ enabled: ready, memoKey: `optyield|${period}|${provider}|${range?.from ?? ''}-${range?.to ?? ''}` },
|
||||
)
|
||||
const [tab, setTab] = useState<OptimizeTab>('waste')
|
||||
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import type { ActReportJson, DailyHistoryEntry, MenubarPayload, YieldJsonReport
|
|||
import { Overview, OverviewContent, deriveSignals, localDateKey } from './Overview'
|
||||
|
||||
function polled(data: MenubarPayload): Polled<MenubarPayload> {
|
||||
return { data, error: null, loading: false, lastSuccessAt: Date.now(), refresh: vi.fn() }
|
||||
return { data, error: null, loading: false, switching: false, lastSuccessAt: Date.now(), refresh: vi.fn() }
|
||||
}
|
||||
|
||||
// Mock the typed bridge so the section fetches our payload instead of spawning
|
||||
|
|
@ -505,6 +505,7 @@ describe('Overview', () => {
|
|||
data: makePayload(now),
|
||||
error: { kind: 'nonzero', message: 'codeburn exited 1' },
|
||||
loading: false,
|
||||
switching: false,
|
||||
lastSuccessAt: Date.now(),
|
||||
refresh: vi.fn(),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -575,8 +575,8 @@ export function OverviewContent({
|
|||
// Gate secondary spawns on the app-level readiness (first overview resolved),
|
||||
// so the cold hydration runs once (via overview) rather than 3 parses at once
|
||||
// on boot. Defaults true so standalone renders/tests poll normally.
|
||||
const actReport = usePolled<ActReportJson>(() => codeburn.getActReport(), [], { enabled: ready })
|
||||
const yieldReport = usePolled<YieldJsonReport>(() => codeburn.getYield(period, provider), [period, provider], { enabled: ready })
|
||||
const actReport = usePolled<ActReportJson>(() => codeburn.getActReport(), [], { enabled: ready, memoKey: 'overview-act' })
|
||||
const yieldReport = usePolled<YieldJsonReport>(() => codeburn.getYield(period, provider), [period, provider], { enabled: ready, memoKey: `overview-yield|${period}|${provider}` })
|
||||
const { data, error } = overview
|
||||
const modelIndex = useMemo(() => data ? buildModelIndex(data) : new Map<string, string>(), [data])
|
||||
|
||||
|
|
|
|||
|
|
@ -30,6 +30,13 @@ function fmtPct(n: number): string {
|
|||
return Number.isInteger(n) ? `${n}%` : `${n.toFixed(1)}%`
|
||||
}
|
||||
|
||||
/** Honest copy for a 429 backoff window (the upstream quota endpoint rate
|
||||
* limited us), replacing the generic "waiting" note. */
|
||||
export function rateLimitedNote(provider: QuotaProvider['provider']): string {
|
||||
const owner = provider === 'claude' ? 'Anthropic' : 'OpenAI'
|
||||
return `${owner} rate limited the quota endpoint, retrying in a few minutes`
|
||||
}
|
||||
|
||||
function cycleEndDate(plan: JsonPlanSummary): Date | null {
|
||||
const date = new Date(plan.periodEnd)
|
||||
if (Number.isNaN(date.getTime())) return null
|
||||
|
|
@ -63,7 +70,7 @@ function manualPlanSummaries(status: StatusJson): JsonPlanSummary[] {
|
|||
}
|
||||
|
||||
export function Plans({ period, refreshToken = 0, onNavigate, ready = true }: { period: Period; refreshToken?: number; onNavigate?: (section: Section, pane?: SettingsPane) => void; ready?: boolean }) {
|
||||
// Force a fresh fetch (bypassing QuotaService's 2-min cache, and its keychain
|
||||
// Force a fresh fetch (bypassing QuotaService's 5-min cache, and its keychain
|
||||
// guard) when the user hits ⌘R or clicks Refresh in the Connect affordance;
|
||||
// the steady 30s poll keeps serving cached quota.
|
||||
const [reconnectNonce, setReconnectNonce] = useState(0)
|
||||
|
|
@ -165,6 +172,7 @@ function QuotaContent({ quota, onReconnect }: { quota: QuotaProvider; onReconnec
|
|||
}
|
||||
if (quota.connection === 'loading') return <p className="quota-connection-note">Loading quota…</p>
|
||||
if (quota.connection === 'stale' || quota.connection === 'transientFailure') {
|
||||
if (quota.rateLimited) return <p className="quota-connection-note">{rateLimitedNote(quota.provider)}</p>
|
||||
return <p className="quota-connection-note">waiting on the CLI…</p>
|
||||
}
|
||||
if (quota.connection === 'terminalFailure') {
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@ export function Sessions({
|
|||
const report = usePolled<SessionRow[]>(
|
||||
() => range ? codeburn.getSessions(period, provider, range) : codeburn.getSessions(period, provider),
|
||||
[period, provider, range?.from, range?.to, refreshToken],
|
||||
{ enabled: ready },
|
||||
{ enabled: ready, memoKey: `sessions|${period}|${provider}|${range?.from ?? ''}-${range?.to ?? ''}` },
|
||||
)
|
||||
const rows = report.data ?? []
|
||||
const q = query.trim().toLowerCase()
|
||||
|
|
|
|||
|
|
@ -12,9 +12,11 @@ import { readDailyBudget } from '../lib/budget'
|
|||
import { formatConverted, formatUsd } from '../lib/format'
|
||||
import { codeburn } from '../lib/ipc'
|
||||
import { motionClass } from '../lib/motion'
|
||||
import { REFRESH_OPTIONS, useRefreshCadence } from '../lib/refreshCadence'
|
||||
import { showToast } from '../lib/toast'
|
||||
import { ToastHost } from '../components/ToastHost'
|
||||
import type { ActionResult, AliasRow, ClaudeConfigSelector, CliError, CombinedUsage, DeviceScanResult, Identity, JsonPlanSummary, MenubarPayload, Period, PlanId, PlanProvider, PriceOverrideList, PriceOverrideRow, PriceRates, QuotaProvider, ShareStatus, StatusJson } from '../lib/types'
|
||||
import { rateLimitedNote } from './Plans'
|
||||
import type { ActionResult, AliasRow, ClaudeConfigSelector, CliError, CombinedUsage, DeviceScanResult, Identity, JsonPlanSummary, MenubarPayload, Period, PlanId, PlanProvider, PriceOverrideList, PriceOverrideRow, PriceRates, QuotaProvider, ShareStatus, StatusJson, TelemetryStatus } from '../lib/types'
|
||||
|
||||
export type SettingsPane = 'general' | 'providers' | 'aliases' | 'pricing' | 'plans' | 'devices' | 'export' | 'privacy'
|
||||
type Pane = SettingsPane
|
||||
|
|
@ -132,6 +134,7 @@ function GeneralPane({ period, refreshToken, claudeConfigs, claudeConfigSource }
|
|||
return saved === 'light' || saved === 'dark' ? saved : 'system'
|
||||
})
|
||||
const [defaultPeriod, setDefaultPeriod] = useState(() => readSetting('codeburn.defaultPeriod') ?? 'today')
|
||||
const cadence = useRefreshCadence()
|
||||
const [budgetKind, setBudgetKind] = useState<'off' | 'usd' | 'tokens'>(() => readDailyBudget()?.kind ?? 'off')
|
||||
const [budgetInput, setBudgetInput] = useState(() => { const budget = readDailyBudget(); return budget ? String(budget.value) : '' })
|
||||
const [budgetError, setBudgetError] = useState('')
|
||||
|
|
@ -190,6 +193,7 @@ function GeneralPane({ period, refreshToken, claudeConfigs, claudeConfigSource }
|
|||
<button className="set-text-button" onClick={() => void codeburn.resetCurrency().then(finishCurrency)}>Reset to USD</button>
|
||||
</span></div>
|
||||
<div className="about-row"><label className="tx" htmlFor="settings-period">Default period<small>Applied on next launch.</small></label><span className="r"><Dropdown id="settings-period" ariaLabel="Default period" value={defaultPeriod} options={[{ value: 'today', label: 'Today' }, { value: 'week', label: '7d' }, { value: '30days', label: '30d' }, { value: 'month', label: 'Month' }, { value: 'all', label: 'All' }]} onChange={value => { setDefaultPeriod(value); writeSetting('codeburn.defaultPeriod', value) }} width={92} /></span></div>
|
||||
<div className="about-row"><label className="tx" htmlFor="settings-refresh">Refresh every<small>How often data auto-refreshes. Manual updates only on ⌘R.</small></label><span className="r"><Dropdown id="settings-refresh" ariaLabel="Refresh every" value={cadence.value} options={REFRESH_OPTIONS.map(option => ({ value: option.value, label: option.label }))} onChange={cadence.setValue} width={124} /></span></div>
|
||||
<div className="about-row"><label className="tx" htmlFor="settings-budget">Daily budget<small>Warns at 80%, alerts at 100%.</small></label><span className="r"><Dropdown id="settings-budget" ariaLabel="Daily budget" value={budgetKind} options={[{ value: 'off', label: 'Off' }, { value: 'usd', label: 'USD amount' }, { value: 'tokens', label: 'Tokens' }]} onChange={value => { const kind = value as 'off' | 'usd' | 'tokens'; setBudgetKind(kind); persistBudget(kind, budgetInput) }} width={120} />{budgetKind !== 'off' && <input className="set-input" type="text" inputMode="decimal" aria-label="Daily budget amount" placeholder={budgetKind === 'usd' ? 'USD' : 'tokens'} value={budgetInput} onChange={event => { setBudgetInput(event.target.value); persistBudget(budgetKind, event.target.value) }} style={{ width: 90 }} />}</span></div>
|
||||
{budgetError && <p className="set-action-msg error">{budgetError}</p>}
|
||||
</div>
|
||||
|
|
@ -313,6 +317,8 @@ function DetectedRow({ quota, onReconnect }: { quota: QuotaProvider; onReconnect
|
|||
<span className="tx">{name}</span>
|
||||
{quota.connection === 'disconnected' || quota.connection === 'accessDenied'
|
||||
? <div className="r set-status"><ConnectAffordance provider={quota.provider} connection={quota.connection} onRefresh={onReconnect} /></div>
|
||||
: quota.rateLimited
|
||||
? <span className="r set-status"><span className="set-dot" />{rateLimitedNote(quota.provider)}</span>
|
||||
: <span className="r set-status"><span className="set-dot ok" />{quota.planLabel ?? 'Connected'}</span>}
|
||||
</div>
|
||||
}
|
||||
|
|
@ -416,11 +422,28 @@ function DevicesPane({ period, refreshToken }: { period: Period; refreshToken: n
|
|||
function PrivacyPane() {
|
||||
return <section className="set-p on"><div><h3 className="set-h">Privacy & data</h3><p className="set-sub">What codeburn does, and does not do, with your data.</p></div><div className="card">
|
||||
<PrivacyClaim title="Local-only" detail="Everything runs on your machine. Data is read from local session files." icon={<><rect x="4.5" y="10" width="15" height="11" rx="2" /><path d="M8 10V7a4 4 0 0 1 8 0v3" /></>} />
|
||||
<PrivacyClaim title="No telemetry" detail="codeburn does not collect or send telemetry." icon={<><path d="M2 12s3.5-7 10-7 10 7 10 7" /><line x1="3" y1="3" x2="21" y2="21" /></>} />
|
||||
<PrivacyClaim title="No API keys" detail="Usage is detected from local files; no provider API keys are required." icon={<path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z" />} />
|
||||
<TelemetryClaim />
|
||||
</div></section>
|
||||
}
|
||||
|
||||
/** The anonymous-telemetry consent toggle, mirroring the onboarding decision. */
|
||||
function TelemetryClaim() {
|
||||
const [status, setStatus] = useState<TelemetryStatus | null>(null)
|
||||
useEffect(() => {
|
||||
if (typeof codeburn.telemetryStatus !== 'function') return
|
||||
codeburn.telemetryStatus().then(value => setStatus(value)).catch(() => {})
|
||||
}, [])
|
||||
if (!status) return null
|
||||
const toggle = () => {
|
||||
if (typeof codeburn.setTelemetryEnabled !== 'function') return
|
||||
codeburn.setTelemetryEnabled(!status.enabled).then(value => setStatus(value)).catch(() => {})
|
||||
}
|
||||
return <div className="set-claim"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 19v-5M9 19V9M14 19v-8M19 19V5" /></svg><div style={{ flex: 1 }}><div className="set-claim-t">Anonymous telemetry</div><div className="set-claim-d">Optional usage statistics: model mix, task success, performance and errors. Never prompts, code or anything identifying.</div></div>
|
||||
<button type="button" role="switch" aria-checked={status.enabled} aria-label="Anonymous telemetry" className={status.enabled ? 'switch on' : 'switch'} onClick={toggle}><span className="switch-knob" /></button>
|
||||
</div>
|
||||
}
|
||||
|
||||
function PrivacyClaim({ title, detail, icon }: { title: string; detail: string; icon: React.ReactNode }) {
|
||||
return <div className="set-claim"><svg viewBox="0 0 24 24" aria-hidden="true">{icon}</svg><div><div className="set-claim-t">{title}</div><div className="set-claim-d">{detail}</div></div></div>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ export function SpendContent({
|
|||
const flow = usePolled<SpendFlow>(
|
||||
() => range ? codeburn.getSpendFlow(period, provider, range) : codeburn.getSpendFlow(period, provider),
|
||||
[period, provider, range?.from, range?.to, refreshToken],
|
||||
{ enabled: ready },
|
||||
{ enabled: ready, memoKey: `spendflow|${period}|${provider}|${range?.from ?? ''}-${range?.to ?? ''}` },
|
||||
)
|
||||
|
||||
if (!overview.data) {
|
||||
|
|
|
|||
|
|
@ -109,6 +109,11 @@ html, body, #root { height: 100%; margin: 0; }
|
|||
body { overflow: hidden; background: var(--bg); color: var(--ink); }
|
||||
.win { height: 100%; min-height: 0; border-radius: 0; background: var(--canvas); box-shadow: none; }
|
||||
.ct { min-height: 0; }
|
||||
/* Subtle in-flight hairline at the top of the section body: shown while a
|
||||
provider/period switch refreshes behind instantly-served memoized data. */
|
||||
.switch-line { flex: 0 0 auto; height: 2px; background: transparent; }
|
||||
.switch-line.on { background: linear-gradient(90deg, transparent, var(--accent), transparent); background-size: 200% 100%; animation: switch-line-shimmer 1.1s linear infinite; }
|
||||
@keyframes switch-line-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
|
||||
.body { overflow-y: auto; min-height: 0; align-items: center; padding: 18px 20px; gap: 16px; }
|
||||
/* Children keep their natural height (don't flex-shrink to fit) so the pane
|
||||
scrolls instead of squishing; capped width keeps content from stretching. */
|
||||
|
|
@ -831,6 +836,7 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); }
|
|||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.skel::after, .section-fade, .toast-in { animation: none; }
|
||||
.switch-line.on { animation: none; background: var(--accent); }
|
||||
.panel, .ov-card, .btnp, .btn, .ov-coach-cta { transition: none; }
|
||||
.panel:hover, .ov-card:hover, .btnp:active, .btn:active, .ov-coach-cta:active { transform: none; }
|
||||
}
|
||||
|
|
@ -927,3 +933,73 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); }
|
|||
.splash-status { animation: none; }
|
||||
.splash-prov.active { animation: none; }
|
||||
}
|
||||
|
||||
/* ————— First-launch onboarding (fixed dark canvas, like the splash) ————— */
|
||||
.onboard {
|
||||
position: fixed; inset: 0; z-index: 3100;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
background: radial-gradient(120% 80% at 50% 42%, color-mix(in srgb, #f2701c 8%, #171310), #171310 70%);
|
||||
}
|
||||
.onboard-card {
|
||||
display: flex; flex-direction: column; align-items: center; gap: 12px;
|
||||
width: min(420px, calc(100vw - 64px)); padding: 36px 36px 24px;
|
||||
text-align: center; border-radius: 14px;
|
||||
background: color-mix(in srgb, #fff 4%, transparent);
|
||||
border: 1px solid color-mix(in srgb, #fff 9%, transparent);
|
||||
}
|
||||
.onboard-glyph { color: #f2701c; display: flex; margin-bottom: 2px; }
|
||||
.onboard-title { margin: 0; font-size: var(--fs-kpi); font-weight: var(--fw-strong); letter-spacing: -0.01em; color: #f4f1ec; }
|
||||
.onboard-body { margin: 0; max-width: 320px; font-size: var(--fs-body); line-height: 1.55; color: #b3a595; }
|
||||
.onboard-consent {
|
||||
margin-top: 6px; display: flex; align-items: center; justify-content: space-between; gap: 16px;
|
||||
width: 100%; padding: 10px 14px; border-radius: 9px;
|
||||
border: 1px solid color-mix(in srgb, #fff 10%, transparent);
|
||||
font-size: var(--fs-body); color: #f4f1ec;
|
||||
}
|
||||
.onboard-link {
|
||||
background: none; border: none; padding: 0; cursor: pointer;
|
||||
font: inherit; font-size: var(--fs-label); color: #b3a595; text-decoration: underline; text-underline-offset: 3px;
|
||||
}
|
||||
.onboard-link:hover, .onboard-link:focus-visible { color: #f4f1ec; outline: none; }
|
||||
.onboard-controls {
|
||||
margin-top: 14px; display: flex; align-items: center; justify-content: space-between; gap: 12px; width: 100%;
|
||||
}
|
||||
.onboard-btn {
|
||||
min-width: 96px; padding: 7px 14px; border-radius: 8px; cursor: pointer;
|
||||
font: inherit; font-size: var(--fs-meta); font-weight: var(--fw-medium);
|
||||
color: #f4f1ec; background: transparent; border: 1px solid color-mix(in srgb, #fff 16%, transparent);
|
||||
}
|
||||
.onboard-btn:hover { background: color-mix(in srgb, #fff 6%, transparent); }
|
||||
.onboard-btn.primary { background: #f2701c; border-color: #f2701c; color: #fff; }
|
||||
.onboard-btn.primary:hover { background: color-mix(in srgb, #f2701c 88%, #fff); }
|
||||
.onboard-btn:focus-visible { outline: 1px solid #f2701c; outline-offset: 1px; }
|
||||
.onboard-btn-ghost { min-width: 96px; }
|
||||
.onboard-dots { display: flex; gap: 6px; }
|
||||
.onboard-dot { width: 6px; height: 6px; border-radius: 50%; background: color-mix(in srgb, #fff 18%, transparent); transition: background 150ms ease; }
|
||||
.onboard-dot.on { background: #f2701c; }
|
||||
.onboard-in { animation: splash-word-in 320ms ease-out both; }
|
||||
|
||||
/* Toggle switch (shared shape; used by onboarding consent + Settings privacy). */
|
||||
.switch {
|
||||
position: relative; width: 38px; height: 22px; flex: none;
|
||||
border-radius: 999px; border: 1px solid color-mix(in srgb, #fff 18%, transparent);
|
||||
background: color-mix(in srgb, #fff 8%, transparent); cursor: pointer; padding: 0;
|
||||
transition: background 150ms ease, border-color 150ms ease;
|
||||
}
|
||||
.switch .switch-knob {
|
||||
position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%;
|
||||
background: #f4f1ec; transition: transform 150ms ease;
|
||||
}
|
||||
.switch.on { background: #f2701c; border-color: #f2701c; }
|
||||
.switch.on .switch-knob { transform: translateX(16px); background: #fff; }
|
||||
.switch:focus-visible { outline: 1px solid #f2701c; outline-offset: 1px; }
|
||||
/* On themed (Settings) surfaces the same switch keys off theme tokens. */
|
||||
.set-p .switch { border-color: var(--line2); background: var(--hover); }
|
||||
.set-p .switch .switch-knob { background: var(--mut); }
|
||||
.set-p .switch.on { background: var(--accent); border-color: var(--accent); }
|
||||
.set-p .switch.on .switch-knob { background: #fff; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.onboard-in { animation: none; }
|
||||
.switch, .switch .switch-knob, .onboard-dot { transition: none; }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,8 +2,12 @@ import '@testing-library/jest-dom/vitest'
|
|||
import { afterEach } from 'vitest'
|
||||
|
||||
// Only wire DOM cleanup in a browser-like (jsdom) environment; node-env tests
|
||||
// (cli/main) have no document and must not import RTL's DOM cleanup.
|
||||
// (cli/main) have no document and must not import RTL's DOM cleanup — nor the
|
||||
// renderer hook graph (usePolled → ipc touches `window` at load).
|
||||
if (typeof document !== 'undefined') {
|
||||
const { cleanup } = await import('@testing-library/react')
|
||||
afterEach(() => cleanup())
|
||||
// The usePolled memo is module-level and persists across renders; clear it
|
||||
// between tests so a cached result from one test never seeds another.
|
||||
const { __resetPolledMemo } = await import('../hooks/usePolled')
|
||||
afterEach(() => { cleanup(); __resetPolledMemo() })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,7 +28,13 @@ import type { DateRange, ProjectSummary } from './types.js'
|
|||
// user changes their `localModelSavings` mapping.
|
||||
export const DAILY_CACHE_VERSION = 12
|
||||
const MIN_SUPPORTED_VERSION = 12
|
||||
const DAILY_CACHE_FILENAME = 'daily-cache.json'
|
||||
// Version-suffixed so different binaries each own a distinct file and never
|
||||
// clobber an incompatible schema. Bumping the version mints a fresh filename.
|
||||
const DAILY_CACHE_FILENAME = `daily-cache.v${DAILY_CACHE_VERSION}.json`
|
||||
// The pre-versioning filename. Never written or deleted anymore (old binaries
|
||||
// own it). Adopt-copied once on first load when the versioned file is absent and
|
||||
// the legacy file's version matches ours; a different version is ignored.
|
||||
const LEGACY_DAILY_CACHE_FILENAME = 'daily-cache.json'
|
||||
|
||||
export type DailyEntry = {
|
||||
date: string
|
||||
|
|
@ -74,6 +80,15 @@ function getCachePath(): string {
|
|||
return join(getCacheDir(), DAILY_CACHE_FILENAME)
|
||||
}
|
||||
|
||||
function getLegacyCachePath(): string {
|
||||
return join(getCacheDir(), LEGACY_DAILY_CACHE_FILENAME)
|
||||
}
|
||||
|
||||
/** Absolute path of the active (version-suffixed) daily cache file. */
|
||||
export function dailyCachePath(): string {
|
||||
return getCachePath()
|
||||
}
|
||||
|
||||
export function emptyCache(savingsConfigHash = ''): DailyCache {
|
||||
return { version: DAILY_CACHE_VERSION, savingsConfigHash, lastComputedDate: null, days: [] }
|
||||
}
|
||||
|
|
@ -105,31 +120,46 @@ function migrateDays(days: Record<string, unknown>[]): DailyEntry[] {
|
|||
}))
|
||||
}
|
||||
|
||||
async function backupOldCache(path: string, version: number): Promise<void> {
|
||||
const backupPath = `${path}.v${version}.bak`
|
||||
try { await rename(path, backupPath) } catch { /* best-effort */ }
|
||||
function migratedFrom(parsed: { version: number; lastComputedDate: string | null; savingsConfigHash?: string; days: Record<string, unknown>[] }): DailyCache {
|
||||
return {
|
||||
version: DAILY_CACHE_VERSION,
|
||||
savingsConfigHash: parsed.savingsConfigHash ?? '',
|
||||
lastComputedDate: parsed.lastComputedDate,
|
||||
days: migrateDays(parsed.days),
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadDailyCache(): Promise<DailyCache> {
|
||||
const path = getCachePath()
|
||||
if (!existsSync(path)) return emptyCache()
|
||||
try {
|
||||
const raw = await readFile(path, 'utf-8')
|
||||
const parsed: unknown = JSON.parse(raw)
|
||||
if (isMigratableCache(parsed)) {
|
||||
const migrated: DailyCache = {
|
||||
version: DAILY_CACHE_VERSION,
|
||||
savingsConfigHash: parsed.savingsConfigHash ?? '',
|
||||
lastComputedDate: parsed.lastComputedDate,
|
||||
days: migrateDays(parsed.days),
|
||||
if (existsSync(path)) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(await readFile(path, 'utf-8'))
|
||||
if (isMigratableCache(parsed)) {
|
||||
const migrated = migratedFrom(parsed)
|
||||
if (parsed.version < DAILY_CACHE_VERSION) await saveDailyCache(migrated).catch(() => {})
|
||||
return migrated
|
||||
}
|
||||
if (parsed.version < DAILY_CACHE_VERSION) {
|
||||
await saveDailyCache(migrated).catch(() => {})
|
||||
}
|
||||
return migrated
|
||||
return emptyCache()
|
||||
} catch {
|
||||
return emptyCache()
|
||||
}
|
||||
}
|
||||
// Versioned file absent: adopt the legacy unversioned file once, only when its
|
||||
// version matches ours. A different-version legacy file is ignored and left
|
||||
// intact — old binaries still own it, so we never write or delete it.
|
||||
return adoptLegacyDailyCache()
|
||||
}
|
||||
|
||||
async function adoptLegacyDailyCache(): Promise<DailyCache> {
|
||||
const legacy = getLegacyCachePath()
|
||||
if (!existsSync(legacy)) return emptyCache()
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(await readFile(legacy, 'utf-8'))
|
||||
if (isMigratableCache(parsed) && parsed.version === DAILY_CACHE_VERSION) {
|
||||
const adopted = migratedFrom(parsed)
|
||||
await saveDailyCache(adopted).catch(() => {})
|
||||
return adopted
|
||||
}
|
||||
const oldVersion = (parsed as { version?: number })?.version
|
||||
if (typeof oldVersion === 'number') await backupOldCache(path, oldVersion)
|
||||
return emptyCache()
|
||||
} catch {
|
||||
return emptyCache()
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import {
|
|||
type CachedTurn,
|
||||
type ProviderSection,
|
||||
type SessionCache,
|
||||
beginColdHydration,
|
||||
cleanupOrphanedTempFiles,
|
||||
computeEnvFingerprint,
|
||||
DURABLE_PROVIDER_NAMES,
|
||||
|
|
@ -2635,9 +2636,25 @@ export async function parseAllSessions(dateRange?: DateRange, providerFilter?: s
|
|||
const cached = sessionCache.get(key)
|
||||
if (cached && Date.now() - cached.ts < CACHE_TTL_MS) return cached.data
|
||||
|
||||
const diskCache = await loadCache()
|
||||
let diskCache = await loadCache()
|
||||
await cleanupOrphanedTempFiles()
|
||||
|
||||
// Cold-hydration coordination (advisory, cross-process). Engages only when the
|
||||
// on-disk cache is empty — a genuine full parse. If another live process is
|
||||
// already hydrating, wait for it, then reload the now-warm cache instead of
|
||||
// double-parsing (kills the menubar-vs-desktop cache clobber). Never a
|
||||
// correctness gate: on any doubt it proceeds unlocked.
|
||||
const hydration = await beginColdHydration(Object.keys(diskCache.providers).length === 0)
|
||||
if (hydration.waited) diskCache = await loadCache()
|
||||
|
||||
try {
|
||||
return await runParse(key, diskCache, dateRange, providerFilter)
|
||||
} finally {
|
||||
await hydration.release()
|
||||
}
|
||||
}
|
||||
|
||||
async function runParse(key: string, diskCache: SessionCache, dateRange?: DateRange, providerFilter?: string): Promise<ProjectSummary[]> {
|
||||
const seenMsgIds = new Set<string>()
|
||||
const seenKeys = new Set<string>()
|
||||
const allSources = await discoverAllSessions(providerFilter)
|
||||
|
|
|
|||
|
|
@ -91,7 +91,16 @@ export type SessionCache = {
|
|||
// never change. Bump forces a one-time re-parse so metered credit costs land.
|
||||
export const CACHE_VERSION = 5
|
||||
|
||||
const CACHE_FILE = 'session-cache.json'
|
||||
// The cache filename is version-suffixed so different binaries (e.g. an old
|
||||
// launchd menubar on a prior release and a newer desktop app) each own a
|
||||
// distinct file and can never clobber each other's incompatible schema. Bumping
|
||||
// CACHE_VERSION automatically mints a fresh filename, superseding the migration
|
||||
// dance the legacy unversioned file used to need.
|
||||
const CACHE_FILE = `session-cache.v${CACHE_VERSION}.json`
|
||||
// The pre-versioning filename. Never written or deleted anymore — old binaries
|
||||
// still own it. On first load we adopt-copy it once (see loadCache) when the
|
||||
// versioned file is absent and the legacy file's version matches ours.
|
||||
const LEGACY_CACHE_FILE = 'session-cache.json'
|
||||
const TEMP_FILE_MAX_AGE_MS = 5 * 60 * 1000
|
||||
|
||||
export const PROVIDER_ENV_VARS: Record<string, string[]> = {
|
||||
|
|
@ -155,6 +164,15 @@ function getCachePath(): string {
|
|||
return join(getCacheDir(), CACHE_FILE)
|
||||
}
|
||||
|
||||
function getLegacyCachePath(): string {
|
||||
return join(getCacheDir(), LEGACY_CACHE_FILE)
|
||||
}
|
||||
|
||||
/** Absolute path of the active (version-suffixed) session cache file. */
|
||||
export function sessionCachePath(): string {
|
||||
return getCachePath()
|
||||
}
|
||||
|
||||
// ── Env Fingerprint ────────────────────────────────────────────────────
|
||||
|
||||
export function computeEnvFingerprint(provider: string): string {
|
||||
|
|
@ -282,6 +300,22 @@ export async function loadCache(): Promise<SessionCache> {
|
|||
const parsed = JSON.parse(raw)
|
||||
if (!validateCache(parsed)) return emptyCache()
|
||||
return parsed
|
||||
} catch {
|
||||
// Versioned file absent/unreadable: try a one-time adoption of the legacy
|
||||
// unversioned file. validateCache requires version === CACHE_VERSION, so a
|
||||
// different-version legacy file is ignored (left intact). We copy it into the
|
||||
// versioned file once via saveCache; the legacy file is never modified.
|
||||
return adoptLegacyCache()
|
||||
}
|
||||
}
|
||||
|
||||
async function adoptLegacyCache(): Promise<SessionCache> {
|
||||
try {
|
||||
const raw = await readFile(getLegacyCachePath(), 'utf-8')
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!validateCache(parsed)) return emptyCache()
|
||||
await saveCache(parsed).catch(() => {})
|
||||
return parsed
|
||||
} catch {
|
||||
return emptyCache()
|
||||
}
|
||||
|
|
@ -420,7 +454,9 @@ export async function cleanupOrphanedTempFiles(): Promise<void> {
|
|||
const entries = await readdir(dir)
|
||||
const now = Date.now()
|
||||
|
||||
const prefix = 'session-cache.json.'
|
||||
// Only our own (versioned) temp files. Legacy `session-cache.json.*.tmp`
|
||||
// temps belong to old binaries mid-write and must not be touched.
|
||||
const prefix = `${CACHE_FILE}.`
|
||||
for (const entry of entries) {
|
||||
if (!entry.startsWith(prefix) || !entry.endsWith('.tmp')) continue
|
||||
try {
|
||||
|
|
@ -433,3 +469,109 @@ export async function cleanupOrphanedTempFiles(): Promise<void> {
|
|||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// ── Hydration Lock ─────────────────────────────────────────────────────
|
||||
//
|
||||
// Advisory, cross-process coordination for the expensive cold hydration. When
|
||||
// two live processes (e.g. an old launchd menubar and the desktop app) both
|
||||
// cold-start against the same cache dir, without this they each parse full
|
||||
// history and race their writes. The first to arrive creates the lock and
|
||||
// hydrates; a second live process waits for release, then reads the now-warm
|
||||
// cache instead of re-parsing. It is strictly an optimization: on any
|
||||
// uncertainty we proceed with the parse, so it can never wedge a cold start.
|
||||
|
||||
const HYDRATION_LOCK_FILE = 'hydrating.lock'
|
||||
const LOCK_FRESH_MS = 15 * 60_000
|
||||
const LOCK_WAIT_MAX_MS = 10 * 60_000
|
||||
const LOCK_POLL_MS = 250
|
||||
|
||||
type LockRecord = { pid: number; at: number }
|
||||
export type HydrationHandle = { waited: boolean; release: () => Promise<void> }
|
||||
|
||||
const NOOP_HANDLE: HydrationHandle = { waited: false, release: async () => {} }
|
||||
|
||||
function lockPath(): string {
|
||||
return join(getCacheDir(), HYDRATION_LOCK_FILE)
|
||||
}
|
||||
|
||||
// Our own pid never counts as a foreign holder: a same-process lock is either
|
||||
// re-entrant or leaked, and waiting on ourselves risks a self-hang. Cross-process
|
||||
// coordination is the only thing this lock is for. EPERM means the pid exists but
|
||||
// belongs to another user — still alive.
|
||||
function pidLooksAlive(pid: number): boolean {
|
||||
if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) return false
|
||||
try { process.kill(pid, 0); return true }
|
||||
catch (err) { return (err as NodeJS.ErrnoException).code === 'EPERM' }
|
||||
}
|
||||
|
||||
async function readLockRecord(): Promise<LockRecord | null> {
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(lockPath(), 'utf-8')) as Partial<LockRecord>
|
||||
if (typeof parsed?.pid === 'number' && typeof parsed?.at === 'number') return { pid: parsed.pid, at: parsed.at }
|
||||
return null
|
||||
} catch { return null }
|
||||
}
|
||||
|
||||
async function writeOurLock(): Promise<boolean> {
|
||||
try {
|
||||
const dir = getCacheDir()
|
||||
if (!existsSync(dir)) await mkdir(dir, { recursive: true })
|
||||
const handle = await open(lockPath(), 'wx', 0o600)
|
||||
try { await handle.writeFile(JSON.stringify({ pid: process.pid, at: Date.now() }), { encoding: 'utf-8' }) }
|
||||
finally { await handle.close() }
|
||||
return true
|
||||
} catch { return false }
|
||||
}
|
||||
|
||||
async function removeOurLock(): Promise<void> {
|
||||
try {
|
||||
const cur = await readLockRecord()
|
||||
if (cur && cur.pid === process.pid) await unlink(lockPath())
|
||||
} catch { /* best-effort; a leaked lock is reclaimed as stale next cold start */ }
|
||||
}
|
||||
|
||||
const releaseHandle: HydrationHandle = { waited: false, release: removeOurLock }
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise(resolve => { setTimeout(resolve, ms) })
|
||||
}
|
||||
|
||||
/**
|
||||
* Coordinate a cold hydration. Pass `isCold = true` only when the on-disk cache
|
||||
* is empty (a genuine full parse is imminent). Returns a handle:
|
||||
* - `waited: true` → another live process was hydrating; we waited for it to
|
||||
* finish (or timed out). The caller should RELOAD the cache and let its normal
|
||||
* reconcile serve the now-warm entries instead of re-parsing. `release` is a
|
||||
* no-op (we never held the lock).
|
||||
* - `waited: false` with a real `release` → we hold the lock; hydrate, then call
|
||||
* `release()` in a finally.
|
||||
* - `waited: false` with a no-op `release` → proceed with the parse unlocked
|
||||
* (not cold, or the lock state was uncertain).
|
||||
*/
|
||||
export async function beginColdHydration(isCold: boolean): Promise<HydrationHandle> {
|
||||
if (!isCold) return NOOP_HANDLE
|
||||
try {
|
||||
if (await writeOurLock()) return releaseHandle
|
||||
const existing = await readLockRecord()
|
||||
const fresh = existing !== null && Date.now() - existing.at < LOCK_FRESH_MS
|
||||
if (existing && fresh && pidLooksAlive(existing.pid)) {
|
||||
// Another live process owns a fresh lock: wait for it to release, go stale,
|
||||
// or die, then let the caller reload the warm cache.
|
||||
const deadline = Date.now() + LOCK_WAIT_MAX_MS
|
||||
while (Date.now() < deadline) {
|
||||
await sleep(LOCK_POLL_MS)
|
||||
const cur = await readLockRecord()
|
||||
if (!cur) break
|
||||
if (Date.now() - cur.at >= LOCK_FRESH_MS) break
|
||||
if (!pidLooksAlive(cur.pid)) break
|
||||
}
|
||||
return { waited: true, release: async () => {} }
|
||||
}
|
||||
// Stale, dead-pid, or unreadable lock: replace it and take over.
|
||||
try { await unlink(lockPath()) } catch { /* another process may have; fine */ }
|
||||
if (await writeOurLock()) return releaseHandle
|
||||
return NOOP_HANDLE
|
||||
} catch {
|
||||
return NOOP_HANDLE
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { join } from 'path'
|
|||
import { tmpdir } from 'os'
|
||||
|
||||
import { parseAllSessions, clearSessionCache } from '../src/parser.js'
|
||||
import { CACHE_VERSION } from '../src/session-cache.js'
|
||||
import { CACHE_VERSION, sessionCachePath } from '../src/session-cache.js'
|
||||
|
||||
let tmpDir: string
|
||||
let cacheDir: string
|
||||
|
|
@ -48,7 +48,7 @@ describe('cold-start cache persistence', () => {
|
|||
const projects = await parseAllSessions()
|
||||
expect(projects.length).toBeGreaterThan(0)
|
||||
|
||||
const raw = JSON.parse(await readFile(join(cacheDir, 'session-cache.json'), 'utf-8'))
|
||||
const raw = JSON.parse(await readFile(sessionCachePath(), 'utf-8'))
|
||||
expect(raw.version).toBe(CACHE_VERSION)
|
||||
const claudeFiles = Object.keys(raw.providers?.claude?.files ?? {})
|
||||
expect(claudeFiles.length).toBeGreaterThan(0)
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import { createHash } from 'crypto'
|
|||
import { join } from 'path'
|
||||
|
||||
import { clearSessionCache, parseAllSessions } from '../src/parser.js'
|
||||
import { sessionCachePath } from '../src/session-cache.js'
|
||||
|
||||
const testRoot = vi.hoisted(() => {
|
||||
const root = `${process.env['TMPDIR'] || '/tmp'}/codex-stale-repro-${process.pid}-${Date.now()}`
|
||||
|
|
@ -74,7 +75,7 @@ describe('codex parser change invalidates stale session-cache (#478/#513)', () =
|
|||
// release: pre-fix envFingerprint, unchanged file fingerprint, cached
|
||||
// turns lack the mcp__ tool. Also reset codex-results.json to v4 so the
|
||||
// provider (if it runs at all) must genuinely re-parse.
|
||||
const cachePath = join(CACHE_DIR, 'session-cache.json')
|
||||
const cachePath = sessionCachePath()
|
||||
const cache = JSON.parse(await readFile(cachePath, 'utf8'))
|
||||
cache.providers.codex.envFingerprint = preFixFingerprint()
|
||||
for (const f of Object.values(cache.providers.codex.files) as any[]) {
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import type { ProjectSummary } from '../src/types.js'
|
|||
|
||||
import {
|
||||
addNewDays,
|
||||
dailyCachePath,
|
||||
DAILY_CACHE_VERSION,
|
||||
type DailyCache,
|
||||
type DailyEntry,
|
||||
|
|
@ -66,7 +67,11 @@ describe('loadDailyCache', () => {
|
|||
expect(cache.days).toEqual([])
|
||||
})
|
||||
|
||||
it('returns an empty cache and backs up when version is too old to migrate', async () => {
|
||||
// With version-suffixed filenames, a legacy unversioned file whose version is
|
||||
// not the current one is simply IGNORED — never migrated, never backed up,
|
||||
// never touched (old binaries still own it). Load returns an empty cache and
|
||||
// the legacy file is left intact on disk.
|
||||
it('ignores (and never rewrites) a legacy file too old to migrate', async () => {
|
||||
const saved = {
|
||||
version: 1,
|
||||
lastComputedDate: '2026-04-10',
|
||||
|
|
@ -74,20 +79,18 @@ describe('loadDailyCache', () => {
|
|||
}
|
||||
const { writeFile, mkdir } = await import('fs/promises')
|
||||
await mkdir(TMP_CACHE_ROOT, { recursive: true })
|
||||
await writeFile(join(TMP_CACHE_ROOT, 'daily-cache.json'), JSON.stringify(saved), 'utf-8')
|
||||
const legacy = join(TMP_CACHE_ROOT, 'daily-cache.json')
|
||||
await writeFile(legacy, JSON.stringify(saved), 'utf-8')
|
||||
const cache = await loadDailyCache()
|
||||
expect(cache.days).toEqual([])
|
||||
expect(cache.lastComputedDate).toBeNull()
|
||||
expect(existsSync(join(TMP_CACHE_ROOT, 'daily-cache.json.v1.bak'))).toBe(true)
|
||||
// Legacy file untouched (no .bak, contents intact); no versioned file written.
|
||||
expect(existsSync(join(TMP_CACHE_ROOT, 'daily-cache.json.v1.bak'))).toBe(false)
|
||||
expect(JSON.parse(await readFile(legacy, 'utf-8'))).toEqual(saved)
|
||||
expect(existsSync(dailyCachePath())).toBe(false)
|
||||
})
|
||||
|
||||
it('discards a v2 cache and starts fresh (provider rollups would be stale)', async () => {
|
||||
// MIN_SUPPORTED_VERSION was raised to DAILY_CACHE_VERSION because the
|
||||
// migration path cannot recompute the providers / categories / models
|
||||
// rollups from session data (the cache does not retain raw sessions),
|
||||
// so a migrated old cache would carry forward stale provider totals
|
||||
// for the full retention window. Older caches now get discarded and
|
||||
// recomputed from scratch on next run.
|
||||
it('ignores a legacy v2 cache (provider rollups would be stale) and leaves it intact', async () => {
|
||||
const saved = {
|
||||
version: 2,
|
||||
lastComputedDate: '2026-04-10',
|
||||
|
|
@ -99,16 +102,17 @@ describe('loadDailyCache', () => {
|
|||
}
|
||||
const { writeFile, mkdir } = await import('fs/promises')
|
||||
await mkdir(TMP_CACHE_ROOT, { recursive: true })
|
||||
await writeFile(join(TMP_CACHE_ROOT, 'daily-cache.json'), JSON.stringify(saved), 'utf-8')
|
||||
const legacy = join(TMP_CACHE_ROOT, 'daily-cache.json')
|
||||
await writeFile(legacy, JSON.stringify(saved), 'utf-8')
|
||||
const cache = await loadDailyCache()
|
||||
expect(cache.version).toBe(DAILY_CACHE_VERSION)
|
||||
expect(cache.days).toEqual([])
|
||||
expect(cache.lastComputedDate).toBeNull()
|
||||
// Old cache is renamed to .v2.bak rather than deleted.
|
||||
expect(existsSync(join(TMP_CACHE_ROOT, 'daily-cache.json.v2.bak'))).toBe(true)
|
||||
expect(existsSync(join(TMP_CACHE_ROOT, 'daily-cache.json.v2.bak'))).toBe(false)
|
||||
expect(JSON.parse(await readFile(legacy, 'utf-8'))).toEqual(saved)
|
||||
})
|
||||
|
||||
it('discards a v5 cache because cached Claude costs predate 1-hour cache pricing', async () => {
|
||||
it('ignores a legacy v5 cache (predates 1-hour cache pricing) and leaves it intact', async () => {
|
||||
const saved = {
|
||||
version: 5,
|
||||
lastComputedDate: '2026-05-01',
|
||||
|
|
@ -130,12 +134,41 @@ describe('loadDailyCache', () => {
|
|||
}
|
||||
const { writeFile, mkdir } = await import('fs/promises')
|
||||
await mkdir(TMP_CACHE_ROOT, { recursive: true })
|
||||
await writeFile(join(TMP_CACHE_ROOT, 'daily-cache.json'), JSON.stringify(saved), 'utf-8')
|
||||
const legacy = join(TMP_CACHE_ROOT, 'daily-cache.json')
|
||||
await writeFile(legacy, JSON.stringify(saved), 'utf-8')
|
||||
const cache = await loadDailyCache()
|
||||
expect(cache.version).toBe(DAILY_CACHE_VERSION)
|
||||
expect(cache.days).toEqual([])
|
||||
expect(cache.lastComputedDate).toBeNull()
|
||||
expect(existsSync(join(TMP_CACHE_ROOT, 'daily-cache.json.v5.bak'))).toBe(true)
|
||||
expect(existsSync(join(TMP_CACHE_ROOT, 'daily-cache.json.v5.bak'))).toBe(false)
|
||||
expect(JSON.parse(await readFile(legacy, 'utf-8'))).toEqual(saved)
|
||||
})
|
||||
|
||||
it('adopts a legacy file whose version matches the current one, once, without deleting it', async () => {
|
||||
const saved = {
|
||||
version: DAILY_CACHE_VERSION,
|
||||
savingsConfigHash: 'legacy-hash',
|
||||
lastComputedDate: '2026-05-01',
|
||||
days: [emptyDay('2026-05-01', 3.5, 9)],
|
||||
}
|
||||
const { writeFile, mkdir } = await import('fs/promises')
|
||||
await mkdir(TMP_CACHE_ROOT, { recursive: true })
|
||||
const legacy = join(TMP_CACHE_ROOT, 'daily-cache.json')
|
||||
await writeFile(legacy, JSON.stringify(saved), 'utf-8')
|
||||
|
||||
// First load: versioned file absent → adopt-copy from legacy.
|
||||
const first = await loadDailyCache()
|
||||
expect(first.days).toEqual(saved.days)
|
||||
expect(first.savingsConfigHash).toBe('legacy-hash')
|
||||
expect(existsSync(dailyCachePath())).toBe(true)
|
||||
// Legacy file is NOT deleted.
|
||||
expect(existsSync(legacy)).toBe(true)
|
||||
|
||||
// Adoption is one-time: mutate the legacy file, load again — the versioned
|
||||
// file now wins and the stale legacy edit is never re-adopted.
|
||||
await writeFile(legacy, JSON.stringify({ ...saved, days: [emptyDay('2000-01-01', 999)] }), 'utf-8')
|
||||
const second = await loadDailyCache()
|
||||
expect(second.days).toEqual(saved.days)
|
||||
})
|
||||
|
||||
it('round-trips a valid cache through save and load', async () => {
|
||||
|
|
@ -164,7 +197,7 @@ describe('saveDailyCache', () => {
|
|||
const files = await readdir(TMP_CACHE_ROOT)
|
||||
const tempLeftovers = files.filter(f => f.endsWith('.tmp'))
|
||||
expect(tempLeftovers).toEqual([])
|
||||
const finalFile = await readFile(join(TMP_CACHE_ROOT, 'daily-cache.json'), 'utf-8')
|
||||
const finalFile = await readFile(dailyCachePath(), 'utf-8')
|
||||
expect(JSON.parse(finalFile)).toEqual(saved)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ import {
|
|||
CACHE_VERSION,
|
||||
computeEnvFingerprint,
|
||||
fingerprintFile,
|
||||
sessionCachePath,
|
||||
type SessionCache,
|
||||
} from '../src/session-cache.js'
|
||||
|
||||
|
|
@ -98,7 +99,7 @@ async function seedCache(execPath: string, envFingerprint: string): Promise<void
|
|||
},
|
||||
}
|
||||
await mkdir(CACHE_DIR, { recursive: true })
|
||||
await writeFile(join(CACHE_DIR, 'session-cache.json'), JSON.stringify(cache))
|
||||
await writeFile(sessionCachePath(), JSON.stringify(cache))
|
||||
}
|
||||
|
||||
async function parseKiroCalls() {
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
|||
|
||||
import { getDateRange } from '../src/cli-date.js'
|
||||
import { clearSessionCache, parseAllSessions } from '../src/parser.js'
|
||||
import { sessionCachePath } from '../src/session-cache.js'
|
||||
import { isSqliteAvailable } from '../src/sqlite.js'
|
||||
import type { DateRange } from '../src/types.js'
|
||||
|
||||
|
|
@ -39,7 +40,7 @@ function createGenMetadataDb(dbPath: string, fixture: Fixture): void {
|
|||
}
|
||||
|
||||
async function cachedAntigravityTurns(cacheDir: string, dbPath: string): Promise<Array<{ timestamp: string }>> {
|
||||
const saved = JSON.parse(await readFile(join(cacheDir, 'session-cache.json'), 'utf-8')) as {
|
||||
const saved = JSON.parse(await readFile(sessionCachePath(), 'utf-8')) as {
|
||||
providers: Record<string, { files: Record<string, { turns: Array<{ timestamp: string }> }> }>
|
||||
}
|
||||
return saved.providers['antigravity']?.files[dbPath]?.turns ?? []
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { join } from 'path'
|
|||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import { clearSessionCache, parseAllSessions } from '../src/parser.js'
|
||||
import { CACHE_VERSION, computeEnvFingerprint } from '../src/session-cache.js'
|
||||
import { CACHE_VERSION, computeEnvFingerprint, sessionCachePath } from '../src/session-cache.js'
|
||||
import type { DateRange } from '../src/types.js'
|
||||
|
||||
let home: string
|
||||
|
|
@ -54,7 +54,7 @@ describe('Gemini session cache migration', () => {
|
|||
}))
|
||||
|
||||
const fileStat = await stat(sessionPath)
|
||||
await writeFile(join(cacheDir, 'session-cache.json'), JSON.stringify({
|
||||
await writeFile(sessionCachePath(), JSON.stringify({
|
||||
version: CACHE_VERSION,
|
||||
providers: {
|
||||
gemini: {
|
||||
|
|
@ -117,7 +117,7 @@ describe('Gemini session cache migration', () => {
|
|||
'gemini:gemini-session-1:g2',
|
||||
])
|
||||
|
||||
const savedCache = JSON.parse(await readFile(join(cacheDir, 'session-cache.json'), 'utf-8'))
|
||||
const savedCache = JSON.parse(await readFile(sessionCachePath(), 'utf-8'))
|
||||
const savedKeys = savedCache.providers.gemini.files[sessionPath].turns.flatMap((turn: { calls: Array<{ deduplicationKey: string }> }) =>
|
||||
turn.calls.map(call => call.deduplicationKey),
|
||||
)
|
||||
|
|
|
|||
138
tests/parser-hydration-lock.test.ts
Normal file
138
tests/parser-hydration-lock.test.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
// Advisory hydration-lock coordination in parseAllSessions. When the on-disk
|
||||
// cache is cold and another LIVE process already holds a fresh lock, a second
|
||||
// process waits for release then reads the now-warm cache instead of re-parsing.
|
||||
// Stale / dead-pid locks are ignored and replaced. The lock is an optimization,
|
||||
// never a correctness gate.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { existsSync } from 'fs'
|
||||
import { mkdir, mkdtemp, rm, unlink, writeFile, readFile } from 'fs/promises'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
|
||||
import { clearSessionCache, parseAllSessions } from '../src/parser.js'
|
||||
import { sessionCachePath } from '../src/session-cache.js'
|
||||
|
||||
let tmpHome: string
|
||||
let cacheDir: string
|
||||
|
||||
function lockPath(): string {
|
||||
return join(cacheDir, 'hydrating.lock')
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise(resolve => { setTimeout(resolve, ms) })
|
||||
}
|
||||
|
||||
function totalOutput(projects: Awaited<ReturnType<typeof parseAllSessions>>): number {
|
||||
return projects
|
||||
.flatMap(p => p.sessions)
|
||||
.flatMap(s => s.turns)
|
||||
.flatMap(t => t.assistantCalls)
|
||||
.reduce((sum, c) => sum + c.usage.outputTokens, 0)
|
||||
}
|
||||
|
||||
async function writeClaudeSession(output: number): Promise<void> {
|
||||
const dir = join(tmpHome, 'projects', 'proj')
|
||||
await mkdir(dir, { recursive: true })
|
||||
await writeFile(join(dir, 'sess.jsonl'), JSON.stringify({
|
||||
type: 'assistant',
|
||||
sessionId: 'sess',
|
||||
timestamp: '2026-05-15T10:00:00Z',
|
||||
cwd: '/tmp/proj',
|
||||
message: {
|
||||
id: 'msg-1', type: 'message', role: 'assistant', model: 'claude-sonnet-4-5',
|
||||
content: [], usage: { input_tokens: 100, output_tokens: output },
|
||||
},
|
||||
}) + '\n')
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
clearSessionCache()
|
||||
tmpHome = await mkdtemp(join(tmpdir(), 'cb-hydlock-home-'))
|
||||
cacheDir = await mkdtemp(join(tmpdir(), 'cb-hydlock-cache-'))
|
||||
process.env['CLAUDE_CONFIG_DIR'] = tmpHome
|
||||
process.env['CODEBURN_CACHE_DIR'] = cacheDir
|
||||
process.env['CODEBURN_DESKTOP_SESSIONS_DIR'] = join(tmpHome, 'desktop-sessions')
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
clearSessionCache()
|
||||
await rm(tmpHome, { recursive: true, force: true })
|
||||
await rm(cacheDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('parseAllSessions hydration lock', () => {
|
||||
it('waits for a live foreign lock, then serves the warm cache instead of re-parsing', async () => {
|
||||
// Warm the cache once from a real on-disk session (output 50), capture the
|
||||
// exact cache structure, then tamper the cached output to a sentinel (999)
|
||||
// that could ONLY come from reading the cache — a fresh parse of the
|
||||
// unchanged source file would yield 50.
|
||||
await writeClaudeSession(50)
|
||||
expect(totalOutput(await parseAllSessions(undefined, 'claude'))).toBe(50)
|
||||
|
||||
const warm = JSON.parse(await readFile(sessionCachePath(), 'utf-8'))
|
||||
for (const section of Object.values(warm.providers) as Array<{ files: Record<string, { turns: Array<{ calls: Array<{ usage: { outputTokens: number } }> }> }> }>) {
|
||||
for (const file of Object.values(section.files)) {
|
||||
for (const turn of file.turns) for (const call of turn.calls) call.usage.outputTokens = 999
|
||||
}
|
||||
}
|
||||
const tampered = JSON.stringify(warm)
|
||||
|
||||
// Go cold: remove the versioned cache and drop the in-memory cache so the
|
||||
// next parse genuinely cold-starts and consults the lock.
|
||||
await unlink(sessionCachePath())
|
||||
clearSessionCache()
|
||||
|
||||
// A fresh lock held by another live process (pid 1 is always alive and is
|
||||
// not us). The cold parse must block on it.
|
||||
await writeFile(lockPath(), JSON.stringify({ pid: 1, at: Date.now() }))
|
||||
|
||||
let resolved = false
|
||||
const promise = parseAllSessions(undefined, 'claude').then(r => { resolved = true; return r })
|
||||
|
||||
await delay(50)
|
||||
// Still waiting on the foreign lock — it has not re-parsed and returned.
|
||||
expect(resolved).toBe(false)
|
||||
|
||||
// The "first process" finishes: it leaves the warm (tampered) cache behind
|
||||
// and releases the lock. The waiter wakes, reloads, and serves the cache.
|
||||
await writeFile(sessionCachePath(), tampered)
|
||||
await unlink(lockPath())
|
||||
|
||||
const result = await promise
|
||||
expect(resolved).toBe(true)
|
||||
expect(totalOutput(result)).toBe(999)
|
||||
// The waiter never held the lock, so nothing to clean up on its side.
|
||||
expect(existsSync(lockPath())).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores and replaces a stale lock, parsing normally and releasing in a finally', async () => {
|
||||
await writeClaudeSession(50)
|
||||
|
||||
// A stale lock (timestamp well past the freshness window) must be ignored,
|
||||
// replaced, and the parse proceeds normally.
|
||||
await mkdir(cacheDir, { recursive: true })
|
||||
await writeFile(lockPath(), JSON.stringify({ pid: 1, at: Date.now() - 20 * 60_000 }))
|
||||
|
||||
const result = await parseAllSessions(undefined, 'claude')
|
||||
expect(totalOutput(result)).toBe(50)
|
||||
// Lock released in the finally.
|
||||
expect(existsSync(lockPath())).toBe(false)
|
||||
// The parse warmed the versioned cache.
|
||||
expect(existsSync(sessionCachePath())).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores a fresh lock whose pid is dead', async () => {
|
||||
await writeClaudeSession(50)
|
||||
|
||||
// Fresh timestamp but a pid that does not exist (ESRCH): treated as dead,
|
||||
// ignored, replaced, and the parse proceeds normally.
|
||||
await mkdir(cacheDir, { recursive: true })
|
||||
await writeFile(lockPath(), JSON.stringify({ pid: 2_147_483_646, at: Date.now() }))
|
||||
|
||||
const result = await parseAllSessions(undefined, 'claude')
|
||||
expect(totalOutput(result)).toBe(50)
|
||||
expect(existsSync(lockPath())).toBe(false)
|
||||
})
|
||||
})
|
||||
|
|
@ -14,7 +14,7 @@ import { createRequire } from 'node:module'
|
|||
|
||||
import { isSqliteAvailable } from '../src/sqlite.js'
|
||||
import { clearSessionCache, parseAllSessions } from '../src/parser.js'
|
||||
import { loadCache, saveCache } from '../src/session-cache.js'
|
||||
import { loadCache, saveCache, sessionCachePath } from '../src/session-cache.js'
|
||||
import type { SessionSource, SessionParser, ParsedProviderCall } from '../src/providers/types.js'
|
||||
|
||||
// ── Synthetic provider state ───────────────────────────────────────────────
|
||||
|
|
@ -439,7 +439,7 @@ describe('(f) durable orphans survive a parse-version bump', () => {
|
|||
// Simulate the fingerprint a PREVIOUS release computed (any mismatching
|
||||
// value takes the same code path as a real parse-version bump).
|
||||
const { readFile, writeFile: writeFileFs } = await import('fs/promises')
|
||||
const cachePath = join(tmpCache, 'session-cache.json')
|
||||
const cachePath = sessionCachePath()
|
||||
const disk = JSON.parse(await readFile(cachePath, 'utf-8')) as { providers: Record<string, { envFingerprint: string }> }
|
||||
expect(disk.providers['copilot']).toBeDefined()
|
||||
disk.providers['copilot']!.envFingerprint = '0000000000000000'
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { tmpdir } from 'os'
|
|||
import { join } from 'path'
|
||||
|
||||
import { clearSessionCache, parseAllSessions } from '../../src/parser.js'
|
||||
import { sessionCachePath } from '../../src/session-cache.js'
|
||||
import { MAX_SESSION_FILE_BYTES } from '../../src/fs-utils.js'
|
||||
import { codewhale, createCodeWhaleProvider } from '../../src/providers/codewhale.js'
|
||||
import type { ParsedProviderCall } from '../../src/providers/types.js'
|
||||
|
|
@ -274,7 +275,7 @@ describe('codewhale provider', () => {
|
|||
expect(first[0]!.totalCostUSD).toBeCloseTo(0.75)
|
||||
expect(second[0]!.totalCostUSD).toBeCloseTo(0.75)
|
||||
|
||||
const cache = JSON.parse(await readFile(join(cacheDir, 'session-cache.json'), 'utf-8')) as {
|
||||
const cache = JSON.parse(await readFile(sessionCachePath(), 'utf-8')) as {
|
||||
providers: { codewhale: { envFingerprint: string } }
|
||||
}
|
||||
expect(cache.providers.codewhale.envFingerprint).toMatch(/^[a-f0-9]{16}$/)
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
|||
import { readFile, rm, writeFile, mkdir } from 'fs/promises'
|
||||
import { existsSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { basename, join } from 'path'
|
||||
|
||||
import {
|
||||
CACHE_VERSION,
|
||||
|
|
@ -19,8 +19,12 @@ import {
|
|||
mergeCallByDedupKey,
|
||||
reconcileFile,
|
||||
saveCache,
|
||||
sessionCachePath,
|
||||
} from '../src/session-cache.js'
|
||||
|
||||
// Version-suffixed filename (e.g. session-cache.v5.json) the cache now writes to.
|
||||
const CACHE_FILE = () => basename(sessionCachePath())
|
||||
|
||||
const TMP_DIR = join(tmpdir(), `codeburn-scache-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`)
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
@ -179,11 +183,73 @@ describe('loadCache / saveCache', () => {
|
|||
|
||||
it('atomic write does not leave partial file on error', async () => {
|
||||
await saveCache(emptyCache())
|
||||
const raw = await readFile(join(TMP_DIR, 'session-cache.json'), 'utf-8')
|
||||
const raw = await readFile(sessionCachePath(), 'utf-8')
|
||||
expect(JSON.parse(raw)).toEqual(emptyCache())
|
||||
})
|
||||
})
|
||||
|
||||
// ── versioned filename + legacy adoption ───────────────────────────────
|
||||
|
||||
describe('versioned cache file + legacy adoption', () => {
|
||||
function validCache(): SessionCache {
|
||||
return {
|
||||
version: CACHE_VERSION,
|
||||
providers: { claude: { envFingerprint: 'abc123', files: { '/path/to/session.jsonl': makeCachedFile() } } },
|
||||
}
|
||||
}
|
||||
|
||||
it('writes and reads the version-suffixed file, never the legacy name', async () => {
|
||||
expect(basename(sessionCachePath())).toBe(`session-cache.v${CACHE_VERSION}.json`)
|
||||
await saveCache(validCache())
|
||||
expect(existsSync(sessionCachePath())).toBe(true)
|
||||
expect(existsSync(join(TMP_DIR, 'session-cache.json'))).toBe(false)
|
||||
expect(await loadCache()).toEqual(validCache())
|
||||
})
|
||||
|
||||
it('adopts a matching-version legacy file once, without deleting or rewriting it', async () => {
|
||||
await mkdir(TMP_DIR, { recursive: true })
|
||||
const legacy = join(TMP_DIR, 'session-cache.json')
|
||||
await writeFile(legacy, JSON.stringify(validCache()))
|
||||
|
||||
// Versioned file absent → adopt-copy from legacy on first load.
|
||||
expect(await loadCache()).toEqual(validCache())
|
||||
expect(existsSync(sessionCachePath())).toBe(true)
|
||||
// Legacy left intact (not deleted, not rewritten).
|
||||
expect(existsSync(legacy)).toBe(true)
|
||||
expect(JSON.parse(await readFile(legacy, 'utf-8'))).toEqual(validCache())
|
||||
|
||||
// Adoption is one-time: a later legacy edit is ignored once the versioned
|
||||
// file exists.
|
||||
const mutated: SessionCache = { version: CACHE_VERSION, providers: { codex: { envFingerprint: 'zzz', files: {} } } }
|
||||
await writeFile(legacy, JSON.stringify(mutated))
|
||||
expect(await loadCache()).toEqual(validCache())
|
||||
})
|
||||
|
||||
it('ignores a different-version legacy file and never touches it', async () => {
|
||||
await mkdir(TMP_DIR, { recursive: true })
|
||||
const legacy = join(TMP_DIR, 'session-cache.json')
|
||||
const stale = { version: 999, providers: { claude: { envFingerprint: 'x', files: {} } } }
|
||||
await writeFile(legacy, JSON.stringify(stale))
|
||||
|
||||
expect((await loadCache()).providers).toEqual({})
|
||||
// No versioned file adopted; legacy left byte-intact.
|
||||
expect(existsSync(sessionCachePath())).toBe(false)
|
||||
expect(JSON.parse(await readFile(legacy, 'utf-8'))).toEqual(stale)
|
||||
})
|
||||
|
||||
it('saveCache never creates or overwrites a pre-existing legacy file', async () => {
|
||||
await mkdir(TMP_DIR, { recursive: true })
|
||||
const legacy = join(TMP_DIR, 'session-cache.json')
|
||||
const legacyContent = JSON.stringify({ version: CACHE_VERSION, providers: {} })
|
||||
await writeFile(legacy, legacyContent)
|
||||
|
||||
await saveCache(validCache())
|
||||
// The versioned file holds the new data; the legacy file is byte-untouched.
|
||||
expect(await readFile(legacy, 'utf-8')).toBe(legacyContent)
|
||||
expect(JSON.parse(await readFile(sessionCachePath(), 'utf-8'))).toEqual(validCache())
|
||||
})
|
||||
})
|
||||
|
||||
// ── computeEnvFingerprint ──────────────────────────────────────────────
|
||||
|
||||
describe('computeEnvFingerprint', () => {
|
||||
|
|
@ -571,7 +637,7 @@ describe('cleanupOrphanedTempFiles', () => {
|
|||
it('removes .tmp files older than 5 minutes', async () => {
|
||||
await mkdir(TMP_DIR, { recursive: true })
|
||||
|
||||
const oldTmp = join(TMP_DIR, 'session-cache.json.abc123.tmp')
|
||||
const oldTmp = join(TMP_DIR, `${CACHE_FILE()}.abc123.tmp`)
|
||||
await writeFile(oldTmp, 'stale')
|
||||
const { utimes } = await import('fs/promises')
|
||||
const oldTime = new Date(Date.now() - 10 * 60 * 1000)
|
||||
|
|
@ -584,7 +650,7 @@ describe('cleanupOrphanedTempFiles', () => {
|
|||
it('preserves recent .tmp files', async () => {
|
||||
await mkdir(TMP_DIR, { recursive: true })
|
||||
|
||||
const recentTmp = join(TMP_DIR, 'session-cache.json.def456.tmp')
|
||||
const recentTmp = join(TMP_DIR, `${CACHE_FILE()}.def456.tmp`)
|
||||
await writeFile(recentTmp, 'recent')
|
||||
|
||||
await cleanupOrphanedTempFiles()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue