Skip to content

fix(opencode): skip claude-code mirror rows already counted by Claude Code logs - #444

Open
ilker-sahin wants to merge 4 commits into
chattymin:mainfrom
ilker-sahin:fix/opencode-skip-claude-code-mirror
Open

ilker-sahin wants to merge 4 commits into
chattymin:mainfrom
ilker-sahin:fix/opencode-skip-claude-code-mirror

Conversation

@ilker-sahin

@ilker-sahin ilker-sahin commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #443.

When Claude Code runs through an OpenCode-based wrapper such as OpenChamber, the wrapper mirrors every request into opencode.db with providerID = "claude-code". Claude Code's own logs already count that usage, so the OpenCode provider counted each token a second time (on the reporter's machine, ~216M "OpenCode" tokens against ~220M Claude Code tokens for the same day, ~98% of it mirror rows).

Mirror rows are dropped only when Claude Code usage covers them.

  • A claude-code row (V2 session_message and legacy message) is matched by time: it is dropped if Claude Code has at least one usage entry inside the row's window (created - 5s … completed + 30s, both edges inclusive). A mirror row has no Claude message id, so a time window is the only link available.
  • If no Claude Code usage covers the row (transcripts not persisted, CLAUDE_CODE_SKIP_PROMPT_HISTORY=1, persistSession: false), the row counts as OpenCode usage, so it is not lost.
  • An unmatched row younger than 90s after its window is held back, because the transcript may not be flushed yet. The incremental OpenCode watermark stops before such a row, and also advances past dropped rows so they are not re-read on every refresh.
  • Claude entries are fetched through the existing LocalUsageCache.claudeEntries only on scans that actually met mirror rows. Users with no mirror rows get the same entries and watermark as before.

Saved counter. When every OpenCode row for the day was a mirror, the provider reports an explicit zero for today (LocalOpenCodeProvider.fetchDaily) instead of no data. The companion ledger then rebases that provider's saved baseline to 0 before new native usage arrives, so the first native tokens after upgrading are credited and old usage is not replayed.

The mirrored provider IDs live in one mirroredProviderIDs set inside the OpenCode reader, so no provider literal is added to a generic path. OpenCode entries are held in memory only (not in usage-cache.json), so no cache or parser version bump is needed. The defect class is recorded in docs/reference/defect-log.md.

Known limits (deliberate):

  • Matching is by time, so a transcript-less mirror row can be dropped when an unrelated Claude Code session was active in the same window.
  • A mirror row kept after the grace period is not retracted if Claude Code usage for it shows up later than that.
  • On a day where every OpenCode row was a mirror, OpenCode now shows 0 tokens instead of disappearing from the provider list.

Type of change

  • Bug fix
  • New feature
  • Refactor / cleanup
  • Documentation
  • Other:

UI changes

No UI code changes. The only visible effect is that the OpenCode total (and the combined total) is lower for users who run Claude Code through OpenCode, and the zero row described above.

Checklist

  • swift build and swift test pass (CI build-test passed on this revision; not run locally, see Validation)
  • PR title follows Conventional Commits and title/description are written in English
  • UI changes include embedded images (before/after for existing screens; image of a new screen), or there is no visible UI change
  • No copyrighted assets, secrets, or private tooling references are committed (see CONTRIBUTING)
  • Tests were added or updated for this change

Validation

New tests in LocalAdditionalUsageTests: covered vs uncovered mirror rows (V2 and legacy); the no-transcript case (a single 210-token row is kept); the window edges; the grace period; a pending row that a later cache scan resolves behind a newer native row, without double counting; the scan resuming after dropped rows; the mirrored-days tracking; and the explicit zero. CompanionTests documents the saved-baseline case. I broke the match, the pending-row watermark pin and the watermark over dropped rows on purpose to confirm each guard fails.

