diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 0b6232479c40a..28b1e0e3c35c2 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -982,6 +982,168 @@ describe("ClaudeAdapterV2 approval cancellation", () => { assert.deepEqual(result, { decision: "cancel" }); }), ); + + it.effect.each([ + { name: "command approval", toolName: "Bash", toolInput: { command: "rm -rf build" } }, + { + name: "user question", + toolName: "AskUserQuestion", + toolInput: { + questions: [ + { + header: "Target", + question: "Deploy where?", + options: [ + { label: "Production", description: "Deploy to production." }, + { label: "Staging", description: "Deploy to staging." }, + ], + multiSelect: false, + }, + ], + }, + }, + ])("closes the $name when the SDK aborts it", ({ toolName, toolInput }) => + Effect.scoped( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: {}, + attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-aborted-request-", + }), + fileSystem, + path: yield* Path.Path, + crypto: yield* Crypto.Crypto, + idAllocator: yield* IdAllocator.IdAllocatorV2, + queryRunner: { + allocateSessionId: Effect.succeed("native-thread-claude-aborted-request"), + open: (input) => + Effect.sync(() => { + openedOptions = input.options; + return { + messages: Stream.never, + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Effect.void, + }; + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: "/workspace", + }); + const threadId = ThreadId.make("thread-claude-aborted-request"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-claude-aborted-request"), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy, + }); + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-aborted-request"), + text: "Clean the build.", + attachments: [], + runtimePolicy, + }), + ); + const canUseTool = openedOptions?.canUseTool; + assert.isFunction(canUseTool); + + const opened = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "runtime_request.updated"), + Stream.runHead, + Effect.forkScoped, + ); + // A PermissionRequest hook that answers first makes the SDK abort this callback. + const controller = new AbortController(); + const result = yield* Effect.promise(() => + canUseTool!(toolName, toolInput, { + signal: controller.signal, + toolUseID: "tool-aborted-request", + requestId: "request-aborted-request", + }), + ).pipe(Effect.forkScoped); + const openedEvent = yield* Fiber.join(opened); + if (Option.isNone(openedEvent) || openedEvent.value.type !== "runtime_request.updated") { + return assert.fail("the request never opened"); + } + const request = openedEvent.value.runtimeRequest; + assert.equal(request.status, "pending"); + + controller.abort(); + assert.equal((yield* Fiber.join(result))?.behavior, "deny"); + // The event queue never ends, so a later plan marks where the abort's updates must be. + const marker = yield* Effect.promise(() => + canUseTool!( + "ExitPlanMode", + { plan: "# Marker" }, + { + signal: new AbortController().signal, + toolUseID: "tool-marker", + requestId: "request-marker", + }, + ), + ); + assert.equal(marker?.behavior, "deny"); + const afterAbort = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "plan.updated"), + Stream.runCollect, + ); + + const closedRequest = afterAbort.findLast( + (event) => + event.type === "runtime_request.updated" && event.runtimeRequest.id === request.id, + ); + assert.deepInclude( + closedRequest?.type === "runtime_request.updated" ? closedRequest.runtimeRequest : {}, + { status: "cancelled" }, + ); + const closedNode = afterAbort.findLast( + (event) => event.type === "node.updated" && event.node.id === request.nodeId, + ); + assert.equal( + closedNode?.type === "node.updated" ? closedNode.node.status : null, + "cancelled", + ); + const closedItem = afterAbort.findLast( + (event) => + event.type === "turn_item.updated" && + "requestId" in event.turnItem && + event.turnItem.requestId === request.id, + ); + assert.equal( + closedItem?.type === "turn_item.updated" ? closedItem.turnItem.status : null, + "cancelled", + ); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); }); const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(function* ( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 792195ebfa80e..63187fe7b596c 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -8848,6 +8848,29 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* handleRoutedSdkMessage(input); }); + // No user response will close a request the SDK aborted, such as one a hook answered. + const cancelRuntimeRequest = Effect.fn("ClaudeAdapterV2.cancelRuntimeRequest")(function* ( + artifacts: Effect.Success>, + ) { + const now = yield* DateTime.now; + const cancelled = { status: "cancelled", completedAt: now } as const; + yield* emitProviderEvent({ + type: "node.updated", + driver: CLAUDE_PROVIDER, + node: { ...artifacts.node, ...cancelled }, + }); + yield* emitProviderEvent({ + type: "runtime_request.updated", + driver: CLAUDE_PROVIDER, + runtimeRequest: { ...artifacts.request, status: "cancelled", resolvedAt: now }, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CLAUDE_PROVIDER, + turnItem: { ...artifacts.turnItem, ...cancelled, updatedAt: now }, + }); + }); + const canUseToolEffect = Effect.fn("ClaudeAdapterV2.canUseTool")(function* ( toolName: Parameters[0], toolInput: Parameters[1], @@ -8957,6 +8980,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), ), ); + if (!(yield* Deferred.isDone(answers))) yield* cancelRuntimeRequest(artifacts); return callbackOptions.signal.aborted ? ({ behavior: "deny", @@ -9074,6 +9098,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), ), ); + if (!(yield* Deferred.isDone(decision))) yield* cancelRuntimeRequest(artifacts); return permissionResultFromDecision({ toolName, diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index 3d2bc8e4b45a8..8abeeea9edba1 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -8,7 +8,6 @@ import { RunAttemptId, RunId, RuntimeRequestId, - NodeId, type ProjectId, ThreadId, } from "@t3tools/contracts"; @@ -73,7 +72,7 @@ export interface EventSinkV2Shape { OrchestrationV2ProviderThread, "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef" >; - readonly guardPendingUserInputCancellations?: boolean; + readonly guardPendingRequestCancellations?: boolean; readonly commandId?: CommandId; readonly events: ReadonlyArray; }) => Effect.Effect, EventSinkV2Error>; @@ -87,13 +86,13 @@ export interface EventSinkV2Shape { OrchestrationV2ProviderThread, "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef" >; - readonly guardPendingUserInputCancellations?: boolean; + readonly guardPendingRequestCancellations?: boolean; readonly commandId?: CommandId; readonly events: ReadonlyArray; readonly effects: ReadonlyArray; }) => Effect.Effect, EventSinkV2Error>; readonly writeIfRunCurrent: (input: { - readonly guardPendingUserInputCancellations?: boolean; + readonly guardPendingRequestCancellations?: boolean; readonly commandId?: CommandId; readonly threadId: ThreadId; readonly runId: RunId; @@ -115,7 +114,7 @@ export interface EventSinkV2Shape { * a newer attempt that already claimed the thread. */ readonly writeIfProviderThreadOwner: (input: { - readonly guardPendingUserInputCancellations?: boolean; + readonly guardPendingRequestCancellations?: boolean; readonly commandId?: CommandId; readonly providerThreadId: ProviderThreadId; readonly runId: RunId; @@ -208,6 +207,17 @@ export class EventSinkV2 extends Context.Service( "t3/orchestration-v2/EventSink/EventSinkV2", ) {} +const cancelledRuntimeRequestId = (event: OrchestrationV2DomainEvent) => + !("status" in event.payload) || event.payload.status !== "cancelled" + ? null + : event.type === "runtime-request.updated" + ? event.payload.id + : event.type === "node.updated" + ? event.payload.runtimeRequestId + : event.type === "turn-item.updated" && "requestId" in event.payload + ? event.payload.requestId + : null; + const layerBase: Layer.Layer< EventSinkV2, never, @@ -293,47 +303,27 @@ const layerBase: Layer.Layer< // A user can answer after terminal normalization reads the pending request. // Recheck inside the write transaction so stale cleanup cannot erase answers. - const guardUserInputCancellations = + const guardRuntimeRequestCancellations = /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ Effect.fnUntraced(function* (events: ReadonlyArray) { const staleRequests = new Set(); - const staleNodes = new Set(); for (const event of events) { + const requestId = cancelledRuntimeRequestId(event); + if (requestId === null) continue; + const current = yield* projectionStore.getRuntimeRequest(event.threadId, requestId); if ( - event.type !== "runtime-request.updated" || - event.payload.kind !== "user_input" || - event.payload.status !== "cancelled" - ) - continue; - const current = yield* projectionStore.getRuntimeRequest( - event.threadId, - event.payload.id, - ); - if ( - current?.status !== "pending" || - current.kind !== "user_input" || - current.providerTurnId !== event.payload.providerTurnId || - current.responseCapability.type === "message" + (event.type === "runtime-request.updated" + ? current?.status !== "pending" || + current.providerTurnId !== event.payload.providerTurnId + : current?.status === "resolved") || + (current?.kind === "user_input" && current.responseCapability.type === "message") ) { - staleRequests.add(event.payload.id); - staleNodes.add(event.payload.nodeId); + staleRequests.add(requestId); } } return events.filter((event) => { - switch (event.type) { - case "runtime-request.updated": - return event.payload.status !== "cancelled" || !staleRequests.has(event.payload.id); - case "node.updated": - return event.payload.status !== "cancelled" || !staleNodes.has(event.payload.id); - case "turn-item.updated": - return ( - event.payload.type !== "user_input_request" || - event.payload.status !== "cancelled" || - !staleRequests.has(event.payload.requestId) - ); - default: - return true; - } + const requestId = cancelledRuntimeRequestId(event); + return requestId === null || !staleRequests.has(requestId); }); }); @@ -443,8 +433,8 @@ const layerBase: Layer.Layer< ) : input.events; const normalized = yield* normalizeEvents( - input.guardPendingUserInputCancellations === true - ? yield* guardUserInputCancellations(events) + input.guardPendingRequestCancellations === true + ? yield* guardRuntimeRequestCancellations(events) : events, ); const committed = yield* eventStore.append({ @@ -502,8 +492,8 @@ const layerBase: Layer.Layer< } const normalized = yield* normalizeEvents( - input.guardPendingUserInputCancellations === true - ? yield* guardUserInputCancellations(input.events) + input.guardPendingRequestCancellations === true + ? yield* guardRuntimeRequestCancellations(input.events) : input.events, ); const storedEvents = yield* eventStore.append({ @@ -567,8 +557,8 @@ const layerBase: Layer.Layer< } const normalized = yield* normalizeEvents( - input.guardPendingUserInputCancellations === true - ? yield* guardUserInputCancellations(input.events) + input.guardPendingRequestCancellations === true + ? yield* guardRuntimeRequestCancellations(input.events) : input.events, ); const storedEvents = yield* eventStore.append({ diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts index 849cedded9292..34c9af2d78133 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts @@ -1151,6 +1151,136 @@ layer("ProviderEventIngestorV2", (it) => { }), ); + it.effect("keeps an approval the user answered before the provider cancelled it", () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const eventSink = yield* EventSink.EventSinkV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const threadEvent = yield* threadCreatedEvent(now); + const threadId = threadEvent.threadId; + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + const providerTurnId = idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: `${threadId}:approvals`, + }); + const fixtures = (["answered", "open"] as const).map((key, ordinal) => { + const nodeId = NodeId.make(`${threadId}:${key}`); + const answered = key === "answered"; + const request: OrchestrationV2RuntimeRequest = { + id: RuntimeRequestId.make(`${threadId}:${key}`), + nodeId, + providerTurnId, + nativeRequestRef: null, + kind: "command", + status: answered ? "resolved" : "pending", + responseCapability: { type: "live", providerSessionId }, + createdAt: now, + resolvedAt: answered ? now : null, + ...(answered ? { decision: "accept" as const } : {}), + }; + const node: OrchestrationV2ExecutionNode = { + id: nodeId, + threadId, + runId: null, + parentNodeId: null, + rootNodeId: nodeId, + kind: "approval_request", + status: answered ? "completed" : "waiting", + countsForRun: false, + providerThreadId: null, + providerTurnId, + nativeItemRef: null, + runtimeRequestId: request.id, + checkpointScopeId: null, + startedAt: now, + completedAt: answered ? now : null, + }; + const item: OrchestrationV2TurnItem = { + id: TurnItemId.make(`${threadId}:${key}`), + threadId, + runId: null, + nodeId, + providerThreadId: null, + providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: answered ? "completed" : "waiting", + title: "Run command?", + startedAt: now, + completedAt: answered ? now : null, + updatedAt: now, + type: "approval_request", + requestId: request.id, + requestKind: "command", + }; + return { request, node, item }; + }); + const seedEvents: Array = [threadEvent]; + for (const { request, node, item } of fixtures) { + for (const payload of [ + { type: "runtime-request.updated" as const, payload: request }, + { type: "node.updated" as const, payload: node }, + { type: "turn-item.updated" as const, payload: item }, + ]) { + seedEvents.push({ + id: yield* idAllocator.allocate.event({ threadId }), + threadId, + occurredAt: now, + ...payload, + }); + } + } + yield* eventSink.write({ events: seedEvents }); + + // A provider abort sends each cancelled record as its own event. + for (const { request, node, item } of fixtures) { + for (const event of [ + { + type: "node.updated" as const, + node: { ...node, status: "cancelled" as const, completedAt: now }, + }, + { + type: "runtime_request.updated" as const, + threadId, + runtimeRequest: { ...request, status: "cancelled" as const, resolvedAt: now }, + }, + { + type: "turn_item.updated" as const, + turnItem: { ...item, status: "cancelled" as const, completedAt: now }, + }, + ]) { + yield* ingestor.ingestNormalized({ + providerSessionId, + providerInstanceId: modelSelection.instanceId, + threadId, + event: { ...event, driver: CODEX_DRIVER }, + }); + } + } + + const projection = yield* projectionStore.getThreadProjection(threadId); + const statuses = fixtures.map(({ request, node, item }) => { + const stored = projection.runtimeRequests.find((entry) => entry.id === request.id); + return { + request: stored?.status, + decision: stored?.decision, + node: projection.nodes.find((entry) => entry.id === node.id)?.status, + item: projection.turnItems.find((entry) => entry.id === item.id)?.status, + }; + }); + assert.deepEqual(statuses, [ + { request: "resolved", decision: "accept", node: "completed", item: "completed" }, + { request: "cancelled", decision: undefined, node: "cancelled", item: "cancelled" }, + ]); + }), + ); + it.effect( "preserves an answer committed after terminal normalization reads a pending question", () => diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 8e916ab79319b..a022f40feddad 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -746,7 +746,7 @@ export const layer: Layer.Layer< if (input.writeIfProviderThreadOwner !== undefined) { const ownerResult = yield* eventSink .writeIfProviderThreadOwner({ - guardPendingUserInputCancellations: true, + guardPendingRequestCancellations: true, ...(input.commandId === undefined ? {} : { commandId: input.commandId }), ...input.writeIfProviderThreadOwner, events, @@ -757,7 +757,7 @@ export const layer: Layer.Layer< if (input.writeIfRunCurrent === undefined) { return yield* eventSink .write({ - guardPendingUserInputCancellations: true, + guardPendingRequestCancellations: true, ...(input.commandId === undefined ? {} : { commandId: input.commandId }), events, }) @@ -765,7 +765,7 @@ export const layer: Layer.Layer< } const result = yield* eventSink .writeIfRunCurrent({ - guardPendingUserInputCancellations: true, + guardPendingRequestCancellations: true, ...(input.commandId === undefined ? {} : { commandId: input.commandId }), threadId: input.threadId, ...input.writeIfRunCurrent,