From 70dd904354b571884cc59db9a213a17175c7a407 Mon Sep 17 00:00:00 2001 From: Roy <22949684+luogao@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:27:48 +0800 Subject: [PATCH 1/3] fix(acp): auto-approve detached full-access permission requests when continuation cannot attach Fixes pingdotgg/t3code#40032. When an ACP agent with wakeOnDetachedRequest sends session/request_permission while no turn is active (for example after a background command finishes in Antigravity): - Offer onRunEndedWithoutStarting alongside clearIfCurrent and wake pending turnAttached waiters as unattached rather than hanging indefinitely. - Avoid resolving turnAttached as cancelled during a settled soft interrupt (when stoppedRunQuarantine is not set). - Evaluate permission disposition before requiring activeContext so full-access auto-approved (or auto-denied) requests succeed when no continuation turn can attach, while still cancelling after explicit Stop (stoppedRunQuarantine) and cancelling approval-required prompts that have no active turn. --- .../Adapters/AntigravityAdapterV2.test.ts | 196 +++++++++++++++++- packages/provider-acp/src/server/adapter.ts | 106 ++++++---- 2 files changed, 264 insertions(+), 38 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..34e50db41778a 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1004,6 +1004,8 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") options?: { readonly profileDirectory?: string; readonly initialToolCalls?: ReadonlyArray; + readonly runtimeMode?: ProviderAdapter.ProviderAdapterV2RuntimePolicy["runtimeMode"]; + readonly disableContinuationRequests?: boolean; }, ) { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -1043,7 +1045,13 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") const adapterOptions: AntigravityAdapterV2Options = { instanceId, selfInvocation, - continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) }, + ...(options?.disableContinuationRequests + ? {} + : { + continuationRequests: { + offer: (request) => Effect.sync(() => void offers.push(request)), + }, + }), makeRuntime: (input) => { terminate = input.onTermination; return makeAntigravityAcpRuntime({ @@ -1137,8 +1145,9 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") onDeferredFinalizeScheduled: (debounce) => Queue.offer(scheduledFinalizes, debounce), }, }); + const runtimeMode = options?.runtimeMode ?? "full-access"; const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", + runtimeMode, interactionMode: "default", cwd: process.cwd(), }); @@ -1179,7 +1188,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") title: "Antigravity wake", providerInstanceId: instanceId, modelSelection, - runtimeMode: "full-access", + runtimeMode, interactionMode: "default", branch: null, worktreePath: process.cwd(), @@ -2010,6 +2019,187 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { assert.equal(opened.cancels(), cancels); }).pipe(Effect.provide(layerSession)), ); + + it.effect( + "auto-approves a detached full-access permission request when its continuation cannot attach", + () => + Effect.gen(function* () { + const { offers, startTurn, throughTerminal, requestPermission } = + yield* openSessionWithRunningCommand({ IsDaemon: true, WaitMsBeforeAsync: 500 }); + yield* startTurn(1, false); + yield* throughTerminal; + + const followUp = { toolCallId: "call_git_push", kind: "execute", title: "git push" }; + const permission = yield* requestPermission( + { + sessionId: "mock-session-1", + toolCall: { ...followUp, status: "pending" }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }, + { requestId: "permission-unattached", method: "session/request_permission" }, + ).pipe(Effect.forkScoped({ startImmediately: true })); + assert.lengthOf(offers, 1); + assert.isDefined(offers[0]!.onRunEndedWithoutStarting); + yield* offers[0]!.onRunEndedWithoutStarting!(); + assert.deepEqual(yield* Fiber.join(permission), { + outcome: { outcome: "selected", optionId: "allow" }, + }); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect( + "auto-approves a detached full-access permission request when continuation is unavailable", + () => + Effect.gen(function* () { + const { startTurn, throughTerminal, requestPermission } = + yield* openSessionWithRunningCommand( + { IsDaemon: true, WaitMsBeforeAsync: 500 }, + undefined, + undefined, + { disableContinuationRequests: true }, + ); + yield* startTurn(1, false); + yield* throughTerminal; + + const response = yield* requestPermission( + { + sessionId: "mock-session-1", + toolCall: { + toolCallId: "call_no_cont", + kind: "execute", + title: "curl https://example.com", + status: "pending", + }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }, + { requestId: "permission-no-cont", method: "session/request_permission" }, + ); + assert.deepEqual(response, { outcome: { outcome: "selected", optionId: "allow" } }); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect( + "auto-approves a detached full-access permission request across a settled soft interrupt", + () => + Effect.gen(function* () { + const opened = yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* opened.startTurn(1, false); + const started = yield* opened.throughPromptSettled; + const turn = started.find((event) => event.type === "provider_turn.updated"); + if (turn?.type !== "provider_turn.updated") return assert.fail("the turn must start"); + + // Soft interrupt (new message, not Stop): leaves background work alive and does not quarantine. + yield* opened.session.interruptTurn({ + providerThread: opened.providerThread, + providerTurnId: turn.providerTurn.id, + }); + yield* opened.throughTerminal; + + const permission = yield* opened + .requestPermission( + { + sessionId: "mock-session-1", + toolCall: { + toolCallId: "call_after_soft_interrupt", + kind: "execute", + title: "git commit", + status: "pending", + }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }, + { requestId: "permission-soft", method: "session/request_permission" }, + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* opened.startTurn(2, false); + assert.deepEqual(yield* Fiber.join(permission), { + outcome: { outcome: "selected", optionId: "allow" }, + }); + yield* opened.releaseSteer; + yield* opened.throughTerminal; + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("cancels a detached permission request after Stop even in full-access mode", () => + Effect.gen(function* () { + const opened = yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* opened.startTurn(1, false); + const started = yield* opened.throughPromptSettled; + const turn = started.find((event) => event.type === "provider_turn.updated"); + if (turn?.type !== "provider_turn.updated") return assert.fail("the turn must start"); + + yield* opened.session.interruptTurn({ + providerThread: opened.providerThread, + providerTurnId: turn.providerTurn.id, + requestRuntimeRestart: true, + }); + yield* opened.throughTerminal; + + const response = yield* opened.requestPermission( + { + sessionId: "mock-session-1", + toolCall: { + toolCallId: "call_after_stop", + kind: "execute", + title: "rm -rf /tmp/unused", + status: "pending", + }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }, + { requestId: "permission-stop", method: "session/request_permission" }, + ); + assert.deepEqual(response, { outcome: { outcome: "cancelled" } }); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect( + "cancels a detached approval-required permission request when its continuation cannot attach", + () => + Effect.gen(function* () { + const { offers, startTurn, throughTerminal, requestPermission } = + yield* openSessionWithRunningCommand( + { IsDaemon: true, WaitMsBeforeAsync: 500 }, + undefined, + undefined, + { runtimeMode: "approval-required" }, + ); + yield* startTurn(1, false); + yield* throughTerminal; + + const permission = yield* requestPermission( + { + sessionId: "mock-session-1", + toolCall: { + toolCallId: "call_ask_unattached", + kind: "execute", + title: "git push", + status: "pending", + }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }, + { requestId: "permission-ask-unattached", method: "session/request_permission" }, + ).pipe(Effect.forkScoped({ startImmediately: true })); + assert.lengthOf(offers, 1); + yield* offers[0]!.clearIfCurrent!(); + assert.deepEqual(yield* Fiber.join(permission), { + outcome: { outcome: "cancelled" }, + }); + }).pipe(Effect.provide(layerSession)), + ); }); describe("AntigravityAdapterV2 subagent reads", () => { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index e214a51586f4c..0aa39ee755680 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2262,7 +2262,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.extractSubagentSessionEvent !== undefined && !followsAgentWorkState ? undefined : flavor.extractSubagentUpdate?.(tool); - let turnAttached = yield* Deferred.make(); + let turnAttached = yield* Deferred.make<"attached" | "unattached" | "cancelled">(); + const resolveTurnAttached = Effect.fnUntraced(function* ( + outcome: "attached" | "unattached" | "cancelled", + ) { + const waiting = turnAttached; + turnAttached = yield* Deferred.make<"attached" | "unattached" | "cancelled">(); + yield* Deferred.succeed(waiting, outcome); + }); const activeSessionId = yield* Ref.make(null); // session/load replays history before activeSessionId names the loaded session. const loadingSessionId = yield* Ref.make(null); @@ -5220,28 +5227,26 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( threadId: route.threadId, providerThreadId: route.providerThreadId, }); + const clearIfOwner = Effect.gen(function* () { + if ((yield* Ref.get(continuationGeneration)) === generation) { + yield* Ref.set(continuationRequested, false); + yield* resolveTurnAttached( + (yield* Ref.get(stoppedRunQuarantine)) ? "cancelled" : "unattached", + ); + } + }); + const clearIfCurrent = () => continuationPermit.withPermit(clearIfOwner); yield* continuationRequests.offer({ threadId: route.threadId, providerThreadId: route.providerThreadId, driver, detail: null, ...(notification === null ? {} : { notification }), - clearIfCurrent: () => - continuationPermit.withPermit( - Effect.gen(function* () { - if ((yield* Ref.get(continuationGeneration)) === generation) { - yield* Ref.set(continuationRequested, false); - } - }), - ), + clearIfCurrent, + onRunEndedWithoutStarting: clearIfCurrent, dispatchIfCurrent: (effect) => continuationPermit.withPermit( Effect.gen(function* () { - const clearIfOwner = Effect.gen(function* () { - if ((yield* Ref.get(continuationGeneration)) === generation) { - yield* Ref.set(continuationRequested, false); - } - }); if (yield* Ref.get(stoppedRunQuarantine)) { yield* clearIfOwner; return Option.none(); @@ -5598,22 +5603,37 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( !followsAgentWorkState && !(postSettleContinuationEnabled && flavor.wakeOnDetachedRequest) ) - return true; + return "attached" as const; while (true) { const waiting = yield* runRuntimeCallbackAtGeneration( generation, Effect.gen(function* () { - if (yield* Ref.get(stoppedRunQuarantine)) return false; - if ((yield* Ref.get(activeTurn)) !== null) return null; + if ( + (yield* Ref.get(stoppedRunQuarantine)) || + (yield* Ref.get(continuationClosed)) + ) { + return "cancelled" as const; + } + if ((yield* Ref.get(activeTurn)) !== null) return "attached" as const; + const pendingAttach = turnAttached; const sessionId = yield* Ref.get(activeSessionId); if (sessionId !== null) yield* offerContinuationRun(sessionId); - return turnAttached; + if ((yield* Ref.get(activeTurn)) !== null) return "attached" as const; + if ( + !followsAgentWorkState && + (continuationRequests === undefined || + sessionId === null || + (yield* Ref.get(lastTurnRoute)) === null) + ) { + return "unattached" as const; + } + return pendingAttach; }), ); if (Option.isNone(waiting)) return yield* Effect.never; - if (waiting.value === false) return false; - if (waiting.value === null) return true; - if (!(yield* Deferred.await(waiting.value))) return false; + if (typeof waiting.value === "string") return waiting.value; + const result = yield* Deferred.await(waiting.value); + if (result !== "attached") return result; } }); @@ -6569,7 +6589,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( request: Effect.Effect, transportRequestId: string, ) { - if (!(yield* awaitRequestTurn(generation))) { + if ((yield* awaitRequestTurn(generation)) !== "attached") { return { answers: null, acknowledgeNativeResponse: Effect.void }; } return yield* runRuntimeCallbackAtGeneration( @@ -6623,11 +6643,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); const cancelPendingRuntimeRequests = Effect.fnUntraced(function* ( - options: { readonly stopMcpCalls: boolean } = { stopMcpCalls: true }, + options: { + readonly stopMcpCalls: boolean; + readonly cancelDetachedRequests?: boolean; + } = { stopMcpCalls: true, cancelDetachedRequests: true }, ) { - const waiting = turnAttached; - turnAttached = yield* Deferred.make(); - yield* Deferred.succeed(waiting, false); + if (options.cancelDetachedRequests !== false) { + yield* resolveTurnAttached("cancelled"); + } // session/cancel does not end the agent's MCP calls; T3 runs them, so it stops them. if (options.stopMcpCalls && runtimeMcpBridge !== undefined) { yield* runtimeMcpBridge.stopCalls; @@ -7349,19 +7372,25 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest = params, ) => (flavor.permissionDisposition ?? acpPermissionDisposition)(policy, request); + let turnState: "attached" | "unattached" | "cancelled" = "attached"; if ( (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") || (postSettleContinuationEnabled && flavor.wakeOnDetachedRequest) ) { - if (!(yield* awaitRequestTurn(handlerGeneration))) + turnState = yield* awaitRequestTurn(handlerGeneration); + if (turnState === "cancelled") return { outcome: { outcome: "cancelled" } } as const; } const admitted = yield* runRuntimeCallbackAtGeneration( handlerGeneration, Effect.gen(function* () { - const context = followsAgentWorkState - ? yield* Ref.get(activeTurn) - : yield* activeContext; + if (yield* Ref.get(stoppedRunQuarantine)) { + return { + _tag: "Immediate" as const, + response: { outcome: { outcome: "cancelled" } } as const, + }; + } + const context = yield* Ref.get(activeTurn); // Kiro sends the tool's kind on its `tool_call` and leaves it // off the permission request for that call; take it from the // tool already seen under the same id so policy can tell a @@ -7393,10 +7422,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( : ({ outcome: { outcome: "selected", optionId } } as const), }; } + if (context === null && turnState === "unattached") { + return { + _tag: "Immediate" as const, + response: { outcome: { outcome: "cancelled" } } as const, + }; + } return { _tag: "Pending" as const, pending: yield* beginApprovalRequest( - yield* activeContext, + context ?? (yield* activeContext), params, handlerGeneration, transportRequestId, @@ -9540,9 +9575,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); if (followsAgentWorkState) yield* runtimeCallbackPermit.withPermit(syncNativeChildren(context)); - const attached = turnAttached; - turnAttached = yield* Deferred.make(); - yield* Deferred.succeed(attached, true); + yield* resolveTurnAttached("attached"); // Every attach ends the deferred-terminal contract, but only the // queued provider continuation owns wake traffic. A user turn may // start before that continuation and must leave its buffer intact. @@ -10382,7 +10415,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* quarantineStoppedRun(); } // A settled soft interrupt keeps background subagents, and with them their MCP calls. - yield* cancelPendingRuntimeRequests({ stopMcpCalls: !settledSoftInterrupt }); + yield* cancelPendingRuntimeRequests({ + stopMcpCalls: !settledSoftInterrupt, + cancelDetachedRequests: !settledSoftInterrupt, + }); // Finalize before killing so projection catches up and concurrent interrupts see activeTurn cleared. if ( (hardRestart || context.promptSettled || settledSoftInterrupt) && From 68f6d565c05003a8c7012e68b97729fc66f7a1c0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 04:55:25 +0000 Subject: [PATCH 2/3] test(acp): drop the soft-interrupt case that passes without the fix Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 44 ------------------- 1 file changed, 44 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 34e50db41778a..93f8a7f4146b0 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2084,50 +2084,6 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); - it.effect( - "auto-approves a detached full-access permission request across a settled soft interrupt", - () => - Effect.gen(function* () { - const opened = yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); - yield* opened.startTurn(1, false); - const started = yield* opened.throughPromptSettled; - const turn = started.find((event) => event.type === "provider_turn.updated"); - if (turn?.type !== "provider_turn.updated") return assert.fail("the turn must start"); - - // Soft interrupt (new message, not Stop): leaves background work alive and does not quarantine. - yield* opened.session.interruptTurn({ - providerThread: opened.providerThread, - providerTurnId: turn.providerTurn.id, - }); - yield* opened.throughTerminal; - - const permission = yield* opened - .requestPermission( - { - sessionId: "mock-session-1", - toolCall: { - toolCallId: "call_after_soft_interrupt", - kind: "execute", - title: "git commit", - status: "pending", - }, - options: [ - { optionId: "allow", name: "Allow", kind: "allow_once" }, - { optionId: "deny", name: "Deny", kind: "reject_once" }, - ], - }, - { requestId: "permission-soft", method: "session/request_permission" }, - ) - .pipe(Effect.forkScoped({ startImmediately: true })); - yield* opened.startTurn(2, false); - assert.deepEqual(yield* Fiber.join(permission), { - outcome: { outcome: "selected", optionId: "allow" }, - }); - yield* opened.releaseSteer; - yield* opened.throughTerminal; - }).pipe(Effect.provide(layerSession)), - ); - it.effect("cancels a detached permission request after Stop even in full-access mode", () => Effect.gen(function* () { const opened = yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); From f2fec28ed0cd9e62662a2157032b9e0c9c57b1fe Mon Sep 17 00:00:00 2001 From: Roy <22949684+luogao@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:22:03 +0800 Subject: [PATCH 3/3] fix(acp): address review edge cases for detached permission admission - Release onRunEndedWithoutStarting in ProviderContinuationService whenever a dispatched continuation run reaches a terminal state (not only when startedAt is null), so start-after-dispatch failures still wake waiting detached requests while adapters guard by generation/token once a turn attaches. - Register nativeResponseAcknowledgement inside the same runRuntimeCallbackAtGeneration callback that checks stoppedRunQuarantine and permission disposition, eliminating the race where a Stop quarantine could land between callbacks. - Cancel detached ask permission requests whenever activeTurn is null, even when continuationRequests is unset. - Drop the unused cancelDetachedRequests option on cancelPendingRuntimeRequests. --- .../Adapters/AntigravityAdapterV2.test.ts | 34 +++++ .../ProviderContinuationService.test.ts | 60 ++++++++ .../ProviderContinuationService.ts | 9 +- packages/provider-acp/src/server/adapter.ts | 133 +++++++----------- .../server/ProviderContinuationRequests.ts | 2 +- 5 files changed, 151 insertions(+), 87 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 93f8a7f4146b0..1b69455825bae 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -2156,6 +2156,40 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }); }).pipe(Effect.provide(layerSession)), ); + + it.effect( + "cancels a detached approval-required permission request when continuation is unavailable", + () => + Effect.gen(function* () { + const { startTurn, throughTerminal, requestPermission } = + yield* openSessionWithRunningCommand( + { IsDaemon: true, WaitMsBeforeAsync: 500 }, + undefined, + undefined, + { runtimeMode: "approval-required", disableContinuationRequests: true }, + ); + yield* startTurn(1, false); + yield* throughTerminal; + + const response = yield* requestPermission( + { + sessionId: "mock-session-1", + toolCall: { + toolCallId: "call_ask_no_cont", + kind: "execute", + title: "git push", + status: "pending", + }, + options: [ + { optionId: "allow", name: "Allow", kind: "allow_once" }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }, + { requestId: "permission-ask-no-cont", method: "session/request_permission" }, + ); + assert.deepEqual(response, { outcome: { outcome: "cancelled" } }); + }).pipe(Effect.provide(layerSession)), + ); }); describe("AntigravityAdapterV2 subagent reads", () => { diff --git a/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts b/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts index 2b23dbb93d802..d862bd9cc8b89 100644 --- a/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts @@ -12,6 +12,7 @@ import { type OrchestrationV2Notification, } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -20,6 +21,7 @@ import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Semaphore from "effect/Semaphore"; +import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -661,4 +663,62 @@ describe("ProviderContinuationService", () => { }); }, ); + + it.effect( + "calls onRunEndedWithoutStarting when a started continuation run fails before attaching a turn", + () => + Effect.gen(function* () { + const continuationRunId = RunId.make("run-provider-continuation-start-failed"); + const released = yield* Deferred.make(); + const startedAt = DateTime.makeUnsafe("2026-11-22T05:00:00.000Z"); + const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => Effect.succeed(projection), + dispatch: (command) => + Effect.succeed({ + sequence: 10, + storedEvents: [ + { + sequence: 10, + event: { + type: "run.created", + payload: { + id: continuationRunId, + userMessageId: "messageId" in command ? command.messageId : undefined, + }, + }, + }, + ], + } as never), + streamStoredEventsFrom: () => + Stream.make({ + sequence: 11, + event: { + type: "run.updated", + payload: { + id: continuationRunId, + status: "failed", + startedAt, + }, + }, + } as never), + }); + const layerWorker = ProviderContinuationService.layer.pipe( + Layer.provide( + Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads), + ), + ); + + yield* Effect.gen(function* () { + const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; + yield* requests.offer({ + ...request(), + onRunEndedWithoutStarting: () => Deferred.succeed(released, undefined), + }); + yield* Deferred.await(released); + }).pipe( + Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)), + Effect.scoped, + ); + }), + ); }); diff --git a/apps/server/src/orchestration-v2/ProviderContinuationService.ts b/apps/server/src/orchestration-v2/ProviderContinuationService.ts index c00c68bce783d..36e86159efda5 100644 --- a/apps/server/src/orchestration-v2/ProviderContinuationService.ts +++ b/apps/server/src/orchestration-v2/ProviderContinuationService.ts @@ -83,7 +83,8 @@ export const layer = Layer.effectDiscard( return [Math.min(100 * 2 ** Math.min(attempt, 6), 5_000), updated] as const; }); - // Cancelling or stopping a queued continuation ends it unstarted; only the request can release the adapter's wake latch. + // Cancelling a queued continuation or failing a started run before a provider turn attaches leaves only the + // request able to release the adapter's wake latch; adapters guard by generation/token once a turn attaches. const releaseIfNeverStarted = Effect.fn("ProviderContinuationService.releaseIfNeverStarted")( function* ( request: ProviderContinuationRequests.ProviderContinuationRequest, @@ -113,11 +114,7 @@ export const layer = Layer.effectDiscard( ), Stream.runHead, Effect.flatMap((ended) => - Option.isSome(ended) && - ended.value.event.type === "run.updated" && - ended.value.event.payload.startedAt === null - ? onRunEndedWithoutStarting() - : Effect.void, + Option.isSome(ended) ? onRunEndedWithoutStarting() : Effect.void, ), Effect.catchCause((cause) => Effect.logWarning("orchestration-v2.provider-continuation.run-watch-failed", { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 0aa39ee755680..eb7c8cb2a61d6 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -6643,14 +6643,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); const cancelPendingRuntimeRequests = Effect.fnUntraced(function* ( - options: { - readonly stopMcpCalls: boolean; - readonly cancelDetachedRequests?: boolean; - } = { stopMcpCalls: true, cancelDetachedRequests: true }, + options: { readonly stopMcpCalls: boolean } = { stopMcpCalls: true }, ) { - if (options.cancelDetachedRequests !== false) { - yield* resolveTurnAttached("cancelled"); - } + yield* resolveTurnAttached("cancelled"); // session/cancel does not end the agent's MCP calls; T3 runs them, so it stops them. if (options.stopMcpCalls && runtimeMcpBridge !== undefined) { yield* runtimeMcpBridge.stopCalls; @@ -7372,94 +7367,75 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest = params, ) => (flavor.permissionDisposition ?? acpPermissionDisposition)(policy, request); - let turnState: "attached" | "unattached" | "cancelled" = "attached"; if ( (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") || (postSettleContinuationEnabled && flavor.wakeOnDetachedRequest) ) { - turnState = yield* awaitRequestTurn(handlerGeneration); - if (turnState === "cancelled") + if ((yield* awaitRequestTurn(handlerGeneration)) === "cancelled") return { outcome: { outcome: "cancelled" } } as const; } const admitted = yield* runRuntimeCallbackAtGeneration( handlerGeneration, Effect.gen(function* () { + let immediateResponse: EffectAcpSchema.RequestPermissionResponse | undefined; if (yield* Ref.get(stoppedRunQuarantine)) { - return { - _tag: "Immediate" as const, - response: { outcome: { outcome: "cancelled" } } as const, - }; - } - const context = yield* Ref.get(activeTurn); - // Kiro sends the tool's kind on its `tool_call` and leaves it - // off the permission request for that call; take it from the - // tool already seen under the same id so policy can tell a - // read from a write. - const knownKind = context?.tools.get(params.toolCall.toolCallId)?.kind; - const disposition = dispositionFor( - context?.input.runtimePolicy ?? latestRuntimePolicy, - params.toolCall.kind == null && knownKind !== undefined - ? { ...params, toolCall: { ...params.toolCall, kind: knownKind } } - : params, - ); - if (disposition === "allow") { - const optionId = selectAutoApprovedPermissionOption(answerableParams); - return { - _tag: "Immediate" as const, - response: + immediateResponse = { outcome: { outcome: "cancelled" } }; + } else { + const context = yield* Ref.get(activeTurn); + // Kiro sends the tool's kind on its `tool_call` and leaves it + // off the permission request for that call; take it from the + // tool already seen under the same id so policy can tell a + // read from a write. + const knownKind = context?.tools.get(params.toolCall.toolCallId)?.kind; + const disposition = dispositionFor( + context?.input.runtimePolicy ?? latestRuntimePolicy, + params.toolCall.kind == null && knownKind !== undefined + ? { ...params, toolCall: { ...params.toolCall, kind: knownKind } } + : params, + ); + if (disposition === "allow") { + const optionId = selectAutoApprovedPermissionOption(answerableParams); + immediateResponse = optionId === undefined - ? ({ outcome: { outcome: "cancelled" } } as const) - : ({ outcome: { outcome: "selected", optionId } } as const), - }; - } - if (disposition === "deny") { - const optionId = selectPermissionOptionId(answerableParams, "decline"); - return { - _tag: "Immediate" as const, - response: + ? { outcome: { outcome: "cancelled" } } + : { outcome: { outcome: "selected", optionId } }; + } else if (disposition === "deny") { + const optionId = selectPermissionOptionId(answerableParams, "decline"); + immediateResponse = optionId === undefined - ? ({ outcome: { outcome: "cancelled" } } as const) - : ({ outcome: { outcome: "selected", optionId } } as const), - }; - } - if (context === null && turnState === "unattached") { - return { - _tag: "Immediate" as const, - response: { outcome: { outcome: "cancelled" } } as const, - }; + ? { outcome: { outcome: "cancelled" } } + : { outcome: { outcome: "selected", optionId } }; + } else if (context === null) { + immediateResponse = { outcome: { outcome: "cancelled" } }; + } else { + return { + _tag: "Pending" as const, + pending: yield* beginApprovalRequest( + context, + params, + handlerGeneration, + transportRequestId, + ), + }; + } } - return { - _tag: "Pending" as const, - pending: yield* beginApprovalRequest( - context ?? (yield* activeContext), - params, - handlerGeneration, - transportRequestId, - ), - }; + const nativeResponseAcknowledgement = yield* Deferred.make< + void, + EffectAcpErrors.AcpError + >(); + yield* registerNativeResponseAcknowledgement( + handlerGeneration, + transportRequestId, + nativeResponseAcknowledgement, + ); + return { _tag: "Immediate" as const, response: immediateResponse }; }), ); if (Option.isNone(admitted)) { return yield* Effect.never; } if (admitted.value._tag === "Immediate") { - const response = admitted.value.response; - const checked = yield* runRuntimeCallbackAtGeneration( - handlerGeneration, - Effect.gen(function* () { - const nativeResponseAcknowledgement = yield* Deferred.make< - void, - EffectAcpErrors.AcpError - >(); - yield* registerNativeResponseAcknowledgement( - handlerGeneration, - transportRequestId, - nativeResponseAcknowledgement, - ); - return response; - }), - ); - return Option.isSome(checked) ? checked.value : yield* Effect.never; + return admitted.value.response; } const { context, @@ -10415,10 +10391,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* quarantineStoppedRun(); } // A settled soft interrupt keeps background subagents, and with them their MCP calls. - yield* cancelPendingRuntimeRequests({ - stopMcpCalls: !settledSoftInterrupt, - cancelDetachedRequests: !settledSoftInterrupt, - }); + yield* cancelPendingRuntimeRequests({ stopMcpCalls: !settledSoftInterrupt }); // Finalize before killing so projection catches up and concurrent interrupts see activeTurn cleared. if ( (hardRestart || context.promptSettled || settledSoftInterrupt) && diff --git a/packages/provider-core/src/server/ProviderContinuationRequests.ts b/packages/provider-core/src/server/ProviderContinuationRequests.ts index 576edcc221a11..4d601c6c6643c 100644 --- a/packages/provider-core/src/server/ProviderContinuationRequests.ts +++ b/packages/provider-core/src/server/ProviderContinuationRequests.ts @@ -30,7 +30,7 @@ export interface ProviderContinuationRequest { effect: Effect.Effect, ) => Effect.Effect, E, R>; readonly clearIfCurrent?: () => Effect.Effect; - /** Called when the run this request dispatched ends without starting, such as a cancelled queued run. */ + /** Called when the run this request dispatched reaches a terminal state; adapters guard by wake generation/token so it is a no-op once a turn attaches. */ readonly onRunEndedWithoutStarting?: () => Effect.Effect; }