Skip to content

Auto-resume rate-limited agents - #8132

Closed
leomleao wants to merge 9 commits into
stablyai:mainfrom
leomleao:feat/auto-resume-rate-limited-agents
Closed

leomleao wants to merge 9 commits into
stablyai:mainfrom
leomleao:feat/auto-resume-rate-limited-agents

Conversation

@leomleao

@leomleao leomleao commented Jul 10, 2026 •

Copy link
Copy Markdown

Summary

Opt-in (off by default) auto-resume for agents stalled on a provider usage limit. When Claude Code or Codex hits its limit — an idle banner or a blocking wait-for-reset menu — Orca detects it on the live PTY output (never terminal-history files) and resumes the agent once the limit resets, replacing the flaky external cron (stale banner matches, content-hash blind spots, 30-min polling blackouts).

  • Detection (usage-limit-stall-detection.ts + runtime per-chunk tail scan): matches Claude's banner/menu (whitespace/case-tolerant for collapsed PTY renders) and Codex's You've hit your usage limit … or try again at <date>. Returns the latest match and anchors reset parsing to the newest banner so a second limit event re-arms correctly. A dedicated UsageLimitStallReason keeps rate-limited agents from being misclassified as needing permission.
  • AgentAutoResumeService: menu → wait the configured agent idle grace, re-verify, press Enter ("Stop and wait for limit to reset"); banner → wait max(banner, provider resetsAt) + 90s, re-verify the banner is still live, resend continue, retry once then give up + notify; PTY-exit → notify. Dedups per PTY, caps attempts, clears on resume, never acts on stale data or pokes a working agent.
  • Setting: autoResumeRateLimitedAgents (default false) in Settings → Agents.
  • UX: amber "Rate-limited" worktree indicator, card label Rate-limited · resumes 3:50pm, status-bar segment N paused · resumes … (click focuses the worktree), native notifications; renderer state hydrated on startup via agentAutoResume:get and kept live via a push channel.

Screenshots

This surfaces an amber hourglass worktree indicator when the session is stalled.
image

Testing

  • pnpm lint (oxlint / reliability gates / max-lines ratchet pass; the only failure is a pre-existing ja.json localization-parity drift that also reproduces on main and is untouched by this PR)
  • pnpm typecheck
  • pnpm test (26,522 passed)
  • pnpm build
  • Added/updated tests: detection patterns (incl. Codex fixtures, collapsed-space menu, two-banner anchoring), reset parsing, per-chunk edge trigger, and the full service state machine with fake timers (grace, resetsAt fallback, re-verify, dedup, reason re-arm, retry cap + give-up, cleared/exit, opt-out teardown)

AI Review Report

Reviewed with an AI coding agent (build + adversarial pass) plus CodeRabbit. Main risks checked: detection false positives/negatives on the live tail, timer/state-machine correctness, and re-arming across repeated limit events. It flagged — and this PR fixes — two real correctness bugs: (1) detection returned the first tail match, so a second limit event couldn't re-arm while the old banner was still retained; now returns the latest match, mirroring the blocked-reason signal. (2) Reset parsing read the oldest banner when two coexisted, risking an early resume; now anchored to the newest banner, with two-banner regression tests. Cross-platform: no hardcoded metaKey, no OS-specific paths; timers use setTimeout/unref; keystroke injection reuses the existing terminal.send path; the reset text carries no timezone so it resolves in the runtime host's zone and the service prefers the provider's structured resets_at.

Security Audit

  • IPC: one new read-only channel (agentAutoResume:get) returning a snapshot; one renderer push. No renderer-supplied input executed.
  • Command/keystroke execution: resumes only ever inject a fixed continue/Enter into the already-authenticated agent terminal via the existing sendTerminal path — no shell command construction, no user/remote-controlled payload.
  • Input handling: detection is pure regex over the PTY tail; reset parsing normalizes a matched date and Date-parses it (no eval). Feature is gated behind an opt-in setting (default off).
  • No secrets, auth, or dependency changes.

