Skip to content

Commit 97d1304

Browse files
feat: continue a stopped thread when its usage limit resets
When Codex or Claude stops a turn on a usage limit, the thread error only carried the rendered sentence, so the user had to come back and resend by hand. The failed turn now carries the provider-reported reset instant (turn.completed usageLimitResetsAt -> session.lastErrorLimitResetsAt), the error banner offers "Continue when limit resets", and a persisted per-thread schedule (thread.auto-continue.set/.clear, autoContinueAt) is fired by a new sweep reactor that starts a Continue turn once the reset passes. The schedule survives restarts, is cancellable from the same banner on web and mobile, and any manual turn, settle, or archive clears it. Built by Claude Fable 5 via Cursor. Co-authored-by: Cursor <[email protected]>
1 parent 9946541 commit 97d1304

41 files changed

Lines changed: 1562 additions & 32 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import type { EnvironmentId, OrchestrationThreadShell } from "@t3tools/contracts";
2+
import { formatDuration } from "@t3tools/shared/usageLimits";
3+
import { useCallback } from "react";
4+
import { Pressable, View } from "react-native";
5+
6+
import { AppText as Text } from "../../components/AppText";
7+
import { appAtomRegistry } from "../../state/atom-registry";
8+
import { environmentServerConfigsAtom } from "../../state/server";
9+
import { threadEnvironment } from "../../state/threads";
10+
import { useAtomCommand } from "../../state/use-atom-command";
11+
12+
function environmentSupportsAutoContinue(environmentId: EnvironmentId) {
13+
return (
14+
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
15+
.threadAutoContinue === true
16+
);
17+
}
18+
19+
/**
20+
* "Continue when the limit resets" for a thread stopped by a provider usage
21+
* limit: offers scheduling while the session error carries a structured reset
22+
* instant, and shows the pending continuation with a cancel once scheduled.
23+
* Hidden on servers that predate thread.auto-continue (version skew).
24+
*/
25+
export function AutoContinueBanner(props: {
26+
readonly environmentId: EnvironmentId;
27+
readonly thread: OrchestrationThreadShell;
28+
}) {
29+
const setAutoContinue = useAtomCommand(threadEnvironment.setAutoContinue, {
30+
reportFailure: false,
31+
});
32+
const clearAutoContinue = useAtomCommand(threadEnvironment.clearAutoContinue, {
33+
reportFailure: false,
34+
});
35+
const { environmentId, thread } = props;
36+
const resetsAt = thread.session?.lastErrorLimitResetsAt ?? null;
37+
const scheduledFor = thread.autoContinueAt ?? null;
38+
39+
const schedule = useCallback(() => {
40+
if (resetsAt === null) return;
41+
void setAutoContinue({
42+
environmentId,
43+
input: { threadId: thread.id, autoContinueAt: resetsAt },
44+
});
45+
}, [environmentId, resetsAt, setAutoContinue, thread.id]);
46+
const cancel = useCallback(() => {
47+
void clearAutoContinue({
48+
environmentId,
49+
input: { threadId: thread.id, reason: "user" },
50+
});
51+
}, [clearAutoContinue, environmentId, thread.id]);
52+
53+
if (!environmentSupportsAutoContinue(environmentId)) return null;
54+
const now = Date.now();
55+
if (scheduledFor !== null) {
56+
const waitMs = Date.parse(scheduledFor) - now;
57+
return (
58+
<View className="shrink-0 px-4 pb-3">
59+
<View className="flex-row items-center gap-3 rounded-2xl border border-border bg-card px-3.5 py-3">
60+
<Text className="flex-1 text-sm text-muted-foreground">
61+
{waitMs > 0
62+
? `Continuing when the limit resets, in ${formatDuration(waitMs)}`
63+
: "Continuing when the limit resets"}
64+
</Text>
65+
<Pressable
66+
accessibilityRole="button"
67+
onPress={cancel}
68+
className="rounded-full bg-secondary px-4 py-2"
69+
>
70+
<Text className="text-sm">Cancel</Text>
71+
</Pressable>
72+
</View>
73+
</View>
74+
);
75+
}
76+
const isLimitError =
77+
thread.session?.status === "error" && resetsAt !== null && Date.parse(resetsAt) > now;
78+
if (!isLimitError || resetsAt === null) return null;
79+
return (
80+
<View className="shrink-0 px-4 pb-3">
81+
<View className="flex-row items-center gap-3 rounded-2xl border border-border bg-card px-3.5 py-3">
82+
<Text className="flex-1 text-sm text-muted-foreground">
83+
Usage limit reached. Resets in {formatDuration(Date.parse(resetsAt) - now)}.
84+
</Text>
85+
<Pressable
86+
accessibilityRole="button"
87+
onPress={schedule}
88+
className="rounded-full bg-secondary px-4 py-2"
89+
>
90+
<Text className="text-sm">Continue on reset</Text>
91+
</Pressable>
92+
</View>
93+
</View>
94+
);
95+
}

