diff --git a/src/cursor-sync.ts b/src/cursor-sync.ts index 65261cc7..6f8f2abd 100644 --- a/src/cursor-sync.ts +++ b/src/cursor-sync.ts @@ -143,6 +143,16 @@ async function invalidate(ranges: CoverageRange[]): Promise { class Skip extends Error {} +type ImportRunner = (apply: () => Promise) => Promise +let deferredImportRunner: ImportRunner | null = null + +/// Where a `deferImport` sync applies its download: a one-shot run once its +/// command is done, serve between two requests, so no parse sees the store +/// change under it. Without a runner the download applies at once. +export function setCursorImportRunner(runner: ImportRunner | null): void { + deferredImportRunner = runner +} + /// Silent unless `force`: a skipped or failed sync returns null and keeps the /// stored usage, and `force` (`codeburn import cursor --sync`) turns every skip /// and failure into an error and ignores the throttle, backoff and off switch. @@ -153,7 +163,7 @@ class Skip extends Error {} /// downloaded once. A `provider` filter that leaves out every Cursor provider /// skips the sync. Earlier accounts' synced usage stays, and a new account's window /// starts after their coverage so no stretch of local usage is replaced twice. -export async function maybeSyncCursor(opts: { force?: boolean; now?: number; fetchImpl?: typeof fetch; provider?: string } = {}): Promise { +export async function maybeSyncCursor(opts: { force?: boolean; now?: number; fetchImpl?: typeof fetch; provider?: string; deferImport?: boolean } = {}): Promise { if (opts.provider !== undefined && opts.provider !== 'all' && !replacedProviders().includes(opts.provider)) return null const force = opts.force === true const now = opts.now ?? Date.now() @@ -214,8 +224,13 @@ export async function maybeSyncCursor(opts: { force?: boolean; now?: number; fet throw new Skip(lastError) } if (!res.ok) throw new Error(`Cursor returned HTTP ${res.status} for the usage export`) - const summary = await importCursorCsvText(await res.text(), now, { from, to: now, source: 'sync', account }) - if (summary?.changed) await invalidate([{ start: new Date(from).toISOString(), end: new Date(now).toISOString() }]) + const text = await res.text() + const apply = async () => { + const imported = await importCursorCsvText(text, now, { from, to: now, source: 'sync', account }) + if (imported?.changed) await invalidate([{ start: new Date(from).toISOString(), end: new Date(now).toISOString() }]) + return imported + } + const summary = opts.deferImport && deferredImportRunner ? await deferredImportRunner(apply) : await apply() const newest = Math.max(state.through?.[account] ?? -Infinity, summary ? Date.parse(summary.lastEvent) : localDayStart(now)) await writeState({ ...attempt, lastSuccessAt: now, through: { ...state.through, [account]: newest } }) return summary diff --git a/src/main.ts b/src/main.ts index 348c1781..31f22865 100644 --- a/src/main.ts +++ b/src/main.ts @@ -526,14 +526,24 @@ async function runJsonReport(period: Period, provider: string, project: string[] // which promise to stay offline. The keepalive beats through the download for // the app watchdogs; it is reference-counted, so the stop never silences a // beat serve armed around the whole request. -async function syncCursor(provider: string): Promise { - const { maybeSyncCursor } = await import('./cursor-sync.js') - startProgressKeepalive() - try { - await maybeSyncCursor({ provider }) - } finally { - stopProgressKeepalive() - } +// +// A JSON or menubar answer never waits on cursor.com: `background` leaves the +// download running beside the command, and its import shows from the next run +// on. Dashboards still wait, since they render once and stay open. One sync at +// a time keeps a serve burst to one download. +let cursorSync: Promise | null = null +async function syncCursor(provider: string, background = false): Promise { + cursorSync ??= (async () => { + const { maybeSyncCursor } = await import('./cursor-sync.js') + startProgressKeepalive() + try { + await maybeSyncCursor({ provider, deferImport: background }) + } finally { + stopProgressKeepalive() + cursorSync = null + } + })() + if (!background) await cursorSync } const program = new Command() @@ -891,7 +901,7 @@ program } const period = toPeriod(opts.period) - await syncCursor(opts.provider) + await syncCursor(opts.provider, opts.format === 'json') if (opts.format === 'json') { await loadPricing() if (daySelection || customRange) { @@ -1066,7 +1076,7 @@ program .option('--no-color', 'Disable ANSI colors') .action(async (opts) => { assertProvider(opts.provider, 'overview') - await syncCursor(opts.provider) + await syncCursor(opts.provider, true) await loadPricing() let customRange: DateRange | null = null try { @@ -1233,7 +1243,7 @@ program const pf = opts.provider const fp = (p: ProjectSummary[]) => filterProjectsByName(p, opts.project, opts.exclude) if (opts.format === 'menubar-json') { - await syncCursor(pf) + await syncCursor(pf, true) const daysSelection = parseDaysFlag(opts.days) const customRange = daysSelection ? null : parseDateRangeFlags(opts.from, opts.to) const daySelection = parseDayFlag(opts.day) @@ -1477,7 +1487,7 @@ program .action(async (opts) => { assertFormat(opts.format, ['tui', 'json'], 'today') assertProvider(opts.provider, 'today') - await syncCursor(opts.provider) + await syncCursor(opts.provider, opts.format === 'json') if (opts.format === 'json') { await runJsonReport('today', opts.provider, opts.project, opts.exclude) return @@ -1496,7 +1506,7 @@ program .action(async (opts) => { assertFormat(opts.format, ['tui', 'json'], 'month') assertProvider(opts.provider, 'month') - await syncCursor(opts.provider) + await syncCursor(opts.provider, opts.format === 'json') if (opts.format === 'json') { await runJsonReport('month', opts.provider, opts.project, opts.exclude) return @@ -3362,5 +3372,12 @@ if (process.argv[2] === 'serve') { startProgressKeepalive() const program = buildProgram() await registerLoadedPluginCommands(program) + // A background Cursor sync applies its download once the command is done, + // never under the command's own parse. + let commandDone = () => {} + const done = new Promise(resolve => { commandDone = resolve }) + program.hook('postAction', () => commandDone()) + const { setCursorImportRunner } = await import('./cursor-sync.js') + setCursorImportRunner(apply => done.then(apply)) program.parse() } diff --git a/src/serve.ts b/src/serve.ts index 6a09ba1e..ded04b74 100644 --- a/src/serve.ts +++ b/src/serve.ts @@ -734,6 +734,22 @@ export async function runStdioServe(buildProgram: () => Command): Promise // Strict serialization: each request chains on the previous one. let queue: Promise = Promise.resolve() + // A Cursor sync a request left running applies its download between two + // requests, and nothing derived before it is served again. The import store + // sits under no watched root, so the watchers would not notice it. + const { setCursorImportRunner } = await import('./cursor-sync.js') + const { clearSessionCache } = await import('./parser.js') + setCursorImportRunner(apply => { + const applied = queue.then(async () => { + const result = await apply() + outputMemo.clear() + clearSessionCache() + return result + }) + queue = applied.then(() => undefined, () => undefined) + return applied + }) + // Progressive cold start (#1110). Ids of requests received but not yet // answered, so work that holds the queue can heartbeat them. const awaiting = new Set() diff --git a/tests/cursor-sync-background.test.ts b/tests/cursor-sync-background.test.ts new file mode 100644 index 00000000..3b195c38 --- /dev/null +++ b/tests/cursor-sync-background.test.ts @@ -0,0 +1,168 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { spawn, type ChildProcess } from 'child_process' +import { existsSync, mkdirSync } from 'fs' +import { mkdtemp, rm, writeFile } from 'fs/promises' +import { createRequire } from 'module' +import { tmpdir } from 'os' +import { dirname, join } from 'path' +import { pathToFileURL } from 'url' + +import { CURSOR_CSV_HEADER, cursorImportPath } from '../src/cursor-import.js' +import { maybeSyncCursor, setCursorImportRunner } from '../src/cursor-sync.js' +import { cursorDatabasePath } from '../src/quota/cursor.js' +import { isSqliteAvailable } from '../src/sqlite.js' + +// The CLI runs that hold a fake cursor.com download open until the test lets go. +vi.setConfig({ testTimeout: 60_000 }) + +const requireForTest = createRequire(import.meta.url) +const CLI = join(__dirname, '..', 'src', 'cli.ts') + +function jwt(): string { + const encode = (value: unknown) => Buffer.from(JSON.stringify(value), 'utf8').toString('base64url') + return `${encode({ alg: 'HS256' })}.${encode({ sub: 'auth0|background_sync', exp: Math.floor(Date.now() / 1000) + 86_400 })}.signature` +} + +function writeToken(home: string): void { + const path = cursorDatabasePath(process.platform, home) + mkdirSync(dirname(path), { recursive: true }) + const { DatabaseSync } = requireForTest('node:sqlite') as { DatabaseSync: new (file: string) => any } + const db = new DatabaseSync(path) + db.exec('CREATE TABLE IF NOT EXISTS ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)') + db.prepare('INSERT INTO ItemTable (key, value) VALUES (?, ?)').run('cursorAuth/accessToken', jwt()) + db.close() +} + +function csv(): string { + const row = [new Date(Date.now() - 2 * 3_600_000).toISOString(), '', '', 'Included', 'auto', 'No', 0, 1234, 0, 0, 1234, 'Included'] + return [CURSOR_CSV_HEADER.join(','), row.map(v => `"${v}"`).join(',')].join('\n') + '\n' +} + +// A cursor.com that answers only once `release` exists, so a run that waits +// on it cannot print anything before the test lets go. +const FAKE_FETCH = ` +import { existsSync, readFileSync } from 'node:fs' +const realFetch = globalThis.fetch +globalThis.fetch = async (url, init) => { + if (!String(url).startsWith('https://cursor.com/')) return realFetch(url, init) + while (!existsSync(process.env.FAKE_CURSOR_RELEASE)) await new Promise(r => setTimeout(r, 25)) + return new Response(readFileSync(process.env.FAKE_CURSOR_CSV, 'utf8'), { status: 200 }) +} +` + +const until = async (check: () => boolean, label: string): Promise => { + const deadline = Date.now() + 30_000 + while (!check()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${label}`) + await new Promise(r => setTimeout(r, 25)) + } +} + +let root: string +let release: string +let env: NodeJS.ProcessEnv + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'cursor-sync-bg-')) + const home = join(root, 'home') + writeToken(home) + // One provider root for serve to watch; without an armed root it memoizes nothing. + mkdirSync(join(home, '.claude', 'projects'), { recursive: true }) + release = join(root, 'release') + await writeFile(join(root, 'fake-fetch.mjs'), FAKE_FETCH) + await writeFile(join(root, 'usage.csv'), csv()) + env = { + ...process.env, + HOME: home, + USERPROFILE: home, + CODEBURN_CACHE_DIR: join(root, 'cache'), + FAKE_CURSOR_RELEASE: release, + FAKE_CURSOR_CSV: join(root, 'usage.csv'), + } + delete env['CODEBURN_CURSOR_SYNC'] + // The in-process sync reads this too; a shell that disables sync must not hang the test. + vi.stubEnv('CODEBURN_CURSOR_SYNC', '') + process.env['CODEBURN_CACHE_DIR'] = join(root, 'cache') +}) + +afterEach(async () => { + vi.unstubAllEnvs() + setCursorImportRunner(null) + await rm(root, { recursive: true, force: true }) +}) + +function start(args: string[]): { child: ChildProcess; stdout: () => string; exited: Promise } { + const child = spawn(process.execPath, ['--import', 'tsx', '--import', pathToFileURL(join(root, 'fake-fetch.mjs')).href, CLI, ...args], { env, stdio: ['pipe', 'pipe', 'ignore'] }) + let out = '' + child.stdout!.on('data', (chunk: Buffer) => { out += chunk.toString() }) + return { child, stdout: () => out, exited: new Promise(resolve => child.on('exit', resolve)) } +} + +const cursorCalls = (report: string): number => { + const parsed = JSON.parse(report) as { overview: { calls: number } } + return parsed.overview.calls +} + +describe.skipIf(!isSqliteAvailable())('background Cursor sync', () => { + it('a deferred import waits for the runner, then lands', async () => { + let applyLater: (() => void) | undefined + setCursorImportRunner(apply => new Promise((resolve, reject) => { applyLater = () => { apply().then(resolve, reject) } })) + vi.stubEnv('HOME', env['HOME']!) + vi.stubEnv('USERPROFILE', env['HOME']!) + const fetchImpl = async () => new Response(csv(), { status: 200 }) + const sync = maybeSyncCursor({ fetchImpl, deferImport: true }) + await until(() => applyLater !== undefined, 'the runner') + expect(existsSync(cursorImportPath())).toBe(false) + applyLater!() + expect((await sync)?.changed).toBe(true) + expect(existsSync(cursorImportPath())).toBe(true) + }) + + it('a one-shot JSON report answers before cursor.com does, and the next run shows the import', async () => { + const args = ['report', '--format', 'json', '--provider', 'cursor', '--period', 'today'] + const first = start(args) + await until(() => first.stdout().trim().endsWith('}'), 'the first answer') + expect(cursorCalls(first.stdout())).toBe(0) + expect(existsSync(cursorImportPath())).toBe(false) + + await writeFile(release, '') + expect(await first.exited).toBe(0) + expect(existsSync(cursorImportPath())).toBe(true) + + const second = start(args) + expect(await second.exited).toBe(0) + expect(cursorCalls(second.stdout())).toBe(1) + }) + + it('serve applies the import between requests and stops serving the answer it memoized', async () => { + const serve = start(['serve', '--stdio']) + let lines: string[] = [] + serve.child.stdout!.on('data', () => { lines = serve.stdout().split('\n').filter(Boolean) }) + const answer = async (id: number, args: string[]): Promise<{ output: string; generation: { n: number } }> => { + serve.child.stdin!.write(JSON.stringify({ id, args }) + '\n') + let found: { id?: number; ok?: boolean; output?: string; generation?: { n: number } } | undefined + await until(() => (found = lines.map(l => JSON.parse(l)).find(m => m.id === id && m.ok !== undefined)) !== undefined, `answer ${id}`) + expect(found!.ok).toBe(true) + return found as { output: string; generation: { n: number } } + } + const args = ['report', '--format', 'json', '--provider', 'cursor', '--period', 'today'] + try { + await until(() => lines.some(l => l.includes('"ready"')), 'serve ready') + expect(cursorCalls((await answer(1, args)).output)).toBe(0) + // Asked again before the download lands: once the watchers are armed, which + // can be after the first few answers on a slow machine, the memo answers. + let id = 2 + let memoized = await answer(id++, args) + for (let next = await answer(id++, args); next.generation.n !== memoized.generation.n; next = await answer(id++, args)) memoized = next + + await writeFile(release, '') + await until(() => existsSync(cursorImportPath()), 'the import') + const after = await answer(id, args) + expect(after.generation.n).toBeGreaterThan(memoized.generation.n) + expect(cursorCalls(after.output)).toBe(1) + } finally { + serve.child.stdin!.end() + await serve.exited + } + }) +})