Skip to content
TypeScript

fix(server): Stop during a restart no longer leaves the thread stuck (#27141)

Theo Browne6d12bb1e9fbd
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index c65005deefb..16865229d94 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -11062,6 +11062,45 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
occurredAt: now,
payload: { ...run, status: "interrupted", completedAt: now },
});
+ // Stop cancels a pending restart, so it must end the turn that restart could not stop.
+ const supersededTurn = projection.providerTurns.findLast(
+ (candidate) =>
+ candidate.status === "running" &&
+ projection.attempts.some(
+ (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id,
+ ),
+ );
+ const supersededOwner =
+ supersededTurn === undefined
+ ? undefined
+ : projection.providerThreads.find(
+ (candidate) => candidate.id === supersededTurn.providerThreadId,
+ );
+ if (
+ supersededTurn !== undefined &&
+ supersededOwner !== undefined &&
+ supersededOwner.providerSessionId !== null &&
+ Option.isSome(
+ yield* providerSessions
+ .get(supersededOwner.providerSessionId)
+ .pipe(Effect.orElseSucceed(() => Option.none())),
+ )
+ ) {
+ const id = `effect:${command.commandId}:provider-turn.interrupt:${supersededTurn.id}`;
+ if (!otherProviderInterrupts.some((effect) => effect.id === id)) {
+ otherProviderInterrupts.push({
+ id,
+ commandId: command.commandId,
+ threadId: command.threadId,
+ request: {
+ type: "provider-turn.interrupt",
+ providerSessionId: supersededOwner.providerSessionId,
+ providerThreadId: supersededOwner.id,
+ providerTurnId: supersededTurn.id,
+ },
+ });
+ }
+ }
yield* stopRemainingWork();
yield* Ref.update(effects, (existing) => [...existing, ...otherProviderInterrupts]);
return {
diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
index 03cdf5e85a6..d059c4c20e9 100644
--- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
+++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
@@ -438,6 +438,118 @@ it.live("retries a failed selection restart session open before completing", ()
),
);
+it.live("Stop during a restart interrupts the turn the restart could not stop", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const cwd = yield* checkpointWorkspace("selection-restart-stop");
+ const threadId = ThreadId.make("thread:selection-restart-stop");
+ const state = yield* Ref.make<RestartAdapterState>({
+ activeTurn: null,
+ opened: [],
+ started: [],
+ closedSessionCount: 0,
+ failedReplacementOpen: false,
+ });
+ const base = makeRestartAdapter(state);
+ // A wedged provider ignores the restart's soft cancel; only Stop ends its turn.
+ const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
+ ...base,
+ openSession: (input) =>
+ base.openSession(input).pipe(
+ Effect.map((session) => ({
+ ...session,
+ interruptTurn: (interrupt: ProviderAdapter.ProviderAdapterV2InterruptInput) =>
+ interrupt.requestRuntimeRestart === true
+ ? session.interruptTurn(interrupt)
+ : Effect.never,
+ })),
+ ),
+ };
+
+ const result = yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const running = yield* orchestrator.streamDomainEvents.pipe(
+ Stream.filter(
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
+ ),
+ Stream.take(1),
+ Stream.runDrain,
+ Effect.forkScoped({ startImmediately: true }),
+ );
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:selection-restart-stop:create"),
+ threadId,
+ projectId: ProjectId.make("project:selection-restart-stop"),
+ title: "Stop during restart",
+ modelSelection: initialSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: cwd,
+ });
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:selection-restart-stop:first"),
+ threadId,
+ messageId: MessageId.make("message:selection-restart-stop:first"),
+ text: "first",
+ attachments: [],
+ modelSelection: initialSelection,
+ dispatchMode: { type: "start_immediately" },
+ });
+ yield* worker.drain();
+ yield* Fiber.join(running);
+ const runId = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!.id;
+
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:selection-restart-stop:steer"),
+ threadId,
+ messageId: MessageId.make("message:selection-restart-stop:steer"),
+ text: "Are you still going?",
+ attachments: [],
+ modelSelection: initialSelection,
+ dispatchMode: { type: "restart_active", targetRunId: runId },
+ });
+ yield* orchestrator.dispatch({
+ type: "run.interrupt",
+ commandId: CommandId.make("command:selection-restart-stop:stop"),
+ threadId,
+ runId,
+ });
+ yield* worker.drain();
+ return {
+ projection: yield* orchestrator.getThreadProjection(threadId),
+ captured: yield* Ref.get(state),
+ };
+ }).pipe(
+ Effect.provide(
+ ProviderReplayHarness.layerWithRegistry(
+ { name: "selection-restart-stop" },
+ ProviderAdapterRegistry.layerSingle(adapter),
+ ),
+ ),
+ );
+
+ assert.isNull(result.captured.activeTurn);
+ assert.lengthOf(result.captured.started, 1);
+ assert.equal(result.projection.runs[0]?.status, "interrupted");
+ assert.deepEqual(
+ result.projection.providerTurns.map((turn) => turn.status),
+ ["interrupted"],
+ );
+ }),
+ ),
+);
+
it.live(
"restarts the live session on a model change when a newer stopped session record exists",
() =>