Repository navigation
feat(analytics): persist local usage session identities - #18759
Conversation
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Adds a local, durable providerSessionId → analyticsSessionId (random UUID v4) mapping as a primitive for future usage analytics, with no telemetry, snapshot, RPC, or UI surface wired up yet.
AnalyticsSessionIdStore— single-owner, lazily-loaded identity store that serializes lookups/writes, persists mappings durably throughUsageCacheSnapshotWriter(fsync + atomic rename), returns IDs only after persistence succeeds, and fails closed on malformed or duplicate persisted state.UsageProviderStoreLifecycle.getAnalyticsSessionId— lazy accessor naming the identity file<cache-name>-analytics-session-ids.jsonbeside the provider cache, withflush()extended to await pending identity writes on shutdown.- Tests — 12 identity-store tests (laziness, restart/resume, 20-request concurrency, provider/host-profile isolation, invalid keys, prototype/delimiter keys, fail-closed invalid state, duplicate detection, write-failure retry, shutdown flushing) plus 2 lifecycle tests.
- Docs — a new reference doc capturing durability, fail-closed behavior, single-owner semantics, and the SSH/execution-host boundary.
I verified the durability claim against durable-file-write.ts (fsync-before-rename, directory fsync, atomic temp rename), the cross-platform path naming against the three concrete stores (orca-claude-usage / orca-codex-usage / orca-opencode-usage), and the serialization/retry semantics against UsageCacheSnapshotWriter. The assertions in the concurrency, write-failure, and shutdown-flush tests are exact and would fail on the bugs they claim to pin. No actionable issues.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Understand this PR’s impact Explore downstream dependencies and potential security impact with Blast Radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughAdds Priority: ⬇️ Low 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is largely inconsistent with the pull request. It describes token-usage telemetry, event reporting, cumulative snapshots, and issue Resolution Rewrite the description to match the actual changes. Describe persistent per-provider analytics session IDs, durable identity-file storage, restart and cache-rebuild stability, serialized access, corruption handling, isolation, flush behavior, and the absence of telemetry, UI, snapshot, and remote-wire changes. Update the linked issue and testing details if needed.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@coderabbitai run pre-merge checks |
✅ Actions performedRunning Pre-merge checks. Results will be posted in the summary comment once complete. |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
1ef4698 to
97807f6
Compare
There was a problem hiding this comment.
Important
The shared Codex/OpenCode projection treats OpenCode's cache-read tokens as part of input, but OpenCode stores them as a separate additive bucket — cache-heavy sessions compute a negative input_tokens and are silently dropped from reporting.
Reviewed changes
This run re-reviews the delta since the prior pullfrog review, which had approved the identity-only version of this PR. The new commits turn the identity primitive into a live token-usage reporting pipeline:
- Added the
agent_token_usagetelemetry event (provider, random conversation ID, revision, input/output/cache-read/cache-write counts), registered in the event registry and locked to main-process ownership so a renderer cannot spoof it. - Added
AgentTokenUsageReporter, which persists cumulative per-conversation snapshots with monotonic revisions before capture, keeps revisions across cache rebuilds and restarts, and retries a failed write without publishing its revision. - Added provider token projections (
claudeTokenSessions,codexOpenCodeTokenSessions) that attribute onlyworktreeId !== nulllocations and separate cache reads from ordinary input. - Wired the reporter into
UsageProviderStoreLifecycleafter each enabled scan, extendedflush()to drain token-usage and identity writes, and kept reporting failures from failing a successful local scan. - Made
trackreturn a boolean and addedisTelemetryEnabled()so producers can skip payload preparation when the consent/build/shutdown gates are closed. - Replaced the standalone analytics identity design doc with an entry in the telemetry documentation.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| // Codex/OpenCode include cache hits in input; Claude records them separately. | ||
| input_tokens: locations.reduce( | ||
| (sum, entry) => sum + entry.inputTokens - entry.cachedInputTokens, |
There was a problem hiding this comment.
OpenCode's cache reads are not part of its input bucket, so subtracting them here undercounts input and can drive input_tokens negative.
The repo's own parser allows cache reads to exceed input (opencode-usage-row-parsing.ts:83), and the captured reproduction fixture has cache read ≈ 19× input; OpenCode's total is computed as input + output + reasoning + cache_read, i.e. the buckets are disjoint. When the computed value is negative, agentTokenCountsSchema.safeParse rejects it and publish silently continues, dropping the entire conversation (output and cache counts included); non-negative sessions report an input figure that double-counts the same tokens already sent as cached_input_tokens. Codex is the only provider whose inputTokens is inclusive of cache.
Technical details
# Split the Codex and OpenCode projections
## Affected sites
- `src/main/usage/agent-token-usage.ts:26-48` — `codexOpenCodeTokenSessions` applies the Codex cache-inclusive formula to both providers; the comment on line 37 is wrong for OpenCode.
- `src/main/opencode-usage/store.ts:54-57` — OpenCode is wired to this shared function.
- `src/main/usage/agent-token-usage-reporter.ts:56-59` — a rejected `safeParse` silently skips the conversation.
- `src/shared/telemetry-agent-token-usage-schema.ts:3,7` — `nonnegative()` is what turns the accounting error into a silent drop rather than a visible failure.
- `src/main/usage/agent-token-usage.test.ts:71-77,91-101` — the OpenCode fixture spreads the Codex fixture, so the parametrized test asserts Codex semantics for OpenCode and cannot catch this.
## Required outcome
- OpenCode sessions report their stored `inputTokens` as `input_tokens` (no subtraction), with `cached_input_tokens` carrying the cache-read count, so cache-heavy sessions are no longer dropped and ordinary sessions are not undercounted.
- Codex keeps subtracting (its `cachedInputTokens` is clamped to `inputTokens` in `codex-usage-record-parser.ts:127`).
- Add an OpenCode-specific test whose `cachedInputTokens` exceeds `inputTokens`, asserting the session is still published rather than silently skipped.
## Suggested approach (optional)
- Give OpenCode its own projection function (or a provider-discriminated parameter) so the two formulas cannot be conflated again, and build the OpenCode test fixture from real OpenCode shapes rather than `{ ...codex }`.
ELI5
Give agent conversations a persistent random ID and use it to report token totals for Claude, Codex, and OpenCode usage attributed to Orca workspaces. Reporting follows the existing analytics consent and local usage-scan settings.
What Changed
agent_token_usagethrough the existing main-process telemetry client, with provider, random conversation ID, revision, and input/output/cache-read/cache-write token counts.Why
The original change supplied conversation identity but did not report usage. This connects those IDs to token totals so we can understand agent usage in Orca. Reusing the existing scanners and consent-controlled transport avoids another scanner or reporting service; cumulative snapshots avoid double-counting resumed conversations and repeated uploads.
Linked Issue
Fixes #18758
Visual Proof
N/A — no rendered UI changes; local persistence, token reporting, and documentation only.
Testing
Validated on macOS:
Focused tests passed for identity persistence, provider stores, token projections, reporter retries/restarts, usage-cache rebuilds, consent, transport, burst limits, event schemas, and renderer IPC rejection.
pnpm tc:nodepassed.Changed-code quality gate passed with no new findings.
git diff --checkpassed.I manually tested these changes locally
Automated tests added/updated, or explained why not below
Review
Checked persistence-before-capture, revision stability, write-failure retries, opt-out during asynchronous work, non-official build/shutdown gates, workspace attribution, cache-token normalization, and renderer spoofing prevention. The session identity implementation is unchanged from the original PR.
Agent skill upstream boundary
Notes
Reports run after existing enabled local usage scans; this adds no background scanner. Existing scanned usage may be included. These are cumulative snapshots, not additive events or exact billing records: queries must use the highest revision for each provider/conversation. Transport remains best effort and uses existing queue and rate limits.
Remote usage is not inferred or collected from a viewing client. SSH reporting remains future work on the execution host. No remote wire or UI changes. Windows/Linux and live SSH were not exercised; full build/lint remain for CI.
Checklist