Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(limits): pause, queue and auto-resume when a CLI hits its usage limit

Chaitanya Giri3d0d34fd54a1
diff --git a/src/main/config.ts b/src/main/config.ts
index 43116a8b..7804d62f 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -12,6 +12,7 @@ import {
import { defaultMcpDefaults } from '../shared/mcpCatalog';
import { expandTilde } from './fs';
import type { IntegrationRecord } from '../shared/integrations';
+import type { LimitHold } from '../shared/rateLimit';
/** A recurring auto-dispatched mission fired on an interval by the scheduler. */
export interface ScheduledMission {
@@ -340,8 +341,47 @@ export interface HarnessConfig {
/** Never condense a file smaller than this; also the section-trigger byte floor.
* DECIDED: 16 KB. */
reflectMinBytes?: number;
+
+ // ─── Usage-limit guard (pause, queue, auto-resume) ─────────────────────────
+ /** How the floor reacts when a CLI reports it has hit its usage limit. */
+ limitGuard?: LimitGuardConfig;
+ /** Holds in force, persisted so a restart does not walk straight back into a
+ * wall. RUNTIME STATE, not a setting — written by the gate, never by the
+ * Settings UI, in the same spirit as `autoDeliveryPausedAgents`. */
+ limitHolds?: LimitHold[];
+}
+
+/**
+ * Usage-limit guard settings.
+ *
+ * `enabled` off restores the pre-feature behaviour exactly: nothing watches for
+ * limits, nothing is held, and messages are typed at a capped-out CLI the way
+ * they were before (where the TUI silently eats them).
+ */
+export interface LimitGuardConfig {
+ /** Master switch for detection + holding. */
+ enabled: boolean;
+ /** Lift a hold by itself when its reset time arrives. Off leaves the hold in
+ * place until the operator presses resume — the queue is still preserved,
+ * it just does not restart on its own. */
+ autoResume: boolean;
+ /** Also stand down for transient throttles (burst 429s, "overloaded").
+ * Default OFF: the CLIs retry those themselves within seconds, so holding
+ * for them mostly adds latency to a hiccup that had already resolved. */
+ holdOnThrottle: boolean;
+ /** Raise a desktop notification when a hold starts and when it lifts, so a
+ * limit hit while the window is in the background is not discovered an hour
+ * later. Honoured only when `notifications` is also on. */
+ notify: boolean;
}
+export const DEFAULT_LIMIT_GUARD: LimitGuardConfig = {
+ enabled: true,
+ autoResume: true,
+ holdOnThrottle: false,
+ notify: true
+};
+
const DEFAULTS: HarnessConfig = {
onboardingComplete: false,
harnessHome: null,
@@ -394,6 +434,12 @@ const DEFAULTS: HarnessConfig = {
reflectSectionTrigger: 50,
reflectRecentKeep: 12,
reflectMinBytes: 16_384,
+ // Usage-limit guard — ON by default. The behaviour it replaces is a silent
+ // data-loss bug (a message typed at a capped-out CLI is swallowed by its TUI
+ // and never runs), so shipping it dark would leave the bug in place for
+ // everyone who never finds the setting.
+ limitGuard: DEFAULT_LIMIT_GUARD,
+ limitHolds: [],
// Enterprise Knowledge Graph — opt-in; dark until the user enables it.
// v0.3.4 fix: default OFF, matching the field's own documentation ("Default
// OFF / dark until enabled") — the true default contradicted it. Existing
diff --git a/src/main/index.ts b/src/main/index.ts
index b5fac95f..5332ce89 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -14,7 +14,8 @@ import { initAutoUpdater } from './updater';
import { RealtimeFloorWatcher } from './realtimeFloorWatcher';
import {
readConfig, writeConfig, resetConfig, ensureHarnessHome, ensureClaudePermissionsAccepted,
- modelForRole, OPS_STANDUP_MISSION, HEARTBEAT_MISSION, COMPACT_MAINTENANCE_MISSION, type HarnessConfig, type ScheduledMission
+ modelForRole, OPS_STANDUP_MISSION, HEARTBEAT_MISSION, COMPACT_MAINTENANCE_MISSION, DEFAULT_LIMIT_GUARD,
+ type HarnessConfig, type ScheduledMission
} from './config';
import { listDir, readFileText, writeFileText, statAbs, expandTilde } from './fs';
import {
@@ -45,6 +46,8 @@ import * as integrations from './integrations';
import { validateBaseUrl, buildAuthHeaders, resolveUpstreamUrl, secretRefFor, INTEGRATION_TEMPLATES } from '../shared/integrations';
import { RosterStore } from './roster';
import { ControlRegistry } from './control';
+import { LimitGate, scopeFor, type LimitHold } from './limitGate';
+import type { LimitSignal } from '../shared/rateLimit';
import { fetchHireManifest, readHireManifestFile } from './hire';
import { parseHireDeepLink, type HireManifest } from '../shared/hire';
import { ClosingTimeController } from './closingTime';
@@ -217,6 +220,10 @@ const hive = new HiveManager(
// #7C — operator control state (pause/gate/steer/halt), read by the HookServer
// when deciding hook returns.
const control = new ControlRegistry();
+// Usage-limit holds. Lives in main so it survives a renderer reload — a floor
+// that forgot it was rate limited every time the window refreshed would type
+// straight back into the wall it was told about.
+const limitGate = new LimitGate();
// Stage 7A — the live observability tap. Receives Claude Code's first-party OTel
// over loopback OTLP/JSON and exposes the locked usage-provider seam. resolveCwd
// lets the transcript fallback find an agent's cwd from the hive registry.
@@ -608,7 +615,12 @@ function syncMissions(): void {
// renderer, which queues a /compact per agent (deduped — never two at
// once) and delivers it only when that agent goes idle (its drain loop),
// so a working agent compacts between steps, never mid-step.
- if (m.autoCompact || m.kind === 'compact') {
+ // Skip compaction entirely while anything is rate limited. /compact is a
+ // model call: sending it into a capped-out CLI spends a rejected attempt
+ // and, worse, leaves a queued /compact ahead of the operator's real
+ // backlog when the window reopens. The next tick picks it up.
+ const compactionHeld = limitGuardSettings().enabled && limitGate.list().length > 0;
+ if ((m.autoCompact || m.kind === 'compact') && !compactionHeld) {
try { liveWebContents()?.send('mission:autoCompact'); } catch { /* window gone */ }
}
const current = readConfig().missions ?? [];
@@ -2981,6 +2993,122 @@ ipcMain.handle('control:halt', (_evt, agentId: unknown) => {
ipcMain.handle('control:snapshot', (_evt, agentId: unknown) =>
typeof agentId === 'string' ? control.snapshot(agentId) : null);
+// ─── Usage-limit guard: stand down, hold the queue, resume by itself ─────────
+// The renderer watches each PTY for "you've hit your limit" (shared/rateLimit.ts)
+// and reports here; main owns the holds, the timer and the persistence. The
+// renderer's drain loop asks `limitHolds` before every send, so a held provider
+// simply stops being written to while its queue keeps filling — nothing is
+// dropped and nothing needs the operator to remember to resend.
+//
+// Deliberately NOT gated: `hive.send`, which writes a message into an agent's
+// inbox file. That is already a queue — the message waits on disk until the
+// agent next runs — so gating it would turn "delayed" into "lost".
+
+function limitGuardSettings(): typeof DEFAULT_LIMIT_GUARD {
+ return { ...DEFAULT_LIMIT_GUARD, ...(readConfig().limitGuard ?? {}) };
+}
+
+/** Persist holds and tell every floor. Both windows drain their own agents, so
+ * a hold known to only one of them would let the other keep typing. */
+function publishLimits(): void {
+ const holds = limitGate.list();
+ try { writeConfig({ limitHolds: holds }); }
+ catch { /* unwritable config — the in-memory gate still holds this session */ }
+ for (const w of allWindows) {
+ if (w.isDestroyed() || w.webContents.isDestroyed()) continue;
+ try { w.webContents.send('limit:changed', holds); } catch { /* window going away */ }
+ }
+}
+
+function limitToast(title: string, body: string): void {
+ const cfg = readConfig();
+ if (!cfg.notifications || !limitGuardSettings().notify) return;
+ try { if (Notification.isSupported()) new Notification({ title, body }).show(); }
+ catch { /* unsupported platform */ }
+}
+
+/** "resumes in 2h 14m" / "resumes at 3:05pm" — short enough for a toast. */
+function describeHold(hold: LimitHold): string {
+ const mins = Math.max(1, Math.round((hold.resetAt - Date.now()) / 60_000));
+ const when = mins >= 90
+ ? new Date(hold.resetAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })
+ : `${mins}m`;
+ return mins >= 90 ? `resumes at ${when}` : `resumes in ${when}`;
+}
+
+ipcMain.handle('limit:report', (_evt, payload: unknown) => {
+ if (!limitGuardSettings().enabled) return null;
+ const p = payload as { agentId?: unknown; provider?: unknown; signal?: LimitSignal } | null;
+ if (!p || typeof p.agentId !== 'string' || typeof p.provider !== 'string') return null;
+ const signal = p.signal;
+ if (!signal || (signal.tier !== 'quota' && signal.tier !== 'throttle')) return null;
+ // A transient 429 is the CLI's problem, not ours: it retries within seconds,
+ // so standing the floor down for it adds latency to a hiccup that had already
+ // resolved. Only hold for throttles when the operator asked us to.
+ if (signal.tier === 'throttle' && !limitGuardSettings().holdOnThrottle) return null;
+
+ const hold = limitGate.arm({
+ agentId: p.agentId,
+ provider: p.provider as AgentProvider,
+ signal,
+ now: Date.now()
+ });
+ if (!hold) return null; // judged a repaint of a notice already served
+ publishLimits();
+ if (hold.armedAt >= Date.now() - 2000) {
+ limitToast(`${p.provider} limit reached`, `Queue held — ${describeHold(hold)}.`);
+ }
+ return hold;
+});
+
+ipcMain.handle('limit:list', () => limitGate.list());
+
+/** Operator pressed "resume now", or an agent was removed. */
+ipcMain.handle('limit:release', (_evt, scope: unknown) => {
+ if (typeof scope !== 'string') return false;
+ const released = limitGate.release(scope, Date.now());
+ if (released) publishLimits();
+ return released;
+});
+
+/** The renderer got a message through. This is what lets a genuine second
+ * rejection re-arm inside the guard window (see LimitGate.noteDelivery). */
+ipcMain.handle('limit:noteDelivery', (_evt, agentId: unknown, provider: unknown) => {
+ if (typeof agentId !== 'string' || typeof provider !== 'string') return false;
+ limitGate.noteDelivery(provider as AgentProvider, agentId, Date.now());
+ return true;
+});
+
+/**
+ * Lift holds whose time has come.
+ *
+ * Ticks every 15s rather than arming one timer per hold: holds are few, a
+ * coarse tick cannot drift, and — the reason that actually matters — a laptop
+ * that slept through a reset wakes up and lifts on the next tick, whereas a
+ * setTimeout would have been suspended and fired late by however long the lid
+ * was shut.
+ */
+setInterval(() => {
+ const guard = limitGuardSettings();
+ // Guard switched off: let everything go at once. Without this the holds would
+ // outlive the setting — the drain reads the hold list, not the flag, so a
+ // disabled guard would still be silently stopping the floor.
+ if (!guard.enabled) {
+ if (limitGate.releaseAll(Date.now()).length) publishLimits();
+ return;
+ }
+ // Auto-resume off means the hold waits for the operator, so nothing is swept.
+ // The UI keeps showing it (past its reset time) with a resume button — see
+ // LimitGate.holdFor on why expiry is a sweep, not a timestamp comparison.
+ if (!guard.autoResume) return;
+ const lifted = limitGate.sweep(Date.now());
+ if (!lifted.length) return;
+ publishLimits();
+ for (const h of lifted) {
+ limitToast(`${h.provider} limit reset`, 'Sending the queued messages now, one at a time.');
+ }
+}, 15_000).unref?.();
+
// ─── IPC: scheduled missions (recurring auto-dispatch) ──────────────────────
ipcMain.handle('missions:list', () => readConfig().missions ?? []);
ipcMain.handle('missions:save', (_evt, missions) => {
@@ -3871,6 +3999,11 @@ app.whenReady().then(() => {
// setMicGate(true)); macOS TCC stays a second gate regardless.
if (readConfig().realtimeVoiceEnabled) writeConfig({ realtimeVoiceEnabled: false });
+ // Reinstate usage-limit holds. A limit does not lapse because the app was
+ // closed, so quitting and reopening must not be a way to walk back into the
+ // wall — `hydrate` keeps only holds with time genuinely left.
+ limitGate.hydrate({ holds: readConfig().limitHolds ?? [] }, Date.now());
+
// A cold-start deep link (Windows/Linux) rides in on OUR argv.
const startupHireLink = process.argv.find((a) => a.startsWith('munderdifflin://'));
if (startupHireLink) void handleHireLink(startupHireLink);
diff --git a/src/main/limitGate.ts b/src/main/limitGate.ts
new file mode 100644
index 00000000..955c1618
--- /dev/null
+++ b/src/main/limitGate.ts
@@ -0,0 +1,233 @@
+/**
+ * LIMIT GATE — the floor's response to "you're cut off until 3pm".
+ *
+ * `shared/rateLimit.ts` decides whether a chunk of terminal output is a limit
+ * notice. This decides what the harness does about it: hold a scope, keep the
+ * backlog intact, and lift by itself when the window reopens. Nothing is
+ * dropped and nothing needs the operator to remember to resend — which is the
+ * whole point, because the failure this replaces is silent. A message typed at a
+ * rate-limited CLI is swallowed by its TUI, and the human only finds out later
+ * that an hour of instructions went nowhere.
+ *
+ * ── Why holds are per PROVIDER, not per agent ─────────────────────────────────
+ * A usage limit belongs to an ACCOUNT. Six workers running `claude` share one
+ * subscription, so the moment one of them hits the wall the other five are
+ * already behind it — they just haven't spoken yet. Holding only the agent that
+ * happened to print the banner would let the next five walk into the same wall
+ * one at a time, losing a message each. So the scope key is the provider.
+ *
+ * The exception is `custom`, where the command is an arbitrary binary the user
+ * supplied: two custom agents have no reason to share an account, so those hold
+ * per agent. `scopeFor` is the single place that decision lives.
+ *
+ * This trades a little precision for safety: an operator who deliberately runs
+ * two Claude accounts across different agents will see both held when one hits a
+ * limit. `release()` is one click, and over-holding costs a wait while
+ * under-holding costs lost instructions.
+ *
+ * Runs in the Electron main process and imports no electron API, so it is
+ * unit-testable and so the authority survives a renderer reload — a floor that
+ * forgot it was rate limited every time the window refreshed would be worse than
+ * no gate at all.
+ */
+import type { AgentProvider } from '../shared/agentProvider';
+import { backoffFor, MAX_HOLD_MS, scopeFor, type LimitHold, type LimitSignal } from '../shared/rateLimit';
+
+// Re-exported so main-process callers have one import for the gate's surface.
+export { scopeFor };
+export type { LimitHold };
+
+/** Serialisable form persisted across restarts. */
+export interface LimitGateState {
+ holds: LimitHold[];
+}
+
+/**
+ * A repaint of the same banner shortly after a release is the same event, not a
+ * fresh rejection — TUIs redraw their scrollback constantly. Only an identical
+ * evidence line inside this window is suppressed, and only while nothing has
+ * actually been delivered since; once a real message goes out, a limit notice
+ * is genuinely new information.
+ */
+const REARM_GUARD_MS = 90_000;
+
+/**
+ * How long a scope's rebuff count survives. Past this, a fresh limit is treated
+ * as the first one and gets the short end of the backoff ladder again —
+ * otherwise an agent that hit its weekly cap once would still be serving
+ * two-hour waits a month later.
+ */
+const ESCALATION_WINDOW_MS = 6 * 60 * 60_000;
+
+export class LimitGate {
+ private readonly holds = new Map<string, LimitHold>();
+ /** Rebuff memory that outlives the hold itself, so backoff can escalate. */
+ private readonly attempts = new Map<string, { count: number; at: number }>();
+ /** When a scope was last released, and whether anything has been delivered
+ * through it since — together these are what tell a real re-hit apart from a
+ * repaint of the banner still sitting in the scrollback. */
+ private readonly released = new Map<string, { at: number; evidence: string; delivered: boolean }>();
+
+ /**
+ * Record a limit notice. Returns the hold in force afterwards, or null when
+ * the signal was judged to be a repaint of one already handled.
+ *
+ * Idempotent on purpose: a TUI may emit the same banner on every frame, and
+ * arming must not ratchet the wait upward each time.
+ */
+ arm(input: {
+ agentId: string;
+ provider: AgentProvider;
+ signal: LimitSignal;
+ now: number;
+ }): LimitHold | null {
+ const { agentId, provider, signal, now } = input;
+ const scope = scopeFor(provider, agentId);
+
+ const existing = this.holds.get(scope);
+ if (existing && existing.resetAt > now) {
+ // Already held. Take the LATER reset and the MORE severe tier: a repaint
+ // showing an older, nearer time must never shorten a hold, or a screen
+ // redraw could release the floor early into a closed window.
+ const merged: LimitHold = {
+ ...existing,
+ tier: signal.tier === 'quota' ? 'quota' : existing.tier,
+ resetAt: Math.max(existing.resetAt, signal.resetAt),
+ resetSource: signal.resetAt > existing.resetAt ? signal.resetSource : existing.resetSource,
+ evidence: signal.evidence || existing.evidence
+ };
+ this.holds.set(scope, merged);
+ return merged;
+ }
+
+ const priorRelease = this.released.get(scope);
+ if (
+ priorRelease
+ && now - priorRelease.at < REARM_GUARD_MS
+ && !priorRelease.delivered
+ && priorRelease.evidence === signal.evidence
+ ) {
+ // Same words, no message actually sent since we let go: the terminal is
+ // redrawing the notice we already served, not reporting a new one.
+ return null;
+ }
+
+ const memory = this.attempts.get(scope);
+ const attempt = memory && now - memory.at < ESCALATION_WINDOW_MS ? memory.count : 0;
+ this.attempts.set(scope, { count: attempt + 1, at: now });
+
+ // An estimated reset is re-derived here rather than trusted from the signal,
+ // because only the gate knows how many times this scope has been rebuffed.
+ const resetAt = signal.resetSource === 'stated'
+ ? signal.resetAt
+ : now + backoffFor(signal.tier, attempt);
+
+ const hold: LimitHold = {
+ scope,
+ provider,
+ agentId,
+ tier: signal.tier,
+ resetAt: Math.min(Math.max(resetAt, now + 1000), now + MAX_HOLD_MS),
+ armedAt: now,
+ resetSource: signal.resetSource,
+ evidence: signal.evidence,
+ attempts: attempt + 1
+ };
+ this.holds.set(scope, hold);
+ this.released.delete(scope);
+ return hold;
+ }
+
+ /**
+ * The hold blocking this agent, or null if it may be spoken to.
+ *
+ * Deliberately does NOT check the clock. A hold ends when it is SWEPT, not
+ * when its timestamp passes, because that is the only way "resume
+ * automatically: off" can mean anything — under a time-based read the hold
+ * would lapse on its own and the setting would be decorative. With auto-resume
+ * on, the 15s sweep makes the difference invisible.
+ */
+ holdFor(provider: AgentProvider, agentId: string): LimitHold | null {
+ return this.holds.get(scopeFor(provider, agentId)) ?? null;
+ }
+
+ /** Lift a hold — either the timer expired or the operator pressed resume. */
+ release(scope: string, now: number): boolean {
+ const hold = this.holds.get(scope);
+ if (!hold) return false;
+ this.holds.delete(scope);
+ this.released.set(scope, { at: now, evidence: hold.evidence, delivered: false });
+ return true;
+ }
+
+ /**
+ * Note that a message really did reach a scope. This is what lets a genuine
+ * second rejection re-arm inside the guard window: if we sent something and
+ * the wall is still there, that is new information rather than an echo.
+ */
+ noteDelivery(provider: AgentProvider, agentId: string, now: number): void {
+ const entry = this.released.get(scopeFor(provider, agentId));
+ if (entry) entry.delivered = true;
+ void now;
+ }
+
+ /**
+ * Drop every hold whose time has come. Returns the scopes that just lifted so
+ * the caller can tell the floor to start draining again.
+ */
+ sweep(now: number): LimitHold[] {
+ const lifted: LimitHold[] = [];
+ for (const [scope, hold] of this.holds) {
+ if (hold.resetAt <= now) {
+ lifted.push(hold);
+ this.holds.delete(scope);
+ this.released.set(scope, { at: now, evidence: hold.evidence, delivered: false });
+ }
+ }
+ return lifted;
+ }
+
+ /** Every hold in force, soonest first. Includes holds whose time has passed
+ * but which have not been swept — with auto-resume off that is the steady
+ * state, and the UI needs them so it can say "reset time passed, press
+ * resume" rather than showing nothing while the queue stays stopped. */
+ list(): LimitHold[] {
+ return Array.from(this.holds.values()).sort((a, b) => a.resetAt - b.resetAt);
+ }
+
+ /** Drop every hold unconditionally (the operator turned the guard off).
+ * Returns what was lifted so the caller can report it. */
+ releaseAll(now: number): LimitHold[] {
+ const all = this.list();
+ for (const h of all) this.release(h.scope, now);
+ return all;
+ }
+
+ /** Forget a scope entirely, rebuff count included (agent deleted / provider
+ * switched). Distinct from `release`, which remembers we just let go. */
+ forget(scope: string): void {
+ this.holds.delete(scope);
+ this.attempts.delete(scope);
+ this.released.delete(scope);
+ }
+
+ /** Persisted form. Only holds with time genuinely left — an expired one is
+ * worth showing in this session's UI but not worth reinstating tomorrow. */
+ serialize(now: number): LimitGateState {
+ return { holds: this.list().filter((h) => h.resetAt > now) };
+ }
+
+ /**
+ * Restore holds across a restart. A limit does not lapse because the app was
+ * closed, so a hold with time left is reinstated; anything already expired or
+ * malformed is discarded rather than trusted.
+ */
+ hydrate(state: LimitGateState | undefined, now: number): void {
+ this.holds.clear();
+ for (const h of state?.holds ?? []) {
+ if (!h || typeof h.scope !== 'string' || typeof h.resetAt !== 'number') continue;
+ if (h.resetAt <= now || h.resetAt > now + MAX_HOLD_MS) continue;
+ this.holds.set(h.scope, { ...h, attempts: Number(h.attempts) || 1 });
+ }
+ }
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index d90bd95e..b2c56d20 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -5,6 +5,7 @@ export type { HireManifest } from '../shared/hire';
import type { IntegrationRecord, IntegrationTemplate } from '../shared/integrations';
export type { IntegrationRecord, IntegrationTemplate } from '../shared/integrations';
import type { UpdateStatus } from '../shared/updateState';
+import type { LimitHold, LimitSignal } from '../shared/rateLimit';
export type { UpdateStatus } from '../shared/updateState';
/** Renderer-visible integration record: the secretRef handle is redacted to a
@@ -311,6 +312,16 @@ export interface HarnessConfig {
providerBaseUrls?: Partial<Record<AgentProvider, string>>;
/** Per-CLI-provider default model slug, used to pre-fill the model picker. */
providerDefaultModels?: Partial<Record<AgentProvider, string>>;
+ /** How the floor reacts when a CLI reports it has hit its usage limit. */
+ limitGuard?: LimitGuardConfig;
+}
+
+/** Mirrors `LimitGuardConfig` in main/config.ts. */
+export interface LimitGuardConfig {
+ enabled: boolean;
+ autoResume: boolean;
+ holdOnThrottle: boolean;
+ notify: boolean;
}
export interface MemoryStatus {
@@ -945,6 +956,29 @@ const api = {
/** Read an agent's current control snapshot. */
controlSnapshot: (agentId: string): Promise<AgentControlSnapshot | null> =>
ipcRenderer.invoke('control:snapshot', agentId),
+ // ─── Usage-limit guard (pause → queue → auto-resume) ───────────────────────
+ /** Report a limit notice seen in an agent's terminal. Returns the hold now in
+ * force, or null when main judged it a repaint of one already served. */
+ limitReport: (payload: {
+ agentId: string;
+ provider: AgentProvider;
+ signal: LimitSignal;
+ }): Promise<LimitHold | null> => ipcRenderer.invoke('limit:report', payload),
+ /** Every hold currently in force, soonest first. */
+ limitList: (): Promise<LimitHold[]> => ipcRenderer.invoke('limit:list'),
+ /** Lift a hold early ("resume now"). */
+ limitRelease: (scope: string): Promise<boolean> => ipcRenderer.invoke('limit:release', scope),
+ /** Tell main a queued message actually reached this agent, so a limit seen
+ * afterwards is treated as a fresh rejection rather than a stale banner. */
+ limitNoteDelivery: (agentId: string, provider: AgentProvider): Promise<boolean> =>
+ ipcRenderer.invoke('limit:noteDelivery', agentId, provider),
+ /** Subscribe to hold changes (armed, released, expired); returns unsubscribe fn. */
+ onLimitChanged: (cb: (holds: LimitHold[]) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, holds: LimitHold[]) => cb(holds);
+ ipcRenderer.on('limit:changed', listener);
+ return () => ipcRenderer.removeListener('limit:changed', listener);
+ },
+
/** Subscribe to gate/deny events (a tool was blocked); returns unsubscribe fn. */
onApprovalRequest: (cb: (e: { agentId: string; tool?: string; reason?: string }) => void): (() => void) => {
const listener = (_e: IpcRendererEvent, payload: { agentId: string; tool?: string; reason?: string }) => cb(payload);
diff --git a/src/renderer/src/components/AgentDetailPanel.tsx b/src/renderer/src/components/AgentDetailPanel.tsx
index b1b73ed8..cea797ad 100644
--- a/src/renderer/src/components/AgentDetailPanel.tsx
+++ b/src/renderer/src/components/AgentDetailPanel.tsx
@@ -12,6 +12,7 @@ import { SidebarTabs } from './SidebarTabs';
import { ThreadsPanel } from './ThreadsPanel';
import { ToolWaterfall } from './ToolWaterfall';
import { AgentControlStrip } from './AgentControlStrip';
+import { LimitBanner } from './LimitBanner';
import { GitTab } from './GitTab';
import { Icon } from './Icon';
import { useStore, type Agent } from '@/store/store';
@@ -146,6 +147,11 @@ export function AgentDetailPanel({ agent }: AgentDetailPanelProps) {
}}>{openTerminalError}</div>
)}
+ {/* Usage-limit hold: why this agent stopped and when it starts again.
+ Above the control strip because it explains the silence the operator
+ is looking at; renders nothing when nothing is held. */}
+ {isReal && <LimitBanner agentId={agent.id} />}
+
{/* #7C — operator control (pause / halt / steer) for live agents */}
{isReal && <AgentControlStrip agentId={agent.id} />}
diff --git a/src/renderer/src/components/CommandCenterPanel.tsx b/src/renderer/src/components/CommandCenterPanel.tsx
index f59501cc..dab6dc13 100644
--- a/src/renderer/src/components/CommandCenterPanel.tsx
+++ b/src/renderer/src/components/CommandCenterPanel.tsx
@@ -17,6 +17,7 @@ import { useFleetTelemetry } from '@/hooks/useTelemetry';
import { COMMAND_GROUPS } from '@shared/claudeCommands';
import { useStore, type Agent } from '@/store/store';
import { usePtyParser } from '@/hooks/usePtyParser';
+import { LimitBanner, LimitSummary } from './LimitBanner';
import {
buildSpawnCommand,
decodeProviderModel,
@@ -183,6 +184,13 @@ export function CommandCenterPanel({ agent, fullscreen = false }: { agent: Agent
</div>
</div>
+ {/* Floor-wide limit summary + this agent's own hold. The summary is here
+ rather than only on the agent card because a limit usually lands on an
+ agent nobody has selected — the operator's first clue that the floor
+ stopped moving should not require finding the right terminal. */}
+ <div style={{ padding: '0 8px', flexShrink: 0 }}><LimitSummary /></div>
+ <LimitBanner agentId={agent.id} />
+
{/* Tab bar — an auto-fit grid of equal-width cells. The tabs wrap onto
extra rows when the panel is narrow (e.g. window fullscreen), but every
column is the same width so the rows line up cleanly. The old flex-wrap
diff --git a/src/renderer/src/components/FullscreenTerminal.tsx b/src/renderer/src/components/FullscreenTerminal.tsx
index a7b85d81..03ab3829 100644
--- a/src/renderer/src/components/FullscreenTerminal.tsx
+++ b/src/renderer/src/components/FullscreenTerminal.tsx
@@ -6,6 +6,7 @@ import { PtyTerminalView } from './PtyTerminalView';
import { terminalInstanceKey } from './terminalRecovery';
import { MessageQueueComposer } from './MessageQueueComposer';
import { AgentControlStrip } from './AgentControlStrip';
+import { LimitBanner } from './LimitBanner';
import { CommandCenterPanel } from './CommandCenterPanel';
import { Icon } from './Icon';
import { SpritePortrait } from './SpritePortrait';
@@ -466,6 +467,7 @@ export function FullscreenTerminal({ config }: FullscreenTerminalProps) {
{/* #7C — pause / halt / steer. These only existed in the docked
sidebar, so going fullscreen took the operator controls away. */}
+ <LimitBanner key={`limit-${agent.id}`} agentId={agent.id} />
<AgentControlStrip key={agent.id} agentId={agent.id} />
<div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
diff --git a/src/renderer/src/components/LimitBanner.tsx b/src/renderer/src/components/LimitBanner.tsx
new file mode 100644
index 00000000..14b28583
--- /dev/null
+++ b/src/renderer/src/components/LimitBanner.tsx
@@ -0,0 +1,124 @@
+import { useEffect, useState } from 'react';
+import { useStore } from '@/store/store';
+import { inferAgentProvider } from '@/store/config';
+import { scopeFor, type LimitHold } from '@shared/rateLimit';
+import { PixelButton } from './PixelButton';
+
+/**
+ * "This agent is capped until 3pm — 4 messages are waiting."
+ *
+ * Renders nothing unless the agent's provider is actually held, so it costs a
+ * hidden div in the common case. When it does appear it has to answer three
+ * questions without the operator opening a terminal: WHY we stopped (the CLI's
+ * own words), WHEN we start again, and WHAT is waiting. A silent pause with no
+ * explanation would be a worse bug than the one this feature fixes.
+ */
+export function LimitBanner({ agentId }: { agentId: string }) {
+ const agent = useStore((s) => s.agents.find((a) => a.id === agentId));
+ const holds = useStore((s) => s.limitHolds);
+ const queued = useStore((s) => s.messageQueues[agentId]?.length ?? 0);
+ const releaseQueued = useStore((s) => s.releaseQueuedMessage);
+ const [, tick] = useState(0);
+
+ const provider = agent ? inferAgentProvider(agent.command, agent.provider) : null;
+ const scope = provider ? scopeFor(provider, agentId) : null;
+ const hold = scope ? holds.find((h) => h.scope === scope) : undefined;
+
+ // Re-render once a second so the countdown counts. Only while held — an idle
+ // floor must not wake React every second for a banner nobody is showing.
+ useEffect(() => {
+ if (!hold) return;
+ const iv = setInterval(() => tick((n) => n + 1), 1000);
+ return () => clearInterval(iv);
+ }, [hold?.scope, hold?.resetAt]);
+
+ if (!hold) return null;
+
+ const resumeNow = async (): Promise<void> => {
+ await window.cth.limitRelease(hold.scope).catch(() => { /* already lifted */ });
+ };
+
+ // "Send anyway" marks the head of the queue manual, which is the same escape
+ // hatch the floor-wide delivery pause already uses — one override, one meaning.
+ const sendAnyway = (): void => {
+ const head = useStore.getState().messageQueues[agentId]?.[0];
+ if (head) releaseQueued(agentId, head.id);
+ };
+
+ return (
+ <div style={{
+ display: 'flex', flexDirection: 'column', gap: 4,
+ padding: '6px 8px', background: 'var(--cth-paper-100)',
+ boxShadow: 'inset 0 0 0 1px var(--cth-coral)', flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
+ <span style={{
+ fontFamily: 'var(--cth-font-display)', fontSize: 9,
+ color: 'var(--cth-coral)', letterSpacing: '0.04em'
+ }}>
+ {hold.tier === 'quota' ? 'LIMIT REACHED' : 'THROTTLED'}
+ </span>
+ <span style={{ fontSize: 11, color: 'var(--cth-ink-900)' }}>
+ {hold.provider} paused · {countdown(hold.resetAt)}
+ </span>
+ <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }}>
+ {queued === 0
+ ? 'nothing queued yet'
+ : `${queued} message${queued === 1 ? '' : 's'} held — ${queued === 1 ? 'it goes' : 'they go'} out one at a time`}
+ </span>
+ <div style={{ flex: 1 }} />
+ {queued > 0 && (
+ <PixelButton variant="secondary" size="sm" onClick={sendAnyway}>send anyway</PixelButton>
+ )}
+ <PixelButton variant="primary" size="sm" onClick={resumeNow}>resume now</PixelButton>
+ </div>
+ <span style={{ fontSize: 11, color: 'var(--cth-ink-500)' }} title={hold.evidence}>
+ {hold.resetSource === 'stated' ? 'Reset time from the CLI' : 'Estimated — the CLI gave no reset time'}
+ {' · '}
+ {truncate(hold.evidence, 96)}
+ </span>
+ </div>
+ );
+}
+
+/**
+ * "resumes in 2h 14m" — minutes below an hour, never a bare "0m".
+ *
+ * Past the reset it says "reset time reached" rather than "resuming…", because
+ * the hold may be waiting on the operator: with auto-resume off it sits here
+ * until the button is pressed, and promising a resume that never comes would be
+ * the worst thing this banner could say.
+ */
+function countdown(resetAt: number): string {
+ const ms = resetAt - Date.now();
+ if (ms <= 0) return 'reset time reached';
+ const mins = Math.ceil(ms / 60_000);
+ if (mins < 60) return `resumes in ${mins}m`;
+ const h = Math.floor(mins / 60);
+ const m = mins % 60;
+ return m ? `resumes in ${h}h ${m}m` : `resumes in ${h}h`;
+}
+
+function truncate(s: string, n: number): string {
+ const t = s.trim();
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
+}
+
+/** Floor-wide summary for the god's Command Center header — one line per hold,
+ * so a limit on an agent nobody has selected is still visible. */
+export function LimitSummary() {
+ const holds = useStore((s) => s.limitHolds);
+ if (!holds.length) return null;
+ return (
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
+ {holds.map((h: LimitHold) => (
+ <span key={h.scope} style={{
+ fontSize: 11, color: 'var(--cth-coral)',
+ padding: '1px 4px', boxShadow: 'inset 0 0 0 1px var(--cth-coral)'
+ }}>
+ {h.provider} · {countdown(h.resetAt)}
+ </span>
+ ))}
+ </div>
+ );
+}
diff --git a/src/renderer/src/components/SettingsModal.tsx b/src/renderer/src/components/SettingsModal.tsx
index 6aed9253..d3ccd6e6 100644
--- a/src/renderer/src/components/SettingsModal.tsx
+++ b/src/renderer/src/components/SettingsModal.tsx
@@ -118,6 +118,38 @@ function clearLocalState(): void {
type Section = 'General' | 'Agents & Models' | 'Autonomy & Budgets' | 'Connections' | 'Voice' | 'Memory & Knowledge';
const NAV_SECTIONS: Section[] = ['General', 'Agents & Models', 'Autonomy & Budgets', 'Connections', 'Voice', 'Memory & Knowledge'];
+/** One labelled on/off row. The surrounding settings pane repeats this
+ * title + blurb + toggle shape inline everywhere; the usage-limit section has
+ * four of them, which is the point at which repeating it stops being cheaper
+ * than naming it. */
+function SettingRow({ title, blurb, on, onClick, disabled }: {
+ title: string;
+ blurb: string;
+ on: boolean;
+ onClick: () => void;
+ disabled?: boolean;
+}) {
+ return (
+ <div style={{
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
+ opacity: disabled ? 0.5 : 1
+ }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
+ <span style={{ fontSize: 13, lineHeight: '20px', color: 'var(--cth-ink-900)' }}>{title}</span>
+ <span style={{ fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' }}>{blurb}</span>
+ </div>
+ <PixelButton
+ variant={on ? 'primary' : 'secondary'}
+ size="sm"
+ onClick={onClick}
+ disabled={disabled}
+ >
+ {on ? 'on' : 'off'}
+ </PixelButton>
+ </div>
+ );
+}
+
export function SettingsModal({ config, onClose }: SettingsModalProps) {
const [confirming, setConfirming] = useState(false);
const [busy, setBusy] = useState(false);
@@ -143,6 +175,21 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
catch { setNotifications(!next); /* revert on failure */ }
};
+ // ─── Usage-limit guard ────────────────────────────────────────────────────
+ // Persisted as one object rather than four scalars so a rapid double-toggle
+ // can't write a half-applied guard: `config:update` shallow-merges, and two
+ // in-flight patches of the same key resolve to the last write, not a blend.
+ const LIMIT_GUARD_FALLBACK = { enabled: true, autoResume: true, holdOnThrottle: false, notify: true };
+ const [limitGuard, setLimitGuard] = useState(
+ () => ({ ...LIMIT_GUARD_FALLBACK, ...(config.limitGuard ?? {}) })
+ );
+ const patchLimitGuard = async (patch: Partial<typeof LIMIT_GUARD_FALLBACK>) => {
+ const next = { ...limitGuard, ...patch };
+ setLimitGuard(next); // optimistic
+ try { await window.cth.updateConfig({ limitGuard: next } as Partial<HarnessConfig>); }
+ catch { setLimitGuard(limitGuard); /* revert on failure */ }
+ };
+
// ─── v0.3.4 redesign: settings that were onboarding-trapped or UI-less ────
const cfgX = config as HarnessConfig & {
strongKeepalive?: boolean; audience?: string; autoMode?: boolean;
@@ -357,6 +404,7 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
if (!alive) return;
const cc = c as BreakerCfgView & SlackConfig & { notifications?: boolean };
setNotifications(cc.notifications === true);
+ setLimitGuard({ ...LIMIT_GUARD_FALLBACK, ...((c as HarnessConfig).limitGuard ?? {}) });
setAgentBudget(cc.costCapTokens != null ? String(cc.costCapTokens) : '');
setVelocityCeiling(cc.circuitBreaker?.tokenVelocityPerMin != null ? String(cc.circuitBreaker.tokenVelocityPerMin) : '');
setSlackEnabled(cc.slackEnabled ?? false);
@@ -818,6 +866,53 @@ export function SettingsModal({ config, onClose }: SettingsModalProps) {
<div style={{ height: 1, background: 'var(--cth-ink-300)' }} />
+ {/* Usage-limit guard — pause, queue, auto-resume */}
+ <div>
+ <div style={{
+ fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px',
+ color: 'var(--cth-ink-500)', textTransform: 'uppercase', marginBottom: 10
+ }}>
+ Usage limits
+ </div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
+ <SettingRow
+ title="Hold the queue when a limit is hit"
+ blurb={'When a CLI reports it has hit its usage limit, stop typing at every agent '
+ + 'on that provider and keep their messages queued. Off types into a capped-out '
+ + 'terminal, where the message is silently discarded.'}
+ on={limitGuard.enabled}
+ onClick={() => { void patchLimitGuard({ enabled: !limitGuard.enabled }); }}
+ />
+ <SettingRow
+ title="Resume automatically"
+ blurb={'Start sending again by itself when the limit resets, one message at a '
+ + 'time. Off keeps the queue held until you press resume.'}
+ on={limitGuard.autoResume}
+ disabled={!limitGuard.enabled}
+ onClick={() => { void patchLimitGuard({ autoResume: !limitGuard.autoResume }); }}
+ />
+ <SettingRow
+ title="Also hold on transient throttling"
+ blurb={'Stand down for burst 429s and "overloaded" errors too. Off by default: '
+ + 'the CLIs retry those themselves within seconds, so holding mostly adds '
+ + 'latency to a hiccup that had already cleared.'}
+ on={limitGuard.holdOnThrottle}
+ disabled={!limitGuard.enabled}
+ onClick={() => { void patchLimitGuard({ holdOnThrottle: !limitGuard.holdOnThrottle }); }}
+ />
+ <SettingRow
+ title="Notify when held and resumed"
+ blurb={'Native toast on both edges, so a limit hit while the window is in the '
+ + 'background is not discovered an hour later. Needs desktop notifications on.'}
+ on={limitGuard.notify}
+ disabled={!limitGuard.enabled}
+ onClick={() => { void patchLimitGuard({ notify: !limitGuard.notify }); }}
+ />
+ </div>
+ </div>
+
+ <div style={{ height: 1, background: 'var(--cth-ink-300)' }} />
+
{/* Scheduled auto-compact (compact-maintenance mission) */}
<div>
<div style={{
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index 40bb9b00..f67c7ec7 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -16,8 +16,27 @@ import {
import type { AgentProvider } from '../../../shared/agentProvider';
import { acquireTerminal, resetTerminal, isTerminalAutomationSafe } from '@/components/terminalPool';
import { deliverWithAcknowledgement } from './queueDelivery';
+import { useLimitWatch } from './useLimitWatch';
+import { scopeFor } from '../../../shared/rateLimit';
import { OFFICE_CAST, DEFAULT_CHARACTER } from '@/scene/office/cast';
+/**
+ * Is this agent behind a usage-limit hold right now?
+ *
+ * Reads the store mirror rather than asking main, because the drain loop
+ * evaluates this for every agent on every tick and an IPC round trip per agent
+ * per tick would be absurd. Main stays the authority: it pushes `limit:changed`
+ * on every arm, release and expiry, so the mirror is never more than one event
+ * behind — and being one tick late only ever costs a few seconds of extra wait.
+ */
+function isLimitHeld(provider: AgentProvider, agentId: string): boolean {
+ const scope = scopeFor(provider, agentId);
+ // Presence, not `resetAt > now`. Main decides when a hold ends (it sweeps, and
+ // only when auto-resume is on); re-deriving expiry from the timestamp here
+ // would quietly resume the floor even with auto-resume turned off.
+ return useStore.getState().limitHolds.some((h) => h.scope === scope);
+}
+
const GOD_ID = 'god';
/** Accent palette for MAIN-spawned (voice-hired) agents — picked deterministically
* from the agent id so the same agent always gets the same colour. Mirrors the
@@ -207,6 +226,11 @@ function stationForTool(tool: string): { station: StationKind; carry?: ToolKind
* doesn't stall while an agent sits at its prompt.
*/
export function useHive(config: HarnessConfig | null): void {
+ // Watch every live pty for "you've hit your limit" and mirror main's holds.
+ // Runs even when the guard is off so the mirror still empties on a settings
+ // change; only the per-pty subscriptions are conditional.
+ useLimitWatch(config?.limitGuard?.enabled !== false);
+
// Per-agent dedup key for the inbox-wake nudge: the newest inbox message id we
// last nudged about. Keyed by id (not count) so an oscillating count after a
// drain doesn't re-nudge for the same message set.
@@ -606,12 +630,18 @@ export function useHive(config: HarnessConfig | null): void {
// (killed mid-boot), don't type into its orphaned pty at all.
const live = useStore.getState().agents.find((x) => x.id === a.id);
if (!live) return;
- if (live.status === 'waiting' || live.status === 'blocked') {
+ const liveProvider = inferAgentProvider(live.command, live.provider);
+ // Same put-it-back rule for a usage-limit hold. An agent spawned into a
+ // capped-out provider would otherwise have its ENTIRE hive protocol
+ // seed typed into a TUI that discards it — the agent then sits there
+ // with no instructions at all, which reads as a hung spawn rather than
+ // a rate limit.
+ if (live.status === 'waiting' || live.status === 'blocked' || isLimitHeld(liveProvider, live.id)) {
seeded.current.delete(a.id);
useStore.getState().updateAgent(a.id, { seedPrompt: seed });
return;
}
- submitToPty(ptyId, seed, inferAgentProvider(live.command, live.provider))
+ submitToPty(ptyId, seed, liveProvider)
.catch(() => { /* pty may have died */ });
}, SEED_BOOT_MS);
}
@@ -653,6 +683,15 @@ export function useHive(config: HarnessConfig | null): void {
// the queue with no escape hatch at all. Idle/draft/picker safety below
// still applies to manual messages; only the pause is bypassed.
if (control?.autoDeliveryPaused && !next.manual) return { sent: false };
+ // Usage-limit hold: the CLI told us it is capped until a stated time, so
+ // typing at it now would have the TUI swallow the message silently — the
+ // exact loss this gate exists to prevent. Leave it at the head of the
+ // queue; main lifts the hold and the very next tick drains it.
+ // "Send now" bypasses this the same way it bypasses the pause: the
+ // operator may know something we don't, and an override with no escape
+ // hatch is worse than a wrong guess.
+ const targetProvider = inferAgentProvider(target.command, target.provider);
+ if (!next.manual && isLimitHeld(targetProvider, target.id)) return { sent: false };
// Hold queued messages until the target finishes its boot sequence.
if ((bootGraceUntil.current[target.id] ?? 0) >= now) return { sent: false };
// The user owns the prompt: a draft they are writing, or a menu they
@@ -690,6 +729,11 @@ export function useHive(config: HarnessConfig | null): void {
);
if (sent) {
delete sendFailures[next.id];
+ // Tell the gate a message really landed. Without this, a limit banner
+ // still sitting in the scrollback after a hold lifts is indistinguishable
+ // from the CLI rejecting us again — so the gate refuses to re-arm until
+ // it knows we actually tried.
+ void window.cth.limitNoteDelivery(target.id, targetProvider).catch(() => { /* older main */ });
return { sent: true, message: next };
}
// Failed write (dead/crashed pty the store still thinks is idle): retry
diff --git a/src/renderer/src/hooks/useLimitWatch.ts b/src/renderer/src/hooks/useLimitWatch.ts
new file mode 100644
index 00000000..c7a08359
--- /dev/null
+++ b/src/renderer/src/hooks/useLimitWatch.ts
@@ -0,0 +1,88 @@
+/**
+ * useLimitWatch — watch every agent's terminal for "you've hit your limit".
+ *
+ * Subscribes to the raw pty stream directly rather than riding the terminal
+ * pool's `onData`, for one reason that matters: `onData` is set by whichever
+ * VIEW is mounted, so it only fires for the agent the operator happens to be
+ * looking at. A limit almost always lands on an agent nobody is watching — that
+ * is the whole reason the message gets lost today — so detection has to be
+ * independent of what is on screen.
+ *
+ * Two subscriptions per pty is fine: `pty:data:<id>` is a plain ipcRenderer
+ * channel and every listener on it receives the same chunk.
+ *
+ * The decision itself lives in main (`limit:report` → `LimitGate`), so a second
+ * floor watching the same agent cannot arm two conflicting holds, and a renderer
+ * reload cannot lose one.
+ */
+import { useEffect, useRef } from 'react';
+import { useStore } from '@/store/store';
+import { inferAgentProvider } from '@/store/config';
+import { createLimitDetector } from '@shared/rateLimit';
+import type { AgentProvider } from '@shared/agentProvider';
+
+interface Watch {
+ unsub: () => void;
+ detector: ReturnType<typeof createLimitDetector>;
+ provider: AgentProvider;
+}
+
+export function useLimitWatch(enabled: boolean): void {
+ const agents = useStore((s) => s.agents);
+ const setLimitHolds = useStore((s) => s.setLimitHolds);
+ const watches = useRef(new Map<string, Watch>());
+
+ // Seed the mirror and keep it fresh. Main owns holds; this is the only path
+ // by which the renderer learns about them, including ones armed by another
+ // floor or reinstated from disk at launch.
+ useEffect(() => {
+ let alive = true;
+ window.cth.limitList()
+ .then((holds) => { if (alive) setLimitHolds(holds); })
+ .catch(() => { /* older main process — the gate is simply absent */ });
+ const off = window.cth.onLimitChanged((holds) => setLimitHolds(holds));
+ return () => { alive = false; off(); };
+ }, [setLimitHolds]);
+
+ useEffect(() => {
+ const live = new Map<string, AgentProvider>();
+ if (enabled) {
+ for (const a of agents) {
+ if (!a.ptyId || a.archived) continue;
+ live.set(a.ptyId, inferAgentProvider(a.command, a.provider));
+ }
+ }
+
+ // Drop watches for ptys that died, were archived, or changed provider (a
+ // respawn under a different CLI needs a detector primed for the new one).
+ for (const [ptyId, watch] of watches.current) {
+ if (live.get(ptyId) === watch.provider) continue;
+ watch.unsub();
+ watches.current.delete(ptyId);
+ }
+
+ for (const [ptyId, provider] of live) {
+ if (watches.current.has(ptyId)) continue;
+ const detector = createLimitDetector(provider);
+ const agentIdFor = (): string | undefined =>
+ useStore.getState().agents.find((a) => a.ptyId === ptyId)?.id;
+
+ const unsub = window.cth.onPtyData(ptyId, (chunk) => {
+ const signal = detector.push(chunk, Date.now());
+ if (!signal) return;
+ const agentId = agentIdFor();
+ if (!agentId) return; // agent removed between the write and this frame
+ void window.cth.limitReport({ agentId, provider, signal })
+ .catch(() => { /* main is mid-teardown; the next chunk retries */ });
+ });
+ watches.current.set(ptyId, { unsub, detector, provider });
+ }
+ }, [agents, enabled]);
+
+ // Unsubscribe everything on unmount — the ref outlives the effect's deps.
+ const watchesRef = watches;
+ useEffect(() => () => {
+ for (const w of watchesRef.current.values()) w.unsub();
+ watchesRef.current.clear();
+ }, [watchesRef]);
+}
diff --git a/src/renderer/src/store/config.ts b/src/renderer/src/store/config.ts
index 5f355270..4440171a 100644
--- a/src/renderer/src/store/config.ts
+++ b/src/renderer/src/store/config.ts
@@ -116,6 +116,14 @@ export interface HarnessConfig {
providerBaseUrls?: Partial<Record<AgentProvider, string>>;
/** Per-CLI-provider default model slug, used to pre-fill the model picker. */
providerDefaultModels?: Partial<Record<AgentProvider, string>>;
+ /** How the floor reacts when a CLI reports it has hit its usage limit.
+ * Mirrors `LimitGuardConfig` in main/config.ts. */
+ limitGuard?: {
+ enabled: boolean;
+ autoResume: boolean;
+ holdOnThrottle: boolean;
+ notify: boolean;
+ };
}
/** The Sonnet model with the 1M-token context window — used for Michael's prep
diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.ts
index 88002744..6010e458 100644
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@ -5,6 +5,7 @@ import type { ThemeId } from '@/scene/office/themeRegistry';
import type { StatusKind } from '@/components/PixelBadge';
import type { AgentProvider } from '@shared/agentProvider';
import type { HireManifest } from '@shared/hire';
+import type { LimitHold } from '@shared/rateLimit';
export type ToolKind =
| 'Read' | 'Edit' | 'Write' | 'Bash' | 'WebFetch' | 'WebSearch'
@@ -167,6 +168,11 @@ interface State {
/** Per-agent tool-call count this session — a lightweight activity/usage proxy
* shown in the command center (interactive sessions don't expose billed $). */
toolCounts: Record<string, number>;
+ /** Usage-limit holds in force, soonest first. MAIN owns these — this is a
+ * read-only mirror kept fresh by `limit:changed`, so a renderer reload can
+ * never lose a hold or invent one. */
+ limitHolds: LimitHold[];
+ setLimitHolds: (holds: LimitHold[]) => void;
bumpToolCount: (id: string) => void;
setGodStatus: (status: GodStatus) => void;
select: (id: string) => void;
@@ -562,6 +568,10 @@ export const useStore = create<State>((set) => ({
godStatus: 'booting',
messageQueues: initialQueues,
toolCounts: {},
+ // Seeded from main by `App.tsx` and refreshed by `limit:changed`; never
+ // written speculatively from the renderer, so the two can't disagree.
+ limitHolds: [],
+ setLimitHolds: (holds) => set({ limitHolds: holds }),
bumpToolCount: (id) =>
set((s) => ({ toolCounts: { ...s.toolCounts, [id]: (s.toolCounts[id] ?? 0) + 1 } })),
setGodStatus: (status) => set({ godStatus: status }),
diff --git a/src/shared/rateLimit.ts b/src/shared/rateLimit.ts
new file mode 100644
index 00000000..c283127a
--- /dev/null
+++ b/src/shared/rateLimit.ts
@@ -0,0 +1,497 @@
+/**
+ * RATE / USAGE LIMIT DETECTION — reading "you're cut off until 3pm" out of a
+ * terminal, so the floor can park work instead of dropping it.
+ *
+ * Every supported CLI eventually says some version of "you have hit your limit,
+ * come back later". When that happens the harness must stop typing at that agent
+ * (each ignored message is a lost instruction the human has to remember and
+ * resend), hold the backlog, and start again by itself once the window reopens.
+ * This module is the part that decides *whether* a chunk of terminal output is
+ * such a message and *when* the window reopens. The parking, the timer and the
+ * one-at-a-time replay live in `main/limitGate.ts`.
+ *
+ * ── Why the patterns are mostly generic rather than per-provider ──────────────
+ * The obvious design is a table of per-CLI strings, the way
+ * `providerAutomation.ts` maps per-CLI slash commands. It does not work here,
+ * and that is a finding rather than a shortcut: the limit text is written by the
+ * *API*, not by the CLI. Reading the shipped artefacts of the installed fleet:
+ *
+ * - `claude` DOES own its wording ("You've hit your session limit · resets
+ * 3pm", "Session limit reached"), because the subscription limit
+ * is a Claude Code concept. Its labels are a fixed set:
+ * five_hour → "session limit", seven_day → "weekly limit",
+ * seven_day_opus → "Opus limit", seven_day_sonnet → "Sonnet limit".
+ * - `codex` keeps a `rate limit: ` / `resetsAt` shape from its own client.
+ * - `pi` ships two classifier regexes of its own, and they draw exactly
+ * the line this module draws: `GoUsageLimitError|
+ * FreeUsageLimitError|Monthly usage limit reached|available
+ * balance|insufficient_quota|out of budget|quota exceeded|billing`
+ * is treated as terminal, while `overloaded|rate.?limit|too many
+ * requests|429|500|502|503|504|…` is treated as retryable.
+ * - `grok`, `agy`, `opencode`, `qwen`, `crush` contain no user-facing limit
+ * copy at all — they surface whatever the provider returned, so
+ * what actually reaches the terminal is the API's own phrasing
+ * ("rate_limit_error", "Too Many Requests", "RESOURCE_EXHAUSTED").
+ *
+ * So the generic set carries the weight and `PROVIDER_QUOTA_HINTS` adds the few
+ * strings a CLI genuinely owns. A provider missing from that table is not
+ * unhandled — it is handled by the generic set, which is where its text comes
+ * from anyway.
+ *
+ * ── Two tiers, because they want opposite responses ───────────────────────────
+ * Conflating them would be the worst bug this feature could ship: a single
+ * transient 503 would park the whole floor for hours.
+ *
+ * throttle — momentary. Burst 429s, "overloaded", "temporarily limiting
+ * requests". The CLI itself usually retries these. We back off for
+ * seconds-to-minutes and say little.
+ * quota — the plan's allowance is spent. Retrying cannot help until the
+ * stated reset. This is the one that parks the queue.
+ *
+ * Pure and dependency-free: imported by main, preload and renderer, and unit
+ * tested directly.
+ */
+import type { AgentProvider } from './agentProvider';
+
+/** How serious a limit is, and therefore how long to stand down. */
+export type LimitTier = 'throttle' | 'quota';
+
+/** Where `resetAt` came from — the UI phrases the countdown differently for a
+ * time the CLI actually told us versus one we picked. */
+export type ResetSource = 'stated' | 'estimated';
+
+export interface LimitSignal {
+ tier: LimitTier;
+ /** Epoch ms we believe access returns. Always set: an unparsed reset falls
+ * back to a backoff estimate so the caller never has to invent one. */
+ resetAt: number;
+ resetSource: ResetSource;
+ /** The matched line, trimmed and capped. Shown to the operator and used to
+ * suppress re-arming from a TUI repainting the same stale banner. */
+ evidence: string;
+}
+
+/**
+ * A limit currently being served — the signal plus who it applies to and for how
+ * long. Lives here rather than in `main/limitGate.ts` because all three layers
+ * handle it: main owns it, preload passes it, and the renderer renders the
+ * countdown from it.
+ */
+export interface LimitHold {
+ /** `provider:claude` or `agent:<id>` — see `scopeFor` in main/limitGate.ts. */
+ scope: string;
+ provider: AgentProvider;
+ tier: LimitTier;
+ /** Epoch ms the hold lifts. */
+ resetAt: number;
+ armedAt: number;
+ resetSource: ResetSource;
+ /** The line that triggered it. Shown to the operator so a stopped floor is
+ * never a mystery — "why is nothing moving" must be answerable at a glance. */
+ evidence: string;
+ /** The agent whose terminal produced the signal. */
+ agentId: string;
+ /** How many times this scope has been re-held in quick succession; drives the
+ * escalating backoff when the CLI never states a reset time. */
+ attempts: number;
+}
+
+/**
+ * The key a hold is filed under.
+ *
+ * A usage limit belongs to an ACCOUNT, so six workers running `claude` are all
+ * behind the same wall the moment one of them hits it — holding only the agent
+ * that printed the banner would let the other five walk into it one at a time,
+ * losing a message each. `custom` is the exception: an arbitrary user-supplied
+ * binary has no reason to share an account with another one, so those hold per
+ * agent.
+ *
+ * Lives here, in the shared module, because main arms holds and the renderer
+ * checks them on every drain tick — if the two derived the key separately they
+ * could disagree, and a hold nobody matches is a hold that does nothing.
+ */
+export function scopeFor(provider: AgentProvider, agentId: string): string {
+ return provider === 'custom' ? `agent:${agentId}` : `provider:${provider}`;
+}
+
+/* ────────────────────────────── negative filters ─────────────────────────── */
+
+/**
+ * Lines that mention a limit but are NOT one being hit right now. Checked first,
+ * so a warning can never park the floor.
+ *
+ * `Approaching …` matters most: Claude renders "Approaching session limit ·
+ * resets 3pm" from the same component that renders "You've hit your session
+ * limit · resets 3pm". Matching the reset clause alone would stand the fleet
+ * down at ~80% usage, hours early, every single session.
+ */
+const NOT_A_LIMIT: RegExp[] = [
+ /\bapproaching\b/i,
+ /\byou'?ve used\s+\d+%/i,
+ /\bclose to your\b/i,
+ // Non-LLM limits from runtimes bundled inside these CLIs (V8, liblzma, SRTP…).
+ /\b(memory|allocation|marking|heap|nodes|key usage|packet index|turn|element)\s+limit\b/i,
+ /\bout of bounds\b/i,
+ // Somebody else's rate limit, mentioned in passing.
+ /\brate limits?\s+(?:for|on|from)\s+(?:github|npm|homebrew|docker|pypi)\b/i,
+ /\bhigher rate limit\b/i,
+ // Documentation, flags and source code that merely talk about limits — this
+ // repo's own files included, since an agent reading them echoes them to screen.
+ /\brate.?limit\w*\s*[:=]\s*(?:[\d{[]|true|false|null|new\b)/i,
+ /--[a-z-]*rate.?limit/i,
+ /\b(?:function|const|let|var|import|export|class|def)\b.*\brate.?limit/i
+];
+
+/* ─────────────────────────────── quota patterns ──────────────────────────── */
+
+/**
+ * The allowance is spent. Natural-language shaped on purpose: a bare token like
+ * `rate_limit` appears in config, logs and source, whereas "you've hit your
+ * session limit" only ever appears when it happened.
+ */
+const QUOTA_PATTERNS: RegExp[] = [
+ /\byou'?ve\s+(?:hit|reached)\s+your\s+[^.\n]{0,48}\blimit\b/i,
+ /\b(?:session|weekly|hourly|daily|monthly|opus|sonnet|usage|usage credit|spend|plan|account)\s+limits?\s+(?:reached|exceeded)\b/i,
+ /\busage\s+limits?\s+(?:reached|exceeded)\b/i,
+ /\bclaude\s+ai\s+usage\s+limit\s+reached\b/i,
+ /\bquota\s+(?:exceeded|reached|exhausted)\b/i,
+ /\binsufficient[_ ]quota\b/i,
+ /\bresource[_ ]exhausted\b/i,
+ /\b(?:go|free)usagelimiterror\b/i,
+ /\bout\s+of\s+(?:usage\s+)?credits?\b/i,
+ /\bcredit\s+balance\s+(?:is\s+)?too\s+low\b/i,
+ /\bout\s+of\s+budget\b/i,
+ /\bavailable\s+balance\b/i,
+ /\bbilling[_ ](?:hard[_ ])?limit\b/i,
+ /\bupgrade\s+to\s+(?:increase|raise)\s+your\s+usage\s+limit\b/i
+];
+
+/**
+ * The handful of strings a CLI genuinely owns, rather than relaying from its
+ * API. Everything else reaches the terminal in the provider's own words and is
+ * caught by the generic set above.
+ */
+const PROVIDER_QUOTA_HINTS: Partial<Record<AgentProvider, RegExp[]>> = {
+ // Claude Code renders these itself; the label set is fixed (see header).
+ claude: [
+ /\b(?:session|weekly|opus|sonnet)\s+limit\b[^\n]{0,40}\bresets?\b/i,
+ /\/upgrade\s+to\s+keep\s+using\s+claude\s+code\b/i
+ ],
+ // Codex's client prints its own `rate limit: …` line carrying a `resetsAt`.
+ codex: [/\brate limit:\s*[^\n]*\bresets?[_ ]?at\b/i],
+ // pi's own terminal-error classifier, verbatim from its bundle.
+ pi: [/\bmonthly\s+usage\s+limit\s+reached\b/i]
+};
+
+/* ───────────────────────────── throttle patterns ─────────────────────────── */
+
+/** Momentary pushback. The CLI usually retries by itself; we only avoid piling
+ * more work on while it does. */
+const THROTTLE_PATTERNS: RegExp[] = [
+ /\btoo\s+many\s+requests\b/i,
+ /\brate[_ -]?limit(?:ed|_error|error)?\b(?![_ ]?(?:ms|s|window|mutation|prompt|read))/i,
+ /\bhttp\s*(?:status\s*)?429\b/i,
+ /\b429\b[^\n]{0,24}\b(?:too many|rate)\b/i,
+ /\boverloaded(?:_error)?\b/i,
+ /\bserver\s+is\s+temporarily\s+limiting\s+requests\b/i,
+ /\bslow\s+down\b.*\brequests?\b/i
+];
+
+/* ────────────────────────────────── backoff ──────────────────────────────── */
+
+/**
+ * How long to stand down when the output says a limit was hit but never says
+ * when it lifts — which is the common case outside Claude Code.
+ *
+ * Escalating rather than fixed, because a wrong guess repeats: if we resume
+ * after 15 minutes and the wall is still there, resuming again 15 minutes later
+ * burns another message against a closed window. Each rebuff roughly doubles the
+ * wait, capped so an unattended floor still recovers the same day.
+ */
+export const QUOTA_BACKOFF_MS = [15 * 60_000, 30 * 60_000, 60 * 60_000, 120 * 60_000] as const;
+export const THROTTLE_BACKOFF_MS = [30_000, 90_000, 300_000, 600_000] as const;
+
+/** Never hold longer than this, whatever the output claimed — a misparsed year
+ * must not park an agent until 2027. */
+export const MAX_HOLD_MS = 14 * 24 * 60 * 60_000;
+
+export function backoffFor(tier: LimitTier, attempt: number): number {
+ const ladder = tier === 'quota' ? QUOTA_BACKOFF_MS : THROTTLE_BACKOFF_MS;
+ const i = Math.min(Math.max(attempt, 0), ladder.length - 1);
+ return ladder[i];
+}
+
+/* ───────────────────────────── the detector ──────────────────────────────── */
+
+const ANSI_RE = /\x1B\[[0-9;?]*[ -/]*[@-~]/g;
+/** Terminal output arrives in arbitrary chunks, so a banner routinely lands
+ * split across two writes. Keep this much of the previous chunk so a message
+ * cut in half is still seen whole exactly once. */
+export const DETECTOR_TAIL_CHARS = 2048;
+/** A line longer than this is a data dump or a minified bundle scrolling past,
+ * not a status banner — real limit notices are short. */
+const MAX_EVIDENCE_LINE = 400;
+
+/** Strip ANSI, box-drawing and cursor noise so patterns see plain prose. */
+export function cleanTerminalText(raw: string): string {
+ return raw
+ .replace(ANSI_RE, '')
+ .replace(/[─-╿▀-▟]/g, ' ') // box-drawing / block glyphs
+ .replace(/\r/g, '\n');
+}
+
+/**
+ * Classify one already-cleaned line. Exported for tests and for callers holding
+ * a single known line (a hook payload, an API error body) rather than a stream.
+ */
+export function classifyLine(line: string, provider?: AgentProvider): LimitTier | null {
+ const t = line.trim();
+ if (!t || t.length > MAX_EVIDENCE_LINE) return null;
+ if (NOT_A_LIMIT.some((re) => re.test(t))) return null;
+ const hints = provider ? PROVIDER_QUOTA_HINTS[provider] ?? [] : [];
+ if (hints.some((re) => re.test(t))) return 'quota';
+ if (QUOTA_PATTERNS.some((re) => re.test(t))) return 'quota';
+ if (THROTTLE_PATTERNS.some((re) => re.test(t))) return 'throttle';
+ return null;
+}
+
+/**
+ * Find a limit notice in a block of terminal output.
+ *
+ * Scans every line and keeps the most severe hit, so a screen showing both a
+ * transient retry notice and the quota banner underneath is read as quota.
+ * `resetAt` prefers a time the output actually stated; failing that it is an
+ * estimate from `backoffFor(tier, attempt)`, so the caller always gets a usable
+ * timestamp and never has to decide "how long is a while".
+ */
+export function detectLimit(
+ text: string,
+ opts: { provider?: AgentProvider; now: number; attempt?: number } = { now: Date.now() }
+): LimitSignal | null {
+ const now = opts.now;
+ const cleaned = cleanTerminalText(text);
+ let best: { tier: LimitTier; line: string } | null = null;
+
+ for (const line of cleaned.split('\n')) {
+ const tier = classifyLine(line, opts.provider);
+ if (!tier) continue;
+ if (!best || (tier === 'quota' && best.tier === 'throttle')) best = { tier, line: line.trim() };
+ if (best.tier === 'quota') break;
+ }
+ if (!best) return null;
+
+ // The reset time is frequently on a neighbouring line ("You've hit your
+ // weekly limit." / "Try again in 3 hours."), so read it from the whole block
+ // rather than from the matched line alone.
+ const stated = parseResetAt(cleaned, now);
+ const resetAt = stated ?? now + backoffFor(best.tier, opts.attempt ?? 0);
+ return {
+ tier: best.tier,
+ resetAt: Math.min(resetAt, now + MAX_HOLD_MS),
+ resetSource: stated ? 'stated' : 'estimated',
+ evidence: best.line.slice(0, MAX_EVIDENCE_LINE)
+ };
+}
+
+/**
+ * Stateful wrapper for a live PTY stream. Holds a short tail so a banner split
+ * across two writes is still matched, and suppresses the repeat that a TUI
+ * repaint would otherwise produce.
+ */
+export function createLimitDetector(provider?: AgentProvider) {
+ let tail = '';
+ let lastEvidence = '';
+ let lastAt = 0;
+ /** A repaint of the same banner within this window is the same event. */
+ const REPEAT_WINDOW_MS = 30_000;
+
+ return {
+ push(chunk: string, now: number, attempt = 0): LimitSignal | null {
+ const hay = tail + chunk;
+ tail = hay.slice(-DETECTOR_TAIL_CHARS);
+ const hit = detectLimit(hay, { provider, now, attempt });
+ if (!hit) return null;
+ if (hit.evidence === lastEvidence && now - lastAt < REPEAT_WINDOW_MS) return null;
+ lastEvidence = hit.evidence;
+ lastAt = now;
+ return hit;
+ },
+ reset(): void { tail = ''; lastEvidence = ''; lastAt = 0; }
+ };
+}
+
+/* ──────────────────────────── reset-time parsing ─────────────────────────── */
+
+const DUR_UNIT_MS: Record<string, number> = {
+ s: 1000, sec: 1000, secs: 1000, second: 1000, seconds: 1000,
+ m: 60_000, min: 60_000, mins: 60_000, minute: 60_000, minutes: 60_000,
+ h: 3_600_000, hr: 3_600_000, hrs: 3_600_000, hour: 3_600_000, hours: 3_600_000,
+ d: 86_400_000, day: 86_400_000, days: 86_400_000
+};
+
+const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
+
+/**
+ * Pull "when does this lift" out of terminal text, in epoch ms.
+ *
+ * Tried most-explicit first, so an ISO timestamp is never reinterpreted as a
+ * wall clock. Returns undefined rather than guessing — the caller's backoff is a
+ * better answer than a bad parse, because a bad parse looks authoritative in the
+ * UI while being wrong.
+ */
+export function parseResetAt(text: string, now: number): number | undefined {
+ const t = cleanTerminalText(text);
+ for (const attempt of [isoReset, epochReset, relativeReset, dateClockReset, clockReset]) {
+ const at = attempt(t, now);
+ if (at !== undefined && at > now && at <= now + MAX_HOLD_MS) return at;
+ }
+ return undefined;
+}
+
+/** `2026-08-10T15:04:05Z`, `…+05:30`, or with a space instead of the T. */
+function isoReset(t: string, _now: number): number | undefined {
+ const m = /\b(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?\s*(Z|[+-]\d{2}:?\d{2})?/i.exec(t);
+ if (!m) return undefined;
+ const zone = m[3] ? m[3].replace(/^([+-]\d{2})(\d{2})$/, '$1:$2') : 'Z';
+ const parsed = Date.parse(`${m[1]}T${m[2].length === 5 ? `${m[2]}:00` : m[2]}${zone}`);
+ return Number.isNaN(parsed) ? undefined : parsed;
+}
+
+/**
+ * A bare epoch, which Claude's non-interactive mode emits as
+ * `Claude AI usage limit reached|1786000000`.
+ *
+ * Only read next to a limit/reset word: a ten-digit number on its own is far
+ * more likely to be a file size, a pid or a hash fragment than a deadline.
+ */
+function epochReset(t: string, _now: number): number | undefined {
+ const m = /(?:limit\s*reached|resets?[_ ]?at|reset|retry|until|expires?)\D{0,12}(1[0-9]{9})(\d{3})?\b/i.exec(t);
+ if (!m) return undefined;
+ return m[2] ? Number(`${m[1]}${m[2]}`) : Number(m[1]) * 1000;
+}
+
+/**
+ * `try again in 4h 32m`, `retry after 90 seconds`, `resets in 2 hours`,
+ * and the bare header form `retry-after: 3600` (seconds, per RFC 9110).
+ */
+function relativeReset(t: string, now: number): number | undefined {
+ const header = /\bretry[- ]?after\s*[:=]\s*(\d{1,6})\b/i.exec(t);
+ if (header) return now + Number(header[1]) * 1000;
+
+ const m = /\b(?:try again|retry|resets?|available|back|wait|again)\b[^.\n]{0,20}?\bin\s+((?:\d+\s*[a-z]+[\s,]*)+)/i.exec(t)
+ ?? /\bin\s+(\d+\s*(?:seconds?|secs?|minutes?|mins?|hours?|hrs?|days?))\b/i.exec(t);
+ if (!m) return undefined;
+
+ let total = 0;
+ const part = /(\d+)\s*([a-z]+)/gi;
+ for (let p: RegExpExecArray | null; (p = part.exec(m[1])) !== null; ) {
+ const unit = DUR_UNIT_MS[p[2].toLowerCase()];
+ if (!unit) continue;
+ total += Number(p[1]) * unit;
+ }
+ return total > 0 ? now + total : undefined;
+}
+
+/** `Nov 12, 3pm` / `Nov 12 at 15:00` — Claude's format past 24 hours out. */
+function dateClockReset(t: string, now: number): number | undefined {
+ const m = new RegExp(
+ `\\b(${MONTHS.join('|')})[a-z]*\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?(?:,)?\\s*(?:at\\s+)?` +
+ `(\\d{1,2})(?::(\\d{2}))?\\s*(am|pm)?\\b(?:[^\\n(]{0,20}\\(([A-Za-z_]+/[A-Za-z_+-]+)\\))?`,
+ 'i'
+ ).exec(t);
+ if (!m) return undefined;
+ const hour = normaliseHour(Number(m[3]), m[5]);
+ if (hour === undefined) return undefined;
+ const zone = m[6];
+ const month = MONTHS.indexOf(m[1].slice(0, 3).toLowerCase());
+ const year = wallClockParts(now, zone).year;
+ const at = fromWallClock({ year, month, day: Number(m[2]), hour, minute: Number(m[4] ?? 0) }, zone);
+ // A date without a year that reads as past is next year's (a late-December
+ // weekly limit resetting in January).
+ return at > now ? at : fromWallClock(
+ { year: year + 1, month, day: Number(m[2]), hour, minute: Number(m[4] ?? 0) },
+ zone
+ );
+}
+
+/**
+ * A bare wall clock — `resets 3pm`, `resets at 3:30pm (America/Los_Angeles)`,
+ * `resets 15:30`. Claude's most common shape, and the fiddliest: it is the only
+ * form whose meaning depends on a timezone we are told about but do not live in.
+ */
+function clockReset(t: string, now: number): number | undefined {
+ const m = /\b(?:resets?|renews?|available|again|until|try again)\b[^.\n]{0,16}?\b(?:at\s+)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b(?:\s*\(([A-Za-z_]+\/[A-Za-z_+-]+)\))?/i
+ .exec(t);
+ if (!m) return undefined;
+ // Reject a bare hour with no meridiem and no colon: "resets in 3" is a
+ // duration we already failed to parse, not 3 o'clock.
+ if (!m[2] && !m[3]) return undefined;
+ const hour = normaliseHour(Number(m[1]), m[3]);
+ if (hour === undefined) return undefined;
+
+ const zone = m[4];
+ const today = wallClockParts(now, zone);
+ const at = fromWallClock({ ...today, hour, minute: Number(m[2] ?? 0) }, zone);
+ return at > now ? at : at + 86_400_000;
+}
+
+function normaliseHour(raw: number, meridiem?: string): number | undefined {
+ if (!Number.isFinite(raw)) return undefined;
+ if (meridiem) {
+ if (raw < 1 || raw > 12) return undefined;
+ const pm = meridiem.toLowerCase() === 'pm';
+ return raw === 12 ? (pm ? 12 : 0) : raw + (pm ? 12 : 0);
+ }
+ return raw >= 0 && raw <= 23 ? raw : undefined;
+}
+
+interface WallClock { year: number; month: number; day: number; hour: number; minute: number }
+
+/**
+ * How far ahead of UTC `zone` is at instant `at`, in ms. Falls back to the
+ * host's own offset for a zone Intl doesn't know, which is the right default:
+ * Claude prints the *operator's* resolved timezone, so "unknown zone" almost
+ * always means a bare abbreviation for the zone we are already in.
+ */
+function zoneOffsetMs(zone: string | undefined, at: number): number {
+ if (!zone) return -new Date(at).getTimezoneOffset() * 60_000;
+ try {
+ const parts = new Intl.DateTimeFormat('en-US', {
+ timeZone: zone, hour12: false,
+ year: 'numeric', month: '2-digit', day: '2-digit',
+ hour: '2-digit', minute: '2-digit', second: '2-digit'
+ }).formatToParts(new Date(at));
+ const get = (type: string): number => Number(parts.find((p) => p.type === type)?.value ?? '0');
+ // hour12:false yields 24 for midnight in some ICU versions.
+ const hour = get('hour') % 24;
+ const asUtc = Date.UTC(get('year'), get('month') - 1, get('day'), hour, get('minute'), get('second'));
+ return asUtc - Math.floor(at / 1000) * 1000;
+ } catch {
+ return -new Date(at).getTimezoneOffset() * 60_000;
+ }
+}
+
+/** The wall-clock date `at` falls on, as seen from `zone`. */
+function wallClockParts(at: number, zone: string | undefined): WallClock {
+ const shifted = new Date(at + zoneOffsetMs(zone, at));
+ return {
+ year: shifted.getUTCFullYear(), month: shifted.getUTCMonth(), day: shifted.getUTCDate(),
+ hour: shifted.getUTCHours(), minute: shifted.getUTCMinutes()
+ };
+}
+
+/**
+ * Turn a wall clock in `zone` back into an instant.
+ *
+ * Solved twice because the offset depends on the answer: a 3pm reset the day a
+ * zone leaves DST sits on a different offset from the one in force right now,
+ * and a single-pass conversion lands an hour out. The second pass uses the
+ * offset in force at the first pass's guess, which converges everywhere except
+ * inside the one ambiguous hour of a fall-back — where either answer is a legal
+ * reading of the printed time.
+ */
+function fromWallClock(w: WallClock, zone: string | undefined): number {
+ const naive = Date.UTC(w.year, w.month, w.day, w.hour, w.minute);
+ const first = naive - zoneOffsetMs(zone, naive);
+ return naive - zoneOffsetMs(zone, first);
+}
diff --git a/test/limit-gate.test.cjs b/test/limit-gate.test.cjs
new file mode 100644
index 00000000..03f2a113
--- /dev/null
+++ b/test/limit-gate.test.cjs
@@ -0,0 +1,281 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const { LimitGate, scopeFor } = loadTs('src/main/limitGate.ts');
+const {
+ QUOTA_BACKOFF_MS, MAX_HOLD_MS, createLimitDetector, scopeFor: sharedScopeFor
+} = loadTs('src/shared/rateLimit.ts');
+
+const NOW = Date.parse('2026-08-10T20:00:00Z');
+const MIN = 60_000;
+
+const quota = (over = {}) => ({
+ tier: 'quota',
+ resetAt: NOW + 60 * MIN,
+ resetSource: 'stated',
+ evidence: "You've hit your session limit · resets 3pm",
+ ...over
+});
+
+/* ───────────────────────────────── scoping ───────────────────────────────── */
+
+test('a limit holds every agent on the same provider, not just the one that saw it', () => {
+ const gate = new LimitGate();
+ gate.arm({ agentId: 'worker-1', provider: 'claude', signal: quota(), now: NOW });
+
+ // The account is spent, so a sibling that has not spoken yet is already behind
+ // the same wall — holding only worker-1 would lose worker-2's next message.
+ assert.ok(gate.holdFor('claude', 'worker-2'));
+ // A different CLI is a different account and keeps working.
+ assert.equal(gate.holdFor('codex', 'worker-3'), null);
+});
+
+test('custom binaries hold per agent, since they share no account', () => {
+ const gate = new LimitGate();
+ gate.arm({ agentId: 'a', provider: 'custom', signal: quota(), now: NOW });
+ assert.ok(gate.holdFor('custom', 'a'));
+ assert.equal(gate.holdFor('custom', 'b'), null);
+ assert.equal(scopeFor('custom', 'a'), 'agent:a');
+ assert.equal(scopeFor('claude', 'a'), 'provider:claude');
+});
+
+/* ─────────────────────────── arming and re-arming ────────────────────────── */
+
+test('re-arming keeps the later reset — a repaint cannot shorten a hold', () => {
+ const gate = new LimitGate();
+ gate.arm({ agentId: 'a', provider: 'claude', signal: quota({ resetAt: NOW + 60 * MIN }), now: NOW });
+ const merged = gate.arm({
+ agentId: 'a', provider: 'claude',
+ signal: quota({ resetAt: NOW + 10 * MIN, evidence: 'stale frame' }),
+ now: NOW + 1000
+ });
+ assert.equal(merged.resetAt, NOW + 60 * MIN);
+});
+
+test('a throttle hold upgrades to quota but never back down', () => {
+ const gate = new LimitGate();
+ gate.arm({
+ agentId: 'a', provider: 'grok',
+ signal: { tier: 'throttle', resetAt: NOW + MIN, resetSource: 'estimated', evidence: '429' },
+ now: NOW
+ });
+ const up = gate.arm({ agentId: 'a', provider: 'grok', signal: quota(), now: NOW + 100 });
+ assert.equal(up.tier, 'quota');
+
+ const down = gate.arm({
+ agentId: 'a', provider: 'grok',
+ signal: { tier: 'throttle', resetAt: NOW + 5 * MIN, resetSource: 'estimated', evidence: '429' },
+ now: NOW + 200
+ });
+ assert.equal(down.tier, 'quota');
+});
+
+test('an estimated reset escalates each time the wall is still there', () => {
+ const gate = new LimitGate();
+ const est = { tier: 'quota', resetAt: 0, resetSource: 'estimated', evidence: 'Session limit reached' };
+
+ let t = NOW;
+ const first = gate.arm({ agentId: 'a', provider: 'claude', signal: est, now: t });
+ assert.equal(first.resetAt - t, QUOTA_BACKOFF_MS[0]);
+
+ // Timer lifts, we try again, and the CLI says the same thing — but only after
+ // a message really went out, so this is a genuine second rejection.
+ t = first.resetAt;
+ gate.sweep(t);
+ gate.noteDelivery('claude', 'a', t);
+ const second = gate.arm({ agentId: 'a', provider: 'claude', signal: est, now: t });
+ assert.equal(second.resetAt - t, QUOTA_BACKOFF_MS[1]);
+ assert.equal(second.attempts, 2);
+});
+
+test('a stated reset is trusted verbatim and never escalated', () => {
+ const gate = new LimitGate();
+ const hold = gate.arm({
+ agentId: 'a', provider: 'claude',
+ signal: quota({ resetAt: NOW + 17 * MIN }), now: NOW
+ });
+ assert.equal(hold.resetAt, NOW + 17 * MIN);
+ assert.equal(hold.resetSource, 'stated');
+});
+
+test('a hold is clamped to the ceiling however far out the signal claimed', () => {
+ const gate = new LimitGate();
+ const hold = gate.arm({
+ agentId: 'a', provider: 'claude',
+ signal: quota({ resetAt: NOW + MAX_HOLD_MS * 4 }), now: NOW
+ });
+ assert.equal(hold.resetAt, NOW + MAX_HOLD_MS);
+});
+
+/* ───────────────────── release, repaint, and genuine re-hits ─────────────── */
+
+test('the same banner repainted just after a release does not re-arm', () => {
+ const gate = new LimitGate();
+ gate.arm({ agentId: 'a', provider: 'claude', signal: quota(), now: NOW });
+ gate.release(scopeFor('claude', 'a'), NOW + MIN);
+
+ // Nothing has been delivered yet, and the words are identical: this is the
+ // notice still sitting in the scrollback, not a fresh rejection.
+ assert.equal(gate.arm({ agentId: 'a', provider: 'claude', signal: quota(), now: NOW + MIN + 500 }), null);
+ assert.equal(gate.holdFor('claude', 'a'), null);
+});
+
+test('the same banner after a real delivery IS a fresh rejection', () => {
+ const gate = new LimitGate();
+ gate.arm({ agentId: 'a', provider: 'claude', signal: quota(), now: NOW });
+ gate.release(scopeFor('claude', 'a'), NOW + MIN);
+ gate.noteDelivery('claude', 'a', NOW + MIN + 100);
+
+ const again = gate.arm({ agentId: 'a', provider: 'claude', signal: quota(), now: NOW + MIN + 200 });
+ assert.ok(again, 'a limit seen after a message actually went out must hold again');
+});
+
+test('different wording after a release re-arms even with nothing delivered', () => {
+ const gate = new LimitGate();
+ gate.arm({ agentId: 'a', provider: 'claude', signal: quota(), now: NOW });
+ gate.release(scopeFor('claude', 'a'), NOW + MIN);
+ const again = gate.arm({
+ agentId: 'a', provider: 'claude',
+ signal: quota({ evidence: "You've hit your weekly limit · resets Nov 12" }),
+ now: NOW + MIN + 500
+ });
+ assert.ok(again);
+});
+
+/* ────────────────────────────── sweep and expiry ─────────────────────────── */
+
+test('sweep lifts holds whose time has come and reports them', () => {
+ const gate = new LimitGate();
+ gate.arm({ agentId: 'a', provider: 'claude', signal: quota({ resetAt: NOW + 10 * MIN }), now: NOW });
+ gate.arm({ agentId: 'b', provider: 'codex', signal: quota({ resetAt: NOW + 90 * MIN }), now: NOW });
+
+ assert.deepEqual(gate.sweep(NOW + 5 * MIN), []);
+ const lifted = gate.sweep(NOW + 11 * MIN);
+ assert.equal(lifted.length, 1);
+ assert.equal(lifted[0].provider, 'claude');
+ assert.equal(gate.holdFor('claude', 'a'), null);
+ assert.ok(gate.holdFor('codex', 'b'));
+});
+
+test('list is soonest-first, and keeps an expired hold until it is swept', () => {
+ const gate = new LimitGate();
+ gate.arm({ agentId: 'a', provider: 'codex', signal: quota({ resetAt: NOW + 90 * MIN }), now: NOW });
+ gate.arm({ agentId: 'b', provider: 'claude', signal: quota({ resetAt: NOW + 10 * MIN }), now: NOW });
+ assert.deepEqual(gate.list().map((h) => h.provider), ['claude', 'codex']);
+
+ // Past claude's reset but with no sweep — this is exactly the "resume
+ // automatically: off" steady state, and the hold must still be listed so the
+ // UI can offer a resume button instead of showing a stopped floor with no
+ // explanation.
+ assert.deepEqual(gate.list().map((h) => h.provider), ['claude', 'codex']);
+ assert.ok(gate.holdFor('claude', 'b'));
+
+ gate.sweep(NOW + 30 * MIN);
+ assert.deepEqual(gate.list().map((h) => h.provider), ['codex']);
+});
+
+test('releaseAll drops everything (the operator turned the guard off)', () => {
+ const gate = new LimitGate();
+ gate.arm({ agentId: 'a', provider: 'claude', signal: quota(), now: NOW });
+ gate.arm({ agentId: 'b', provider: 'codex', signal: quota(), now: NOW });
+ assert.equal(gate.releaseAll(NOW).length, 2);
+ assert.deepEqual(gate.list(), []);
+});
+
+test('serialize persists only holds with time left', () => {
+ const gate = new LimitGate();
+ gate.arm({ agentId: 'a', provider: 'claude', signal: quota({ resetAt: NOW + 10 * MIN }), now: NOW });
+ assert.equal(gate.serialize(NOW).holds.length, 1);
+ // An expired hold is worth showing in this session, not worth reinstating
+ // after a restart.
+ assert.equal(gate.serialize(NOW + 30 * MIN).holds.length, 0);
+});
+
+/* ─────────────────────────────── persistence ─────────────────────────────── */
+
+test('a hold with time left survives a restart', () => {
+ const gate = new LimitGate();
+ gate.arm({ agentId: 'a', provider: 'claude', signal: quota({ resetAt: NOW + 40 * MIN }), now: NOW });
+ const saved = gate.serialize(NOW);
+
+ // A limit does not lapse because the app was closed.
+ const revived = new LimitGate();
+ revived.hydrate(saved, NOW + 5 * MIN);
+ assert.ok(revived.holdFor('claude', 'zzz'));
+});
+
+test('an expired or malformed persisted hold is discarded, not trusted', () => {
+ const gate = new LimitGate();
+ gate.hydrate({
+ holds: [
+ { ...quota(), scope: 'provider:claude', provider: 'claude', agentId: 'a', armedAt: NOW, attempts: 1, resetAt: NOW - MIN },
+ { scope: 'provider:codex' },
+ null
+ ]
+ }, NOW);
+ assert.deepEqual(gate.list(), []);
+});
+
+test('forget clears the rebuff count as well as the hold', () => {
+ const gate = new LimitGate();
+ const est = { tier: 'quota', resetAt: 0, resetSource: 'estimated', evidence: 'Session limit reached' };
+ gate.arm({ agentId: 'a', provider: 'claude', signal: est, now: NOW });
+ gate.forget(scopeFor('claude', 'a'));
+
+ const fresh = gate.arm({ agentId: 'a', provider: 'claude', signal: est, now: NOW + MIN });
+ assert.equal(fresh.attempts, 1, 'a forgotten scope starts back at the bottom of the ladder');
+});
+
+/* ──────────────────────── detector → gate, end to end ────────────────────── */
+
+test('main and the renderer derive the same scope key', () => {
+ // The gate files holds under this key and the renderer's drain loop looks
+ // them up by it. If the two ever derived it separately and drifted, every
+ // hold would be armed and then matched by nobody — a gate that silently
+ // does nothing. One exported function, re-exported, is the guarantee.
+ assert.equal(scopeFor, sharedScopeFor);
+});
+
+test('a real claude banner flows from pty chunk to a held provider', () => {
+ const gate = new LimitGate();
+ const detector = createLimitDetector('claude');
+ const now = Date.parse('2026-08-10T20:00:00Z');
+
+ const signal = detector.push(
+ "\x1b[31m✗\x1b[0m You've hit your session limit · resets 3pm (America/Los_Angeles)\r\n",
+ now
+ );
+ assert.ok(signal, 'the banner must be detected');
+
+ const hold = gate.arm({ agentId: 'worker-1', provider: 'claude', signal, now });
+ assert.equal(hold.tier, 'quota');
+ assert.equal(hold.resetAt, Date.parse('2026-08-10T22:00:00Z'));
+
+ // Held now, and still held five minutes before the reset...
+ assert.ok(gate.holdFor('claude', 'worker-1'));
+ assert.deepEqual(gate.sweep(hold.resetAt - 5 * MIN), []);
+ // ...and clear once the sweep past its reset time lifts it.
+ assert.equal(gate.sweep(hold.resetAt + 1000).length, 1);
+ assert.equal(gate.holdFor('claude', 'worker-1'), null);
+});
+
+test('a screen full of repaints produces exactly one hold', () => {
+ const gate = new LimitGate();
+ const detector = createLimitDetector('claude');
+ const frame = "You've hit your session limit · resets 3pm (America/Los_Angeles)\n";
+ let armed = 0;
+ let t = NOW;
+
+ // A TUI redrawing at ~10fps for three seconds.
+ for (let i = 0; i < 30; i += 1) {
+ t += 100;
+ const signal = detector.push(frame, t);
+ if (!signal) continue;
+ if (gate.arm({ agentId: 'a', provider: 'claude', signal, now: t })) armed += 1;
+ }
+ assert.equal(armed, 1);
+ assert.equal(gate.list().length, 1);
+});
diff --git a/test/rate-limit.test.cjs b/test/rate-limit.test.cjs
new file mode 100644
index 00000000..1376a3b1
--- /dev/null
+++ b/test/rate-limit.test.cjs
@@ -0,0 +1,222 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const {
+ detectLimit,
+ classifyLine,
+ parseResetAt,
+ createLimitDetector,
+ backoffFor,
+ QUOTA_BACKOFF_MS,
+ MAX_HOLD_MS
+} = loadTs('src/shared/rateLimit.ts');
+
+/** 2026-08-10 20:00 UTC = 13:00 PDT. Fixed so clock parsing is host-independent. */
+const NOW = Date.parse('2026-08-10T20:00:00Z');
+const iso = (s) => Date.parse(s);
+
+/* ─────────────────────────── quota, the real thing ───────────────────────── */
+
+test('claude session-limit banner is a quota hit with the stated reset', () => {
+ const hit = detectLimit(
+ "You've hit your session limit · resets 3pm (America/Los_Angeles)",
+ { provider: 'claude', now: NOW }
+ );
+ assert.equal(hit.tier, 'quota');
+ assert.equal(hit.resetSource, 'stated');
+ assert.equal(hit.resetAt, iso('2026-08-10T22:00:00Z'));
+});
+
+test('a reset clock already past today means the same time tomorrow', () => {
+ // 1pm Los Angeles is exactly `NOW`, so the next one is a day out.
+ const hit = detectLimit(
+ "You've hit your weekly limit · resets 1pm (America/Los_Angeles)",
+ { provider: 'claude', now: NOW }
+ );
+ assert.equal(hit.resetAt, iso('2026-08-11T20:00:00Z'));
+});
+
+test('a dated reset across a DST boundary lands on the right instant', () => {
+ // Nov 12 2026 is PST (UTC-8); "now" is still PDT (UTC-7). A single-pass
+ // offset conversion would put this an hour out.
+ const hit = detectLimit(
+ "You've hit your weekly limit · resets Nov 12, 3pm (America/Los_Angeles)",
+ { provider: 'claude', now: Date.parse('2026-10-31T20:00:00Z') }
+ );
+ assert.equal(hit.tier, 'quota');
+ assert.equal(hit.resetAt, iso('2026-11-12T23:00:00Z'));
+});
+
+test('claude non-interactive epoch form is read as seconds', () => {
+ const at = Math.floor(NOW / 1000) + 3600;
+ const hit = detectLimit(`Claude AI usage limit reached|${at}`, { provider: 'claude', now: NOW });
+ assert.equal(hit.tier, 'quota');
+ assert.equal(hit.resetSource, 'stated');
+ assert.equal(hit.resetAt, at * 1000);
+});
+
+test('bare "Session limit reached" holds even with no time stated', () => {
+ const hit = detectLimit('Session limit reached', { provider: 'claude', now: NOW });
+ assert.equal(hit.tier, 'quota');
+ assert.equal(hit.resetSource, 'estimated');
+ assert.equal(hit.resetAt, NOW + QUOTA_BACKOFF_MS[0]);
+});
+
+test("pi's own terminal-error vocabulary is quota", () => {
+ for (const line of [
+ 'Monthly usage limit reached',
+ 'GoUsageLimitError: plan allowance spent',
+ 'Error: insufficient_quota',
+ 'quota exceeded for this project'
+ ]) {
+ assert.equal(detectLimit(line, { provider: 'pi', now: NOW })?.tier, 'quota', line);
+ }
+});
+
+test('gemini-lineage RESOURCE_EXHAUSTED is quota', () => {
+ assert.equal(
+ detectLimit('[429] RESOURCE_EXHAUSTED: Quota exceeded for quota metric', { provider: 'qwen', now: NOW })?.tier,
+ 'quota'
+ );
+});
+
+/* ────────────────────────── throttle, the other tier ─────────────────────── */
+
+test('transient pushback is a throttle, not a quota hold', () => {
+ for (const line of [
+ '429 Too Many Requests',
+ 'API Error: rate_limit_error',
+ 'Provider overloaded_error, retrying',
+ 'Server is temporarily limiting requests (not your usage limit)'
+ ]) {
+ assert.equal(detectLimit(line, { now: NOW })?.tier, 'throttle', line);
+ }
+});
+
+test('throttle backs off in seconds where quota backs off in minutes', () => {
+ const hit = detectLimit('429 Too Many Requests', { now: NOW });
+ assert.equal(hit.resetAt - NOW, backoffFor('throttle', 0));
+ assert.ok(hit.resetAt - NOW < QUOTA_BACKOFF_MS[0]);
+});
+
+test('quota outranks throttle when both are on screen', () => {
+ const screen = [
+ '429 Too Many Requests — retrying',
+ '429 Too Many Requests — retrying',
+ "You've hit your session limit · resets 3pm (America/Los_Angeles)"
+ ].join('\n');
+ assert.equal(detectLimit(screen, { provider: 'claude', now: NOW }).tier, 'quota');
+});
+
+/* ─────────────────────────────── false positives ─────────────────────────── */
+
+test('the approaching-limit warning does NOT park the floor', () => {
+ // Claude renders this from the same component as the real banner, at ~80%
+ // usage. Matching it would stand the fleet down hours early, every session.
+ assert.equal(
+ detectLimit('Approaching session limit · resets 3pm', { provider: 'claude', now: NOW }),
+ null
+ );
+ assert.equal(detectLimit("You've used 82% of your session limit", { provider: 'claude', now: NOW }), null);
+});
+
+test('source code and config mentioning rate limits is not a limit', () => {
+ for (const line of [
+ 'const rateLimitMs = options?.rateLimitMs ?? RATE_LIMIT_MS;',
+ ' ...rateLimit ? { rateLimit: true } : {},',
+ 'export const RATE_LIMIT = 120;',
+ ' enforceRateLimit(outputDir, now, rateLimitMs);',
+ 'Supply a token to download code from GitHub with a higher rate limit',
+ '--rate-limit-window 60'
+ ]) {
+ assert.equal(classifyLine(line), null, line);
+ }
+});
+
+test('non-LLM limits from bundled runtimes are ignored', () => {
+ for (const line of [
+ 'old generation allocation limit reached',
+ '[IncrementalMarking] 90% of the memory limit reached',
+ 'SRTP event: reached hard key usage limit',
+ 'Hard turn limit reached (consecutive-interrupt safety net).'
+ ]) {
+ assert.equal(classifyLine(line), null, line);
+ }
+});
+
+test('a minified bundle scrolling past cannot trigger a hold', () => {
+ const long = `${'x'.repeat(600)} rate_limit_error ${'y'.repeat(600)}`;
+ assert.equal(classifyLine(long), null);
+});
+
+/* ──────────────────────────── reset-time parsing ─────────────────────────── */
+
+test('relative durations', () => {
+ assert.equal(parseResetAt('Try again in 4h 32m', NOW), NOW + (4 * 3600 + 32 * 60) * 1000);
+ assert.equal(parseResetAt('rate limited, retry in 90 seconds', NOW), NOW + 90_000);
+ assert.equal(parseResetAt('resets in 2 hours', NOW), NOW + 7_200_000);
+});
+
+test('retry-after header is seconds per RFC 9110', () => {
+ assert.equal(parseResetAt('retry-after: 3600', NOW), NOW + 3_600_000);
+});
+
+test('ISO timestamps win over any clock text on the same screen', () => {
+ assert.equal(
+ parseResetAt('limit resets at 2026-08-10T23:30:00Z (3pm local)', NOW),
+ iso('2026-08-10T23:30:00Z')
+ );
+});
+
+test('24-hour clocks parse', () => {
+ assert.equal(
+ parseResetAt('resets at 23:30 (America/Los_Angeles)', NOW),
+ iso('2026-08-11T06:30:00Z')
+ );
+});
+
+test('an unparseable reset returns undefined rather than a guess', () => {
+ assert.equal(parseResetAt('resets soon', NOW), undefined);
+ assert.equal(parseResetAt('resets in 3', NOW), undefined);
+ assert.equal(parseResetAt('no time here at all', NOW), undefined);
+});
+
+test('a reset further out than the hold ceiling is refused', () => {
+ const at = new Date(NOW + MAX_HOLD_MS + 86_400_000).toISOString();
+ assert.equal(parseResetAt(`limit resets at ${at}`, NOW), undefined);
+});
+
+test('detectLimit clamps a hold to the ceiling', () => {
+ const hit = detectLimit('Session limit reached', { now: NOW, attempt: 99 });
+ assert.ok(hit.resetAt <= NOW + MAX_HOLD_MS);
+});
+
+/* ───────────────────────────── streaming behaviour ───────────────────────── */
+
+test('a banner split across two pty writes is still caught, once', () => {
+ const d = createLimitDetector('claude');
+ assert.equal(d.push("You've hit your ses", NOW), null);
+ const hit = d.push('sion limit · resets 3pm (America/Los_Angeles)\n', NOW + 20);
+ assert.equal(hit?.tier, 'quota');
+ assert.equal(hit.resetAt, iso('2026-08-10T22:00:00Z'));
+});
+
+test('a tui repainting the same banner reports it once', () => {
+ const d = createLimitDetector('claude');
+ const frame = "You've hit your session limit · resets 3pm (America/Los_Angeles)\n";
+ assert.ok(d.push(frame, NOW));
+ assert.equal(d.push(frame, NOW + 1000), null);
+ assert.equal(d.push(frame, NOW + 5000), null);
+ // Past the repeat window it is treated as news again; the gate then decides
+ // whether it is a genuine second rejection.
+ assert.ok(d.push(frame, NOW + 60_000));
+});
+
+test('ansi colouring does not hide a banner', () => {
+ const d = createLimitDetector('claude');
+ const hit = d.push('Session limit reached\r\n', NOW);
+ assert.equal(hit?.tier, 'quota');
+});