Skip to content

Port upstream 0.67.0: OpenCode Go local token counts - #671

Closed
Finesssee wants to merge 2 commits into
port/upstream-0.67.0from
port/micro-0.67.0-opencodego-local-tokens
Closed

Finesssee wants to merge 2 commits into
port/upstream-0.67.0from
port/micro-0.67.0-opencodego-local-tokens

Conversation

@Finesssee

Copy link
Copy Markdown
Collaborator

Summary

OpenCode Go's local SQLite reader now reads the recorded tokens object, so daily and per-model local history carry tokens. Costs stay the recorded cost field and are never derived from tokens.

  • SQL: both the message-only query and the message + step-finish query select json_extract(data,'$.tokens') only when json_type(data,'$.tokens') = 'object'. Step-finish parts keep precedence over their parent message (no double count); message rows are used when no step-finish exists, as before.
  • New providers/opencodego/tokens.rs: RowTokens::parse deserializes {total, input, output, reasoning, cache:{read, write}} with #[derive(Deserialize)]. resolved_total = total, else the checked sum of the five components only when all five are present. A row is usable only when every present count (including total) is >= 0 and a total resolves. Malformed JSON, non-integer counts, or overflow leave the row's tokens unknown (never zero).
  • TokenSums aggregates per day+model (DailyModelCost.tokens), per model, and per window (ModelCostSummary). It tracks completeness separately: any row without usable tokens makes complete_total() / complete_reasoning() return None, while class sums keep what rows did record.
  • CostScanner::scan_opencodego_with_cancel now fills input_tokens, output_tokens, cached_tokens, reasoning_tokens (Some only when every row reports it) and by_model_tokens. Models with no usable row get no by_model_tokens entry.
  • Usage & Spend: the OpenCode Go row now shows 7/30-day tokens (input + output, same as the Claude row) from the local history; the cost column is unchanged.

Upstream reference

  • Release 0.67.0 item 17 (OpenCode Go local token counts); triage entry opencodego-local-tokens.
  • Sources/CodexBarCore/Providers/OpenCodeGo/[email protected] (providerMessagesSQL, messageAndPartUsageSQL, TokenCounts, resolvedTotal, isValid, dailyEntries).
  • Fixtures: the two token payloads from upstream OpenCodeGoLocalUsageReaderTests (daily entries carry message token counts per day and model): {"total":1600,"input":100,"output":20,"reasoning":30,"cache":{"read":1400,"write":50}} and the older no-total row {"input":10,"output":5,"reasoning":1,"cache":{"read":4,"write":0}}; expected day totals 1620 total / 110 input / 25 output / 31 reasoning / 1404 cache read / 50 cache write.

Ported / Deferred

Ported: everything in the spec above.

Notes and deferrals:

  • CostSummary and ModelTokenCounts have no cache-write class, so cached_tokens = cache read + cache write (the existing Claude/Pi convention). The exact read/write split and total live on TokenSums (daily / per-model / window) but are not surfaced in the shared summary; adding a cache-write field to the shared structs would touch every scanner and is left out of this micro PR.
  • CostSummary.input_tokens/output_tokens/cached_tokens are plain u64, so a window with unusable rows shows the sum of the usable rows (and reasoning_tokens = None) rather than a distinct "unknown"; a model with no usable row is omitted from by_model_tokens. The complete/unknown distinction is exact on TokenSums.
  • The daily cost-history series (daily_cost_series) still feeds cost only; there is no per-day token consumer on Windows yet.
  • local.rs was already over 1000 lines (1229) before this PR; the new logic and tests live in tokens.rs and local/tokens_tests.rs, and local.rs grows by ~35 lines of query/plumbing.

Validation

Toolchain cargo +1.98.0, E-core wrappers, slot-3 target dir.

  • cargo +1.98.0 fmt --all: clean
  • cargo +1.98.0 clippy --workspace --all-targets -- -D warnings: pass
  • cargo +1.98.0 test -p codexbar opencodego -- --test-threads=4: 51 passed (7 new token tests + existing)
  • cargo +1.98.0 test -p codexbar -- --test-threads=4 (full, cost_scanner touched): 2167 passed, 0 failed, 1 ignored
  • cargo +1.98.0 test -p codexbar-desktop-tauri usage_spend -- --test-threads=4: 6 passed (1 new)

New tests cover: total vs component-sum resolution, negative/malformed/non-integer/overflow rows, the upstream two-message day fixture, step-finish precedence over parent message tokens, message fallback, day/window incompleteness with unusable rows, per-model summaries, and the Usage & Spend unknown-vs-zero guard.

Affected areas

  • Rust backend (rust/src/providers/opencodego, cost_scanner.rs)
  • Tauri shell command (usage_spend.rs, value plumbing only)
  • Frontend / UI components
  • Settings / tray / float bar
  • Docs (docs/PROVIDERS.md)
  • No new dependencies.

UI proof

Not applicable (the existing Usage & Spend token columns render the new values; no UI code changed).

@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 1ba145be-28a1-4b4b-ad86-a28c904899bc

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

@Finesssee

Copy link
Copy Markdown
Collaborator Author

Reviewed by Codex gpt-6-luna (xhigh); verified and validated by Claude

Thermo-nuclear review of #671 (OpenCode Go recorded local token counts). Findings:

  • Medium, commands/usage_spend.rs: Usage & Spend could show a partial input+output sum as exact when another row lacked usable tokens or lacked either class. Fixed: the value is shown only when every row has usable input and output counts and the sum does not overflow; otherwise it is unknown. The logic moved into the provider (TokenSums::complete_input_output, CostScanner::scan_opencodego_usage_tokens_with_cancel), replacing the shell-side helper.
  • Low, providers/opencodego/tokens.rs: cache read + write could silently saturate into a wrong count. Fixed: an unrepresentable combined count is omitted, with a regression test.

