diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 16004ccf28e09..6b87148e011ca 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -488,6 +488,7 @@ function makeMockRuntime(input: { | ((runtimeOrdinal: number) => Readonly>); readonly protocolEvents?: Queue.Queue; readonly cancelBehavior?: AcpSessionRuntime.AcpSessionRuntimeOptions["cancelBehavior"]; + readonly cancelMeta?: AcpSessionRuntime.AcpSessionRuntimeOptions["cancelMeta"]; // Also opts into replay-idle readiness, which runtimes leave off by default. readonly sessionLoadReplayIdleGap?: Duration.Input; readonly ownDescendantProcessGroups?: boolean; @@ -530,6 +531,7 @@ function makeMockRuntime(input: { AcpSessionRuntime.layer({ ...runtimeInput, ...(input.cancelBehavior === undefined ? {} : { cancelBehavior: input.cancelBehavior }), + ...(input.cancelMeta === undefined ? {} : { cancelMeta: input.cancelMeta }), ...(input.sessionLoadReplayIdleGap === undefined ? {} : { @@ -1362,7 +1364,7 @@ describe("AcpAdapterV2", () => { assert.equal(promptOrdinal, 2, "continuation turn must not dispatch session/prompt"); }).pipe(Effect.provide(layerTest)), ); - it.live("fails an end_turn the outcome check rejects and restarts before the next turn", () => + it.effect("fails an end_turn the outcome check rejects and restarts before the next turn", () => Effect.gen(function* () { const checking = yield* Deferred.make(); const releaseCheck = yield* Deferred.make(); @@ -1523,8 +1525,10 @@ describe("AcpAdapterV2", () => { }), }), ); - yield* Deferred.await(cancelled); + yield* TestClock.adjust(0); + const cancelledDuringCheck = yield* Deferred.isDone(cancelled); yield* Deferred.succeed(releaseCheck, undefined); + assert.isFalse(cancelledDuringCheck); const interruptedEvents = yield* Fiber.join(turn); yield* Fiber.join(stop); const interrupted = interruptedEvents.at(-1); @@ -1576,8 +1580,11 @@ describe("AcpAdapterV2", () => { mockAgentPath: yield* bundledMockAgentPath, wrapRuntime: (runtime) => ({ ...runtime, - prompt: (payload) => - Effect.sync(() => { + prompt: (payload, promptOptions) => + Effect.gen(function* () { + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } promptTexts.push( payload.prompt .flatMap((block) => (block.type === "text" ? [block.text] : [])) @@ -6735,6 +6742,711 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("finalizes the turn when the start effect is cancelled mid-start", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const holdBeforePrompt = yield* Deferred.make(); + const reachedBeforePrompt = yield* Deferred.make(); + const instanceId = ProviderInstanceId.make("acp-start-cancelled"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath: yield* bundledMockAgentPath, + environment: () => ({}), + }), + }, + selfInvocation: yield* resolveSelfInvocation(), + testHooks: { + beforePromptDispatch: () => + Deferred.succeed(reachedBeforePrompt, undefined).pipe( + Effect.andThen(Deferred.await(holdBeforePrompt)), + ), + }, + }); + const threadId = ThreadId.make("thread-acp-start-cancelled"); + 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("provider-session-acp-start-cancelled"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const start = yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), + ) + .pipe(Effect.forkScoped); + yield* Deferred.await(reachedBeforePrompt); + // Cancelling the in-flight start effect interrupts its fiber, the same + // path an interrupt-before-provider-start takes through the effect worker. + yield* Fiber.interrupt(start); + yield* Deferred.succeed(holdBeforePrompt, undefined); + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), + ); + const terminals = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.take(2), + Stream.runCollect, + Effect.map((events) => + Array.from(events, (event) => { + if (event.type !== "turn.terminal") throw new Error("Expected a turn terminal"); + return event; + }), + ), + ); + assert.equal(terminals[0]?.status, "interrupted"); + assert.equal(terminals[1]?.status, "completed"); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("does not dispatch the prompt of a turn interrupted before registration", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const protocolEvents = yield* Queue.unbounded(); + const holdPrompt = yield* Deferred.make(); + const cancelSignalled = yield* Deferred.make(); + const instanceId = ProviderInstanceId.make("acp-interrupted-before-dispatch"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath: yield* bundledMockAgentPath, + environment: () => ({}), + protocolEvents, + wrapRuntime: (runtime) => ({ + ...runtime, + prompt: (payload, options) => + Deferred.await(holdPrompt).pipe( + Effect.andThen(() => runtime.prompt(payload, options)), + ), + cancel: Deferred.succeed(cancelSignalled, undefined).pipe( + Effect.andThen(() => runtime.cancel), + ), + }), + }), + }, + selfInvocation: yield* resolveSelfInvocation(), + }); + const threadId = ThreadId.make("thread-acp-interrupted-before-dispatch"); + 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("provider-session-acp-interrupted"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + messageText: "interrupted prompt", + }), + ); + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), + }); + const interrupt = yield* runtime + .interruptTurn({ providerThread, providerTurnId }) + .pipe(Effect.forkScoped); + // The cancel reaches the runtime while the prompt is still parked + // ahead of registration, the race the stopped check must close. + yield* Deferred.await(cancelSignalled); + yield* Deferred.succeed(holdPrompt, undefined); + yield* Fiber.join(interrupt); + const firstTerminal = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.take(1), + Stream.runCollect, + Effect.map((events) => + Array.from(events, (event) => { + if (event.type !== "turn.terminal") throw new Error("Expected a turn terminal"); + return event; + }), + ), + ); + assert.equal(firstTerminal[0]?.status, "interrupted"); + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal: 2, + messageText: "second prompt", + }), + ); + const secondTerminal = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.take(1), + Stream.runCollect, + Effect.map((events) => + Array.from(events, (event) => { + if (event.type !== "turn.terminal") throw new Error("Expected a turn terminal"); + return event; + }), + ), + ); + assert.equal(secondTerminal[0]?.status, "completed"); + const logged = yield* Queue.takeAll(protocolEvents); + const dispatchedPrompts = logged.filter( + (event) => event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", + ); + assert.equal(dispatchedPrompts.length, 1); + assert.isTrue( + typeof dispatchedPrompts[0]?.payload === "string" && + dispatchedPrompts[0].payload.includes("second prompt"), + ); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("starts the cancel hold at prompt handoff", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const beforePrompt = yield* Deferred.make(); + const releasePrompt = yield* Deferred.make(); + const protocolEvents = yield* Queue.unbounded(); + const cancelHeld = yield* Deferred.make(); + const cancelCalled = yield* Deferred.make(); + const instanceId = ProviderInstanceId.make("acp-start-cancel-hold"); + const threadId = ThreadId.make("thread-acp-start-cancel-hold"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + cancelAfterPromptStarts: { bound: "1 second", isStart: () => false }, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath: yield* bundledMockAgentPath, + environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, + protocolEvents, + wrapCancel: (cancel) => + Deferred.succeed(cancelCalled, undefined).pipe(Effect.andThen(cancel)), + }), + }, + testHooks: { + beforePromptDispatch: () => + Deferred.succeed(beforePrompt, undefined).pipe( + Effect.andThen(Deferred.await(releasePrompt)), + ), + afterPromptFork: () => Effect.never, + onCancelHeld: () => Deferred.succeed(cancelHeld, undefined).pipe(Effect.asVoid), + }, + }); + 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("provider-session-acp-start-cancel-hold"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const start = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ) + .pipe(Effect.forkScoped); + yield* Deferred.await(beforePrompt); + yield* TestClock.adjust("2 seconds"); + yield* Deferred.succeed(releasePrompt, undefined); + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", + ), + Stream.runHead, + ); + const interrupt = yield* Fiber.interrupt(start).pipe(Effect.forkScoped); + yield* Deferred.await(cancelHeld); + yield* TestClock.adjust("500 millis"); + assert.isFalse(yield* Deferred.isDone(cancelCalled)); + yield* TestClock.adjust("500 millis"); + yield* Deferred.await(cancelCalled); + yield* Fiber.join(interrupt); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("measures the cancel hold from the prompt's registration", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const promptReachedRuntime = yield* Deferred.make(); + const releasePromptToRuntime = yield* Deferred.make(); + const protocolEvents = yield* Queue.unbounded(); + const cancelHeld = yield* Deferred.make(); + const cancelCalled = yield* Deferred.make(); + const instanceId = ProviderInstanceId.make("acp-start-cancel-registration"); + const threadId = ThreadId.make("thread-acp-start-cancel-registration"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + cancelAfterPromptStarts: { bound: "1 second", isStart: () => false }, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath: yield* bundledMockAgentPath, + environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, + protocolEvents, + wrapCancel: (cancel) => + Deferred.succeed(cancelCalled, undefined).pipe(Effect.andThen(cancel)), + wrapRuntime: (runtime) => ({ + ...runtime, + prompt: (payload, options) => + Deferred.succeed(promptReachedRuntime, undefined).pipe( + Effect.andThen(Deferred.await(releasePromptToRuntime)), + Effect.andThen(runtime.prompt(payload, options)), + ), + }), + }), + }, + testHooks: { + afterPromptFork: () => Effect.never, + onCancelHeld: () => Deferred.succeed(cancelHeld, undefined).pipe(Effect.asVoid), + }, + }); + 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("provider-session-acp-start-cancel-registration"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const start = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ) + .pipe(Effect.forkScoped); + yield* Deferred.await(promptReachedRuntime); + // Time the prompt spends before its registration must not shorten the hold. + yield* TestClock.adjust("2 seconds"); + yield* Deferred.succeed(releasePromptToRuntime, undefined); + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", + ), + Stream.runHead, + ); + const interrupt = yield* Fiber.interrupt(start).pipe(Effect.forkScoped); + yield* Deferred.await(cancelHeld); + assert.isFalse(yield* Deferred.isDone(cancelCalled)); + yield* TestClock.adjust("500 millis"); + assert.isFalse(yield* Deferred.isDone(cancelCalled)); + yield* TestClock.adjust("500 millis"); + yield* Deferred.await(cancelCalled); + yield* Fiber.join(interrupt); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect.each(["approval", "elicitation"] as const)( + "drains an in-flight %s admission before native start cancellation", + (kind) => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const admitting = yield* Deferred.make(); + const releaseAdmission = yield* Deferred.make(); + const cancelCalled = yield* Deferred.make(); + let requestAfterCutoff: Effect.Effect = Effect.die( + "Expected the mock agent to request input", + ); + let lateResponse: unknown; + let startCount = 0; + let runtimeCount = 0; + const instanceId = ProviderInstanceId.make("acp-start-cancel-admission"); + const threadId = ThreadId.make("thread-acp-start-cancel-admission"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath: yield* bundledMockAgentPath, + cancelBehavior: "wait-for-prompt", + environment: + kind === "approval" + ? { T3_ACP_EMIT_TOOL_CALLS: "1" } + : { T3_ACP_EMIT_ELICITATION: "1" }, + wrapRuntime: (runtime) => { + runtimeCount += 1; + return { + ...runtime, + handleRequestPermission: (handler) => + runtime.handleRequestPermission((params, context) => { + requestAfterCutoff = handler(params, { ...context, requestId: "late" }); + return handler(params, context); + }), + handleElicitation: (handler) => + runtime.handleElicitation((params, context) => { + requestAfterCutoff = handler(params, { ...context, requestId: "late" }); + return handler(params, context); + }), + cancel: Effect.gen(function* () { + yield* Deferred.succeed(cancelCalled, undefined); + lateResponse = yield* requestAfterCutoff; + yield* runtime.cancel; + }), + }; + }, + }), + }, + testHooks: { + afterPromptFork: () => (++startCount === 1 ? Effect.never : Effect.void), + onNativeResponseLifecycle: (event) => + event.type === "registered" + ? Deferred.succeed(admitting, undefined).pipe( + Effect.andThen(Deferred.await(releaseAdmission)), + ) + : Effect.void, + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-start-cancel-admission"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const startTurn = (ordinal: number) => + DateTime.now.pipe( + Effect.flatMap((now) => + runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal, + }), + ), + ), + ); + const start = yield* startTurn(1).pipe(Effect.forkScoped); + yield* Deferred.await(admitting); + const interrupt = yield* Fiber.interrupt(start).pipe(Effect.forkScoped); + yield* TestClock.adjust(0); + const cancelledBeforeAdmission = yield* Deferred.isDone(cancelCalled); + yield* Deferred.succeed(releaseAdmission, undefined); + assert.isFalse(cancelledBeforeAdmission); + yield* Fiber.join(interrupt); + assert.deepEqual( + lateResponse, + kind === "approval" ? { outcome: { outcome: "cancelled" } } : { action: "cancel" }, + ); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + assert.deepEqual( + events.flatMap((event) => + event.type === "runtime_request.updated" ? [event.runtimeRequest.status] : [], + ), + ["pending", "cancelled"], + ); + const terminal = events.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "interrupted"); + yield* startTurn(2); + assert.equal(runtimeCount, 1); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect.each(["interrupt", "wait-for-prompt"] as const)( + "replaces the runtime when a registered prompt fails to cancel during start (%s)", + (cancelBehavior) => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const natives: Array = []; + const cancelMeta: NonNullable = { + get circular() { + return cancelMeta; + }, + }; + const instanceId = ProviderInstanceId.make("acp-start-cancel-failed"); + const threadId = ThreadId.make("thread-acp-start-cancel-failed"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath: yield* bundledMockAgentPath, + cancelBehavior, + cancelMeta, + environment: (ordinal) => + ordinal === 1 ? { T3_ACP_EMIT_TRACKED_TOOL_CALL_KIND_THEN_HANG: "execute" } : {}, + wrapRuntime: (runtime) => { + natives.push(runtime); + return runtime; + }, + }), + }, + selfInvocation: yield* resolveSelfInvocation(), + testHooks: { afterPromptFork: () => (natives.length === 1 ? Effect.never : Effect.void) }, + }); + 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("provider-session-acp-start-cancel-failed"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const cancelWhileIdle = yield* natives[0]!.cancel.pipe(Effect.flip); + assert.equal(cancelWhileIdle._tag, "AcpProtocolParseError"); + + const now = yield* DateTime.now; + const startTurn = (ordinal: number) => + runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal }), + ); + const start = yield* startTurn(1).pipe(Effect.forkScoped); + yield* runtime.events.pipe( + Stream.filter( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "tracked-tool-call", + ), + Stream.runHead, + ); + assert.lengthOf(natives, 1); + yield* Fiber.interrupt(start); + yield* startTurn(2); + assert.lengthOf(natives, 2); + + const terminals = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.take(2), + Stream.runCollect, + ); + assert.deepEqual( + terminals.map((event) => (event.type === "turn.terminal" ? event.status : undefined)), + ["interrupted", "completed"], + ); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect.each(["superseded", "stopped", "failed"] as const)( + "declines a %s steer that never dispatched", + (outcome) => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const instanceId = ProviderInstanceId.make("acp-steer-superseded-wait"); + const threadId = ThreadId.make("thread-acp-steer-superseded-wait"); + const steerOneAttempted = yield* Deferred.make(); + const cancelCalled = yield* Deferred.make(); + const holdInitialPrompt = yield* Deferred.make< + EffectAcpSchema.PromptResponse, + EffectAcpErrors.AcpError + >(); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + steersWithPrompt: () => true, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapCancel: (cancel) => + Deferred.succeed(cancelCalled, undefined).pipe(Effect.andThen(cancel)), + wrapRuntime: (runtime) => ({ + ...runtime, + prompt: (payload, promptOptions) => + Effect.gen(function* () { + const text = payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"); + if (text.includes("steer one")) { + // Park the first steer in the busy retry so the second + // steer can supersede it. A refusal is not a registration, + // so nothing settles the dispatched wait for this attempt. + yield* Deferred.succeed(steerOneAttempted, undefined); + return yield* EffectAcpErrors.AcpRequestError.internalError( + outcome === "failed" + ? "Prompt failed before registration" + : "Agent is already processing. Use steer() or followUp() to queue messages.", + ); + } + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + if (text.includes("steer two")) { + return { stopReason: "end_turn" as const }; + } + return yield* Deferred.await(holdInitialPrompt); + }), + }), + }), + }, + }); + 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("provider-session-acp-steer-superseded-wait"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + messageText: "Start turn 1", + }), + ); + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), + }); + const steer = (ordinal: number, text: string) => + runtime.steerTurn({ + threadId, + runId: RunId.make(`run:${threadId}:${ordinal}`), + providerThread, + providerTurnId, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`steer-${ordinal}`), + text, + attachments: [], + }, + appContext: [], + }); + const firstSteer = yield* steer(1, "steer one").pipe(Effect.forkScoped); + yield* Deferred.await(steerOneAttempted); + if (outcome === "superseded") yield* steer(2, "steer two"); + const interrupt = + outcome === "stopped" + ? yield* runtime + .interruptTurn({ providerThread, providerTurnId }) + .pipe(Effect.forkScoped) + : undefined; + if (interrupt !== undefined) yield* Deferred.await(cancelCalled); + if (outcome !== "failed") yield* TestClock.adjust("2 seconds"); + const error = yield* Fiber.join(firstSteer).pipe(Effect.flip); + assert.equal(error._tag, "ProviderAdapterSteerDeclinedError"); + if (interrupt !== undefined) yield* Fiber.join(interrupt); + const terminal = Option.getOrThrow( + yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + ), + ); + if (terminal.type !== "turn.terminal") return yield* Effect.die("Expected a turn terminal"); + const expected = { superseded: "completed", stopped: "interrupted", failed: "failed" }; + assert.equal(terminal.status, expected[outcome]); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("sends no more prompts once a follow-up waiting on a busy agent is stopped", () => Effect.gen(function* () { let promptCalls = 0; diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index f829391b7e9ba..895d86f4d2c60 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -1191,12 +1191,15 @@ export class AcpSessionRuntime extends Context.Service< /** * options.dispatched settles when cancel can target this prompt. options.released lets the * next prompt go out while this one's response is still held; it still resolves this call. + * options.stopped, rechecked under the dispatch permit right before registration, keeps a + * prompt whose turn was interrupted from reaching the agent at all. */ readonly prompt: ( payload: Omit, options?: { readonly dispatched?: Deferred.Deferred; readonly released?: Deferred.Deferred; + readonly stopped?: () => boolean; }, ) => Effect.Effect; readonly cancel: Effect.Effect; @@ -2641,11 +2644,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( Effect.timeoutOption(options.cancelTimeout ?? defaultCancelTimeout), ) : Effect.void; - if (options.cancelBehavior !== "wait-for-prompt") { - if (options.interruptPromptOnCancel === false) { - yield* promptQueued; - return yield* acp.agent.cancel(cancelPayload); - } + if (options.cancelBehavior !== "wait-for-prompt" && options.interruptPromptOnCancel !== false) { if (Option.isSome(activePrompt)) { yield* Fiber.interrupt(activePrompt.value.fiber).pipe(Effect.ignore); } @@ -2655,8 +2654,16 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( } yield* promptQueued; - yield* acp.agent.cancel(cancelPayload); - if (Option.isNone(activePrompt)) { + yield* acp.agent.cancel(cancelPayload).pipe( + Effect.tapError((error) => + Effect.gen(function* () { + if (Option.isSome(activePrompt) && (yield* Ref.get(activePromptRef)) === activePrompt) { + yield* retireRuntime(error); + } + }), + ), + ); + if (options.cancelBehavior !== "wait-for-prompt" || Option.isNone(activePrompt)) { return; } const completed = yield* Effect.gen(function* () { @@ -2884,6 +2891,22 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( Effect.acquireUseRelease( promptDispatchSemaphore.withPermit( Effect.gen(function* () { + // Checked under the dispatch permit: a cancel that waits for the + // same permit can no longer slip between this check and the + // registration below. A stopped prompt never reaches the agent, + // so it cannot strand the serialization permit either. + if (promptOptions?.stopped?.()) { + const cancelledFiber = yield* Effect.succeed({ + stopReason: "cancelled", + } satisfies EffectAcpSchema.PromptResponse).pipe(Effect.forkIn(runtimeScope)); + const cancelledCompleted = yield* Deferred.make(); + const cancelledQueued = yield* Deferred.make(); + return { + fiber: cancelledFiber, + completed: cancelledCompleted, + queued: cancelledQueued, + } satisfies AcpActivePrompt; + } const started = yield* getStartedState; yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }); yield* Ref.set(assistantUpdatesOpenRef, true); @@ -2960,12 +2983,10 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( : joinPrompt(outcome.fiber), ), ), - // A cancel that waits for its prompt holds the dispatch permit, so a next prompt cannot reach - // the agent ahead of it and take the cancel meant for the prompt before. - cancel: - options.cancelBehavior === "wait-for-prompt" || options.interruptPromptOnCancel === false - ? promptDispatchSemaphore.withPermit(cancel) - : cancel, + // The dispatch permit keeps a cancel from slipping between a stopped + // prompt's check and its registration, and a next prompt from reaching + // the agent ahead of a cancel that waits for its prompt. + cancel: promptDispatchSemaphore.withPermit(cancel), ...(options.ownDetachedProcessGroup === true ? { terminateProcessGroup } : {}), // A session's mode is its `category: "mode"` config option. ACP v1 agents // that only advertise `modes` (gemini-cli) take `session/set_mode` diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 744b02815e178..c001de6edeb95 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -220,17 +220,24 @@ function sendPromptWhenIdle( turn: { readonly interrupted: boolean; readonly finalized: boolean }, prompt: () => Effect.Effect, superseded: () => boolean = () => false, + stoppedValue?: A, ): Effect.Effect { // A Stop or a prompt-steer can land during the wait, so both are rechecked before each resend. const stopped = () => turn.interrupted || turn.finalized || superseded(); - return prompt().pipe( + return Effect.suspend(() => + stopped() && stoppedValue !== undefined ? Effect.succeed(stoppedValue) : prompt(), + ).pipe( Effect.catchIf( (error) => isAgentBusyPromptError(error) && !stopped(), (error) => Effect.sleep(ACP_BUSY_PROMPT_RETRY_INTERVAL).pipe( Effect.andThen( Effect.suspend(() => - stopped() ? Effect.fail(error) : sendPromptWhenIdle(turn, prompt, superseded), + stopped() + ? stoppedValue === undefined + ? Effect.fail(error) + : Effect.succeed(stoppedValue) + : sendPromptWhenIdle(turn, prompt, superseded, stoppedValue), ), ), ), @@ -932,6 +939,9 @@ export interface AcpAdapterV2Options { }; readonly testHooks?: { readonly onDeferredFinalizeScheduled?: (debounce: Duration.Input) => Effect.Effect; + /** Suspends the start fiber right before `session/prompt` is handed to the runtime. */ + readonly beforePromptDispatch?: () => Effect.Effect; + readonly afterPromptFork?: () => Effect.Effect; /** `cancelAfterPromptStarts`: Stop is holding `session/cancel` until the prompt starts. */ readonly onCancelHeld?: () => Effect.Effect; readonly afterPromptWireSettled?: () => Effect.Effect; @@ -2013,6 +2023,13 @@ interface ActiveAcpTurn { promptWireSettled: Deferred.Deferred; /** Completed once `session/prompt` is the runtime's active prompt. */ readonly promptDispatched: Deferred.Deferred; + /** + * Set immediately before the prompt fiber is forked. A start fiber + * interrupted from that point on may have already put the prompt on the + * wire, so the interrupt cleanup must send `session/cancel` rather than + * assume nothing was dispatched. + */ + promptForked: boolean; /** Frees the runtime for the next prompt while the agent still holds this one's response. */ foregroundIdle: Deferred.Deferred; /** Counts the turn's prompts; only the latest one settles the turn. */ @@ -3518,7 +3535,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( agentRequests.clear(); yield* Ref.set(wakeBuffer, []); yield* Ref.set(continuationRequested, false); - yield* cancelPendingRuntimeRequests(); + yield* cancelPendingRuntimeRequestsUnderPermit(); for (const tool of held.tools.values()) { const status = toolStatus(tool.status); if (status === "pending" || status === "running" || status === "waiting") { @@ -3550,7 +3567,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( agentRequests.clear(); yield* Ref.set(wakeBuffer, []); yield* Ref.set(continuationRequested, false); - yield* cancelPendingRuntimeRequests(); + yield* cancelPendingRuntimeRequestsUnderPermit(); const context = yield* Ref.get(activeTurn); if (context !== null) { if (!context.finalized && !context.interrupted) { @@ -7703,11 +7720,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const beginUserInputRequest = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, request: AcpAdapterV2UserInputRequest, generation: number, transportRequestId: string, ) { - const context = yield* activeContext; yield* closeTextStreams(context); const requestId = yield* idAllocator.allocate.runtimeRequest({ driver, @@ -7840,14 +7857,22 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } return yield* runRuntimeCallbackAtGeneration( generation, - request.pipe( - Effect.flatMap((value) => - beginUserInputRequest(value, generation, transportRequestId), - ), - ), + Effect.gen(function* () { + const context = yield* Ref.get(activeTurn); + if (context === null || context.interrupted || context.finalized) return null; + return yield* beginUserInputRequest( + context, + yield* request, + generation, + transportRequestId, + ); + }), ).pipe( Effect.flatMap((pending) => { if (Option.isNone(pending)) return Effect.never; + if (pending.value === null) { + return Effect.succeed({ answers: null, acknowledgeNativeResponse: Effect.void }); + } const { answers, requestId, transportRequestId } = pending.value; return Deferred.await(answers).pipe( Effect.flatMap((result) => @@ -7888,7 +7913,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ); - const cancelPendingRuntimeRequests = Effect.fnUntraced(function* ( + const cancelPendingRuntimeRequestsUnderPermit = Effect.fnUntraced(function* ( options: { readonly stopMcpCalls: boolean } = { stopMcpCalls: true }, ) { const waiting = turnAttached; @@ -7948,6 +7973,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }); + const cancelPendingRuntimeRequests = (options?: { readonly stopMcpCalls: boolean }) => + runtimeCallbackPermit.withPermit(cancelPendingRuntimeRequestsUnderPermit(options)); + const mutateCarryoverSubagentStatus = Effect.fnUntraced(function* ( subagent: ActiveAcpSubagent, status: OrchestrationV2Subagent["status"], @@ -8637,9 +8665,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const admitted = yield* runRuntimeCallbackAtGeneration( handlerGeneration, Effect.gen(function* () { - const context = followsAgentWorkState - ? yield* Ref.get(activeTurn) - : yield* activeContext; + const context = yield* Ref.get(activeTurn); + if ( + context?.interrupted || + context?.finalized || + (context === null && !followsAgentWorkState) + ) { + return { _tag: "Cancelled" as const }; + } const disposition = dispositionFor( context?.input.runtimePolicy ?? latestRuntimePolicy, policyRequest( @@ -8668,10 +8701,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( : ({ outcome: { outcome: "selected", optionId } } as const), }; } + if (context === null) return { _tag: "Cancelled" as const }; return { _tag: "Pending" as const, pending: yield* beginApprovalRequest( - yield* activeContext, + context, params, handlerGeneration, transportRequestId, @@ -8682,6 +8716,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (Option.isNone(admitted)) { return yield* Effect.never; } + if (admitted.value._tag === "Cancelled") { + return { outcome: { outcome: "cancelled" } } as const; + } if (admitted.value._tag === "Immediate") { const response = admitted.value.response; const checked = yield* runRuntimeCallbackAtGeneration( @@ -9194,7 +9231,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( { discard: true }, ); } - yield* cancelPendingRuntimeRequests(); + yield* cancelPendingRuntimeRequestsUnderPermit(); if (previousScope !== undefined) { yield* Scope.close(previousScope, Exit.void).pipe( Effect.catchCause((cause) => @@ -10230,7 +10267,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* quarantineNativeTransportAtGeneration(generation); yield* advanceRuntimeCallbackGeneration; yield* requireRuntimeRestart; - yield* cancelPendingRuntimeRequests(); + yield* cancelPendingRuntimeRequestsUnderPermit(); yield* terminalizeOpenForegroundTools(context, "failed"); // Bounded: it runs under the transition permit that Stop and the next turn wait on. const recorded = @@ -10802,6 +10839,23 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }; + // A cancelled start/restart effect interrupts this fiber mid-flight, + // which neither cancels the agent nor finalizes the turn. Finalize as + // interrupted; cancel best effort once the prompt may be on the wire. + const finalizeInterruptedStart = Effect.fnUntraced(function* () { + const context = yield* Ref.get(activeTurn); + if (context === null || context.finalized) return; + context.interrupted = true; + yield* cancelPendingRuntimeRequests(); + if ( + (context.promptForked || (yield* Deferred.isDone(context.promptDispatched))) && + (yield* promptStillRunsAfterHold(context)) + ) { + yield* runtime.cancel.pipe(Effect.ignore); + } + yield* finalizeTurn(context, "interrupted"); + }); + const startTurnUnlocked = Effect.fn("AcpAdapterV2.startTurn")( function* (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) { yield* awaitRuntimeTeardown(); @@ -10999,6 +11053,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( workAccepted: false, promptWireSettled, promptDispatched, + promptForked: false, foregroundIdle: yield* Deferred.make(), promptSequence: 0, outcomeResumed: false, @@ -11172,7 +11227,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( dispatched: context.promptDispatched, released: context.foregroundIdle, }; - context.promptSentAt = yield* Clock.currentTimeMillis; if (promptInactivityTimeoutMillis !== undefined) { context.inactivityWatchdog = yield* watchPromptInactivity( context, @@ -11194,14 +11248,33 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( sequence: ++context.appContextSequence, } : undefined; + yield* options.testHooks?.beforePromptDispatch?.() ?? Effect.void; + // The cancel hold runs from the runtime's registration of the prompt, so + // time spent handing it over cannot shorten the hold. + yield* Effect.gen(function* () { + yield* Deferred.await(context.promptDispatched); + context.promptSentAt = yield* Clock.currentTimeMillis; + }).pipe(Effect.forkIn(sessionScope)); + // Set before the fork: an interrupt processed at the fork's own + // suspension point can no longer recall the prompt, so the cleanup + // must treat it as dispatched from here on. + context.promptForked = true; yield* followPrompt( context, (superseded) => compactSession === undefined ? sendPromptWhenIdle( context, - () => runtime.prompt({ prompt: promptParts!.prompt }, promptOptions), + () => + runtime.prompt( + { prompt: promptParts!.prompt }, + { + ...promptOptions, + stopped: () => context.interrupted || context.finalized || superseded(), + }, + ), superseded, + { stopReason: "cancelled" } satisfies EffectAcpSchema.PromptResponse, ) : Deferred.succeed(context.promptDispatched, undefined).pipe( Effect.andThen(compactSession.compact(runtime, requestedSessionId)), @@ -11217,9 +11290,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( compactSession, }, ).pipe(Effect.forkIn(sessionScope)); + yield* options.testHooks?.afterPromptFork?.() ?? Effect.void; }, (effect, turnInput) => effect.pipe( + // Runs while the transition permit is still held: the dying + // start fiber owns `activeTurn` until this cleanup finalizes it. + Effect.onInterrupt(() => finalizeInterruptedStart()), Effect.mapError( (cause) => new ProviderAdapter.ProviderAdapterTurnStartError({ @@ -11245,6 +11322,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const steerWithPrompt = Effect.fn("AcpAdapterV2.steerWithPrompt")(function* ( turnInput: ProviderAdapter.ProviderAdapterV2SteerInput, ) { + const decline = () => + new ProviderAdapter.ProviderAdapterSteerDeclinedError({ + driver, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + }); const isNativeSlashCommand = turnInput.message.text.trimStart().startsWith("/"); const text = yield* providerMessageTextWithAttachmentPaths({ text: turnInput.message.text, @@ -11256,7 +11339,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( text, turnInput.message.attachments, ); - const [dispatched, context] = yield* runtimeTransitionPermit.withPermit( + const [dispatched, context, promptFiber] = yield* runtimeTransitionPermit.withPermit( Effect.gen(function* () { const context = yield* Ref.get(activeTurn); if ( @@ -11265,10 +11348,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context.interrupted || context.providerTurnId !== turnInput.providerTurnId ) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver, - detail: `Provider turn ${turnInput.providerTurnId} is not active and cannot be steered.`, - }); + return yield* decline(); } const generation = yield* Ref.get(runtimeCallbackGeneration); const checkPromptOutcome = @@ -11342,7 +11422,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ).pipe(Effect.forkIn(sessionScope)); } const releasedForSteer = context.foregroundIdle; - yield* followPrompt( + const promptFiber = yield* followPrompt( context, (superseded) => sendPromptWhenIdle( @@ -11350,9 +11430,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( () => runtime.prompt( { prompt: steerPrompt }, - { dispatched, released: releasedForSteer }, + { + dispatched, + released: releasedForSteer, + stopped: () => + context.interrupted || context.finalized || superseded(), + }, ), superseded, + { stopReason: "cancelled" } satisfies EffectAcpSchema.PromptResponse, ), { generation, @@ -11363,19 +11449,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }, ).pipe(Effect.forkIn(sessionScope)); yield* Deferred.succeed(released, undefined); - return true; + return promptFiber; }), ); - if (!Option.contains(steered, true)) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver, - detail: `Provider turn ${turnInput.providerTurnId} ended before it could be steered.`, - }); + if (Option.isNone(steered) || steered.value === false) { + return yield* decline(); } - return [dispatched, context] as const; + return [dispatched, context, steered.value] as const; }), ); - yield* Deferred.await(dispatched); + yield* Effect.raceFirst(Deferred.await(dispatched), Fiber.await(promptFiber)); + if (!(yield* Deferred.isDone(dispatched))) return yield* decline(); // A wake run sent no prompt, so its inactivity watchdog waits for this one. yield* Deferred.succeed(context.promptDispatched, undefined); }); @@ -11779,7 +11863,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (effect, turnInput) => effect.pipe( Effect.mapError((cause) => - cause._tag === "ProviderAdapterSteerRunUnsupportedError" + cause._tag === "ProviderAdapterSteerRunUnsupportedError" || + cause._tag === "ProviderAdapterSteerDeclinedError" ? cause : new ProviderAdapter.ProviderAdapterSteerRunError({ driver, @@ -11886,7 +11971,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( nativeChildren.clear(); yield* quarantineStoppedRun(); if (context !== null) context.interrupted = true; - yield* cancelPendingRuntimeRequests(); + yield* cancelPendingRuntimeRequestsUnderPermit(); yield* terminalizeCarryoverSubagents(carryover); if (context !== null) { yield* finalizeTurn(context, "interrupted");