feat(usage-limit): recover gracefully when a subscription runs out #11215
Closedsaphid(GitHub profile, opens in a new tab)wants to merge 4 commits into
main fromrefs/pull/11215/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/web/src/components/ChatView.tsx line 9517Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -8357,3 +8429,4 @@83578429 />83588430 <ThreadErrorBanner83598431 error={visibleThreadError}8432+ usageLimitResetsAt={usageLimitResetsAt}apps/server/src/persistence/Layers/ProjectionThreadSessions.ts lines 56 to 56Resolvedby saphid(GitHub profile, opens in a new tab)@@ -48,3 +52,5 @@4852 runtime_mode = excluded.runtime_mode,4953 active_turn_id = excluded.active_turn_id,5054 last_error = excluded.last_error,55+ last_error_kind = excluded.last_error_kind,56+ last_error_resets_at = excluded.last_error_resets_at,apps/server/src/orchestration/UsageLimitResumeReactor.ts line 59OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +39,21 @@39+ const nowMs = DateTime.toEpochMillis(yield* DateTime.now);40+ const dueThreads = snapshot.threads.filter(41+ (thread) =>42+ thread.usageLimitResumeAt !== null &&43+ thread.usageLimitResumeAt !== undefined &&44+ thread.session?.status !== "running" &&45+ thread.session?.status !== "starting" &&46+ DateTime.make(thread.usageLimitResumeAt).pipe(47+ Option.match({48+ onNone: () => false,49+ onSome: (resumeAt) => DateTime.toEpochMillis(resumeAt) <= nowMs,50+ }),51+ ),52+ );53+54+ yield* Effect.forEach(55+ dueThreads,56+ Effect.fn("UsageLimitResumeReactor.resumeThread")(function* (thread) {57+ // The turn.start itself disarms the resume in the decider; if the58+ // provider rejects the turn again the failure re-arms a fresh window.59+ yield* engine.dispatch({apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts line 1749Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1605,3 +1605,6 @@16051605 : status === "ready" || status === "interrupted"16061606 ? null16071607 : (thread.session?.lastError ?? null);1608+ // A usage-limit failure keeps the failure classified until the next1609+ // failure overwrites it or the session recovers to ready/interrupted.1610+ const lastErrorKind =apps/server/src/provider/Layers/CodexAdapter.ts line 2390Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2384,4 +2385,6 @@23842385 ? completedPayload.turn.error23852386 : undefined;23862387 if (turnError?.codexErrorInfo === "usageLimitExceeded") {2387- usageLimitMessage = codexUsageLimitMessage(rateLimits, event.createdAt);2388+ const limit = codexUsageLimitMessage(rateLimits, event.createdAt);2389+ usageLimitMessage = limit.message;2390+ usageLimitResetsAtMs = limit.resetsAtMs;@@ -284,3 +285,4 @@284285 Layer.provideMerge(CheckpointReactorLive),285286 Layer.provideMerge(ThreadDeletionReactorLive),286287 Layer.provideMerge(ThreadSettlementReactor.layer),288+ Layer.provideMerge(UsageLimitResumeReactor.layer),apps/web/src/components/ChatView.tsx line 5885OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -5855,0 +5865,21 @@5865+ // A usage-limit failure parks this thread; the card explains the window and5866+ // owns the auto-resume toggle. `session.lastErrorKind === "usage_limit"`5867+ // carries the failure class and `lastErrorResetsAt` the window end; the5868+ // armed state lives in `usageLimitResumeAt` on the thread shell.5869+ const armUsageResumeMutation = useAtomCommand(threadEnvironment.armUsageResume, {5870+ reportFailure: false,5871+ });5872+ const disarmUsageResumeMutation = useAtomCommand(threadEnvironment.disarmUsageResume, {5873+ reportFailure: false,5874+ });5875+ const usageLimitFailure = activeThread?.session ?? null;5876+ const isUsageLimitFailed =5877+ usageLimitFailure?.status === "error" &&5878+ usageLimitFailure.lastErrorKind === "usage_limit" &&5879+ typeof usageLimitFailure.lastErrorResetsAt === "string";5880+ const usageLimitResumeArmed = activeThreadShell?.usageLimitResumeAt != null;5881+ const handleToggleUsageResume = useCallback(() => {5882+ if (!activeThreadRef || !isUsageLimitFailed) return;5883+ const resetsAt = usageLimitFailure.lastErrorResetsAt;5884+ if (typeof resetsAt !== "string") return;5885+ void (usageLimitResumeArmedapps/server/src/provider/Layers/ClaudeAdapter.ts line 2783Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2620,3 +2632,7 @@26202632 ? { totalCostUsd: result.total_cost_usd }26212633 : {}),26222634 ...(errorMessage ? { errorMessage } : {}),2635+ ...(failure2636+ ? {2637+ failureReason: failure.reason,2638+ ...(failure.resetsAtMs !== undefined ? { failureResetsAt: failure.resetsAtMs } : {}),apps/server/src/orchestration/decider.ts line 1416OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1388,3 +1396,21 @@1396+ commandId: command.commandId,1397+ })),1398+ type: "thread.usage-resume-disarmed",1399+ payload: {1400+ threadId: command.threadId,1401+ reason: "turn-started",1402+ },1403+ });1404+ }13881405 return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];13891406 }139014071408+ case "thread.usage-resume.arm": {1409+ const thread = yield* requireThread({1410+ readModel,1411+ command,1412+ threadId: command.threadId,1413+ });1414+ // Arm only when the window is actually in the future; the provider1415+ // reactor disarms separately when the failure clears early.1416+ if (!(Date.parse(command.resumeAt) > Date.parse(command.createdAt))) {apps/server/src/orchestration/decider.ts line 1563Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1388,3 +1388,21 @@1388+ // A user-sent (or auto-resume) turn supersedes any armed usage-limit1389+ // resume: the failure is about to be retried by this very turn.1390+ if (targetThread.usageLimitResumeAt != null) {1391+ lifecycleResetEvents.push({1392+ ...(yield* withEventBase({1393+ aggregateKind: "thread",1394+ aggregateId: command.threadId,1395+ occurredAt: command.createdAt,1396+ commandId: command.commandId,1397+ })),1398+ type: "thread.usage-resume-disarmed",1399+ payload: {1400+ threadId: command.threadId,1401+ reason: "turn-started",1402+ },1403+ });1404+ }13881405 return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];13891406 }139014071408+ case "thread.usage-resume.arm": {
- apps/server/src/orchestration/decider.ts lines 1416 to 1422OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1388,3 +1402,21 @@1402+ },1403+ });1404+ }13881405 return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];13891406 }139014071408+ case "thread.usage-resume.arm": {1409+ const thread = yield* requireThread({1410+ readModel,1411+ command,1412+ threadId: command.threadId,1413+ });1414+ // Arm only when the window is actually in the future; the provider1415+ // reactor disarms separately when the failure clears early.1416+ if (!(Date.parse(command.resumeAt) > Date.parse(command.createdAt))) {1417+ return yield* new OrchestrationCommandInvariantError({1418+ commandType: command.type,1419+ detail: `thread ${command.threadId} usage-resume time ${command.resumeAt} is not in the future`,1420+ });1421+ }1422+ if (thread.session?.status === "running" || thread.session?.status === "starting") {apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts lines 1610 to 1631OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1607,0 +1611,21 @@1611+ event.type === "turn.completed" &&1612+ normalizeRuntimeTurnState(event.payload.state) === "failed" &&1613+ event.payload.failureReason === "usage_limit"1614+ ? ("usage_limit" as const)1615+ : status === "ready" || status === "interrupted"1616+ ? undefined1617+ : (thread.session?.lastErrorKind ?? undefined);1618+ const lastErrorResetsAt =1619+ event.type === "turn.completed" &&1620+ normalizeRuntimeTurnState(event.payload.state) === "failed" &&1621+ event.payload.failureReason === "usage_limit"1622+ ? typeof event.payload.failureResetsAt === "number" &&1623+ Number.isFinite(event.payload.failureResetsAt)1624+ ? DateTime.make(event.payload.failureResetsAt).pipe(1625+ Option.match({1626+ onNone: () => null,1627+ onSome: (resetsAt) => DateTime.formatIso(resetsAt),1628+ }),1629+ )1630+ : null1631+ : undefined;apps/server/src/orchestration/UsageLimitResumeReactor.ts lines 54 to 101Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +57,21 @@57+ // The turn.start itself disarms the resume in the decider; if the58+ // provider rejects the turn again the failure re-arms a fresh window.59+ yield* engine.dispatch({60+ type: "thread.turn.start",61+ commandId: CommandId.make(62+ `server:usage-limit-resume:${thread.id}:${yield* crypto.randomUUIDv4}`,63+ ),64+ threadId: ThreadId.make(thread.id),65+ message: {66+ messageId: MessageId.make(yield* crypto.randomUUIDv4),67+ role: "user",68+ text: USAGE_LIMIT_RESUME_PROMPT,69+ attachments: [],70+ },71+ runtimeMode: thread.runtimeMode,72+ interactionMode: thread.interactionMode,73+ createdAt: DateTime.formatIso(yield* DateTime.now),74+ });75+ }),76+ { concurrency: 1, discard: true },77+ );apps/server/src/provider/Layers/ClaudeAdapter.ts lines 3924 to 3927OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3886,5 +3912,16 @@38863912 // Current blocking evidence is independent of whether its warning has38873913 // already been shown. A recovery can omit or advance the reset time;38883914 // its window type remains stable without clearing another window.3889- if (blocked) context.turnState.rejectedRateLimitTypes.add(limitType);3890- else if (3915+ if (blocked) {3916+ context.turnState.rejectedRateLimitTypes.add(limitType);3917+ const resetsAtMs =3918+ rateLimitInfo.resetsAt !== undefined ? rateLimitInfo.resetsAt * 1000 : undefined;3919+ const nowMs = yield* Clock.currentTimeMillis;3920+ if (3921+ resetsAtMs !== undefined &&3922+ Number.isFinite(resetsAtMs) &&3923+ resetsAtMs <= nowMs + CLAUDE_USAGE_LIMIT_MAX_WAIT_MS &&3924+ (context.turnState.usageLimitResetsAtMs === undefined ||3925+ resetsAtMs > context.turnState.usageLimitResetsAtMs)3926+ ) {3927+ context.turnState.usageLimitResetsAtMs = resetsAtMs;apps/server/src/provider/Layers/CodexAdapter.ts lines 2388 to 2390Resolvedby saphid(GitHub profile, opens in a new tab)@@ -2384,4 +2385,6 @@23842385 ? completedPayload.turn.error23852386 : undefined;23862387 if (turnError?.codexErrorInfo === "usageLimitExceeded") {2387- usageLimitMessage = codexUsageLimitMessage(rateLimits, event.createdAt);2388+ const limit = codexUsageLimitMessage(rateLimits, event.createdAt);2389+ usageLimitMessage = limit.message;2390+ usageLimitResetsAtMs = limit.resetsAtMs;apps/web/src/components/chat/ThreadErrorBanner.test.tsx line 84OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -69,3 +69,16 @@6969 it("never shows a null error", () => {7070 expect(shouldShowThreadErrorBanner("env:thread-e", null, false)).toBe(false);7171 });72+73+ it("calms a usage-limit failure to a countdown notice instead of the raw error", () => {74+ const markup = renderToStaticMarkup(75+ <ThreadErrorBanner76+ error="Your org has used all tokens under the current rate limit"77+ usageLimitResetsAt="2099-01-01T12:00:00.000Z"78+ onDismiss={() => {}}79+ />,80+ );81+82+ expect(markup).toContain("Reached your plan's usage limit");83+ expect(markup).toContain("resets in");84+ expect(markup).not.toContain("rate limit exceeded");
- apps/web/src/components/chat/ComposerUsageLimit.tsx line 27Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +5,21 @@5+import type { ComposerBannerStackItem } from "./ComposerBannerStack";6+import { UsageLimitCountdown } from "./UsageLimitCountdown";7+8+/**9+ * The composer card for a usage-limit failure. The unavailable state stays10+ * visible the whole window; the action toggles auto-resume on and back off11+ * without ever hiding the notice. Auto-resume here mirrors the server's own12+ * sweep — both dispatch an ordinary turn when the window passes.13+ */14+export function usageLimitBannerItem(input: {15+ readonly threadId: string;16+ readonly resetsAt: string;17+ readonly autoResumeArmed: boolean;18+ readonly onArmAutoResume: () => void;19+ readonly onCancelAutoResume: () => void;20+}): ComposerBannerStackItem {21+ const { threadId, resetsAt, autoResumeArmed, onArmAutoResume, onCancelAutoResume } = input;22+ // Track whether the window has passed so the arm action can't fire once23+ // the server would reject it; the countdown flips its label at the same24+ // moment, and a re-render every 30s is enough to catch the flip.25+ const [windowPassed, setWindowPassed] = useState(() => Date.now() >= Date.parse(resetsAt));
- apps/web/src/components/chat/ComposerUsageLimit.tsx line 27Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +5,21 @@5+import type { ComposerBannerStackItem } from "./ComposerBannerStack";6+import { UsageLimitCountdown } from "./UsageLimitCountdown";7+8+/**9+ * The composer card for a usage-limit failure. The unavailable state stays10+ * visible the whole window; the action toggles auto-resume on and back off11+ * without ever hiding the notice. Auto-resume here mirrors the server's own12+ * sweep — both dispatch an ordinary turn when the window passes.13+ */14+export function usageLimitBannerItem(input: {15+ readonly threadId: string;16+ readonly resetsAt: string;17+ readonly autoResumeArmed: boolean;18+ readonly onArmAutoResume: () => void;19+ readonly onCancelAutoResume: () => void;20+}): ComposerBannerStackItem {21+ const { threadId, resetsAt, autoResumeArmed, onArmAutoResume, onCancelAutoResume } = input;22+ // Track whether the window has passed so the arm action can't fire once23+ // the server would reject it; the countdown flips its label at the same24+ // moment, and a re-render every 30s is enough to catch the flip.25+ const [windowPassed, setWindowPassed] = useState(() => Date.now() >= Date.parse(resetsAt));
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 4070Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3886,5 +3931,12 @@38863931 // Current blocking evidence is independent of whether its warning has38873932 // already been shown. A recovery can omit or advance the reset time;38883933 // its window type remains stable without clearing another window.3889- if (blocked) context.turnState.rejectedRateLimitTypes.add(limitType);3890- else if (3934+ if (blocked) {3935+ context.turnState.rejectedRateLimitTypes.add(limitType);3936+ const resetsAtMs =3937+ rateLimitInfo.resetsAt !== undefined ? rateLimitInfo.resetsAt * 1000 : undefined;3938+ const nowMs = yield* Clock.currentTimeMillis;3939+ if (3940+ resetsAtMs !== undefined &&3941+ Number.isFinite(resetsAtMs) &&3942+ resetsAtMs > nowMs &&
- apps/web/src/components/chat/ComposerUsageLimit.tsx lines 40 to 40OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +20,21 @@20+ readonly onCancelAutoResume: () => void;21+}) {22+ const { resetsAt, autoResumeArmed, onArmAutoResume, onCancelAutoResume } = input;23+ // Track whether the window has passed so the arm action can't fire once the24+ // server would reject it; the countdown flips its label at the same moment,25+ // and a re-render every 30s is enough to catch the flip. Re-syncing whenever26+ // a new window arrives keeps a passed window from disabling the next one.27+ const [windowPassed, setWindowPassed] = useState(() => Date.now() >= Date.parse(resetsAt));28+ useEffect(() => {29+ setWindowPassed(Date.now() >= Date.parse(resetsAt));30+ const interval = window.setInterval(() => {31+ setWindowPassed(Date.now() >= Date.parse(resetsAt));32+ }, 30_000);33+ return () => window.clearInterval(interval);34+ }, [resetsAt]);35+ const armed = autoResumeArmed && !windowPassed;36+ return (37+ <Button38+ size="xs"39+ variant="ghost"40+ onClick={armed ? onCancelAutoResume : onArmAutoResume}
- apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts line 1700OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1642,7 +1687,14 @@16421687 runtimeMode: thread.session?.runtimeMode ?? "full-access",16431688 activeTurnId: nextActiveTurnId,16441689 lastError,1690+ ...(lastErrorKind !== undefined ? { lastErrorKind } : {}),1691+ ...(lastErrorResetsAt !== undefined ? { lastErrorResetsAt } : {}),16451692 updatedAt: now,16461693 },16471694 createdAt: now,16481695 });1696+1697+ // Arming is the user's call (the composer card toggles it); the1698+ // ingestion only drops a stale arm when the thread recovers to1699+ // ready, so the sweep never resurrects a thread that got better.1700+ if (status === "ready" && thread.usageLimitResumeAt != null) {
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -6269,0 +6296,21 @@6296+ });6297+ const usageLimitFailure = activeThread?.session ?? null;6298+ const isUsageLimitFailed =6299+ usageLimitFailure?.status === "error" &&6300+ usageLimitFailure.lastErrorKind === "usage_limit" &&6301+ typeof usageLimitFailure.lastErrorResetsAt === "string";6302+ const usageLimitResumeArmed = activeThreadShell?.usageLimitResumeAt != null;6303+ const handleToggleUsageResume = useCallback(() => {6304+ if (!activeThreadRef || !isUsageLimitFailed) return;6305+ const resetsAt = usageLimitFailure.lastErrorResetsAt;6306+ if (typeof resetsAt !== "string") return;6307+ if (usageLimitResumeArmed) {6308+ void disarmUsageResumeMutation({6309+ environmentId: activeThreadRef.environmentId,6310+ input: { threadId: activeThreadRef.threadId },6311+ });6312+ return;6313+ }6314+ // The server rejects an arm whose window already ended; skip the dispatch6315+ // for the click that lands between expiry and the card's next refresh.6316+ if (Date.now() >= Date.parse(resetsAt)) return;apps/server/src/provider/Layers/ClaudeAdapter.ts line 299Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -277,0 +279,21 @@279+ /**280+ * Credible reset time (epoch ms) per blocked window type. Reported on281+ * turn.completed as the max across the windows still rejected at that282+ * moment — a turn parked on two windows can only resume once the later one283+ * resets, and a window that recovers must stop contributing its stamp.284+ */285+ usageLimitResetsAtMsByType: Map<string, number>;286+}287+288+/**289+ * The failure's reset time: the latest stamp among the windows still blocked290+ * when the turn ended. A window that recovered earlier must not extend the291+ * wait past the windows that actually parked the turn.292+ */293+function maxUsageLimitResetMs(turn: {294+ readonly rejectedRateLimitTypes: ReadonlySet<string>;295+ readonly usageLimitResetsAtMsByType: ReadonlyMap<string, number>;296+}): number | undefined {297+ let max: number | undefined;298+ for (const limitType of turn.rejectedRateLimitTypes) {299+ const resetsAtMs = turn.usageLimitResetsAtMsByType.get(limitType);
- apps/server/src/orchestration/UsageLimitResumeReactor.ts line 129Resolvedby saphid(GitHub profile, opens in a new tab)@@ -0,0 +109,21 @@109+ cause: Cause.pretty(cause),110+ }),111+ ),112+ );113+ const worker = yield* makeDrainableWorker(() => runSweep);114+115+ const start: UsageLimitResumeReactor["Service"]["start"] = Effect.fn(116+ "UsageLimitResumeReactor.start",117+ )(function* () {118+ yield* forkParked(119+ Effect.gen(function* () {120+ yield* worker.enqueue(undefined);121+ yield* worker.drain;122+ }).pipe(Effect.repeat(Schedule.spaced(USAGE_LIMIT_RESUME_SWEEP_INTERVAL)), Effect.asVoid),123+ );124+ });125+126+ return { start, drain: worker.drain } satisfies UsageLimitResumeReactor["Service"];127+});128+129+export const layer = Layer.effect(UsageLimitResumeReactor, make);
juliusmarminge closed this
Sign in to join this conversation.






macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed