Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(opencode): surface context-window usage and session cost on the meter #8659

Closedardevdevts(GitHub profile, opens in a new tab)wants to merge 12 commits intomain fromrefs/pull/8659/headopened View on GitHub

Problem

OpenCode sessions never reported token usage, so the context-window meter stayed empty for them while Codex and Claude sessions render usage.

Change

  • OpenCodeAdapter now emits thread.token-usage.updated: per-message counts from assistant message.updated events folded with cumulative session totals and USD cost from session.updated events. Emissions are deduped over every input that shapes the snapshot, so unchanged session replays don't spam the event log while real changes (including output-only growth mid-stream) re-emit.
  • Context-window size (maxTokens) is resolved once per model from the provider.list catalog; a transient catalog failure is retried on the next session.updated instead of giving up for the session's lifetime.
  • Zero-token updates (e.g. compaction summary messages) no longer clobber the meter's per-message usage.
  • Contract: optional cost on ThreadTokenUsageSnapshot; the web context-window meter renders a Cost row when a provider reports it.

Note: Claude's total_cost_usd currently lands on the turn.completed payload and is not wired into the meter — left as-is for now.

Verification

Focused tests pass (OpenCodeAdapter 92, ContextWindowMeter + contextWindow 11) covering the mapping, dedupe, late/retried catalog resolution, zero-token handling, and model switches; targeted typecheck is clean.

image

Model: glm-5.3-flash · harness: opencode

Note

Add context-window usage and session cost reporting to OpenCodeAdapter meter

  • OpenCodeAdapter now emits thread.token-usage.updated events carrying a ThreadTokenUsageSnapshot with input/cache/output/reasoning token counts, cumulative session totals, resolved model context capacity, and cumulative session cost.
  • A per-turn contribution ledger records token usage from assistant messages, deduplicates same-key reports, and fences ownership so late updates from a prior turn cannot contaminate a later turn. The ownership map is bounded to 1,000 entries via oldest-first eviction in trimContributionTurnMap.
  • Model context limits are resolved best-effort through provider.list with a 5-second timeout and a 30-second retry cooldown per model. Failed lookups leave capacity unset rather than blocking usage emission.
  • ContextWindowMeter.tsx now renders a Cost row in its popover when the snapshot contains a positive cost, formatted by contextWindow.ts.
  • ThreadTokenUsageSnapshot in providerRuntime.ts gains an optional finite, nonnegative cost field.
  • Behavioral Change: failed, aborted, or interrupted turns now discard their contribution ledger entries via clearOpenCodeTurnContributions, so no usage payload is attached to those turn completions.
Macroscope summarized bf3d9ab.

Note

Medium Risk Changes the OpenCode event pump (catalog calls on session updates) and token accounting visible in the UI; bounded by timeout and extensive tests, but still on a hot path for live threads.

Overview OpenCode sessions now drive the context-window meter the same way other providers do, by emitting thread.token-usage.updated from assistant message.updated and session.updated events.

The adapter adds normalizeOpenCodeTokenCounts / normalizeOpenCodeTokenUsage to clamp bad token payloads and map OpenCode’s split counts (input, cache, output, reasoning) into a ThreadTokenUsageSnapshot, including optional totalProcessedTokens, maxTokens from provider.list (once per model, 5s timeout, retry on later session updates), and cumulative USD cost. Emissions are deduped; zero-token assistant messages no longer wipe prior usage; model switches clear stale limits.

Contracts gain optional cost on the snapshot; the web ContextWindowMeter shows a Cost row via formatContextWindowCost when cost is reported.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit bd0a80e5c6d811e67fd63398ceb7a2876fa171f9. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. 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: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 0a20ac01-005b-431a-bc60-299cca213b4b

      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

      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR adds a substantial, automatically active OpenCode usage and cost-metering feature across the server event pump, shared contracts, and web UI, including catalog lookups and new turn accounting. An unresolved Medium-severity comment also concerns possible prior-turn usage contamination.

      Not approved because:

      • 1 blocking correctness issue found at or above your repo's Minimum Blocking Severity
      Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).

      Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit bd0a80e5c6d811e67fd63398ceb7a2876fa171f9. Configure [here](https://www.cursor.com/dashboard/bugbot).
    5. Note

      🤖 GPT-6 Astra (preview) responding on behalf of Theo

      This note is part of an automated cleanup pass.

      Preserve the live-usage cases from #8918 at its head commit. OpenCodeAdapter.test.ts covers zero-token updates, replacement of duplicate message.updated totals, accumulated usage and cost across tool steps, and usage plus modelUsage on idle turn completion. These cases are separate from the historical scanner in #8456. Before porting them, check message/part/session deduplication and fence late events to their owning turn. Keep context occupancy distinct from cumulative processed tokens. This records cases for review, not code that has already been ported.

    6. Bugbot is paused — on-demand spend limit reached

      Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

      A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

    7. Bugbot is paused — on-demand spend limit reached

      Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

      A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

    8. Thanks for the PR. We're not taking changes to the orchestration and provider layers right now: that part of the server is being rewritten for V2, and merging into the current code would either conflict with or be thrown away by that work.

      Closing for now. If this is still an issue once V2 lands, please reopen (or open a fresh PR against the new code) and we'll take a proper look.

    9. juliusmarminge closed this

Sign in to join this conversation.