diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index b7808ef897ee7..f634e3b799302 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -6933,6 +6933,112 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + 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.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 4ea7b6f8008e4..35ac66a9dd140 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,19 +13109,45 @@ 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; } - // 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 ownedLiveQuery = yield* Ref.modify(queryContext, (current) => + current?.query === existing.query ? [true, null] : [false, current], + ); + 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; + } + // 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/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; } diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index 5de7f965474bd..68096385af375 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -349,6 +349,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 332c4bee95ec6..29ed53c7c0c8e 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -9375,6 +9375,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 58f1773974069..31ab5025c094a 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -587,6 +587,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 {