Repository navigation
Add period-vs-period comparison (Compare periods) with contribution drill-down - #1323
Merged
Merged
Conversation
…f engine Add src/period-diff.ts: pure period-vs-period difference engine. Totals come from the shared buildPeriodData rules; contributions per project and per model carry status new/gone/up/down/flat with pct=null at A=0 (labeled New, never an infinite percentage); normalized views per day and per 100 calls print their denominators; day arithmetic walks local midnights so DST and month boundaries count calendar days. historyBasis cross-checks the durable daily cache and reports aggregate-only carried days separately instead of force-reconciling them into the totals. diffSessions joins the drill-down on the canonical session identity (provider + project path + sessionId), attributing the model's own slice for the model lens. New command: compare-periods --format json|sessions with explicit --from-a/--to-a/--from-b/--to-b (local YYYY-MM-DD, validated loudly) defaulting to the last seven complete days vs the seven before, plus --provider and the existing --project/--exclude filtering. Range slicing reuses parseAllSessions' call-granularity behavior, so a session straddling the boundary contributes to each side by its own calls. Tests: engine fixtures including the X/Y/Z acceptance reconciliation, A=0/B=0, unequal lengths, DST and month walks, carried history, a real-parse boundary session split by call and joined back into one drill-down row, and CLI runs on a temp HOME fixture.
Two bridge channels follow the existing envelope + argv-validation pattern: codeburn:getPeriodCompare spawns compare-periods --format json with two REQUIRED local YYYY-MM-DD range pairs (validated per range), and codeburn:getPeriodCompareSessions spawns the sessions drill-down for one project/model contribution key. Contribution keys ride the --key VALUE position, so a dash-leading slug (Claude sanitizes /work/pricing to -work-pricing) passes vContributionKey where vToken would wrongly reject it. Preload and the renderer CodeburnBridge types mirror the two calls.
New sidebar section 'periods' (Compare periods, shortcut 9) rendering sections/PeriodCompare.tsx: preset last-7-complete-days vs prior 7 or two custom calendars with a swap control; range meta shows both spans, the duration delta and any overlap; totals, normalized per-day and per-100-calls tables (denominators printed, zero denominators render as em dash); project and model contribution lenses with New/Gone badges and click-to-inspect session drill-down joined across A and B; coverage block for unpriced models and aggregate-only carried history. A/B selection, lens and view persist in localStorage so returning to the screen keeps the selection. Navigation adapter until the goal-8 navigation lands: onInspectRange opens the existing Sessions section scoped to the requested range via the app's custom-range state; the Overview entry card links here. Renderer styling follows the existing panel/table conventions. Includes component tests (fixture report, New/Gone labels, per-100-calls recomputation with zero-call sides, persistence across remounts, lens switching) and user documentation at docs/compare-periods.md.
…rrors Rebase fixes on top of #1296. - App.tsx shipped a stub inspectRange calling a setCustomRange that no longer exists after #1316. Replaced with the real navigation: commitNav to Sessions with the clicked side's range AND projectFilters/modelFilters for the contribution key, so the drill-through lands on the population the row describes instead of the whole range. - getPeriodCompare and getPeriodCompareSessions carried no projectArgs(), so a saved project filter did not scope either fetch (#1307). Added, and the "scopes every fetch" main-process test now covers both channels. - compare-periods --format sessions ignored --project/--exclude, so a drill-down could surface a session from a hidden project. It now filters like the report. - A bad --from-a/--to-a printed a raw stack trace: parseDateRangeFlags throws and the null check could never fire. Wrapped in the same try/catch every other date-flag command uses. - Totals card now says inline how much daily history has no session detail behind it. On a machine with aged-off sources the detail-only total is far below report/status for the same range; the Coverage card alone was three cards away from the number it qualifies.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Supersedes #1296. All feature work by @ozymandiashh; rebased onto main (post #1316 drill-through, #1307 project scope, #1319 spend-by-branch) with review fixes in one follow-up commit.
Rebase conflicts
app/renderer/styles/plain.css— both sides appended a block at EOF. Kept both.app/renderer/sections/Overview.tsx— Add drill-through: from aggregates to the sessions that compose them #1316 addedonInvestigate, PR widenedonNavigateto'periods'. Kept both.app/electron/main.test.ts— Add Spend by branch & worktree lens (project x branch attribution) #1319 claimedcalls[2]in the project-filter test. Kept it, renumbered the new assertions tocalls[3]/calls[4].Review fixes
inspectRangeadapter callingsetCustomRange, which no longer exists after Add drill-through: from aggregates to the sessions that compose them #1316 — it did not compile on current main. Replaced with the real drill-through:commitNavto Sessions with the clicked side's range andprojectFilters/modelFiltersfor the contribution key, so the destination is the population the row describes, not the whole range.projectArgs()on both new IPC channels (feat(app): Projects pane that scopes the desktop app to chosen projects #1307). A saved project filter scoped neithergetPeriodComparenorgetPeriodCompareSessions. The "scopes every fetch" main-process test now covers both.compare-periods --format sessionsskippedfilterProjectsByName, so a hidden project could surface behind a contribution. Fixed, with a test.parseDateRangeFlagsthrows; the PR'sif (!a || !b)guard could never fire. Wrapped in the same try/catch every other date-flag command uses.report/statusfor the same range; the Coverage card was three cards below the number it qualifies.Proof on real data (frozen ranges, A 2026-06-01..06-30 vs B 2026-07-01..07-30)
Totals reconcile exactly —
B − A − diff == 0for every component:Lens sums vs totals (float noise only):
Basis:
compare-periodstotals equalmodels --format jsonfor the same range to 2e-12 (A exact, B -2.27e-12) — the transcript basissessions/models/spenduse. They do not equalreport/status, which read the durable daily history. The gap is reported exactly:history.historyCostA 1214.1750341 / B 5636.89843685 matchesreport --format jsonoverview cost to the digit on both sides, andaggregateOnlyA $1049.52 (10 days) / B $4398.49 (19 days) is excluded from totals and lenses, as the basis line says.Normalized: cost/day uses each side's own calendar days (A 30, B 30 — printed in
denominators), cost/100 calls each side's own calls (A 766, B 13,070). Both recompute by hand to the last digit; a zero denominator yieldsnull, rendered—.Unpriced models are disclosed, never folded: on a 30-day pair with unpriced usage, coverage listed
big-pickle(231 calls),cursor-grok-4.6-high(749),x-preview-f-free(107),Qwen3.8-Flash-Next-FP8(1) atpricingCoverageA0.9856, and none of them appear as a zero-cost lens row.Drill-down reconciles with its lens row:
/Users/torukmakto/Projects/eywaB sum 366.53678760000037 vs lens 366.53678760000037 (delta 0.0);Opus 51.6350025 vs 1.6350025. Project keys arespendProjectIdentityids — all 299 keys with B cost matched asessions --format json --contributionsprojectIdexactly, so the rewired drill-through lands correctly.Contract
report,sessions,models,spend --format flow-jsonbyte-identical on a frozen range between main and this branch.status --format menubar-jsonandcompare --format jsondiffer only ingenerated/liveSessions/history, and differ identically between two runs of main — live-data drift, not this branch.serve --stdiodoes not allowlistcompare-periods(src/serve.ts:81SERVE_OPTIONS). Per the module's own contract a rejected command falls back to a normal spawn, so this is correct but cold: each desktop fetch is a full CLI start. Left for a follow-up, since the command hydrates the daily cache by default and the allowlist is a reviewed read-only surface.sanitizeForSharing(src/sharing/sanitize.ts:9) only takesMenubarPayload; MCP registersget_usageandget_savingsonly (src/mcp/server.ts:47,95), both from redacted menubar data.period-diff.tsis imported bysrc/main.tsalone.'9'bindings areApp.tsx:785andSidebar.tsx:33.Tests
npx tsc --noEmitclean;npm test4042 passed, 5 skipped, 0 failed.cd app && npm run typecheckclean;npx vitest run939 passed, 29 failed, 4 skipped. All 29 failures are one local environment gap — jsdom 29.1.1 here exposes nolocalStorage(Cannot read properties of undefined). 27 are the known usePolled/overviewSnapshot baseline; the 2 in PeriodCompare have the same cause. With a localStorage shim PeriodCompare is 9/9 and overviewSnapshot 6/6.costB - costAincontribution()kills 8 tests; flippingb.cost - a.costindiffTotalskills 8; droppingprojectArgs()fromgetPeriodComparekills the scopes-every-fetch test; droppingfilterProjectsByNamefrom the sessions branch kills the new CLI filter test.Performance (this machine, ~138 days of history)
--format sessions): 9.64s, 712 bytesKnown, not fixed
callsA/callsBsums run slightly undertotals.callsbecause zero-cost rows are dropped from a cost-contribution lens (unpriced and free models). Costs still reconcile exactly and the dropped models are listed in coverage.diffSessionscountssession.apiCallswhile the project lens countsproject.totalApiCalls; on one real project that differed by 2 calls in 5255. Cost is unaffected and calls are not rendered in the drill table.