From 5cec1f4d580e5d89ef0186e1f427c485c7df170c Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Mon, 16 Nov 2026 02:21:12 +0100 Subject: [PATCH] fix(server): a later Claude wake's approval stays out of a paused Monitor continuation A continuation attaches its turn under the SDK message lock and then replays the wake buffer, which can suspend on workflow transcript reads. Claude can ask for a later wake's tool meanwhile, and canUseTool took the attached turn at once, so the approval landed in the Monitor run while the tool stayed buffered for the later wake's own continuation. When the attached turn's session still has a wake buffer, canUseTool now waits for the lock (or the request's withdrawal), and denies as before if the tool's tool_use is still buffered after the replay. --- .../Adapters/ClaudeAdapterV2.test.ts | 221 ++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 49 +++- 2 files changed, 269 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 4bb712aa9ffca..e8295b93a19bf 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -22781,6 +22781,227 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect( + "keeps a later wake's tool request out of a Monitor continuation while its replay is paused", + () => + Effect.gen(function* () { + const digestStarted = yield* Deferred.make(); + const releaseDigest = yield* Deferred.make(); + let pauseDigest = false; + yield* Effect.gen(function* () { + const harness = yield* makeWorkflowHarnessWithOptions({ close: Queue.shutdown }); + const now = yield* DateTime.now; + const approvalPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: "/workspace", + }); + const monitorTaskId = "bmonitorreplay"; + const monitorToolUseId = "toolu_monitor_replay"; + const bashToolUseId = "toolu_01PausedReplayBash"; + const startTurn = (attempt: string, providerTurnOrdinal: number, continuation: boolean) => + harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(attempt), + text: continuation ? "Background task completed." : "Watch the run.", + attachments: [], + providerTurnOrdinal, + runtimePolicy: approvalPolicy, + ...(continuation + ? { + messageCreatedBy: "agent" as const, + messageCreationSource: "provider" as const, + } + : {}), + }), + ); + yield* startTurn("attempt-claude-paused-replay-1", 1, false); + for (const frame of [ + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_monitor_replay", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: monitorToolUseId, + name: "Monitor", + input: { description: "line monitor", command: "./watch.sh" }, + }, + ], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 1, output_tokens: 1 }, + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000003201", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: monitorTaskId, + tool_use_id: monitorToolUseId, + description: "line monitor", + is_backgrounded: true, + task_type: "local_bash", + uuid: "00000000-0000-4000-8000-000000003202", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: monitorToolUseId, + content: `Monitor started (task ${monitorTaskId}). You will be notified on each event.`, + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000003203", + session_id: WAKE_NATIVE_SESSION, + tool_use_result: { taskId: monitorTaskId, persistent: false }, + }), + ]) { + yield* harness.offerAndWait(frame); + } + yield* launchWorkflow({ + harness, + snapshotUuid: "00000000-0000-4000-8000-000000003204", + }); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000003205", + result: "Watching and running.", + }), + ); + yield* Queue.take(harness.terminalReceipts); + + // A Monitor event wakes Claude; the workflow finishes inside that wake. + yield* harness.offerAndWait(wakeTurnInit); + yield* Queue.take(harness.continuationReceipts); + assert.equal(harness.continuationRequests[0]?.notification?.source.kind, "monitor"); + yield* harness.offerAndWait( + workflowNotification({ + uuid: "00000000-0000-4000-8000-000000003206", + status: "completed", + }), + ); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000003207", + result: "Noted.", + origin: { kind: "task-notification" }, + }), + ); + // A later wake's tool_use stays buffered behind the Monitor continuation. + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "init", + uuid: "00000000-0000-4000-8000-000000003208", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_paused_replay_bash", + type: "message", + role: "assistant", + content: [ + { type: "tool_use", id: bashToolUseId, name: "Bash", input: { command: "ls" } }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000003209", + session_id: WAKE_NATIVE_SESSION, + }), + ); + + // The Monitor continuation attaches, then its replay pauses on a transcript read. + pauseDigest = true; + const replay = yield* startTurn("attempt-claude-paused-replay-2", 2, true).pipe( + Effect.forkScoped, + ); + yield* Deferred.await(digestStarted); + // @effect-diagnostics-next-line abortControllerInEffect:off - Claude, not the test fiber, owns the request. + const withdrawal = new AbortController(); + const listening = Promise.withResolvers(); + const addEventListener = withdrawal.signal.addEventListener.bind(withdrawal.signal); + withdrawal.signal.addEventListener = ( + ...args: Parameters + ) => { + addEventListener(...args); + listening.resolve(); + }; + const decision = yield* Effect.promise(() => + harness.getOpenedOptions()!.canUseTool!( + "Bash", + { command: "ls" }, + { + signal: withdrawal.signal, + toolUseID: bashToolUseId, + requestId: "request-paused-replay-bash", + }, + ), + ).pipe(Effect.forkScoped); + yield* Effect.promise(() => listening.promise); + yield* Deferred.succeed(releaseDigest, undefined); + yield* Fiber.join(replay); + + assert.isFalse(harness.events.some((event) => event.type === "runtime_request.updated")); + assert.equal((yield* Fiber.join(decision))?.behavior, "deny"); + const bashRuns = () => + harness.events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === bashToolUseId + ? [event.turnItem.runId] + : [], + ); + // The Monitor continuation settles without the later wake's tool, which gets its own run. + yield* Queue.take(harness.terminalReceipts); + assert.isEmpty(bashRuns()); + yield* Queue.take(harness.continuationReceipts); + yield* startTurn("attempt-claude-paused-replay-3", 3, true); + yield* harness.until(() => bashRuns().length > 0); + assert.isTrue( + bashRuns().every((runId) => runId === RunId.make("run-attempt-claude-paused-replay-3")), + ); + }).pipe( + Effect.provideService(WorkflowAgentTranscriptReadObserver, () => + Effect.gen(function* () { + if (pauseDigest) { + pauseDigest = false; + yield* Deferred.succeed(digestStarted, undefined); + yield* Deferred.await(releaseDigest); + } + }), + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect.each([ ["api_error", false, false], ["aborted_streaming", false, false], diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index bced035fed011..014c9aad2d7b4 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -4331,6 +4331,14 @@ function toSessionPermissionUpdates( ]; } +const awaitAbortSignal = (signal: AbortSignal) => + Effect.callback((resume) => { + const abort = () => resume(Effect.void); + signal.addEventListener("abort", abort, { once: true }); + if (signal.aborted) abort(); + return Effect.sync(() => signal.removeEventListener("abort", abort)); + }); + export const awaitClaudeApprovalDecision = Effect.fn("awaitClaudeApprovalDecision")(function* ( decision: Deferred.Deferred, signal: AbortSignal, @@ -12005,13 +12013,52 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* handleRoutedSdkMessage(input); }); + const isToolUseBuffered = (nativeThreadId: string, toolUseId: string) => + Effect.map(Ref.get(wakeBuffers), (buffers) => + (buffers.get(nativeThreadId)?.messages ?? []).some( + (message) => + message.type === "assistant" && + message.message.content.some( + (block) => block.type === "tool_use" && block.id === toolUseId, + ), + ), + ); + + // A wake replay attaches its turn under the lock and then suspends on transcript reads, and + // Claude can ask for a later wake's tool meanwhile. Wait for the replay; a tool still + // buffered after it belongs to a wake this turn did not drain. + const activeTurnForToolRequest = Effect.fnUntraced(function* ( + signal: AbortSignal, + toolUseId: string, + ) { + const attached = yield* Ref.get(activeTurn); + if (attached === null || !(yield* Ref.get(wakeBuffers)).has(attached.nativeThreadId)) { + return attached; + } + return yield* Effect.raceFirst( + sdkMessageLock.withPermits(1)( + Effect.gen(function* () { + const context = yield* Ref.get(activeTurn); + if (context === null) return null; + return (yield* isToolUseBuffered(context.nativeThreadId, toolUseId)) + ? null + : context; + }), + ), + awaitAbortSignal(signal).pipe(Effect.as(null)), + ); + }); + const canUseToolEffect = Effect.fn("ClaudeAdapterV2.canUseTool")(function* ( toolName: Parameters[0], toolInput: Parameters[1], callbackOptions: Parameters[2], options?: { readonly startToolCall?: boolean }, ) { - const context = yield* Ref.get(activeTurn); + const context = yield* activeTurnForToolRequest( + callbackOptions.signal, + callbackOptions.toolUseID, + ); if (context === null) { return { behavior: "deny",