‎apps/mobile/src/features/threads/ThreadDetailScreen.tsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ import type {
8080
PendingUserInputDraftAnswer,
8181
ThreadFeedEntry,
8282
} from "../../lib/threadActivity";
83+
import { AutoContinueBanner } from "./AutoContinueBanner";
8384
import { PendingApprovalCard } from "./PendingApprovalCard";
8485
import { ComposerFeedback } from "./ComposerFeedback";
8586
import { ComposerUsageLimits } from "./ComposerUsageLimits";
@@ -1016,6 +1017,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
10161017
) : null}
10171018
</View>
10181019

1020+
<AutoContinueBanner
1021+
environmentId={props.environmentId}
1022+
thread={props.selectedThread}
1023+
/>
10191024
{/* Hidden (not unmounted) while a user-input request owns the
10201025
composer slot, so composer drafts and editor state survive.
10211026
A rejected creation has no thread to send to; the failure card

‎apps/server/integration/OrchestrationEngineHarness.integration.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ import {
6868
} from "../src/orchestration/Services/OrchestrationEngine.ts";
6969
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
7070
import * as ThreadSettlementReactor from "../src/orchestration/ThreadSettlementReactor.ts";
71+
import * as AutoContinueReactor from "../src/orchestration/AutoContinueReactor.ts";
7172
import * as PullRequestSyncReactor from "../src/orchestration/PullRequestSyncReactor.ts";
7273
import * as ThreadPullRequestReactor from "../src/orchestration/ThreadPullRequestReactor.ts";
7374
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
@@ -412,6 +413,12 @@ export const makeOrchestrationIntegrationHarness = (
412413
drain: Effect.void,
413414
}),
414415
),
416+
Layer.provideMerge(
417+
Layer.succeed(AutoContinueReactor.AutoContinueReactor, {
418+
start: () => Effect.void,
419+
drain: Effect.void,
420+
}),
421+
),
415422
Layer.provideMerge(
416423
Layer.succeed(PullRequestSyncReactor.PullRequestSyncReactor, {
417424
start: () => Effect.void,

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ export const make = Effect.gen(function* () {
230230
threadRestartContinuation: true,
231231
projectSettingsOverrides: true,
232232
threadSnooze: true,
233+
threadAutoContinue: true,
233234
environmentThemes: true,
234235
usageLimitSources: true,
235236
usagePriceOverrides: true,
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
import {
2+
ProjectId,
3+
ProviderInstanceId,
4+
ThreadId,
5+
type OrchestrationCommand,
6+
type OrchestrationShellSnapshot,
7+
type OrchestrationThreadShell,
8+
} from "@t3tools/contracts";
9+
import { assert, describe, it } from "@effect/vitest";
10+
import * as Crypto from "effect/Crypto";
11+
import * as Deferred from "effect/Deferred";
12+
import * as Effect from "effect/Effect";
13+
import * as Layer from "effect/Layer";
14+
import * as Queue from "effect/Queue";
15+
import * as Ref from "effect/Ref";
16+
import { TestClock } from "effect/testing";
17+
18+
import { ServerActivation } from "../serverActivation.ts";
19+
import * as AutoContinueReactor from "./AutoContinueReactor.ts";
20+
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
21+
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
22+
23+
const NOW = "2026-08-28T12:00:00.000Z";
24+
const DUE_AT = "2026-08-28T11:00:00.000Z";
25+
const LATER_AT = "2026-08-28T14:00:00.000Z";
26+
const PROJECT_ID = ProjectId.make("auto-continue-project");
27+
28+
type FireCommand = Extract<OrchestrationCommand, { readonly type: "thread.auto-continue.fire" }>;
29+
30+
const testCrypto = Crypto.make({
31+
randomBytes: (size) => new Uint8Array(size).fill(1),
32+
digest: (_algorithm, data) => Effect.succeed(data),
33+
});
34+
35+
function makeThread(
36+
id: string,
37+
overrides: Partial<OrchestrationThreadShell> = {},
38+
): OrchestrationThreadShell {
39+
return {
40+
id: ThreadId.make(id),
41+
projectId: PROJECT_ID,
42+
title: id,
43+
modelSelection: {
44+
instanceId: ProviderInstanceId.make("codex"),
45+
model: "gpt-5",
46+
},
47+
runtimeMode: "full-access",
48+
interactionMode: "default",
49+
pullRequests: [],
50+
branch: null,
51+
worktreePath: null,
52+
latestTurn: null,
53+
createdAt: "2026-08-01T00:00:00.000Z",
54+
updatedAt: NOW,
55+
archivedAt: null,
56+
settledOverride: null,
57+
settledAt: null,
58+
session: null,
59+
latestUserMessageAt: null,
60+
hasPendingApprovals: false,
61+
hasPendingUserInput: false,
62+
hasActionableProposedPlan: false,
63+
...overrides,
64+
};
65+
}
66+
67+
function makeSnapshot(
68+
threads: ReadonlyArray<OrchestrationThreadShell>,
69+
): OrchestrationShellSnapshot {
70+
return {
71+
snapshotSequence: 1,
72+
projects: [],
73+
threads,
74+
updatedAt: NOW,
75+
};
76+
}
77+
78+
const makeHarness = Effect.fn("makeAutoContinueHarness")(function* (
79+
snapshot: OrchestrationShellSnapshot,
80+
) {
81+
const activation = yield* Deferred.make<void>();
82+
const snapshotReads = yield* Queue.unbounded<void>();
83+
const commands = yield* Ref.make<ReadonlyArray<FireCommand>>([]);
84+
85+
const dependencies = Layer.mergeAll(
86+
Layer.mock(ProjectionSnapshotQuery)({
87+
getShellSnapshot: () => Queue.offer(snapshotReads, undefined).pipe(Effect.as(snapshot)),
88+
}),
89+
Layer.mock(OrchestrationEngineService)({
90+
dispatch: (command) => {
91+
if (command.type !== "thread.auto-continue.fire") {
92+
return Effect.die(new Error(`Unexpected command: ${command.type}`));
93+
}
94+
return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
95+
Effect.as({ sequence: 1 }),
96+
);
97+
},
98+
}),
99+
Layer.succeed(ServerActivation, Deferred.await(activation)),
100+
Layer.succeed(Crypto.Crypto, testCrypto),
101+
);
102+
103+
return {
104+
activation,
105+
snapshotReads,
106+
commands,
107+
layer: AutoContinueReactor.layer.pipe(Layer.provide(dependencies)),
108+
};
109+
});
110+
111+
describe("AutoContinueReactor", () => {
112+
it.effect("fires due continuations as thread.auto-continue.fire commands", () =>
113+
Effect.scoped(
114+
Effect.gen(function* () {
115+
yield* TestClock.setTime(Date.parse(NOW));
116+
const harness = yield* makeHarness(
117+
makeSnapshot([makeThread("due-thread", { autoContinueAt: DUE_AT })]),
118+
);
119+
yield* Effect.provide(
120+
Effect.gen(function* () {
121+
const reactor = yield* AutoContinueReactor.AutoContinueReactor;
122+
yield* reactor.start();
123+
yield* Deferred.succeed(harness.activation, undefined);
124+
yield* Queue.take(harness.snapshotReads);
125+
yield* reactor.drain;
126+
}),
127+
harness.layer,
128+
);
129+
const dispatched = yield* Ref.get(harness.commands);
130+
assert.strictEqual(dispatched.length, 1);
131+
assert.strictEqual(dispatched[0]?.threadId, "due-thread");
132+
assert.strictEqual(dispatched[0]?.autoContinueAt, DUE_AT);
133+
assert.isTrue(dispatched[0]?.commandId.startsWith("server:auto-continue:due-thread:"));
134+
assert.isString(dispatched[0]?.messageId);
135+
}),
136+
),
137+
);
138+
139+
it.effect("leaves future schedules, archived threads, and unscheduled threads alone", () =>
140+
Effect.scoped(
141+
Effect.gen(function* () {
142+
yield* TestClock.setTime(Date.parse(NOW));
143+
const harness = yield* makeHarness(
144+
makeSnapshot([
145+
makeThread("later-thread", { autoContinueAt: LATER_AT }),
146+
makeThread("archived-thread", { autoContinueAt: DUE_AT, archivedAt: NOW }),
147+
makeThread("plain-thread"),
148+
]),
149+
);
150+
yield* Effect.provide(
151+
Effect.gen(function* () {
152+
const reactor = yield* AutoContinueReactor.AutoContinueReactor;
153+
yield* reactor.start();
154+
yield* Deferred.succeed(harness.activation, undefined);
155+
yield* Queue.take(harness.snapshotReads);
156+
yield* reactor.drain;
157+
}),
158+
harness.layer,
159+
);
160+
const dispatched = yield* Ref.get(harness.commands);
161+
assert.strictEqual(dispatched.length, 0);
162+
}),
163+
),
164+
);
165+
});

0 commit comments

Comments
 (0)