Notes

  • Detection stays provider-pluggable (gemini/opencode can be added later); v1 covers Claude Code + Codex only.
  • Non-goals: no per-repo/per-worktree overrides; dead-PTY case is notify-only (relaunch stays with the existing sleeping-agent resume path); no automations-subsystem changes.
  • Manual test tooling (usage-limit simulator scripts) lives outside this repo.

ELI5

Optional auto-resume watches live terminal output for Claude/Codex usage-limit stalls and restarts the agent when the limit resets. You do not need a flaky external cron; it stays off by default until you enable it.

leomleao and others added 6 commits July 10, 2026 19:01
Add event-driven detection of Claude Code / Codex usage-limit stalls
against the live PTY tail buffer (never history files). New module
usage-limit-stall-detection.ts matches the wait-for-reset menu and the
idle limit banner (whitespace/case-tolerant for collapsed PTY renders),
reusing the Claude reset parser for resetsAt.

Wired into the runtime per-chunk tail scan via a dedicated
usageLimitSignal + tailGainedNewerUsageLimitStall edge trigger, so the
timer arms once per fresh limit event. A separate UsageLimitStallReason
(not RuntimeTerminalWaitBlockedReason) keeps rate-limited agents from
being misclassified as needing permission. Exposes
subscribeUsageLimitStall / getUsageLimitStallSnapshot and emits
detected/cleared/exited events for the upcoming AgentAutoResumeService.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add the opt-in main-process service that drives resumes off the runtime's
usage-limit stall events:
- usage-limit-menu: wait the user's configured agent idle timeout (menu
  grace), re-verify the menu is still live, then press Enter to select
  "Stop and wait for limit to reset".
- usage-limit-banner: arm max(banner resetsAt, provider resetsAt)+90s,
  re-verify the banner, resend "continue"; retry once then give up +
  notify. Dedups per PTY, caps attempts, clears on resume.
- PTY exit while limited: notify (dead-PTY hand-off).

Wire it in the composition root (subscribe to runtime events, push
snapshots to the renderer, native notifications gated by
NotificationSettings), add the autoResumeRateLimitedAgents global setting
(default false) and toggle it live via registerSettingsHandlers.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Cover banner/menu pattern matching (incl. collapsed-space renders and
/usage-table false negatives), reset-time extraction, the per-chunk edge
trigger, and the full service state machine with fake timers — menu
grace, banner resetsAt+grace, provider-reset fallback, re-verification,
dedup, reason re-arm, retry cap + give-up notify, cleared/exit paths, and
opt-out timer teardown.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…, settings)

- New 'rate-limited' worktree status (amber hourglass indicator), promoted
  below permission/working and above done; fed by a new auto-resume store
  slice mirroring the main-process snapshot push.
- Worktree card status label shows "Rate-limited · resumes 3:50pm".
- Status-bar segment "N paused · resumes 3:50pm"; click focuses the
  soonest-resuming worktree.
- Opt-in settings toggle (default off) mounted in the Agents pane next to
  the keep-awake toggle.
- Preload channel + api-types for agentAutoResume:update, consumed in
  useIpcEvents.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Guard the auto-resume worktree selectors against an absent autoResumeEntries
so section-activity summaries built from partial state snapshots (and early
hydration) don't throw.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Codex phrases its usage-limit reset as "…or try again at Apr 23rd, 2026
10:42 AM." which the Claude "resets …" parser can't read. Add a Codex
reset parser (strips the day ordinal, then Date-parses) tried ahead of the
Claude parser in extractUsageLimitResetAt. Detection already matched the
"hit your usage limit" prefix; the structured resets_at path is still
preferred via the RateLimitService provider cross-check. Covered with the
captured Codex fixtures.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds opt-in auto-resume support for Claude Code and Codex usage-limit stalls. PTY tails detect banner and wait-for-reset states, parse reset times, and emit lifecycle events. A main-process service verifies live state, sends resume keystrokes, retries with limits, handles PTY exits, and delivers notifications. Shared snapshots flow through preload IPC into renderer state, enabling a settings toggle, rate-limited worktree status, status-bar information, and focus behavior. Documentation and Vitest coverage describe provider patterns, parsing, and service state transitions.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and clearly summarizes the main change: auto-resuming rate-limited agents.
Description check ✅ Passed The description matches the template and covers summary, screenshots, testing, AI review, security, and notes, with only minor detail gaps.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🧹 Nitpick comments (2)
src/main/agent-auto-resume-service.test.ts (1)

