Repository navigation
feat(v2): resume limited threads when usage resets #12686
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
juliusmarminge
merged 10 commits into
port-provider-limits-to-v2
from
provider-limits/auto-resume
Sep 21, 2026
+687
−4
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
a3a9fb3
feat(v2): resume limited threads at reset
juliusmarminge 67f4c90
fix(web): keep limit recovery above the composer
juliusmarminge 4be5d81
fix(v2): invalidate cancelled recovery deliveries
juliusmarminge e66c32a
fix(mobile): surface failed limit recovery changes
juliusmarminge 49a2b74
fix(web): show limit recovery in the banner stack
juliusmarminge a51df13
fix(web): preserve timeline spacing with recovery banners
juliusmarminge 0d83249
fix(web): keep usage limit banner concise
juliusmarminge ae6fa23
fix(server): retry continuations after a snooze race
juliusmarminge 96c0d27
refactor(server): qualify recovery service dependencies
juliusmarminge 9eea14d
refactor(server): name limit recovery as a worker
juliusmarminge File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
77 changes: 77 additions & 0 deletions
77
apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; | ||
| import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; | ||
| import type { EnvironmentId } from "@t3tools/contracts"; | ||
| import * as DateTime from "effect/DateTime"; | ||
| import { useState } from "react"; | ||
| import { Pressable, View } from "react-native"; | ||
| import { AppText as Text } from "../../components/AppText"; | ||
| import { threadEnvironment } from "../../state/threads"; | ||
| import { useAtomCommand } from "../../state/use-atom-command"; | ||
|
|
||
| export function UsageLimitRecoveryCard({ | ||
| thread, | ||
| environmentId, | ||
| }: { | ||
| thread: EnvironmentThreadShell; | ||
| environmentId: EnvironmentId; | ||
| }) { | ||
| const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata); | ||
| const [pending, setPending] = useState(false); | ||
| const [error, setError] = useState<string | null>(null); | ||
| const resetAt = thread.runtime?.usageLimitResetAt ?? null; | ||
| const canSchedule = | ||
| resetAt !== null && | ||
| Date.parse(resetAt) > Date.parse(thread.latestRun?.completedAt ?? thread.updatedAt); | ||
| const runId = thread.latestRun?.runId; | ||
| const recovery = thread.limitRecovery; | ||
| const scheduled = | ||
| recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume; | ||
| if ( | ||
| thread.runtime?.status !== "failed" || | ||
| thread.runtime.lastErrorClass !== "usage_limit" || | ||
| !runId | ||
| ) | ||
| return null; | ||
| async function toggle() { | ||
| if (!resetAt || !runId || !canSchedule) return; | ||
| setPending(true); | ||
| setError(null); | ||
| try { | ||
| const result = await updateMetadata({ | ||
| environmentId, | ||
| input: { threadId: thread.id, limitRecovery: { runId, resetAt, autoResume: !scheduled } }, | ||
| }); | ||
| if (result._tag === "Failure") throw squashAtomCommandFailure(result); | ||
| } catch (cause) { | ||
| setError(cause instanceof Error ? cause.message : "Could not change limit recovery."); | ||
| } finally { | ||
| setPending(false); | ||
| } | ||
| } | ||
| return ( | ||
| <View className="mx-3 mb-2 gap-2 rounded-xl border border-warning-foreground/25 bg-background p-3"> | ||
| <Text className="text-sm text-warning-foreground"> | ||
| {resetAt | ||
| ? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.` | ||
| : "The provider did not report a reset time. Retry manually when your limit is available."} | ||
| </Text> | ||
| {canSchedule ? ( | ||
| <Pressable | ||
| accessibilityRole="button" | ||
| disabled={pending} | ||
| onPress={() => void toggle()} | ||
| className="self-start rounded-lg bg-subtle px-3 py-2 active:opacity-70" | ||
| > | ||
| <Text className="text-sm text-foreground"> | ||
| {scheduled ? "Cancel auto-resume" : "Resume at reset"} | ||
| </Text> | ||
| </Pressable> | ||
| ) : null} | ||
| {error ? ( | ||
| <Text accessibilityRole="alert" className="text-sm text-destructive"> | ||
| {error} | ||
| </Text> | ||
| ) : null} | ||
| </View> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
109 changes: 109 additions & 0 deletions
109
apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| import { | ||
| CommandId, | ||
| MessageId, | ||
| type OrchestrationV2ThreadShell, | ||
| type OrchestrationV2Command, | ||
| } from "@t3tools/contracts"; | ||
| import * as DateTime from "effect/DateTime"; | ||
| import * as Effect from "effect/Effect"; | ||
| import * as Layer from "effect/Layer"; | ||
| import * as Schedule from "effect/Schedule"; | ||
| import * as ServerSettings from "../serverSettings.ts"; | ||
| import * as ProjectionStore from "./ProjectionStore.ts"; | ||
| import * as ThreadManagement from "./ThreadManagementService.ts"; | ||
|
|
||
| /** The persisted run and reset form the identity of one recovery opportunity. */ | ||
| export function limitRecoveryCommand( | ||
| thread: OrchestrationV2ThreadShell, | ||
| autoResume: boolean, | ||
| nowMs: number, | ||
| ): OrchestrationV2Command | null { | ||
| if ( | ||
| thread.status !== "failed" || | ||
| thread.lastErrorClass !== "usage_limit" || | ||
| !thread.latestRunId || | ||
| !thread.usageLimitResetAt || | ||
| thread.archivedAt !== null || | ||
| thread.settledOverride === "settled" || | ||
| thread.pendingRuntimeRequest !== null | ||
| ) | ||
| return null; | ||
| const resetMs = Date.parse(thread.usageLimitResetAt); | ||
| // An already-expired window reported with a fresh failure cannot start a retry loop. | ||
| if ( | ||
| !Number.isFinite(resetMs) || | ||
| resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt) | ||
| ) | ||
| return null; | ||
| const identity = `${thread.id}:${thread.latestRunId}:${resetMs}`; | ||
| const recovery = thread.limitRecovery; | ||
| if (recovery?.runId !== thread.latestRunId || recovery.resetAt !== thread.usageLimitResetAt) { | ||
| if (!autoResume) return null; | ||
| return { | ||
| type: "thread.metadata.update", | ||
| commandId: CommandId.make(`limit-arm:${identity}`), | ||
| threadId: thread.id, | ||
| limitRecovery: { runId: thread.latestRunId, resetAt: thread.usageLimitResetAt, autoResume }, | ||
| }; | ||
| } | ||
| if ( | ||
| !recovery.autoResume || | ||
| resetMs > nowMs || | ||
| (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs) | ||
| ) | ||
| return null; | ||
| const deliveryIdentity = `${identity}:${recovery.requestId ?? "legacy"}`; | ||
| return { | ||
| type: "message.dispatch", | ||
| commandId: CommandId.make(`limit-resume:${deliveryIdentity}`), | ||
| messageId: MessageId.make(`limit-resume:${deliveryIdentity}`), | ||
| threadId: thread.id, | ||
| usageLimitContinuationOfRunId: thread.latestRunId, | ||
| ...(recovery.requestId === undefined | ||
| ? {} | ||
| : { usageLimitRecoveryRequestId: recovery.requestId }), | ||
| text: "Continue where you left off.", | ||
| attachments: [], | ||
| dispatchMode: { type: "start_immediately" }, | ||
| createdBy: "user", | ||
| creationSource: "server", | ||
| }; | ||
| } | ||
|
|
||
| const makeSweep = Effect.gen(function* () { | ||
| const projections = yield* ProjectionStore.ProjectionStoreV2; | ||
| const threads = yield* ThreadManagement.ThreadManagementService; | ||
| const settings = yield* ServerSettings.ServerSettingsService; | ||
| return Effect.fn("UsageLimitRecoveryWorker.sweep")(function* () { | ||
| const preferences = yield* settings.getSettings; | ||
| const snapshot = yield* projections.getShellSnapshot(); | ||
| const nowMs = DateTime.toEpochMillis(yield* DateTime.now); | ||
| for (const thread of snapshot.threads) { | ||
| const command = limitRecoveryCommand(thread, preferences.autoResumeLimitedThreads, nowMs); | ||
| if (command === null) continue; | ||
| yield* threads.dispatch(command).pipe( | ||
| Effect.catchCause((cause) => | ||
| Effect.logWarning("orchestration-v2.limit-recovery.dispatch-failed", { | ||
| threadId: thread.id, | ||
| cause, | ||
| }), | ||
| ), | ||
| ); | ||
| } | ||
| }); | ||
| }); | ||
|
|
||
| // The schedule is derived from persisted failures and thread recovery choices, | ||
| // so restarts need no timer restoration and disconnected clients need not run it. | ||
| export const workerLive = Layer.effectDiscard( | ||
| Effect.gen(function* () { | ||
| const sweep = yield* makeSweep; | ||
| yield* sweep().pipe( | ||
| Effect.catchCause((cause) => | ||
| Effect.logWarning("orchestration-v2.limit-recovery.sweep-failed", { cause }), | ||
| ), | ||
| Effect.repeat(Schedule.spaced("30 seconds")), | ||
| Effect.forkScoped, | ||
| ); | ||
| }), | ||
| ); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.