Skip to content
Source
Sign inSign up
pingdotgg/t3code

Show provider usage-limit stops in the UI instead of failing silently #5077

ClosedZeus-Deus(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/5077/headopened View on GitHub

Problem

When a provider hits a usage window (e.g. Claude's 5-hour or weekly limit), the run just stops with no indication why. Three paths conspired to make the stop silent:

  • the SDK's rate_limit_event (which carries status: "rejected", the window type, and the reset timestamp) was forwarded as account.rate-limits.updated and then dropped — the event had no consumer anywhere in ingestion
  • handleResultMessage ignored terminal_reason, so blocking_limit results collapsed into the generic failed/interrupted buckets with no message
  • a stream that died mid-turn was completed as interrupted, which ingestion + projector mapped to session ready / turn completed / lastError: null — i.e. the UI showed a clean, successful finish

What this does

Contracts — a structured usage-limit concept (windowType, resetsAt, message) flows end to end: TurnCompletedPayload.usageLimit, normalized fields on AccountRateLimitsUpdatedPayload, and OrchestrationSession.usageLimit (persisted via migration 036). Provider-agnostic: messaging is built from structured fields, never raw error strings, so the existing redaction guarantees hold.

Claude adapter — records rejected rate-limit windows on the session context; maps blocking_limit / rapid_refill_breaker terminal reasons; attributes silent stream ends to the recorded limit instead of a benign interrupt; adds a stderr callback that parses the CLI's usage limit reached|<epoch> line as a fallback (only the epoch is kept).

Codex adapter — normalizes its rateLimitReachedType / primary / secondary snapshot onto the same fields (window ≤ 8h → five_hour, else seven_day), driving the same UI.

Ingestion / projector — a usage-limit.reached activity row, session usageLimit set/carried/cleared at the right lifecycle points, and limit-stopped turns settle as interrupted rather than completed.

Web UI — a slim strip docked to the top edge of the composer (a vertical mirror of the branch toolbar below it): hourglass, 5-hour limit reached · resets in 1h 23m, live per-minute countdown, absolute time on hover, and client-side auto-hide the moment the reset passes. The work log gets an amber row at the exact point the run stopped, and the sidebar shows "Usage limit" instead of "Error occurred". No top-of-timeline banner — that slot stays reserved for real errors.

Screenshots

The composer strip while a window is exhausted:

Usage-limit strip above the composer

Close-up — it reads as part of the composer chrome:

Close-up of the strip

The work-log row marking where the run stopped:

Work-log row

Testing

  • pnpm typecheck (all 15 workspaces) and pnpm lint clean
  • new tests: blocking-limit result handling, silent-stream-end attribution, stderr fallback (ClaudeAdapter); banner + work-log row and raw-shape rate-limit set/clear (ingestion); interrupted settle (projector); countdown formatting, dock geometry, and hide-on-expiry (ComposerUsageLimitStrip); plus shared usageLimit helpers
  • full suites green: server 700 passed, web 1699 passed, shared 320, client-runtime 502; the pre-existing imageCompression.test.ts timing flake under parallel load passes in isolation
  • the existing "keeps Claude stream failure events structural" redaction test passes unchanged
  • verified visually against a live dev stack (screenshots above); the auto-hide was also observed live once the seeded reset time passed

Note

Medium Risk Touches provider lifecycle, session projection, and persistence across Claude/Codex ingestion paths; behavior changes how limit stops are classified (ready vs error) and how turns settle, though coverage is strong in adapter and ingestion tests.

Overview Provider usage-window exhaustion is now modeled end-to-end instead of looking like a clean stop or a generic failure.

Contracts & persistence — OrchestrationSession.usageLimit, TurnCompletedPayload.usageLimit, and normalized fields on account.rate-limits.updated carry structured window type, reset time, and messages built from shared @t3tools/shared/usageLimit helpers (not raw provider error text). Migration 036 adds usage_limit on projection_thread_sessions; projection upserts and snapshot queries read/write it.

Claude & Codex adapters — Claude maps blocking_limit / rapid_refill_breaker, rate-limit events, silent stream ends, and CLI stderr usage limit reached|<epoch> into turn.completed with usageLimit and account.rate-limits.updated. Codex normalizes rateLimitReachedType onto the same vocabulary.

Ingestion & projection — Usage-limit stops keep session ready (not error), clear lastError, emit usage-limit.reached work-log activities from turn.completed, set/clear the session banner from rate-limit updates and turn lifecycle, and settle turns as interrupted when usageLimit is set (including in projector and client threadReducer).

Web UI — ComposerUsageLimitStrip docks above the composer with countdown and client-side hide after reset; sidebar prefers “Usage limit” over error; timeline work log uses amber hourglass styling and locale-formatted reset labels.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit fe7d85add8107285aa7d4b7aa3eae9f9f5b1fc3c. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Show provider usage-limit stops in the chat UI instead of failing silently

  • Adds OrchestrationSessionUsageLimit to session contracts and persists it in a new usage_limit column (migration 036) on projection_thread_sessions.
  • Claude and Codex adapters now emit normalized status, windowType, and resetsAt fields on account.rate-limits.updated; Claude also detects blocking_limit/rapid_refill_breaker terminal reasons and stderr usage-limit lines, completing turns as interrupted with a structured usageLimit instead of emitting runtime.error.
  • The orchestration layer sets session.usageLimit on usage-limit turn completions, clears it on new turn starts, and propagates it through rate-limit update events; turns with a usageLimit settle as interrupted in both the server projector and the client reducer.
  • A new ComposerUsageLimitStrip component renders a warning-toned strip above the composer with a live countdown and tooltip; it auto-hides when the reset time passes.
  • The sidebar thread tooltip shows a 'Usage limit' hourglass indicator (taking precedence over error indicators), and timeline work-log rows for usage-limit.reached show an amber hourglass instead of the failure 'x'.
  • Behavioral Change: usage-limit stops no longer set lastError or error status on the session; they are shown as interrupted turns with a dedicated UI strip rather than appearing as errors in the timeline.
📊 Macroscope summarized fe7d85a. 20 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted

🗂️ Filtered Issues

No issues evaluated.

    1. 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: 0e5f8233-c7cc-4334-aec3-a0e3e8bfaf82

      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

      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.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. 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). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit fe7d85add8107285aa7d4b7aa3eae9f9f5b1fc3c. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -1081,3 +1081,4 @@
      10811081 runtimeMode: event.payload.session.runtimeMode,
      10821082 activeTurnId: event.payload.session.activeTurnId,
      10831083 lastError: event.payload.session.lastError,
      1084+ usageLimit: event.payload.session.usageLimit ?? null,

      Durable turns ignore usage-limit settle

      Medium Severity

      applyThreadTurnsProjection still settles leaving-running turns only from session status, so a usage-limit stop (ready + usageLimit) is persisted as completed. The in-memory projector and client reducer already map that case to interrupted, so after a reload from the projection store the turn looks like a clean finish again.

      Additional Locations (2)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit fe7d85add8107285aa7d4b7aa3eae9f9f5b1fc3c. Configure [here](https://www.cursor.com/dashboard/bugbot).
    4. @@ -3640,3 +3776,4 @@
      36403776 lastKnownTotalProcessedTokens: undefined,
      36413777 lastAssistantUuid: resumeState?.resumeSessionAt,
      36423778 lastThreadStartedId: undefined,
      3779+ usageLimit: pendingStderrUsageLimit,

      🟡 Medium Layers/ClaudeAdapter.ts:3779

      pendingStderrUsageLimit is copied into context.usageLimit, but the first-turn startup path unconditionally overwrites context.usageLimit = undefined before consuming the stream. If the CLI emits its fallback usage-limit stderr line during createQuery/session initialization (before sessions.set), the callback buffers it, this line installs it, and starting the turn erases it — so a usage-limit-blocked stream completes as a generic interruption with no usage-limit indication. Preserve the buffered startup signal through the first turn rather than clearing it unconditionally.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/ClaudeAdapter.ts around line 3779:
      
      `pendingStderrUsageLimit` is copied into `context.usageLimit`, but the first-turn startup path unconditionally overwrites `context.usageLimit = undefined` before consuming the stream. If the CLI emits its fallback usage-limit stderr line during `createQuery`/session initialization (before `sessions.set`), the callback buffers it, this line installs it, and starting the turn erases it — so a usage-limit-blocked stream completes as a generic interruption with no usage-limit indication. Preserve the buffered startup signal through the first turn rather than clearing it unconditionally.
      @@ -149,0 +165,21 @@
      165+}
      166+
      167+/**
      168+ * Normalize Codex's rate-limit snapshot onto the shared
      169+ * `account.rate-limits.updated` fields.
      170+ *
      171+ * `rateLimitReachedType` is Codex's authoritative "this account is blocked"
      172+ * flag; anything else is treated as an open window.
      173+ */
      174+function normalizeCodexRateLimitSnapshot(
      175+ snapshot: EffectCodexSchema.V2AccountRateLimitsUpdatedNotification["rateLimits"],
      176+): {
      177+ readonly status?: RuntimeRateLimitStatus;
      178+ readonly windowType?: string;
      179+ readonly resetsAt?: number;
      180+} {
      181+ const reached = snapshot.rateLimitReachedType ?? null;
      182+ if (reached === null) {
      183+ return { status: "allowed" };
      184+ }
      185+ const window = snapshot.primary ?? snapshot.secondary ?? null;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/CodexAdapter.ts:185

      normalizeCodexRateLimitSnapshot always picks snapshot.primary ?? snapshot.secondary, so when rateLimitReachedType is set but the exhausted window is secondary, it publishes the primary window's windowType and resetsAt. The UI then shows the primary window's reset time even though the blocked window is the secondary one, which can hide the usage-limit warning too early. Consider resolving resetsAt and windowType from the window that matches rateLimitReachedType rather than unconditionally preferring primary.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/CodexAdapter.ts around line 185:
      
      `normalizeCodexRateLimitSnapshot` always picks `snapshot.primary ?? snapshot.secondary`, so when `rateLimitReachedType` is set but the exhausted window is `secondary`, it publishes the `primary` window's `windowType` and `resetsAt`. The UI then shows the primary window's reset time even though the blocked window is the secondary one, which can hide the usage-limit warning too early. Consider resolving `resetsAt` and `windowType` from the window that matches `rateLimitReachedType` rather than unconditionally preferring `primary`.
      @@ -149,0 +164,21 @@
      164+ return "seven_day";
      165+}
      166+
      167+/**
      168+ * Normalize Codex's rate-limit snapshot onto the shared
      169+ * `account.rate-limits.updated` fields.
      170+ *
      171+ * `rateLimitReachedType` is Codex's authoritative "this account is blocked"
      172+ * flag; anything else is treated as an open window.
      173+ */
      174+function normalizeCodexRateLimitSnapshot(
      175+ snapshot: EffectCodexSchema.V2AccountRateLimitsUpdatedNotification["rateLimits"],
      176+): {
      177+ readonly status?: RuntimeRateLimitStatus;
      178+ readonly windowType?: string;
      179+ readonly resetsAt?: number;
      180+} {
      181+ const reached = snapshot.rateLimitReachedType ?? null;
      182+ if (reached === null) {
      183+ return { status: "allowed" };
      184+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/CodexAdapter.ts:181

      normalizeCodexRateLimitSnapshot returns { status: "allowed" } whenever rateLimitReachedType is null, ignoring snapshot.spendControlReached. When Codex signals a blocked account via spendControlReached alone, this function reports status "allowed", so downstream ingestion clears or omits the usage-limit state while Codex still cannot run turns. Consider also checking spendControlReached before returning the allowed state.

      -  const reached = snapshot.rateLimitReachedType ?? null;
      -  if (reached === null) {
      -    return { status: "allowed" };
      -  }
      +  const reached = snapshot.rateLimitReachedType ?? null;
      +  const spendControlReached = snapshot.spendControlReached ?? null;
      +  if (reached === null && spendControlReached === null) {
      +    return { status: "allowed" };
      +  }
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/CodexAdapter.ts around lines 181-184:
      
      `normalizeCodexRateLimitSnapshot` returns `{ status: "allowed" }` whenever `rateLimitReachedType` is null, ignoring `snapshot.spendControlReached`. When Codex signals a blocked account via `spendControlReached` alone, this function reports status `"allowed"`, so downstream ingestion clears or omits the usage-limit state while Codex still cannot run turns. Consider also checking `spendControlReached` before returning the allowed state.
    5. Approvability

      Verdict: Needs human review

      3 blocking correctness issues found. This PR introduces a substantial new feature (~1400 lines) that changes runtime behavior across orchestration, persistence, and UI layers. Four unresolved review comments identify potential bugs in turn settlement, rate-limit signal handling, and Codex adapter logic.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    6. Note: GPT-5 on behalf of shivam (@shivamhwp).

      Thanks for working on this. We are closing this because much of the problem is now covered by newer work. #9507 added the Claude and Codex subscription Limits tab, and #7165 added an explanation in the thread when Claude pauses on a usage limit.

      The composer countdown and sidebar badge here are additional UI, so this is not an exact duplicate. However, we would prefer to build on the existing handling rather than revive this broader implementation, which has not been updated since July 31 and now has merge conflicts.

      If you find a remaining case where a provider stops silently on current main, a focused PR for that specific gap would be welcome.

Sign in to join this conversation.