feat: align context usage metrics - #411
Conversation
📝 WalkthroughWalkthroughThis PR derives effective input limits, compaction thresholds, and usage from model tokens/config, exposes helpers for tone and clamped ring percent, integrates those into session metrics, UI, overflow detection, tests, and i18n. (≤50 words) ChangesContext usage derivation & UI/overflow integration
Sequence DiagramsequenceDiagram
participant UI as SessionContextUsage (UI)
participant Metrics as SessionContextMetrics
participant Derive as deriveContextUsage
participant Overflow as Overflow Logic
participant Render as ProgressCircle/Tooltip
UI->>Metrics: getSessionContextMetrics(messages, providers, config)
Metrics->>Derive: deriveContextUsage({ model, tokens, compaction, defaultReserveTokens })
Derive->>Derive: compute usedTokens, effectiveInputLimit, reserved, compactThreshold, usagePercent
Derive-->>Metrics: context usage metrics
Metrics-->>UI: context metrics
UI->>Derive: contextUsageTone(usagePercent) & contextUsageRingPercent(usagePercent)
Derive-->>UI: tone, percent
UI->>Render: set --progress-circle-progress (ringColor), percent
UI->>Overflow: isOverflow(...) uses deriveContextUsage
Overflow-->>UI: overflow boolean
Render-->>UI: rendered ring + tooltip
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Code Review
This pull request centralizes context usage and compaction logic into a shared utility package, ensuring consistent calculations across the UI and core session logic. It enhances the user interface to display more granular metrics, including context windows, input limits, and auto-compaction thresholds. A high-severity issue was identified in the new utility where reasoning tokens were omitted from the total token summation, which would lead to inaccurate usage reporting and overflow detection for models that report reasoning tokens separately.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/app/src/components/session/session-context-metrics.test.ts`:
- Around line 74-94: The test's message object in the "uses input limit and
custom compaction reserve for usage metrics" case creates a total token count
(238_000) while also setting non-zero component fields
(input/output/reasoning/read/write), which can cause a mismatch if
getSessionContextMetrics treats total as the sum of components; fix the test by
making the message components consistent with total—either set all component
fields to 0 so total is the sole source of usedTokens, or adjust total to equal
the sum of the component fields—so that getSessionContextMetrics returns
usedTokens matching the expected 238_000.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 041948e0-8ac0-4de5-8b9c-93330a01c392
📒 Files selected for processing (13)
packages/app/src/components/session-context-usage-state.tspackages/app/src/components/session-context-usage.test.tspackages/app/src/components/session-context-usage.tsxpackages/app/src/components/session/session-context-metrics.test.tspackages/app/src/components/session/session-context-metrics.tspackages/app/src/components/session/session-context-tab.tsxpackages/app/src/i18n/en.tspackages/app/src/i18n/zh.tspackages/opencode/src/session/overflow.tspackages/opencode/test/session/compaction.test.tspackages/ui/src/components/progress-circle.csspackages/util/src/context-usage.tspackages/util/test/context-usage.test.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/app/src/components/session/session-context-metrics.ts (1)
93-95: ⚡ Quick winDrop the ambiguous
limitalias.
limitnow carrieseffectiveInputLimit, whilecontextWindowis also present beside it. That makes the API easy to misuse and reintroduces the exact “which limit is this?” ambiguity this PR is trying to remove.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/app/src/components/session/session-context-metrics.ts` around lines 93 - 95, The object currently exposes a confusing alias `limit` that duplicates `effectiveInputLimit`; remove the `limit` property so the object only exposes `effectiveInputLimit` (from usage.effectiveInputLimit) and `contextWindow` (from model?.limit.context), and update any consumers to reference `effectiveInputLimit` directly instead of `limit`; ensure the symbols `effectiveInputLimit`, `contextWindow`, and `usage.effectiveInputLimit` are used/returned consistently in the `session-context-metrics` code paths.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/app/src/components/session/session-context-metrics.ts`:
- Around line 93-95: The object currently exposes a confusing alias `limit` that
duplicates `effectiveInputLimit`; remove the `limit` property so the object only
exposes `effectiveInputLimit` (from usage.effectiveInputLimit) and
`contextWindow` (from model?.limit.context), and update any consumers to
reference `effectiveInputLimit` directly instead of `limit`; ensure the symbols
`effectiveInputLimit`, `contextWindow`, and `usage.effectiveInputLimit` are
used/returned consistently in the `session-context-metrics` code paths.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: ff27bd42-cd1e-49e6-b21d-5a6f99907e16
📒 Files selected for processing (8)
packages/app/src/components/session-context-usage.tsxpackages/app/src/components/session/session-context-metrics.test.tspackages/app/src/components/session/session-context-metrics.tspackages/app/src/components/session/session-context-tab.tsxpackages/app/src/i18n/en.tspackages/app/src/i18n/zh.tspackages/util/src/context-usage.tspackages/util/test/context-usage.test.ts
✅ Files skipped from review due to trivial changes (3)
- packages/app/src/i18n/en.ts
- packages/util/test/context-usage.test.ts
- packages/app/src/i18n/zh.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/util/src/context-usage.ts
- packages/app/src/components/session-context-usage.tsx
- packages/app/src/components/session/session-context-metrics.test.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/util/src/context-usage.ts`:
- Around line 70-73: The code reads input.compaction?.reserved directly into
reserved and uses it to compute compactThreshold, which can produce NaN or
values > effectiveInputLimit if reserved is negative or non-finite;
clamp/normalize the value first by replacing input.compaction?.reserved with a
sanitizedReserved (e.g., Number.isFinite(...) ? Math.max(0, value) : 0) before
computing compactThreshold and usagePercent, ensuring reserved is a non-negative
finite number; update references to use sanitizedReserved in the Math.min(...)
and Math.max(...) expressions in this module (where reserved, compactThreshold,
usagePercent, and effectiveInputLimit are computed).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 3a0aeb12-fd22-465a-abca-f42121821e99
📒 Files selected for processing (6)
packages/app/src/components/session-context-usage.tsxpackages/app/src/components/session/session-context-metrics.test.tspackages/app/src/components/session/session-context-metrics.tspackages/opencode/src/session/overflow.tspackages/util/src/context-usage.tspackages/util/test/context-usage.test.ts
✅ Files skipped from review due to trivial changes (2)
- packages/app/src/components/session-context-usage.tsx
- packages/util/test/context-usage.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/opencode/src/session/overflow.ts
- packages/app/src/components/session/session-context-metrics.test.ts
|
Post-merge trace note for #411 / #403. What merged
Key decisions
Verification before merge
|
Summary
@opencode-ai/util/context-usagehelper for context usage, compact threshold, and used-token math.Why
Issue #403 needs the UI to show real usable input context instead of the theoretical context window, while keeping runtime compaction and UI display on the same calculation.
Related Issue
Closes #403
Human Review Status
Pending. A human should make the final merge decision after reviewing the final diff and verification evidence.
Review Focus
@opencode-ai/util/context-usage.packages/opencode/src/session/overflow.tsand app context metrics.tokens.total, cache tokens, reasoning tokens, unknown limits, and customcompaction.reserved.Risk Notes
ProviderTransform.maxOutputTokenscap; this keeps the displayed threshold stable across runtime output-token cap experiments.How To Verify
Screenshots or Recordings
Not included. I attempted a local render check at
127.0.0.1:54544; the page returned 200, but the backend atlocalhost:4096was not running, so the screenshot only showed the empty app shell and was not useful evidence for the context indicator.Checklist
dev, and my PR title and commit messages use Conventional Commits in EnglishSummary by CodeRabbit
New Features
Improvements
Tests
Internationalization