Skip to content

feat: Limit auto-claude window usage based on budget #1907

Open
eyalk11 wants to merge 1 commit intoAndyMik90:developfrom
eyalk11:budget
Open

feat: Limit auto-claude window usage based on budget #1907
eyalk11 wants to merge 1 commit intoAndyMik90:developfrom
eyalk11:budget

Conversation

@eyalk11
Copy link

@eyalk11 eyalk11 commented Feb 28, 2026

  • Add budgetCapPercent setting: a single unified slider that caps both session and weekly thresholds, preventing usage beyond the configured percentage of the plan (e.g. 80% budget cap).
    • Add noExtraUsage toggle: marks an account unavailable once either usage limit hits 100%, preventing Anthropic extra-usage (pay-per-use overage) from being consumed.
    • Apply both settings in profile-scorer (availability checks, fallback scoring, unified account scoring, proactive switch logic) and in usage-monitor threshold checks.
    • Add UI controls (budget cap slider + toggle) in AccountSettings below the weekly threshold slider, visible when proactive monitoring is on.
    • Add i18n keys for both new controls in en/fr settings locales.
    • Move budget cap and noExtraUsage controls into a dedicated "Usage Limits" section visible regardless of account count (no longer gated by totalAccounts > 1).
    • Budget cap and noExtraUsage now work independently of the auto-switch master toggle, so single-account users can also enforce plan limits.
    • When a budget limit is hit and no alternative account is available, emit budget-exhausted from UsageMonitor → initializeUsageMonitorForwarding calls agentManager.killAll() to stop all running agents immediately.
    • Pass agentManager into initializeUsageMonitorForwarding in index.ts (both the primary and fallback init paths).

Base Branch

  • [ X] This PR targets the develop branch (required for all feature/fix PRs)
  • This PR targets main (hotfix only - maintainers)

Description

It makes auto-claude stop when reaches X% of allowed tokens in the 5-hours window . Also, make auto-claude not consume extra-usage even if available.

Looks like that :

image

Related Issue

Closes #

Type of Change

  • 🐛 Bug fix
  • [X ] ✨ New feature
  • 📚 Documentation
  • ♻️ Refactor
  • 🧪 Test

Area

  • [ X] Frontend
  • Backend
  • Fullstack

Commit Message Format

Follow conventional commits: <type>: <subject>

Types: feat, fix, docs, style, refactor, test, chore

Example: feat: add user authentication system

AI Disclosure

  • [X ] This PR includes AI-generated code (Claude, Codex, Copilot, etc.)

Tool(s) used:
Testing level:

  • Untested -- AI output not yet verified

  • [ X ] Lightly tested -- ran the app / spot-checked key paths . I checked that it works.

  • Fully tested -- all tests pass, manually verified behavior

  • [ X] I understand what this PR does ** but not how the underlying code works**

Checklist

  • [X ] I've synced with develop branch
  • I've tested my changes locally
  • I've followed the code principles (SOLID, DRY, KISS)
  • [X ] My PR is small and focused (< 400 lines ideally)

Platform Testing Checklist

CRITICAL: This project supports Windows, macOS, and Linux. Platform-specific bugs are a common source of breakage.

  • [ X] Windows tested (either on Windows or via CI)
  • macOS tested (either on macOS or via CI)
  • Linux tested (CI covers this)
  • Used centralized platform/ module instead of direct process.platform checks
  • No hardcoded paths (used findExecutable() or platform abstractions)

If you only have access to one OS: CI now tests on all platforms. Ensure all checks pass before submitting.

CI/Testing Requirements

  • All CI checks pass on all platforms (Windows, macOS, Linux)
  • All existing tests pass
  • New features include test coverage
  • Bug fixes include regression tests

Screenshots

Before After

