Skip to content

fix: clamp overflowing context usage display#777

Merged
jeffscottward merged 2 commits intoRunMaestro:mainfrom
jeffscottward:codex/codex-context-ui
Apr 9, 2026
Merged

fix: clamp overflowing context usage display#777
jeffscottward merged 2 commits intoRunMaestro:mainfrom
jeffscottward:codex/codex-context-ui

Conversation

@jeffscottward
Copy link
Copy Markdown
Contributor

@jeffscottward jeffscottward commented Apr 9, 2026

Summary by CodeRabbit

  • Bug Fixes

    • Ensure token counts are clamped to the configured context window when accumulated tokens exceed the limit; clamp any fallback percentage to 100% before converting to tokens.
  • Tests

    • Updated coverage to assert clamped token/percentage behavior and added a test for fallback percentages >100%.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 9, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5d164b94-d6a3-4ecc-a626-8bb5bbe0df8d

📥 Commits

Reviewing files that changed from the base of the PR and between dc02bb8 and cbe43f6.

📒 Files selected for processing (2)
  • src/__tests__/renderer/utils/contextUsage.test.ts
  • src/renderer/utils/contextUsage.ts

📝 Walkthrough

Walkthrough

The calculateContextDisplay overflow path now always clamps when raw > contextWindow: if a valid fallbackPercentage exists it's first clamped to 100% before deriving tokens; if no valid fallback is present, tokens is clamped to contextWindow. Tests updated accordingly.

Changes

Cohort / File(s) Summary
Context Display Logic
src/renderer/utils/contextUsage.ts
Always run overflow handling when raw > contextWindow; clamp provided fallbackPercentage to a max of 100% before computing tokens; when no valid fallback, set tokens to contextWindow instead of leaving raw overflow.
Context Display Tests
src/__tests__/renderer/utils/contextUsage.test.ts
Updated test assertions: expect tokens to be clamped to contextWindow and percentage to be 100 when overflow occurs and fallback is missing or >100 (clamped).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Tokens hop, then find the bound,
A gentle clamp brings them home round,
Percentages trimmed to one hundred,
No wild counts left unbounded,
I nibble bugs and celebrate the sound.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: clamp overflowing context usage display' clearly and directly summarizes the main change in the pull request, which is to clamp context usage values to prevent overflow.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 and usage tips.

@greptile-apps
Copy link
Copy Markdown

greptile-apps bot commented Apr 9, 2026

Greptile Summary

This PR fixes an overflow display bug in calculateContextDisplay: when accumulated multi-tool turn token counts exceed the context window and no fallback percentage is available, tokens was previously left at the raw (impossible) value (e.g., 1008000 tokens for a 200K window). The fix clamps tokens to contextWindow in that case, making the UI display a sensible 100% rather than an impossible token count. The accompanying test is updated to assert the new clamped behavior.

Confidence Score: 5/5

Safe to merge — minimal, targeted fix with no regressions.

The change is a one-branch addition in a pure utility function. All findings are P2 or lower; the logic is correct, the test is accurate, and the fix is consistent with the existing ContextDisplayResult interface documentation.

No files require special attention.

Vulnerabilities

No security concerns identified.

Important Files Changed

Filename Overview
src/renderer/utils/contextUsage.ts Adds an else branch to clamp tokens to contextWindow when raw values overflow and no fallback percentage is available; logic is correct and the ContextDisplayResult jsdoc already documents this capping behavior.
src/tests/renderer/utils/contextUsage.test.ts Test title and assertion updated to match the new clamped behavior (result.tokens now expected to be 200000 rather than the raw 1008000); accurately covers the no-fallback overflow branch.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[calculateContextDisplay called] --> B{contextWindow <= 0?}
    B -->|yes| C[Return zeros]
    B -->|no| D[raw = calculateContextTokens]
    D --> E{raw > contextWindow?}
    E -->|no| F[tokens = raw]
    E -->|yes| G{fallbackPercentage != null\nAND >= 0?}
    G -->|yes| H["tokens = round(fallbackPercentage/100 × contextWindow)\n(multi-tool turn: use preserved %)"]
    G -->|no| I["tokens = contextWindow\n(NEW: clamp to window — no trustworthy fallback)"]
    F --> J["percentage = min(100, round(tokens/contextWindow × 100))"]
    H --> J
    I --> J
    J --> K[Return tokens, percentage, contextWindow]
Loading

Reviews (1): Last reviewed commit: "fix: clamp overflowing context usage dis..." | Re-trigger Greptile

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

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 `@src/renderer/utils/contextUsage.ts`:
- Around line 171-173: In the branch inside src/renderer/utils/contextUsage.ts
where you compute tokens from fallbackPercentage (the block checking
fallbackPercentage != null && fallbackPercentage >= 0), clamp fallbackPercentage
to a maximum of 100 before deriving tokens so you never compute tokens >
contextWindow; e.g., compute an effectivePercent = Math.min(fallbackPercentage,
100) and then set tokens = Math.round((effectivePercent / 100) * contextWindow)
(or wrap the final tokens with Math.min(tokens, contextWindow)) to guarantee
tokens never exceed contextWindow.
🪄 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

Run ID: 7dbcbbfe-79d1-4991-82b4-d31e91d6bb81

📥 Commits

Reviewing files that changed from the base of the PR and between 0d3c6fc and dc02bb8.

📒 Files selected for processing (2)
  • src/__tests__/renderer/utils/contextUsage.test.ts
  • src/renderer/utils/contextUsage.ts

Comment thread src/renderer/utils/contextUsage.ts Outdated
@jeffscottward
Copy link
Copy Markdown
Contributor Author

Review pass completed on April 9, 2026.

No blocking issues found in the changed surface I exercised.

Validated:

  • overflowed context usage now clamps to the configured window when no fallback percentage is available
  • hover details show Context Tokens capped at 128,000 / 128,000 and Usage at 100%
  • npx vitest run src/tests/renderer/utils/contextUsage.test.ts

Screenshot:

PR 777 context usage clamped

@jeffscottward
Copy link
Copy Markdown
Contributor Author

Addressed the unresolved CodeRabbit review point from review 4085702297.

Change pushed:

  • cbe43f603 fix: clamp fallback context percentages

What changed:

  • bounded fallbackPercentage to 100 before deriving tokens in calculateContextDisplay
  • added a regression test covering fallbackPercentage > 100
  • verified with npx vitest run src/__tests__/renderer/utils/contextUsage.test.ts

Updated verification screenshot for the over-100 fallback case:

PR 777 fallback percentage clamped

@jeffscottward jeffscottward merged commit a49bf70 into RunMaestro:main Apr 9, 2026
3 checks passed
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