1-219: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Good coverage of the sequential state machine; consider adding a regression test for the in-flight race.

None of the current tests interleave a detected/cleared/exited event with an in-flight sendKeys(...) await for the same ptyId (all events are dispatched either before a timer fires or after advanceTimersByTimeAsync fully settles). Given the stale-continuation race flagged in agent-auto-resume-service.ts (onActionDue/onPostSendVerify), a test that resolves sendKeys only after dispatching a competing event for the same PTY would directly validate that fix.

Happy to draft this test (deferring sendKeys's mock promise, then calling handleEvent with a different reason before resolving it) if useful.

src/renderer/src/store/slices/auto-resume.ts (1)

62-74: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Hardcoded English strings bypass the app's i18n pipeline.

Unlike auto-resume-copy.ts in this same PR (which routes every user-facing string through translate(...)), formatRateLimitedLabel returns literal English strings. If this label is rendered in worktree cards / the status bar (as its name and the PR stack outline suggest), it will not be localized for non-English users, inconsistent with the rest of the auto-resume feature's copy.

♻️ Proposed fix using the existing translate() pattern
+import { translate } from '`@/i18n/i18n`'
+
 export function formatRateLimitedLabel(resumesAt: number | null): string {
   if (typeof resumesAt !== 'number' || !Number.isFinite(resumesAt)) {
-    return 'Rate-limited · waiting for reset'
+    return translate(
+      'auto.components.sidebar.worktree-section-activity.waiting-for-reset',
+      'Rate-limited · waiting for reset'
+    )
   }
   try {
     const time = new Date(resumesAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })
-    return `Rate-limited · resumes ${time}`
+    return translate(
+      'auto.components.sidebar.worktree-section-activity.resumes-at',
+      'Rate-limited · resumes {{time}}',
+      { time }
+    )
   } catch {
-    return 'Rate-limited · waiting for reset'
+    return translate(
+      'auto.components.sidebar.worktree-section-activity.waiting-for-reset',
+      'Rate-limited · waiting for reset'
+    )
   }
 }

Based on learnings, "when localizing user-facing strings inside settings components... use hash-based locale keys with translate('auto.components.<Dir>.<ComponentFile>.<hash>', 'Default English text')". This label isn't in components/settings/, but is the same class of user-facing copy shipped alongside localized strings elsewhere in this PR — please confirm whether it's actually rendered to the user and, if so, apply the same convention.

Source: Learnings


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ba7aaf4c-e251-4a69-b09f-524dad9e26b0

📥 Commits

Reviewing files that changed from the base of the PR and between 970d446 and 37d8de2.

📒 Files selected for processing (35)
  • notes/auto-resume-rate-limited-agents.md
  • notes/codex-usage-limit-patterns.md
  • src/main/agent-auto-resume-notifications.ts
  • src/main/agent-auto-resume-service.test.ts
  • src/main/agent-auto-resume-service.ts
  • src/main/codex-accounts/runtime-home-service.test.ts
  • src/main/codex-accounts/service.test.ts
  • src/main/index.ts
  • src/main/ipc/register-core-handlers.test.ts
  • src/main/ipc/register-core-handlers.ts
  • src/main/ipc/settings.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/pty-transcript-prune-wait-cache.test.ts
  • src/main/runtime/usage-limit-stall-detection.test.ts
  • src/main/runtime/usage-limit-stall-detection.ts
  • src/main/runtime/usage-limit-tail-state.test.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/settings/AgentsPane.tsx
  • src/renderer/src/components/settings/AutoResumeRateLimitedSetting.tsx
  • src/renderer/src/components/settings/auto-resume-copy.ts
  • src/renderer/src/components/sidebar/StatusIndicator.tsx
  • src/renderer/src/components/sidebar/WorktreeCardStatusSlot.tsx
  • src/renderer/src/components/sidebar/use-worktree-activity-status.ts
  • src/renderer/src/components/sidebar/worktree-section-activity.ts
  • src/renderer/src/components/status-bar/AutoResumeStatusSegment.tsx
  • src/renderer/src/components/status-bar/StatusBar.tsx
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/worktree-status.ts
  • src/renderer/src/store/index.ts
  • src/renderer/src/store/slices/auto-resume.ts
  • src/renderer/src/store/types.ts
  • src/shared/agent-auto-resume-types.ts
  • src/shared/constants.ts
  • src/shared/types.ts

Comment thread src/main/runtime/orca-runtime.ts Resolved
Comment thread src/renderer/src/hooks/useIpcEvents.ts Resolved
leomleao and others added 3 commits July 10, 2026 19:36
…nner

Address review feedback: detectUsageLimitStall returned the first match, so
a second usage-limit event couldn't re-arm the auto-resume timer while the
first banner/menu still sat in the retained tail. Return the latest match
(matchAll over global patterns), matching the blocked-reason signal's
lastIndexOf. Likewise anchor reset parsing to the newest banner (latest Codex
"or try again at" match; Claude scan scoped to the last banner line) so a
stale earlier banner can't supply an old resetsAt and trigger an early resume.

Add two-banner regression tests for both providers and pin the wall-clock
reset tests to a fixed system time.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add an agentAutoResume:get IPC so the renderer syncs the current snapshot on
mount — the service otherwise only pushes on state changes, leaving the card /
status-bar stale if a stall was detected before the subscription. Also tag the
plan-doc fenced block with a language (MD040).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address review feedback: the status-bar segment and rate-limited card label
hard-coded English. Route them through translate() with English fallbacks,
using constant keys (matching the settings-copy pattern) so the localization
catalog verifier — which statically checks only literal keys — stays green
without churning the locale catalogs.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@leomleao

Copy link
Copy Markdown
Author

at the moment plugin is not a viable alternative:

Why PR #8132 Requires Core Engine Implementation

  1. No Live PTY / Terminal Output Streaming (terminal:read)
    • PR Auto-resume rate-limited agents #8132 requirement: Inspects raw PTY chunks in real-time (usage-limit-stall-detection.ts) to detect Claude Code and Codex rate-limit banners and
    menus.
    • Plugin limitation: Orca plugins only have plugin-capabilities.ts:17 (write-only). Orca explicitly does not provide terminal read or PTY interception
    APIs to plugins for security (to prevent third-party plugins from capturing tokens, passwords, or sensitive shell output).
  2. No Core UI Badges or Status Bar Injections
    • PR Auto-resume rate-limited agents #8132 requirement: Displays amber "Rate-limited" badges on worktree cards, stall reason labels, and status bar indicators.
    • Plugin limitation: Plugins can only render within their own isolated sidebar panels (PluginPanel.tsx:220-233). They cannot inject badges or custom
    metadata into Orca's native tab bars, worktree cards, or status bar.
  3. Core Agent State Machine Integration
    • PR Auto-resume rate-limited agents #8132 requirement: Hooks into Orca's internal agent lifecycle (UsageLimitStallReason, agent pause/resume state transitions).
    • Plugin limitation: Plugins can only listen to read-only events (agent.status.changed) via plugin-manifest.ts:65-76. They cannot intercept or mutate
    agent state transitions.
  4. Persistent Host Daemon
    • PR Auto-resume rate-limited agents #8132 requirement: Runs as a daemon in the main process waiting for hours until reset timestamps.
    • Plugin limitation: Plugin worker processes are plugin-host-protocol.ts:112 of inactivity.

@leomleao

Copy link
Copy Markdown
Author

Claude finally does this natively now, and hope that codex will follow suit, rendering this no longer required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants