Skip to content

feat(analytics): persist local usage session identities - #18759

Merged
nwparker merged 6 commits into
stablyai:mainfrom
blaksmatic:feat/analytics-session-id
Sep 27, 2026
Merged

nwparker merged 6 commits into
stablyai:mainfrom
blaksmatic:feat/analytics-session-id

Conversation

@blaksmatic

@blaksmatic blaksmatic commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Keep the original per-provider session identity mapping, including restart/resume stability and separation from disposable usage caches.
  • Add agent_token_usage through the existing main-process telemetry client, with provider, random conversation ID, revision, and input/output/cache-read/cache-write token counts.
  • Normalize cache counts so cache hits are not counted again as ordinary input. Include only usage attributed to Orca workspaces, including folder workspaces.
  • Persist cumulative snapshots and revisions before sending. Repeated or out-of-order reports can be deduplicated by selecting the highest revision per provider/conversation before summing counts.
  • Exclude raw provider session IDs, model details, activity timestamps, estimated costs, prompts, code, and paths. Update the existing telemetry documentation and remove the standalone identity design doc.

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:node passed.

  • Changed-code quality gate passed with no new findings.

  • git diff --check passed.

  • 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

  • Not applicable; no upstream skill content copied.

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

  • This PR is small and focused
  • I explained what changed and why
  • Visual proof marked N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • Full lint, typecheck, tests, and build pass (remaining coverage left to CI)

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 through UsageCacheSnapshotWriter (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.json beside the provider cache, with flush() 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Understand this PR’s impact

Explore downstream dependencies and potential security impact with Blast Radius.

View blast radius →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: de6f1de9-ac23-47c5-bd4f-26cab316bdf2

📥 Commits

Reviewing files that changed from the base of the PR and between 97807f6 and fe787f8.

📒 Files selected for processing (1)
  • src/main/usage/analytics-session-id-store.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/usage/analytics-session-id-store.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

Adds AnalyticsSessionIdStore to create and persist UUID v4 mappings for provider session IDs. The store validates input and persisted data, serializes operations, detects duplicates, and supports flushing. UsageProviderStoreLifecycle exposes getAnalyticsSessionId, stores identities in a separate cache-adjacent file, and flushes pending identity writes. Tests cover persistence, concurrency, isolation, validation, failures, and cache rebuilds. Documentation describes the accessor and local-only identity scope.

Priority: ⬇️ Low

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is largely inconsistent with the pull request. It describes token-usage telemetry, event reporting, cumulative snapshots, and issue #18758, but the changes add only persistent local an… 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 behavi…
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation meets the coding requirements in [#18758]. AnalyticsSessionIdStore creates independent UUID v4 values, stores provider-session mappings in a separate per-cache identity file, rest…
Out of Scope Changes check ✅ Passed The changes stay within [#18758]. The new implementation, integration, tests, and reference documentation support local persistent identity mappings. The diff adds no telemetry events, snapshot revisi…
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 4 files.
Title check ✅ Passed The title clearly summarizes the main change: persisting local analytics session identities.
Full details: Description check

Explanation

The description is largely inconsistent with the pull request. It describes token-usage telemetry, event reporting, cumulative snapshots, and issue #18758, but the changes add only persistent local analytics session IDs and related tests and documentation. It also states that the session identity implementation is unchanged, although the implementation is newly added.

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.

  • Fix all pre-merge checks with AI

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@blaksmatic

Copy link
Copy Markdown
Contributor Author

@coderabbitai run pre-merge checks

@coderabbitai

coderabbitai Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Running Pre-merge checks. Results will be posted in the summary comment once complete.

@blaksmatic

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@nwparker
nwparker force-pushed the feat/analytics-session-id branch from 1ef4698 to 97807f6 Compare September 21, 2026 22:08

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_usage telemetry 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 only worktreeId !== null locations and separate cache reads from ordinary input.
  • Wired the reporter into UsageProviderStoreLifecycle after each enabled scan, extended flush() to drain token-usage and identity writes, and kept reporting failures from failing a successful local scan.
  • Made track return a boolean and added isTelemetryEnabled() 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +37 to +39
// Codex/OpenCode include cache hits in input; Claude records them separately.
input_tokens: locations.reduce(
(sum, entry) => sum + entry.inputTokens - entry.cachedInputTokens,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 }`.

@nwparker
nwparker merged commit ef987e4 into stablyai:main Sep 27, 2026
1 check failed
Jinwoo-H added a commit that referenced this pull request Sep 27, 2026
#18759's test fixture predates #22360 adding required long-context token
fields to Codex session and location breakdowns, so main's typecheck fails.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add persistent local analytics session IDs for usage reporting

2 participants