I can't run swift build / swift test locally (Command Line Tools only, no Xcode), so CI is the test run, and it passes. Before pushing I compiled the real Sources/PokeTokenBar/Core files with swiftc and ran the LocalAdditionalUsageTests file through a small XCTest stand-in, and ran a standalone probe against the real CompanionStore that reproduces the reviewer's scenario (key absent: first native 100 credited as 0; explicit zero: credited as 100). On real data from the reporter's machine, all 121 mirror rows for the day were covered by Claude Code usage and none were kept; every mirror row that carries tokens also has time.completed.

@ilker-sahin
ilker-sahin marked this pull request as ready for review October 14, 2026 21:52
@chattymin

Copy link
Copy Markdown
Owner

Two cases need fixes before merge.

[P2] Preserve usage when the Claude transcript is absent

With the OpenChamber claude-code provider and CLAUDE_CODE_SKIP_PROMPT_HISTORY=1, Claude disables both prompt history and session transcripts (official documentation). Tracing the plugin's environment construction, SDK invocation, ordinary assistant environment forwarding, and OpenCode assistant token persistence establishes a reachable condition where only the OpenCode usage remains.

The unconditional provider filter then removes the only available usage. A production-parser fixture with one 210-token OpenCode assistant row and no Claude transcript produced:

  • Main control: Claude 0, OpenCode 210.
  • PR head: Claude 0, OpenCode 0.

Expected: retain those 210 tokens. Please suppress a mirror only when corresponding Claude usage is available, or retain a fallback when its transcript is unavailable. The integration condition was established from source; no live paid API request was made.

Source: LocalAdditionalUsageProvider.swift:390 (also applies to the second parser guard below).

[P2] Rebase the saved counter before new native OpenCode usage

Seed an existing installation on the same date with Claude 1,000 and OpenCode mirror 1,000, with usedSinceInstall=0. After upgrading, refresh before any native OpenCode usage. Filtering removes the last OpenCode row, so the provider key disappears while its saved 1,000 baseline remains. A new native batch of 100 is then treated as a counter decrease.

The production CompanionStore probe credited 0 for that first new 100; the main-map control credited 100. Increasing native usage to 200 credited only 100 in total. Expected: credit the first newly generated 100 tokens as well. Please reconcile the stored provider baseline when filtering removes its remaining mirror rows, before accepting new native usage, without replaying old usage.

Source: LocalAdditionalUsageProvider.swift:482.

ilker-sahin and others added 2 commits October 16, 2026 08:08
… Code logs

OpenCode wrappers such as OpenChamber run Claude Code through a claude-code provider and mirror every request into opencode.db. The Claude Code provider already counts that usage from its own logs, so the OpenCode reader counted each token twice. Skip rows with providerID claude-code in both the V2 session_message and legacy message parsers. Fixes chattymin#443.
Dropping every claude-code row removed the only record of usage when Claude Code did not persist a transcript (persistSession false, CLAUDE_CODE_SKIP_PROMPT_HISTORY). A mirror row is now dropped only when Claude Code has usage inside its time window; otherwise it counts. Unmatched rows younger than a grace period are held back until the transcript is flushed, and the incremental watermark stops before them.

When filtering leaves OpenCode with no usage for the day, report an explicit zero so the companion ledger rebases its saved baseline before new native usage is credited.
@ilker-sahin
ilker-sahin force-pushed the fix/opencode-skip-claude-code-mirror branch from 982e50e to 3325bdd Compare October 16, 2026 07:20
…; log the defect class

Adds tests for the match window boundaries, a pending mirror row resolved on a later scan behind a newer native row, and the scan resuming after dropped mirror rows. Records the wrapper double-count class in docs/reference/defect-log.md.
@ilker-sahin

Copy link
Copy Markdown
Contributor Author

Updated - just putting here in case you hadn't seen. Thanks.

This branch has not been deployed

No deployments
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.

OpenCode provider double-counts Claude Code usage when Claude Code runs through OpenCode (e.g. OpenChamber)

2 participants