From 4bea20509042b12829242541db4dd92c20da3283 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 30 Oct 2026 12:58:29 -0700 Subject: [PATCH 1/4] fix(server): a model change mid-turn no longer stalls when the agent ignores Stop Since Stop stopped ending turns the agent never confirmed, the restart a model or selection change runs got the same unconfirmed-stop error and retried until it failed, so the replacement turn never started. A restart now asks the adapter to end the old turn itself after the stop wait, as before; Stop still leaves it open for Force stop. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AcpAdapterV2.test.ts | 106 ++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 23 +++- .../ProviderTurnControlService.ts | 1 + packages/provider-acp/src/server/adapter.ts | 16 +++ .../src/server/ProviderAdapter.ts | 2 + 5 files changed, 146 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index b924f6efb3e70..b0a70bdb2a942 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -4257,6 +4257,112 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); + it.effect("ends the turn for a restart when the agent never confirms the cancel", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const selfInvocation = yield* resolveSelfInvocation(); + const protocolEvents = yield* Queue.unbounded(); + let runtimeOrdinalSeen = 0; + const instanceId = ProviderInstanceId.make("acp-unconfirmed-cancel"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath: yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ), + // Only the first agent ignores the cancel; a replacement runtime answers normally. + environment: (runtimeOrdinal) => + runtimeOrdinal === 1 ? { T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL: "1" } : {}, + protocolEvents, + wrapRuntime: (runtime, runtimeOrdinal) => { + runtimeOrdinalSeen = runtimeOrdinal; + return runtime; + }, + }), + }, + selfInvocation, + }); + const threadId = ThreadId.make("thread-acp-unconfirmed-cancel"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("session-acp-unconfirmed-cancel"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), + ); + const started = Option.getOrThrow( + yield* runtime.events.pipe( + Stream.filter( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "native-cancel-tool", + ), + Stream.runHead, + ), + ); + if (started.type !== "turn_item.updated" || started.turnItem.providerTurnId === null) { + return yield* Effect.die("Expected the native cancellable command"); + } + const providerTurnId = started.turnItem.providerTurnId; + const interrupt = yield* runtime + .interruptTurn({ providerThread, providerTurnId, endOnTimeout: true }) + .pipe(Effect.forkScoped); + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "incoming" && + typeof event.payload === "string" && + event.payload.includes("native-cancel-received"), + ), + Stream.runHead, + ); + yield* TestClock.adjust("10 seconds"); + yield* Fiber.join(interrupt); + const terminal = Option.getOrThrow( + yield* runtime.events.pipe( + Stream.filter( + (event) => event.type === "turn.terminal" && event.providerTurnId === providerTurnId, + ), + Stream.runHead, + ), + ); + assert.equal(terminal.type === "turn.terminal" && terminal.status, "interrupted"); + // The unconfirmed prompt may still write to the old session, so the next turn must not share it. + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), + ); + const nextTerminal = Option.getOrThrow( + yield* runtime.events.pipe( + Stream.filter( + (event) => event.type === "turn.terminal" && event.providerTurnId !== providerTurnId, + ), + Stream.runHead, + ), + ); + assert.equal(nextTerminal.type === "turn.terminal" && nextTerminal.status, "completed"); + assert.equal(runtimeOrdinalSeen, 2); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.effect("cancels pending permission requests while interrupting an ACP turn", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f42f37d1ab1b1..812203a66eaba 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -10479,13 +10479,32 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (Option.isSome(closed)) { return; } - // The turn stays open: the CLI may still be working, and the user decides - // whether to Force stop it. yield* Effect.logWarning("orchestration-v2.claude-query-interrupt-timeout", { providerSessionId: input.providerSessionId, providerThreadId: turnInput.providerThread.id, providerTurnId: turnInput.providerTurnId, }); + if (turnInput.endOnTimeout === true) { + const completedAt = yield* DateTime.now; + const ownedLiveQuery = yield* Ref.modify(queryContext, (current) => + current?.query === existing.query ? [true, null] : [false, current], + ); + if (ownedLiveQuery) { + existing.stopping = true; + yield* finalizeActiveTurnAfterQueryExit(existing); + yield* endSubagentCallsOfClosedQuery(existing.nativeThreadId, "interrupted"); + } else if ((yield* Ref.get(activeTurn)) === currentTurn) { + yield* finalizeActiveTurn({ + context: currentTurn, + status: "interrupted", + completedAt, + }); + } + yield* Deferred.succeed(existing.closed, undefined); + return; + } + // The turn stays open: the CLI may still be working, and the user decides + // whether to Force stop it. return yield* new ProviderAdapter.ProviderAdapterInterruptTimeoutError({ driver: CLAUDE_PROVIDER, providerThreadId: turnInput.providerThread.id, diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index bd225bb41773b..5932a112e3325 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -293,6 +293,7 @@ export const layer: Layer.Layer< yield* loaded.session.value.interruptTurn({ providerThread: loaded.providerThread, providerTurnId: loaded.providerTurn.id, + endOnTimeout: true, }); for (let remaining = 1_000; remaining > 0; remaining -= 1) { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index c895abe3f5ef8..505e8eceef970 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -8257,6 +8257,22 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const stopped = yield* Deferred.await(context.completed).pipe( Effect.timeoutOption(ACP_STOP_CONFIRM_TIMEOUT_MS), ); + if (Option.isNone(stopped) && turnInput.endOnTimeout === true) { + // The agent may still be writing to this session; the next turn gets a fresh one. + yield* Ref.set(runtimeRestartRequired, true); + // Under the permit, so no request is admitted between the sweep and finalization. + yield* runtimeCallbackPermit.withPermit( + Effect.gen(function* () { + yield* quarantineStoppedRun(); + // The agent may have asked for approval while ignoring the cancel. + yield* cancelPendingRuntimeRequests(); + if (!context.finalized) { + yield* finalizeTurn(context, "interrupted"); + } + }), + ); + return; + } // The turn stays open: the agent may still be working, and the user // decides whether to Force stop it. if (Option.isNone(stopped)) { diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index cadf4173a60b1..5b4007dbf6f05 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -467,6 +467,8 @@ export interface ProviderAdapterV2InterruptInput { readonly providerThread: OrchestrationV2ProviderThread; readonly providerTurnId: ProviderTurnId; readonly requestRuntimeRestart?: boolean; + /** A caller replacing the turn needs it ended even when the agent never confirms the stop. */ + readonly endOnTimeout?: boolean; } export interface ProviderAdapterV2RuntimeRequestResponseInput { From 8ed4bf370e7d38f5a1d35164d0247fa570657edc Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 11:02:34 +0000 Subject: [PATCH 2/4] fix(server): a Claude restart ends within the interrupt timeout when the CLI ignores Stop Main now bounds the native interrupt write at 10 seconds before the Stop confirmation wait, so a restart could run past ProviderSessionManager's 15-second interrupt timeout and fail. A restart now shares one budget between the two waits. Adds a Claude adapter case for the unconfirmed Stop. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 53 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 12 ++++- 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 92f0e4205b639..a5968521d2b7a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -12873,6 +12873,59 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("ends the turn for a restart when the query never confirms the Stop", () => + Effect.gen(function* () { + // The CLI never answers the interrupt, and the default close leaves the query running. + const interruptStarted = yield* Deferred.make(); + const harness = yield* makeWakeHarnessWithOptions({ + interrupt: Deferred.succeed(interruptStarted, undefined).pipe(Effect.andThen(Effect.never)), + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("unconfirmed-stop"), + text: "Work until stopped", + attachments: [], + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ), + ); + const active = harness.events.find( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ); + if (active?.type !== "provider_turn.updated") + return yield* Effect.die("Missing running native turn"); + const stop = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: active.providerTurn.id, + endOnTimeout: true, + }) + .pipe(Effect.forkChild); + yield* Deferred.await(interruptStarted); + yield* TestClock.adjust("11 seconds"); + yield* Fiber.join(stop); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "interrupted"); + assert.lengthOf(harness.terminalEvents(), 1); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("preserves settled background work until an explicit stop", () => Effect.gen(function* () { let closes = 0; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 61c0291abd024..e326686ed49c0 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -13096,6 +13096,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( next.add(turnInput.providerTurnId); return next; }); + const stopStartedAt = yield* Clock.currentTimeMillis; if (!(yield* Deferred.isDone(existing.closed))) { yield* existing.query.interrupt.pipe( Effect.timeoutOption("10 seconds"), @@ -13108,8 +13109,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); yield* existing.query.close.pipe(Effect.ignore); } + // A restart must end within ProviderSessionManager's interrupt timeout, so it shares one budget. + const confirmWaitMs = + turnInput.endOnTimeout === true + ? Math.max( + 0, + CLAUDE_STOP_CONFIRM_TIMEOUT_MS - + ((yield* Clock.currentTimeMillis) - stopStartedAt), + ) + : CLAUDE_STOP_CONFIRM_TIMEOUT_MS; const closed = yield* Deferred.await(existing.closed).pipe( - Effect.timeoutOption(CLAUDE_STOP_CONFIRM_TIMEOUT_MS), + Effect.timeoutOption(confirmWaitMs), ); if (Option.isSome(closed)) { return; From ed4fe570aac9c869cb7bdbb009d430d15a467e8f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 11:11:37 +0000 Subject: [PATCH 3/4] fix(server): a Claude restart timeout no longer settles a turn the query reader is settling When the Stop confirmation timed out but the query reader had already claimed the query, the restart fallback finalized the same turn again and published a second terminal event. It now leaves the turn to the claimant and waits for its closed signal. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index e326686ed49c0..35ac66a9dd140 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -13130,21 +13130,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( providerTurnId: turnInput.providerTurnId, }); if (turnInput.endOnTimeout === true) { - const completedAt = yield* DateTime.now; const ownedLiveQuery = yield* Ref.modify(queryContext, (current) => current?.query === existing.query ? [true, null] : [false, current], ); - if (ownedLiveQuery) { - existing.stopping = true; - yield* finalizeActiveTurnAfterQueryExit(existing); - yield* endSubagentCallsOfClosedQuery(existing.nativeThreadId, "interrupted"); - } else if ((yield* Ref.get(activeTurn)) === currentTurn) { - yield* finalizeActiveTurn({ - context: currentTurn, - status: "interrupted", - completedAt, - }); + if (!ownedLiveQuery) { + // Whoever claimed the query settles its turn, then signals closed. + if ((yield* Ref.get(activeTurn)) === currentTurn) { + yield* Deferred.await(existing.closed); + } + return; } + existing.stopping = true; + yield* finalizeActiveTurnAfterQueryExit(existing); + yield* endSubagentCallsOfClosedQuery(existing.nativeThreadId, "interrupted"); yield* Deferred.succeed(existing.closed, undefined); return; } From 1eac37b6620114b8d487d7f99995a973f9d1d76e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 11:28:45 +0000 Subject: [PATCH 4/4] fix(server): a Codex replacement turn no longer stalls when Codex never confirms Stop Codex handed an unconfirmed Stop to a background watcher and failed with an interrupt timeout, so a replacement requested with endOnTimeout never reached detach and start. A replacement now settles the interrupted lineage at the timeout, as the adapter already does when no root is left to defer to. Ordinary Stop is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/CodexAdapterV2.test.ts | 14 ++++++++++++-- .../orchestration-v2/Adapters/CodexAdapterV2.ts | 7 ++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 76c10382b3cb8..92bea9db7648e 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -9838,6 +9838,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { "its thread is unloaded", "Codex completes it after the session's Stop deadline", "Codex completes it after a second Stop fails", + "a replacement turn ends it", ] as const)("keeps a turn open after an unconfirmed Stop until %s", (ending) => Effect.gen(function* () { const nativeThreadId = "unconfirmed-stop-thread"; @@ -9850,6 +9851,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { reasoningOutputTokens: 1, }; const pastDeadline = ending === "Codex completes it after the session's Stop deadline"; + const replacement = ending === "a replacement turn ends it"; const harness = yield* makeCodexReplayHarness( makeCodexReplayTranscript({ scenario: `unconfirmed-stop-${ending.length}`, @@ -9951,6 +9953,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { driver: CodexAdapterV2.CODEX_DRIVER_KIND, nativeTurnId, }), + ...(replacement ? { endOnTimeout: true } : {}), }) .pipe( // The session manager bounds every Stop the same way. @@ -9974,9 +9977,16 @@ describe("CodexAdapterV2 post-settle continuation", () => { const stopped = yield* Fiber.join(stopping); assert.equal( stopped._tag === "Failure" ? stopped.failure._tag : "confirmed", - pastDeadline ? "SessionStopDeadline" : "ProviderAdapterInterruptTimeoutError", + replacement + ? "confirmed" + : pastDeadline + ? "SessionStopDeadline" + : "ProviderAdapterInterruptTimeoutError", + ); + assert.deepEqual( + harness.terminalEvents().map((event) => event.status), + replacement ? ["interrupted"] : [], ); - assert.deepEqual(harness.terminalEvents(), []); if (ending === "Codex completes it after a second Stop fails") { const second = yield* harness.runtime diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index f7d3b49a687e5..0e3b208926b7c 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -8395,7 +8395,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ], { concurrency: "unbounded" }, ); - if (Option.isSome(completed) || !(yield* deferToActiveRoots)) { + // A replacement turn cannot wait for Codex to confirm, so it settles the lineage now. + if ( + Option.isSome(completed) || + turnInput.endOnTimeout === true || + !(yield* deferToActiveRoots) + ) { yield* settleInterruptedLineage; return false; }