Everything else matches the spec: the query and step-finish precedence, recorded-cost handling, daily and per-model aggregates, siloing, and test coverage. No locale, accessibility or bridge-type changes were needed.

@Finesssee

Copy link
Copy Markdown
Collaborator Author

Follow-up: both findings above are fixed and pushed. Nothing left open.

The one visible effect: the OpenCode Go 7-day and 30-day token columns in Usage & Spend now show "unknown" instead of a partial sum when some rows lack input or output counts. No layout or copy changed.

Commands run (Rust 1.98.0, E-cores): cargo fmt --all; clippy --all-targets -D warnings on rust and apps/desktop-tauri/src-tauri (clean); cargo test --lib opencodego (54 passed) and cost_scanner; shell usage_spend tests (5 passed). I corrected one Codex-added overflow test whose fixture overflowed the wrong total. No CUA pass was run; no UI structure changed.

@Finesssee

Copy link
Copy Markdown
Collaborator Author

Port review: OpenCode Go local token counts (#671, GAP-40 / 0.67.0 item 17)

Reviewed the branch diff 86eab224 vs port/upstream-0.67.0 (commits 0be3280 "Port upstream 0.67.0: read OpenCode Go recorded local token counts" + 86eab22 "Address thermo review") against the 0.67.0 manifest spec for item 17 / PR 15 (upstream OpenCodeGoLocalUsageReader.swift providerMessagesSQL/TokenCounts/resolvedTotal/isValid, steipete#3995, commit a2cf7fa; tests OpenCodeGoLocalUsageReaderTests.swift).

What I checked:

  • SQL shape: both readers (message rows and the step-finish part CTE) now select json_extract(data,'$.tokens') only when json_type(data,'$.tokens') = 'object', exactly the spec's guard. Step-finish parts take precedence over the parent message (the NOT EXISTS anti-join keeps message rows only when no step-finish part exists), so multi-step sessions are not double counted and message rows still serve when no step-finish exists.
  • TokenCounts / resolvedTotal / isValid: RowTokens::parse maps {total, input, output, reasoning, cache:{read, write}} with Option<i64> per class; non_negative distinguishes "not recorded" (inner None) from "negative → invalid row" (outer None), so any negative count including total makes the row unusable. resolved_total = recorded total, else the checked sum of the five components only when all five are present (try_fold over value?), matching upstream resolvedTotal; malformed shapes ("12", 1.5, cache: 7, not-JSON, {} with no components) are unknown, never zero.
  • Aggregation semantics: TokenSums adds only what rows recorded per class and tracks completeness separately (rows, unusable_rows, per-class counters). complete_total is Some only when every row had usable tokens (the spec's "a day containing a row without usable tokens has no complete total"); complete_input_output requires every row to record both classes; complete_reasoning requires every row to record it. Checked adds make an overflowing row unusable rather than wrapping. Costs always stay the recorded cost field (asserted in the daily test).
  • Shared-summary mapping: to_model_token_counts follows the local Claude/Pi convention (cached_tokens = cache read + write, since the shared summary has no separate cache-write class) and yields None when no row had usable tokens — so the cost summary's token fields stay zero/default rather than a fabricated value, matching the manifest's "costs stay recorded, never derived".
  • Scanner/Usage & Spend wiring: scan_opencodego_with_cancel fills input/output/cached/reasoning tokens plus by_model_tokens (per-model entries with unusable-token sums are dropped, not zeroed); the new scan_opencodego_usage_tokens_with_cancel gives Usage & Spend an exact input+output total only when every contributing row has both. The usage_spend.rs "opencodego" arm fills seven_day_tokens/thirty_day_tokens from it and leaves the cost side as before.
  • Tests: tokens_tests.rs (278 lines, 10 tests) covers the upstream fixture matrix verbatim (FULL 1600-total message + NO_TOTAL 20-sum older row → day totals 1620/110/25/31/1404/50; step-finish replacing parent tokens; incomplete-not-zero days; per-model partial marking; negative/malformed/overflow rejection at both row and sum level).
  • Thermo round: 86eab22 moved the token plumbing out of usage_spend.rs into the scanner (−36 lines there), hardened the SQL path, and added 46 lines of tests — the current shape is the reviewed one.

Result: no findings. The port matches the upstream semantics on the SQL guard, precedence, resolved-total rule, validity rule and never-invent-zero aggregation, with costs untouched. Files under the cap (tokens.rs 187, tokens_tests.rs 278, local.rs +49). No dependency, locale, bridge-shape or UI change; the UI already renders token columns for providers that have them.

@Finesssee

Copy link
Copy Markdown
Collaborator Author

Shipped in v0.70.0: this PR's head is included in main via #735 (merge commit 9d0a37a). Closing as integrated.

@Finesssee Finesssee closed this Oct 3, 2026
junglesub-bot Bot pushed a commit to junglesub/Win-CodexBar that referenced this pull request Oct 4, 2026
…ounts

Conflict in rust/src/cost_scanner.rs: the release scanner resolves windows
from its reporting period (calendar_window) and replaced
get_claude_projects_dir with claude_projects_roots. The OpenCode Go
summary helper now scans calendar_window(now, None).days, and the release
Claude roots helper is kept next to scan_opencodego_usage_tokens_with_cancel.

usage_spend.rs: the release cached_spend takes the reporting period; the
OpenCode Go arm also fills period_tokens from the local history (7d/30d
reuse the fixed scans, other periods scan once), like Grok and Antigravity.
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.

1 participant