Skip to content
TypeScript

fix(server): stopped usage-limit threads no longer auto-resume (#21114)

fixfon60f224635805
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 10fd37dc501..41077ee95db 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -27,6 +27,7 @@ import {
type ModelSelection,
OrchestrationV2Command,
type OrchestrationV2InternalCommand,
+ type OrchestrationV2LimitRecoveryUpdate,
type OrchestrationV2ServerCommand,
type ThreadPullRequestLink,
type ThreadPullRequestWatch,
@@ -312,6 +313,11 @@ export interface OrchestratorV2Shape {
readonly dispatch: (
command: OrchestrationV2ServerCommand,
) => Effect.Effect<OrchestratorV2DispatchResult, OrchestratorV2Error>;
+ readonly autoArmLimitRecovery: (input: {
+ readonly commandId: CommandId;
+ readonly threadId: ThreadId;
+ readonly limitRecovery: OrchestrationV2LimitRecoveryUpdate;
+ }) => Effect.Effect<void, OrchestratorV2Error>;
readonly searchThreadStream: (
input: OrchestrationV2SearchThreadInput,
) => Stream.Stream<OrchestrationV2SearchThreadResult, OrchestratorV2Error>;
@@ -8978,7 +8984,49 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
readonly now: DateTime.Utc;
}) {
const emitEvent = emit(input.events, input.command);
- const { thread, runs, subagents } = input.projection;
+ const { runs, subagents } = input.projection;
+ let { thread } = input.projection;
+ let recovery = thread.limitRecovery;
+ const latest = latestExecutedRun(runs);
+ if (latest?.status === "failed") {
+ const { turnItems } = yield* projectionStore
+ .getThreadRecords(thread.id, ["turnItems"], {
+ turnItemTypes: ["error"],
+ turnItemRunIds: [latest.id],
+ })
+ .pipe(mapDispatchError(input.command));
+ const failure = latestRootProviderFailure(latest, turnItems);
+ if (
+ failure?.class === "usage_limit" &&
+ failure.resetAt != null &&
+ Number.isFinite(Date.parse(failure.resetAt)) &&
+ (recovery?.runId !== latest.id || recovery.resetAt !== failure.resetAt)
+ ) {
+ recovery = {
+ runId: latest.id,
+ resetAt: failure.resetAt,
+ autoResume: false,
+ snooze: false,
+ };
+ }
+ }
+ if (recovery && (recovery !== thread.limitRecovery || recovery.autoResume)) {
+ thread = {
+ ...thread,
+ limitRecovery: {
+ ...recovery,
+ autoResume: false,
+ requestId: input.command.commandId,
+ },
+ updatedAt: input.now,
+ };
+ yield* emitEvent({
+ type: "thread.metadata-updated",
+ threadId: thread.id,
+ occurredAt: input.now,
+ payload: thread,
+ });
+ }
const queuedRuns = runs.filter((run) => run.status === "queued");
const queuedMessages =
queuedRuns.length === 0
@@ -11760,6 +11808,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
awaitRestartContinuation: (run) =>
effectOutbox.awaitSettled(`effect:restart-continuation:${run.id}`).pipe(Effect.ignore),
dispatch: dispatchWithReceipt,
+ autoArmLimitRecovery: (input) =>
+ threadDispatch.withLock(
+ input.threadId,
+ Effect.gen(function* () {
+ const thread = yield* projectionStore
+ .getThread(input.threadId)
+ .pipe(
+ Effect.mapError(
+ (cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }),
+ ),
+ );
+ // Stop or an explicit recovery choice can commit after the sweep reads its candidate.
+ if (
+ thread.limitRecovery?.runId === input.limitRecovery.runId &&
+ thread.limitRecovery.resetAt === input.limitRecovery.resetAt
+ )
+ return;
+ yield* dispatchWithReceiptEffect({ type: "thread.metadata.update", ...input });
+ }),
+ ),
searchThreadStream: (input) =>
projectionStore
.searchThreadStream(input)
@@ -11909,6 +11977,8 @@ const layerUnavailable: Layer.Layer<OrchestratorV2> = Layer.succeed(
delegatedTaskResultPending: () => Effect.succeed(false),
restartContinuationPending: () => Effect.succeed(false),
awaitRestartContinuation: () => Effect.void,
+ autoArmLimitRecovery: (input) =>
+ Effect.fail(new OrchestratorProjectionError({ threadId: input.threadId })),
dispatch: (command) =>
Effect.fail(
new OrchestratorDispatchError({
diff --git a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts
index 352c71ef62f..b6ebedfec4c 100644
--- a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts
+++ b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts
@@ -5,6 +5,7 @@ import * as Layer from "effect/Layer";
import * as Scheduler from "../scheduling/Scheduler.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
+import * as Orchestrator from "./Orchestrator.ts";
import * as ThreadManagement from "./ThreadManagementService.ts";
export function limitRecoveryCommand(
@@ -73,6 +74,7 @@ export function limitRecoveryCommand(
const makeSweep = Effect.gen(function* () {
const projections = yield* ProjectionStore.ProjectionStoreV2;
const threads = yield* ThreadManagement.ThreadManagementService;
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
const settings = yield* ServerSettings.ServerSettingsService;
return Effect.fn("UsageLimitRecoveryWorker.sweep")(function* () {
const preferences = yield* settings.getSettings;
@@ -91,7 +93,17 @@ const makeSweep = Effect.gen(function* () {
preferences.snoozeLimitedThreads,
);
if (command === null) continue;
- yield* threads.dispatch(command).pipe(
+ yield* Effect.gen(function* () {
+ if (command.type === "thread.metadata.update" && command.limitRecovery != null) {
+ yield* orchestrator.autoArmLimitRecovery({
+ commandId: command.commandId,
+ threadId: command.threadId,
+ limitRecovery: command.limitRecovery,
+ });
+ } else {
+ yield* threads.dispatch(command);
+ }
+ }).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("orchestration-v2.limit-recovery.dispatch-failed", {
threadId: thread.id,
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index 0dd515a1a8c..5ab27737554 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -6198,6 +6198,9 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
"independent-patches",
"expired-snooze",
"wake",
+ "stop",
+ "stop-before-arm",
+ "stop-before-arm-mismatched-recovery",
] as const)("guards a scheduled usage-limit continuation against %s", (scenario) =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -6354,8 +6357,68 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
].includes(scenario);
const autoResume = scenario !== "snooze-only" && scenario !== "wake";
const arm = limitRecoveryCommand(shell, autoResume, DateTime.toEpochMillis(now), snooze);
- assert.isNotNull(arm);
- yield* orchestrator.dispatch(arm!);
+ assert(arm?.type === "thread.metadata.update" && arm.limitRecovery != null);
+ const automaticArm = {
+ commandId: arm.commandId,
+ threadId,
+ limitRecovery: arm.limitRecovery,
+ };
+ const stopBeforeArm =
+ scenario === "stop-before-arm" || scenario === "stop-before-arm-mismatched-recovery";
+ if (stopBeforeArm) {
+ if (scenario === "stop-before-arm-mismatched-recovery") {
+ const current = yield* orchestrator.getThreadProjection(threadId);
+ yield* events.write({
+ events: [
+ {
+ id: EventId.make(`recovery:older-window:${scenario}`),
+ type: "thread.metadata-updated",
+ threadId,
+ occurredAt: now,
+ payload: {
+ ...current.thread,
+ limitRecovery: {
+ runId: run.id,
+ resetAt: DateTime.formatIso(DateTime.add(now, { minutes: 2 })),
+ autoResume: true,
+ snooze: false,
+ },
+ },
+ },
+ ],
+ });
+ }
+ yield* orchestrator.dispatch({
+ type: "thread.stop",
+ commandId: CommandId.make(`recovery:stop:${scenario}`),
+ threadId,
+ });
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ assert.isUndefined(
+ (yield* projections.getLimitRecoveryCandidates({
+ now,
+ autoResume: true,
+ snooze: false,
+ })).find((row) => row.id === threadId),
+ );
+ const stoppedShell = (yield* orchestrator.getShellSnapshot()).threads.find(
+ (thread) => thread.id === threadId,
+ )!;
+ assert.isNull(limitRecoveryCommand(stoppedShell, true, DateTime.toEpochMillis(now)));
+ yield* orchestrator.autoArmLimitRecovery(automaticArm);
+ assert.deepEqual((yield* orchestrator.getThreadProjection(threadId)).thread.limitRecovery, {
+ runId: run.id,
+ resetAt,
+ autoResume: false,
+ snooze: false,
+ requestId: CommandId.make(`recovery:stop:${scenario}`),
+ });
+ }
+ const armCommand = stopBeforeArm
+ ? { ...arm, commandId: CommandId.make(`recovery:explicit-rearm:${scenario}`) }
+ : arm;
+ if (stopBeforeArm) yield* orchestrator.dispatch(armCommand);
+ else yield* orchestrator.autoArmLimitRecovery(automaticArm);
let armedShell = (yield* orchestrator.getShellSnapshot()).threads.find(
(thread) => thread.id === threadId,
)!;
@@ -6364,7 +6427,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
resetAt,
autoResume,
snooze,
- requestId: arm!.commandId,
+ requestId: armCommand.commandId,
});
if (snooze)
assert.equal(DateTime.toEpochMillis(armedShell.snoozedUntil!), Date.parse(resetAt));
@@ -6568,6 +6631,17 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
commandId: CommandId.make(`recovery:settle:${scenario}`),
threadId,
});
+ if (scenario === "stop") {
+ yield* orchestrator.dispatch({
+ type: "thread.stop",
+ commandId: CommandId.make(`recovery:stop:${scenario}`),
+ threadId,
+ });
+ const stoppedShell = (yield* orchestrator.getShellSnapshot()).threads.find(
+ (thread) => thread.id === threadId,
+ )!;
+ assert.deepInclude(stoppedShell.limitRecovery, { runId: run.id, autoResume: false });
+ }
if (scenario === "replacement") {
const current = yield* orchestrator.getThreadProjection(threadId);
const error = current.turnItems.find((item) => item.type === "error")!;
@@ -6626,6 +6700,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
after.runs,
before.runs.length +
(scenario === "resume" ||
+ stopBeforeArm ||
scenario === "queued-resume" ||
scenario === "snooze-resume" ||
scenario === "wake-preserve-resume" ||
@@ -6638,6 +6713,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
after.messages,
before.messages.length +
(scenario === "resume" ||
+ stopBeforeArm ||
scenario === "queued-resume" ||
scenario === "snooze-resume" ||
scenario === "wake-preserve-resume" ||
@@ -6646,6 +6722,28 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
? 1
: 0),
);
+ if (scenario === "stop") {
+ assert.deepInclude(after.thread.limitRecovery, { runId: run.id, autoResume: false });
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const sweep = { now: yield* DateTime.now, autoResume: true, snooze: false };
+ assert.isUndefined(
+ (yield* projections.getLimitRecoveryCandidates(sweep)).find((row) => row.id === threadId),
+ );
+ yield* orchestrator.dispatch({
+ type: "thread.metadata.update",
+ commandId: CommandId.make("recovery:rearm-after-stop"),
+ threadId,
+ limitRecovery: { runId: run.id, resetAt, autoResume: true },
+ });
+ const rearmed = (yield* projections.getLimitRecoveryCandidates(sweep)).find(
+ (row) => row.id === threadId,
+ )!;
+ assert.isDefined(rearmed);
+ const freshResume = limitRecoveryCommand(rearmed, true, DateTime.toEpochMillis(sweep.now));
+ assert.isNotNull(freshResume);
+ yield* orchestrator.dispatch(freshResume!);
+ assert.lengthOf((yield* orchestrator.getThreadProjection(threadId)).runs, 2);
+ }
if (scenario === "queued-resume") {
const held = after.runs[1]!;
assert.equal(held.status, "queued");
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts
index fef1dd484f4..ad4c7ecda87 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.ts
@@ -368,7 +368,13 @@ export const layerProduction = Layer.mergeAll(
layerScheduledTaskProvided,
layerSecretRequestsProvided,
UsageLimitRecoveryWorker.layer.pipe(
- Layer.provide(Layer.mergeAll(ProjectionStore.layer, layerThreadManagementProvided)),
+ Layer.provide(
+ Layer.mergeAll(
+ ProjectionStore.layer,
+ layerThreadManagementProvided,
+ layerOrchestratorProvided,
+ ),
+ ),
),
layerProviderContinuationWorkerProvided,
layerAgentSessionImporterProvided,
diff --git a/apps/server/src/scheduling/Scheduler.integration.test.ts b/apps/server/src/scheduling/Scheduler.integration.test.ts
index c9388d12029..089b12f991e 100644
--- a/apps/server/src/scheduling/Scheduler.integration.test.ts
+++ b/apps/server/src/scheduling/Scheduler.integration.test.ts
@@ -19,6 +19,7 @@ import * as SqlClient from "effect/sql/SqlClient";
import * as TestClock from "effect/testing/TestClock";
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
+import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as UsageLimitRecoveryWorker from "../orchestration-v2/UsageLimitRecoveryWorker.ts";
@@ -89,6 +90,7 @@ it.effect.each(["on time", "after restart"])(
const receipts = yield* Queue.unbounded<"task" | "retry">();
const layerDependencies = Layer.mergeAll(
NodeCrypto.layer,
+ Layer.mock(Orchestrator.OrchestratorV2)({}),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({
launch: () =>
Queue.offer(receipts, "task").pipe(
diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md
index 63732eb4a10..d08db265792 100644
--- a/docs/user/thread-sidebar.md
+++ b/docs/user/thread-sidebar.md
@@ -206,8 +206,8 @@ continuation. You can cancel it from the thread. Enable **Auto-resume limited
threads** in **Settings → General** on web and desktop, or **Settings → Thread
behavior** on mobile, to schedule limit stops by default.
The environment must be running when the reset arrives; it resumes overdue
-continuations after a restart. Sending a new message, archiving, or settling the
-thread prevents a pending continuation from starting.
+continuations after a restart. Stopping the thread, sending a new message,
+archiving, or settling it prevents a pending continuation from starting.
Choose **Snooze until reset** to hide the thread until its allowance returns.
Snooze and auto-resume are independent: snooze alone wakes the thread without