Feature Toggle

  • Behind localStorage flag: use_feature_name
  • Behind settings toggle
  • Behind environment variable/config
  • N/A - Feature is complete and ready for all users
  • New Features

    • Added Usage Limits settings section with a budget cap slider to constrain plan usage across all accounts and a no extra usage toggle to prevent overage
    • Agents automatically stop when budget limits are exhausted and no alternative accounts are available
  • Documentation

    • Added localization strings in English and French for new usage limits controls

    - Add `budgetCapPercent` setting: a single unified slider that caps both
      session and weekly thresholds, preventing usage beyond the configured
      percentage of the plan (e.g. 80% budget cap).
    - Add `noExtraUsage` toggle: marks an account unavailable once either
      usage limit hits 100%, preventing Anthropic extra-usage (pay-per-use
      overage) from being consumed.
    - Apply both settings in profile-scorer (availability checks, fallback
      scoring, unified account scoring, proactive switch logic) and in
      usage-monitor threshold checks.
    - Add UI controls (budget cap slider + toggle) in AccountSettings below
      the weekly threshold slider, visible when proactive monitoring is on.
    - Add i18n keys for both new controls in en/fr settings locales.
    - Move budget cap and noExtraUsage controls into a dedicated "Usage Limits"
      section visible regardless of account count (no longer gated by totalAccounts > 1).
    - Budget cap and noExtraUsage now work independently of the auto-switch master
      toggle, so single-account users can also enforce plan limits.
    - When a budget limit is hit and no alternative account is available, emit
      budget-exhausted from UsageMonitor → initializeUsageMonitorForwarding calls
      agentManager.killAll() to stop all running agents immediately.
    - Pass agentManager into initializeUsageMonitorForwarding in index.ts (both
      the primary and fallback init paths).
@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 28, 2026

📝 Walkthrough

Walkthrough

This PR introduces budget cap and noExtraUsage policies for Claude auto-switch settings. It adds optional budgetCapPercent (0-100) and noExtraUsage (boolean) fields that constrain usage thresholds, emit a budget-exhausted event when limits are reached with no alternatives, kill running agents, and expose UI controls for configuring these policies.

Changes

Cohort / File(s) Summary
Profile Scoring & Thresholds
profile-scorer.ts, profile-storage.ts, agent.ts
Adds budgetCapPercent and noExtraUsage fields to auto-switch settings. Computes effective thresholds by clamping weekly/session thresholds to budgetCapPercent, and enforces 100% hard stop when noExtraUsage is true. Updates scoring logic, availability checks, and proactive switch decisions to use effective thresholds instead of raw values.
Usage Monitoring & Agent Control
usage-monitor.ts, terminal-handlers.ts, index.ts
Extends usage-monitor method signatures to accept budgetCapPercent and noExtraUsage parameters. Adds budget-exhausted event emission when no alternatives exist. Updates terminal-handlers to receive AgentManager and kill all running agents on budget exhaustion before emitting renderer event. Updates index.ts call sites to pass agentManager.
UI & Localization
AccountSettings.tsx, en/settings.json, fr/settings.json
Adds new Usage Limits section in settings with budget cap slider (0-100%, with "off" state) and noExtraUsage toggle. Includes English and French localization keys for usageLimits and autoSwitching budget-related controls. Note: AccountSettings.tsx contains duplicated Usage Limits section blocks.

Sequence Diagram(s)

sequenceDiagram
    participant UsageMonitor as Usage Monitor
    participant ProfileScorer as Profile Scorer
    participant ProactiveSwap as Proactive Swap
    participant AgentManager as Agent Manager
    participant TerminalHandlers as Terminal Handlers
    participant Renderer as Renderer

    UsageMonitor->>UsageMonitor: checkUsageAndSwap()
    UsageMonitor->>ProfileScorer: Evaluate effective thresholds<br/>(budgetCapPercent, noExtraUsage)
    ProfileScorer-->>UsageMonitor: exceeds threshold at 100%?
    
    alt Budget Policy Active & No Alternatives
        UsageMonitor->>ProactiveSwap: performProactiveSwap(stopIfExhausted=true)
        ProactiveSwap-->>UsageMonitor: No alternatives found
        UsageMonitor->>UsageMonitor: Emit budget-exhausted event
        UsageMonitor->>TerminalHandlers: Relay budget-exhausted
        TerminalHandlers->>AgentManager: killAll()
        AgentManager-->>TerminalHandlers: Cleanup complete
        TerminalHandlers->>Renderer: Emit budget_exhausted to UI
    else Alternatives Available
        UsageMonitor->>ProactiveSwap: Switch to alternative profile
        ProactiveSwap-->>UsageMonitor: Switch successful
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

feature, area/frontend, size/M

Suggested reviewers

  • AndyMik90
  • AlexMadera

Poem

🐰 A budget cap arrives with grace,
With noExtraUsage keeping pace,
When usage hits the 100 wall,
The agents heed the budget's call,
And switch to safer pastures tall! 💨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately captures the main feature: adding budget-based usage limits to restrict auto-claude window usage. It directly reflects the core change across all modified files.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the Claude profile management system by introducing robust usage limit controls. It allows users to define a budget cap for both session and weekly usage and to prevent extra usage beyond their plan limits. These new settings are deeply integrated into the system's logic for determining profile availability and proactive switching, and are exposed through a new, dedicated section in the user interface. The changes ensure that agents are stopped if budget limits are hit and no alternative accounts are available, providing better cost control and preventing unexpected overages.

Highlights

  • Usage Limit Controls: Introduced a budgetCapPercent setting, a unified slider that caps both session and weekly usage thresholds, and a noExtraUsage toggle to prevent consumption beyond 100% of the plan, avoiding pay-per-use overage.
  • Core Logic Integration: Integrated the new budgetCapPercent and noExtraUsage settings into profile-scorer for availability checks, fallback scoring, and unified account scoring, and into usage-monitor for threshold checks and proactive switching logic.
  • User Interface Enhancements: Added dedicated UI controls for the budget cap slider and no extra usage toggle in the AccountSettings page, now grouped under a new 'Usage Limits' section that is visible independently of the number of accounts.
  • Independent Operation: Ensured that the budget cap and no extra usage controls function independently of the auto-switch master toggle, allowing single-account users to also enforce plan limits.
  • Agent Termination on Budget Exhaustion: Implemented logic to emit a budget-exhausted event from UsageMonitor which, when no alternative account is available, triggers agentManager.killAll() to immediately stop all running agents.
  • Agent Manager Integration: Modified initializeUsageMonitorForwarding in index.ts and terminal-handlers.ts to accept and utilize the agentManager for agent termination upon budget exhaustion.
  • Internationalization: Added new i18n keys for the budget cap and no extra usage controls in both English and French locales.
Changelog
  • apps/frontend/src/main/claude-profile/profile-scorer.ts
    • Updated availability checks to incorporate noExtraUsage and budgetCapPercent.
    • Modified fallback scoring to use effective thresholds based on budgetCapPercent.
    • Adjusted unified account scoring to respect noExtraUsage and budgetCapPercent.
  • apps/frontend/src/main/claude-profile/profile-storage.ts
    • Added budgetCapPercent and noExtraUsage with default values to DEFAULT_AUTO_SWITCH_SETTINGS.
  • apps/frontend/src/main/claude-profile/usage-monitor.ts
    • Revised handleUsageUpdate to consider budget policies independently of proactive swap settings.
    • Updated checkThresholdsExceeded to calculate effective session and weekly thresholds based on budgetCapPercent and noExtraUsage.
    • Modified performProactiveSwap to include a stopIfExhausted parameter and emit a budget-exhausted event when no alternative profile is found under budget policy.
  • apps/frontend/src/main/index.ts
    • Updated calls to initializeUsageMonitorForwarding to pass the agentManager instance.
  • apps/frontend/src/main/ipc-handlers/terminal-handlers.ts
    • Imported AgentManager type.
    • Modified initializeUsageMonitorForwarding to accept an optional agentManager parameter.
    • Added an event listener for budget-exhausted to kill all running agents via agentManager.
  • apps/frontend/src/renderer/components/settings/AccountSettings.tsx
    • Added a new 'Usage Limits' section with a slider for budgetCapPercent and a switch for noExtraUsage.
    • Implemented logic to update auto-switch settings based on user interaction with the new controls.
    • Moved the 'Usage Limits' section to be always visible, independent of the number of accounts.
  • apps/frontend/src/shared/i18n/locales/en/settings.json
    • Added new translation keys for 'usageLimits' title and description.
    • Added new translation keys for 'budgetCap', 'budgetCapOff', 'budgetCapDescription', 'noExtraUsage', and 'noExtraUsageDescription' under 'autoSwitching'.
  • apps/frontend/src/shared/i18n/locales/fr/settings.json
    • Added new French translation keys for 'usageLimits' title and description.
    • Added new French translation keys for 'budgetCap', 'budgetCapOff', 'budgetCapDescription', 'noExtraUsage', and 'noExtraUsageDescription' under 'autoSwitching'.
  • apps/frontend/src/shared/types/agent.ts
    • Extended the ClaudeAutoSwitchSettings interface to include budgetCapPercent and noExtraUsage properties with their respective JSDoc comments.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

