diff --git a/src/cursor-import.ts b/src/cursor-import.ts index 71217466..368e4956 100644 --- a/src/cursor-import.ts +++ b/src/cursor-import.ts @@ -128,26 +128,36 @@ export function parseCursorUsageCsv(text: string): CursorUsageEvent[] { } /// `2026-08-27`, an ISO instant, or epoch milliseconds (what the dashboard's -/// export URL carries). A bare date is a whole UTC day: its start for `from`, -/// its last millisecond for `to`. +/// export URL carries). A bare date is a whole local day, the same day reports +/// bucket by: its start for `from`, its last millisecond for `to`. export function parseBoundary(value: string, edge: 'from' | 'to'): number { const v = value.trim() let ms: number if (/^\d{9,}$/.test(v)) ms = Number(v) - else if (/^\d{4}-\d{2}-\d{2}$/.test(v)) ms = Date.parse(`${v}T00:00:00.000Z`) + (edge === 'to' ? 86_400_000 - 1 : 0) + else if (/^\d{4}-\d{2}-\d{2}$/.test(v)) { + const [y, m, d] = v.split('-').map(Number) as [number, number, number] + ms = edge === 'to' ? new Date(y, m - 1, d + 1).getTime() - 1 : new Date(y, m - 1, d).getTime() + } else ms = Date.parse(v) if (Number.isNaN(ms)) throw new Error(`--${edge} must be a date (2026-08-27), an ISO timestamp or epoch milliseconds, got "${value}"`) return ms } -function utcDayStart(ms: number): number { - return Math.floor(ms / 86_400_000) * 86_400_000 +function localDayStart(ms: number): number { + const d = new Date(ms) + return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime() +} + +function localDayEnd(ms: number): number { + const d = new Date(ms) + return new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1).getTime() - 1 } /// The span one export covers. The export records no range of its own, so it -/// is the `--from`/`--to` the user exported with, else the UTC days of its -/// first and last event. The end never passes the moment the file was saved: -/// usage after the export is not in it and keeps its local estimate. +/// is the `--from`/`--to` the user exported with, else the local days of its +/// first and last event, so no report day is split between imported and local +/// usage. The end never passes the moment the file was saved: usage after the +/// export is not in it and keeps its local estimate. function exportCoverage( events: CursorUsageEvent[], fileSavedMs: number, @@ -157,8 +167,8 @@ function exportCoverage( const times = events.map(e => Date.parse(e.date)) const first = Math.min(...times) const last = Math.max(...times) - const start = from ?? utcDayStart(first) - const declaredEnd = to ?? utcDayStart(last) + 86_400_000 - 1 + const start = from ?? localDayStart(first) + const declaredEnd = to ?? localDayEnd(last) if (start > declaredEnd) throw new Error('--from is after --to') if (first < start || last > declaredEnd) { throw new Error(`the export holds events from ${new Date(first).toISOString()} to ${new Date(last).toISOString()}, outside ${new Date(start).toISOString()} .. ${new Date(declaredEnd).toISOString()}`) diff --git a/src/main.ts b/src/main.ts index 004641c2..d8bbb12b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1628,8 +1628,8 @@ program program .command('import [file]') .description('Replace local estimates with usage a tool exported itself. Supported: cursor (Export CSV at cursor.com/dashboard/usage)') - .option('--from ', 'Start of the exported range (date, ISO time or epoch ms). Default: the first event\'s UTC day') - .option('--to ', 'End of the exported range (date, ISO time or epoch ms). Default: the last event\'s UTC day') + .option('--from ', 'Start of the exported range (date, ISO time or epoch ms). Default: the first event\'s local day') + .option('--to ', 'End of the exported range (date, ISO time or epoch ms). Default: the last event\'s local day') .option('--remove', 'Delete the imported usage and go back to local estimates') .action(async (tool: string, file: string | undefined, opts: { from?: string; to?: string; remove?: boolean }) => { if (tool !== 'cursor') { diff --git a/src/providers/cursor-agent.ts b/src/providers/cursor-agent.ts index 634c534e..7f153342 100644 --- a/src/providers/cursor-agent.ts +++ b/src/providers/cursor-agent.ts @@ -818,6 +818,7 @@ function createParser( reasoningTokens, webSearchRequests: 0, costUSD, + costIsEstimated: true, tools: turn.assistant.tools, bashCommands: [], timestamp, diff --git a/src/session-cache.ts b/src/session-cache.ts index 65f9d00e..d2f067a6 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -423,7 +423,7 @@ export const PROVIDER_PARSE_VERSIONS: Record = { // once per user message instead of once per assistant message. // store-db-v1 (#986): sessions with no exported transcript are read from // ~/.cursor/chats/*/*/store.db. - 'cursor-agent': 'workspaceless-transcript-v1-full-turn-accounting-v2-store-db-v1', + 'cursor-agent': 'workspaceless-transcript-v1-full-turn-accounting-v2-store-db-v1-est-cost', // source-provenance-v1 (#944): CLI sessions were misread as VS Code // transcripts (both carry producer 'copilot-agent'), skipping the shutdown // input/cache rollup; this bump re-parses them so the missing tokens land. diff --git a/tests/cursor-import.test.ts b/tests/cursor-import.test.ts index 63cd1327..4d86640c 100644 --- a/tests/cursor-import.test.ts +++ b/tests/cursor-import.test.ts @@ -212,6 +212,43 @@ describe('Cursor import through the report pipeline', () => { }) }) +describe('Cursor import coverage in a non-UTC zone', () => { + it.each(['America/Los_Angeles', 'Asia/Kolkata'])('%s: a local day is wholly imported and its neighbours keep their estimates', async (tz) => { + process.env.TZ = tz + const b = new Date(base) + const at = (dayOffset: number, hour: number, minute = 0) => + new Date(b.getUTCFullYear(), b.getUTCMonth(), b.getUTCDate() + dayOffset, hour, minute).getTime() + const day = toDateString(new Date(at(0, 12))) + + await writeAgentTranscript('prev-evening', at(-1, 20)) + await writeAgentTranscript('same-day', at(0, 12)) + await writeAgentTranscript('next-night', at(1, 1)) + const path = await writeCsv([ + { date: new Date(at(0, 0, 30)).toISOString(), model: 'auto', input: 100 }, + { date: new Date(at(0, 23, 30)).toISOString(), model: 'auto', input: 200 }, + ], 'tz.csv') + + const s = await importCursorCsv(path) + expect([toDateString(new Date(s.coverage.start)), toDateString(new Date(s.coverage.end))]).toEqual([day, day]) + + clearSessionCache() + const perDay: Record> = {} + for (const p of await parseAllSessions(whole, 'all')) for (const ses of p.sessions) for (const t of ses.turns) for (const c of t.assistantCalls) { + const d = perDay[toDateString(new Date(c.timestamp))] ??= {} + d[c.provider] = (d[c.provider] ?? 0) + 1 + } + expect(perDay).toEqual({ + [toDateString(new Date(at(-1, 20)))]: { 'cursor-agent': 1 }, + [day]: { cursor: 2 }, + [toDateString(new Date(at(1, 1)))]: { 'cursor-agent': 1 }, + }) + + // The same day passed as --from/--to is the span inferred above. + const explicit = await importCursorCsv(path, { from: parseBoundary(day, 'from'), to: parseBoundary(day, 'to') }) + expect(explicit).toMatchObject({ changed: false, coverage: { start: new Date(at(0, 0)).toISOString(), end: new Date(at(1, 0) - 1).toISOString() } }) + }) +}) + describe('invalidateProviderDays', () => { it('drops only the named providers on the named days and pulls the watermark back', async () => { const day = (date: string): DailyEntry => ({ diff --git a/tests/providers/cursor-agent.test.ts b/tests/providers/cursor-agent.test.ts index 09eca805..3e1a2bb4 100644 --- a/tests/providers/cursor-agent.test.ts +++ b/tests/providers/cursor-agent.test.ts @@ -185,6 +185,7 @@ describe('cursor-agent provider', () => { expect(calls[0]!.outputTokens).toBe(estimateTokensFromChars(assistantText.length)) expect(calls[0]!.reasoningTokens).toBe(0) expect(calls[0]!.deduplicationKey).toBe(`cursor-agent:${FIXED_UUID}:0`) + expect(calls[0]!.costIsEstimated).toBe(true) }) it('parses without sqlite db and defaults model', async () => {