diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..1b69455825bae 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,177 @@ 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("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)), + ); + + 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 e214a51586f4c..eb7c8cb2a61d6 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( @@ -6625,9 +6645,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const cancelPendingRuntimeRequests = Effect.fnUntraced(function* ( options: { readonly stopMcpCalls: boolean } = { stopMcpCalls: true }, ) { - const waiting = turnAttached; - turnAttached = yield* Deferred.make(); - yield* Deferred.succeed(waiting, 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; @@ -7353,78 +7371,71 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (followsAgentWorkState && dispositionFor(latestRuntimePolicy) === "ask") || (postSettleContinuationEnabled && flavor.wakeOnDetachedRequest) ) { - if (!(yield* awaitRequestTurn(handlerGeneration))) + if ((yield* awaitRequestTurn(handlerGeneration)) === "cancelled") return { outcome: { outcome: "cancelled" } } as const; } const admitted = yield* runRuntimeCallbackAtGeneration( handlerGeneration, Effect.gen(function* () { - const context = followsAgentWorkState - ? yield* Ref.get(activeTurn) - : yield* activeContext; - // 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: + let immediateResponse: EffectAcpSchema.RequestPermissionResponse | undefined; + if (yield* Ref.get(stoppedRunQuarantine)) { + 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), - }; + ? { 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( - 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, @@ -9540,9 +9551,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. 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; }