🎉 Thanks for your first PR!

A maintainer will review it soon. Please make sure:

  • Your branch is synced with develop
  • CI checks pass
  • You've followed our contribution guide

Welcome to the Auto Claude community!

@sentry
Copy link

sentry bot commented Feb 28, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Comment on lines +1113 to +1118
const effectiveSession = settings.budgetCapPercent !== undefined
? Math.min(baseSession, settings.budgetCapPercent)
: baseSession;
const effectiveWeekly = settings.budgetCapPercent !== undefined
? Math.min(baseWeekly, settings.budgetCapPercent)
: baseWeekly;
Copy link

Choose a reason for hiding this comment

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

Bug: The UI allows setting budgetCapPercent to 0. This creates an impossible 0% usage threshold, marking all accounts as unavailable and triggering termination of all running agents.
Severity: HIGH

Suggested Fix

Prevent the budgetCapPercent from being set to 0. This can be done by adjusting the min value of the slider in the UI from 0 to a more sensible minimum, such as 1 or 5.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent.
Verify if this is a real issue. If it is, propose a fix; if not, explain why it's not
valid.

Location: apps/frontend/src/main/claude-profile/usage-monitor.ts#L1113-L1118

Potential issue: The UI slider for `budgetCapPercent` in `AccountSettings.tsx` allows a
minimum value of 0. When this value is set, the logic in `usage-monitor.ts` calculates
effective usage thresholds using `Math.min(baseThreshold, 0)`, which results in 0.
Consequently, any account with usage greater than 0% is considered to have exceeded its
budget. This leads to all accounts being marked as unavailable. When the system tries to
find an alternative account and fails, it emits a `budget-exhausted` event, which in
turn calls `agentManager.killAll()` and terminates all active user agents.

Did we get this right? 👍 / 👎 to inform future reviews.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a budget cap feature to limit token usage by auto-claude. It adds budgetCapPercent and noExtraUsage settings, which are correctly implemented across the profile scoring, usage monitoring, and UI components. The logic to stop agents when the budget is exhausted and no alternative accounts are available is also well-implemented. My main feedback is to refactor some duplicated code for calculating effective thresholds into a shared helper function to improve maintainability.

Comment on lines +73 to +79
// Effective thresholds: budget cap (if set) acts as a ceiling on both thresholds
const effectiveWeeklyThreshold = settings.budgetCapPercent !== undefined
? Math.min(settings.weeklyThreshold, settings.budgetCapPercent)
: settings.weeklyThreshold;
const effectiveSessionThreshold = settings.budgetCapPercent !== undefined
? Math.min(settings.sessionThreshold, settings.budgetCapPercent)
: settings.sessionThreshold;
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

To improve maintainability and adhere to the DRY (Don't Repeat Yourself) principle, consider extracting the logic for calculating effective thresholds into a helper function. This logic is duplicated in several places in this file (calculateFallbackScore, scoreUnifiedAccount, shouldProactivelySwitch) and also in apps/frontend/src/main/claude-profile/usage-monitor.ts in the checkThresholdsExceeded function.

A shared utility function could look like this:

function getEffectiveThresholds(settings: ClaudeAutoSwitchSettings) {
  const baseSession = settings.sessionThreshold ?? 95;
  const baseWeekly = settings.weeklyThreshold ?? 99;

  const effectiveSessionThreshold = settings.budgetCapPercent !== undefined
    ? Math.min(baseSession, settings.budgetCapPercent)
    : baseSession;
  const effectiveWeeklyThreshold = settings.budgetCapPercent !== undefined
    ? Math.min(baseWeekly, settings.budgetCapPercent)
    : baseWeekly;

  return { effectiveSessionThreshold, effectiveWeeklyThreshold };
}

Copy link
Contributor

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/frontend/src/main/claude-profile/usage-monitor.ts (1)

1927-1979: ⚠️ Potential issue | 🔴 Critical

Budget exhaustion can be missed because alternatives aren’t policy-filtered.

At Line 1928-Line 1959, alternatives are collected by auth/availability only. If every alternative is already over budget/no-extra limits, unifiedAccounts.length is still non-zero, so the budget-exhausted branch at Line 1965 may never run.

Suggested fix
   private async performProactiveSwap(
@@
   ): Promise<void> {
     const profileManager = getClaudeProfileManager();
+    const settings = profileManager.getAutoSwitchSettings();
     const excludeIds = new Set([currentProfileId, ...additionalExclusions]);
@@
     for (const profile of oauthProfiles) {
       if (!excludeIds.has(profile.id)) {
+        if (stopIfExhausted && profile.usage) {
+          const session = profile.usage.sessionUsagePercent;
+          const weekly = profile.usage.weeklyUsagePercent;
+          const budgetCap = settings.budgetCapPercent;
+          const overBudgetCap = budgetCap !== undefined && (session >= budgetCap || weekly >= budgetCap);
+          const overNoExtra = !!settings.noExtraUsage && (session >= 100 || weekly >= 100);
+          if (overBudgetCap || overNoExtra) {
+            continue;
+          }
+        }
         const unifiedId = `oauth-${profile.id}`;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/frontend/src/main/claude-profile/usage-monitor.ts` around lines 1927 -
1979, After collecting oauth and api alternatives into unifiedAccounts (from
profileManager.getProfilesSortedByAvailability and loadProfilesFile), filter
unifiedAccounts by the same budget/policy check used for the current profile so
accounts that are over-budget or have "no extra limits" are excluded; e.g. call
the existing budget-check helper (create or reuse a helper like
isAccountWithinBudget or isProfileAllowedByPolicy) for each
unifiedAccount.unifiedId or id and only keep those that pass before checking
unifiedAccounts.length, then if filtered list is empty follow the
stopIfExhausted -> emit('budget-exhausted', ...) or
emit('proactive-swap-failed', ...) branches accordingly (also reference
excludeIds and additionalExclusions when emitting).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/frontend/src/main/claude-profile/usage-monitor.ts`:
- Around line 1105-1124: The function checkThresholdsExceeded currently seeds
baseSession/baseWeekly to 95/99 which causes noExtraUsage-only mode to trigger
before 100%; change the baseline when settings.noExtraUsage is true so
thresholds default to 100 instead of 95/99. Concretely, in
checkThresholdsExceeded adjust how baseSession and baseWeekly are computed (or
override effectiveSession/effectiveWeekly) to use 100 when settings.noExtraUsage
is true, then apply the budgetCapPercent ceiling (Math.min) only afterwards if
budgetCapPercent is provided; keep the rest of the
sessionExceeded/weeklyExceeded checks unchanged and reference the existing
symbols baseSession, baseWeekly, effectiveSession, effectiveWeekly, and
settings.noExtraUsage.

---

Outside diff comments:
In `@apps/frontend/src/main/claude-profile/usage-monitor.ts`:
- Around line 1927-1979: After collecting oauth and api alternatives into
unifiedAccounts (from profileManager.getProfilesSortedByAvailability and
loadProfilesFile), filter unifiedAccounts by the same budget/policy check used
for the current profile so accounts that are over-budget or have "no extra
limits" are excluded; e.g. call the existing budget-check helper (create or
reuse a helper like isAccountWithinBudget or isProfileAllowedByPolicy) for each
unifiedAccount.unifiedId or id and only keep those that pass before checking
unifiedAccounts.length, then if filtered list is empty follow the
stopIfExhausted -> emit('budget-exhausted', ...) or
emit('proactive-swap-failed', ...) branches accordingly (also reference
excludeIds and additionalExclusions when emitting).

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 60c4890 and a5c6f5e.

📒 Files selected for processing (9)
  • apps/frontend/src/main/claude-profile/profile-scorer.ts
  • apps/frontend/src/main/claude-profile/profile-storage.ts
  • apps/frontend/src/main/claude-profile/usage-monitor.ts
  • apps/frontend/src/main/index.ts
  • apps/frontend/src/main/ipc-handlers/terminal-handlers.ts
  • apps/frontend/src/renderer/components/settings/AccountSettings.tsx
  • apps/frontend/src/shared/i18n/locales/en/settings.json
  • apps/frontend/src/shared/i18n/locales/fr/settings.json
  • apps/frontend/src/shared/types/agent.ts

Comment on lines 1105 to +1124
private checkThresholdsExceeded(
usage: ClaudeUsageSnapshot,
settings: { sessionThreshold?: number; weeklyThreshold?: number }
settings: { sessionThreshold?: number; weeklyThreshold?: number; budgetCapPercent?: number; noExtraUsage?: boolean }
): { sessionExceeded: boolean; weeklyExceeded: boolean; anyExceeded: boolean } {
const sessionExceeded = usage.sessionPercent >= (settings.sessionThreshold ?? 95);
const weeklyExceeded = usage.weeklyPercent >= (settings.weeklyThreshold ?? 99);
const baseSession = settings.sessionThreshold ?? 95;
const baseWeekly = settings.weeklyThreshold ?? 99;

// Budget cap acts as a ceiling on both thresholds
const effectiveSession = settings.budgetCapPercent !== undefined
? Math.min(baseSession, settings.budgetCapPercent)
: baseSession;
const effectiveWeekly = settings.budgetCapPercent !== undefined
? Math.min(baseWeekly, settings.budgetCapPercent)
: baseWeekly;

// noExtraUsage: also flag when hitting 100%
const sessionExceeded = usage.sessionPercent >= effectiveSession ||
(!!settings.noExtraUsage && usage.sessionPercent >= 100);
const weeklyExceeded = usage.weeklyPercent >= effectiveWeekly ||
(!!settings.noExtraUsage && usage.weeklyPercent >= 100);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Budget-only mode is still enforcing proactive thresholds.

Line 1109 and Line 1110 always seed 95/99 (or configured) thresholds, so noExtraUsage-only mode can trigger exhaustion flow before 100%. That contradicts the “stop at 100%” behavior.

Suggested fix
-  private checkThresholdsExceeded(
+  private checkThresholdsExceeded(
     usage: ClaudeUsageSnapshot,
-    settings: { sessionThreshold?: number; weeklyThreshold?: number; budgetCapPercent?: number; noExtraUsage?: boolean }
+    settings: { sessionThreshold?: number; weeklyThreshold?: number; budgetCapPercent?: number; noExtraUsage?: boolean },
+    useProactiveThresholds: boolean
   ): { sessionExceeded: boolean; weeklyExceeded: boolean; anyExceeded: boolean } {
-    const baseSession = settings.sessionThreshold ?? 95;
-    const baseWeekly = settings.weeklyThreshold ?? 99;
+    const baseSession = useProactiveThresholds ? (settings.sessionThreshold ?? 95) : 100;
+    const baseWeekly = useProactiveThresholds ? (settings.weeklyThreshold ?? 99) : 100;
-        const thresholds = this.checkThresholdsExceeded(usage, settings);
+        const thresholds = this.checkThresholdsExceeded(usage, settings, isProactiveEnabled);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/frontend/src/main/claude-profile/usage-monitor.ts` around lines 1105 -
1124, The function checkThresholdsExceeded currently seeds
baseSession/baseWeekly to 95/99 which causes noExtraUsage-only mode to trigger
before 100%; change the baseline when settings.noExtraUsage is true so
thresholds default to 100 instead of 95/99. Concretely, in
checkThresholdsExceeded adjust how baseSession and baseWeekly are computed (or
override effectiveSession/effectiveWeekly) to use 100 when settings.noExtraUsage
is true, then apply the budgetCapPercent ceiling (Math.min) only afterwards if
budgetCapPercent is provided; keep the rest of the
sessionExceeded/weeklyExceeded checks unchanged and reference the existing
symbols baseSession, baseWeekly, effectiveSession, effectiveWeekly, and
settings.noExtraUsage.

@AndyMik90 AndyMik90 self-assigned this Mar 2, 2026
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.

3 participants