From 9ad7000288c08199662cd27106ec2d9a9121e8b3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 05:53:56 +0000 Subject: [PATCH 1/2] test(server): a fresh Claude session retries a stalled MCP registration (#37935) Fails on main: ClaudeAgentSdkQueryRunner.open retries a registration timeout only when the session is resumed, so a fresh thread fails once and stays failed. Co-Authored-By: Claude Opus 5.5 --- .../ClaudeAgentSdkQueryRunner.test.ts | 35 +++++++++++-------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 28072c29d7fda..d185c852bf5b0 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -464,21 +464,24 @@ it.effect("cancels a stalled registration without retrying or retaining its prom }).pipe(Effect.provide(realQueryRunner)), ); -it.effect("does not reuse a fresh session ID after MCP registration times out", () => +it.effect("retries a fresh session once after MCP registration times out", () => Effect.gen(function* () { const registrationStarted = Promise.withResolvers(); const disposed = vi.fn(async () => {}); - const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( - () => - ({ - initializationResult: async () => ({}), - setMcpServers: () => { - registrationStarted.resolve(); - return new Promise(() => {}); - }, - [Symbol.asyncDispose]: disposed, - }) as unknown as ClaudeSdk.Query, - ); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => { + const first = querySpy.mock.calls.length === 1; + return { + initializationResult: async () => ({}), + setMcpServers: () => { + registrationStarted.resolve(); + return first + ? new Promise(() => {}) + : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} }); + }, + close: vi.fn(), + [Symbol.asyncDispose]: disposed, + } as unknown as ClaudeSdk.Query; + }); yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); const runner = yield* ClaudeAgentSdkQueryRunner; const { resume, ...options } = resumedMcpQueryInput.options; @@ -492,9 +495,13 @@ it.effect("does not reuse a fresh session ID after MCP registration times out", yield* TestClock.adjust("90 seconds"); const result = yield* Fiber.join(opening); - assert.equal(result._tag, "Failure"); - assert.equal(querySpy.mock.calls.length, 1); + assert.equal(result._tag, "Success"); + if (result._tag === "Success") yield* result.success.close; + assert.equal(querySpy.mock.calls.length, 2); assert.equal(disposed.mock.calls.length, 1); + // A fresh ID may already have a transcript, so the retry must not open it as fresh again. + const retry = querySpy.mock.calls[1]![0].options; + assert.isFalse(retry?.sessionId === resume && retry?.resume === undefined); }).pipe(Effect.provide(realQueryRunner)), ); From 78192459742f24428a2995f75f04773fd3851a12 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 06:05:30 +0000 Subject: [PATCH 2/2] fix(server): retry a fresh Claude session once after a startup or MCP registration timeout A fresh Claude thread whose CLI stalled in initialize or setMcpServers failed for good, so a webhook- or schedule-started run was lost. Only resumed opens were retried, because reopening a fresh session ID can collide with a transcript Claude already wrote. Retry a fresh open once under a newly allocated session ID. The adapter already adopts a differing init session_id (as after /clear) and persists it, so later turns resume the session that actually ran. Fixes pingdotgg/t3code#37935 Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 922 +++++++++--------- .../ClaudeAgentSdkQueryRunner.test.ts | 43 +- 2 files changed, 483 insertions(+), 482 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 262f67ca93f80..1fe81be7f2166 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1453,490 +1453,486 @@ export const layerQueryRunner: Layer.Layer< return { refresh: refresh(true).pipe(Effect.asVoid), stop }; }; - return ClaudeAgentSdkQueryRunner.of({ - allocateSessionId: random.uuidV4(), - open: Effect.fn("ClaudeAgentSdkQueryRunner.open")( - function* (input: ClaudeAgentSdkQueryOpenInput) { - const protocolLogger = makeClaudeAgentSdkProtocolLogger({ - nativeEventLogger, - threadId: input.threadId, - providerSessionId: input.providerSessionId, + // The open span below is the tracing boundary for both attempts. + const openQuery = Effect.fnUntraced(function* (input: ClaudeAgentSdkQueryOpenInput) { + const protocolLogger = makeClaudeAgentSdkProtocolLogger({ + nativeEventLogger, + threadId: input.threadId, + providerSessionId: input.providerSessionId, + }); + const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) => + protocolLogger === undefined ? Effect.void : protocolLogger(event); + // A failed open shuts down its queue before retrying, so the old CLI cannot take the prompt. + const promptQueue = yield* Queue.unbounded(); + const prompt = Stream.fromQueue(promptQueue).pipe( + Stream.catchCause((cause) => + Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause), + ), + Stream.toAsyncIterable, + ); + // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments. + const { mcpServers, ...sdkOptions } = input.options; + // Jobs the agent starts inherit the thread, so port discovery can attribute their servers. + let resumeSessionAt = sdkOptions.resumeSessionAt; + if (input.resume && sdkOptions.resume !== undefined) { + const messages = yield* runClaudeWorker({ + method: "getSessionMessages", + sessionId: sdkOptions.resume, + options: sdkOptions.cwd === undefined ? {} : { dir: sdkOptions.cwd }, + environment: sdkOptions.env ?? hostEnvironment, + }).pipe( + Effect.flatMap(decodeClaudeHistoryMessages), + Effect.mapError((cause) => queryRunnerError(cause, "getSessionMessages")), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(Path.Path, path), + ); + const boundary = + resumeSessionAt === undefined + ? messages.length + : messages.findIndex((message) => message.uuid === resumeSessionAt) + 1; + resumeSessionAt = claudeResumeSessionAt(messages.slice(0, boundary)) ?? resumeSessionAt; + } + const queryOptions = { + ...sdkOptions, + ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }), + env: { + ...(sdkOptions.env ?? hostEnvironment), + ...(input.resume + ? { + CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1", + CLAUDE_CODE_RESUME_REASON: "user_resume", + } + : {}), + [PortScanner.AGENT_THREAD_ENV]: input.threadId, + }, + }; + // The SDK can prepend a scope wrapper to native binaries; script entries run through node. + const binaryPath = queryOptions.pathToClaudeCodeExecutable; + const launch = + binaryPath === undefined || CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext)) + ? undefined + : yield* agentScope.wrap({ + command: binaryPath, + args: [], + name: "claude", + threadId: input.threadId, + env: queryOptions.env, + }); + const options = + launch === undefined || launch.args.length === 0 + ? queryOptions + : { + ...queryOptions, + pathToClaudeCodeExecutable: launch.command, + executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])], + }; + const unit = launch?.unit; + const stopScope = unit === undefined ? undefined : () => void runFork(agentScope.stop(unit)); + // Only a CLI that fails before its first message explains itself on + // stderr. The known root refusal becomes a curated failure; any other + // stderr can hold private text, so it stays out of turn failures. + let stderrTail = ""; + let stderrClosed: Promise = Promise.resolve(); + let answered = false; + let conversationMissing = false; + const appendStderr = (text: string) => { + if (answered) return; + stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH); + }; + let refreshDescendants: Effect.Effect = Effect.void; + const spawnProcess = + options.spawnClaudeCodeProcess ?? + ((spawnOptions: ClaudeSpawnOptions) => { + if (platform !== "win32") { + // Node can report "exit" before it has read the stderr the CLI wrote. + let stderrDone = () => {}; + stderrClosed = new Promise((resolve) => (stderrDone = resolve)); + const child = spawnClaudeProcessGroup( + spawnOptions, + stopScope, + appendStderr, + stderrDone, + providerProcesses.register, + ); + if (unit === undefined && child.pid !== undefined) { + const tracker = trackDescendants(child.pid); + const polling = runFork( + tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))), + ); + child.once("exit", () => + runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))), + ); + refreshDescendants = tracker.refresh; + } + return child; + } + const child = SpawnWorker.spawnPiped(spawnOptions.command, spawnOptions.args, { + cwd: spawnOptions.cwd, + env: spawnOptions.env, + signal: spawnOptions.signal, + windowsHide: true, }); - const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) => - protocolLogger === undefined ? Effect.void : protocolLogger(event); - // A failed open shuts down its queue before retrying, so the old CLI cannot take the prompt. - const promptQueue = yield* Queue.unbounded(); - const prompt = Stream.fromQueue(promptQueue).pipe( - Stream.catchCause((cause) => - Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause), + child.stderr.setEncoding("utf8").on("data", (chunk: string) => options.stderr?.(chunk)); + return child; + }); + let spawnedProcess: ClaudeSpawnedProcess | undefined; + let processExited = false; + let processExit: Promise | undefined; + const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => { + const child = spawnProcess(spawnOptions); + spawnedProcess = child; + // A spawn that fails emits only "error". + const releaseAgent = portDiscovery.trackAgent(); + child.once("exit", releaseAgent); + child.on("error", releaseAgent); + processExited = child.exitCode !== null || child.signalCode != null; + processExit = new Promise((resolve) => { + if (processExited) resolve(); + else + child.once("exit", () => { + processExited = true; + resolve(); + }); + }); + return child; + }; + const queryRuntime = yield* Effect.uninterruptibleMask((restore) => + Effect.try({ + try: () => + withoutClaudeCanUseToolShadowedWarning(() => + query({ + prompt, + options: { ...options, spawnClaudeCodeProcess }, + }), ), - Stream.toAsyncIterable, - ); - // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments. - const { mcpServers, ...sdkOptions } = input.options; - // Jobs the agent starts inherit the thread, so port discovery can attribute their servers. - let resumeSessionAt = sdkOptions.resumeSessionAt; - if (input.resume && sdkOptions.resume !== undefined) { - const messages = yield* runClaudeWorker({ - method: "getSessionMessages", - sessionId: sdkOptions.resume, - options: sdkOptions.cwd === undefined ? {} : { dir: sdkOptions.cwd }, - environment: sdkOptions.env ?? hostEnvironment, - }).pipe( - Effect.flatMap(decodeClaudeHistoryMessages), - Effect.mapError((cause) => queryRunnerError(cause, "getSessionMessages")), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provideService(Path.Path, path), - ); - const boundary = - resumeSessionAt === undefined - ? messages.length - : messages.findIndex((message) => message.uuid === resumeSessionAt) + 1; - resumeSessionAt = claudeResumeSessionAt(messages.slice(0, boundary)) ?? resumeSessionAt; - } - const queryOptions = { - ...sdkOptions, - ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }), - env: { - ...(sdkOptions.env ?? hostEnvironment), - ...(input.resume - ? { - CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1", - CLAUDE_CODE_RESUME_REASON: "user_resume", - } - : {}), - [PortScanner.AGENT_THREAD_ENV]: input.threadId, - }, - }; - // The SDK can prepend a scope wrapper to native binaries; script entries run through node. - const binaryPath = queryOptions.pathToClaudeCodeExecutable; - const launch = - binaryPath === undefined || - CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext)) - ? undefined - : yield* agentScope.wrap({ - command: binaryPath, - args: [], - name: "claude", - threadId: input.threadId, - env: queryOptions.env, - }); - const options = - launch === undefined || launch.args.length === 0 - ? queryOptions - : { - ...queryOptions, - pathToClaudeCodeExecutable: launch.command, - executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])], - }; - const unit = launch?.unit; - const stopScope = - unit === undefined ? undefined : () => void runFork(agentScope.stop(unit)); - // Only a CLI that fails before its first message explains itself on - // stderr. The known root refusal becomes a curated failure; any other - // stderr can hold private text, so it stays out of turn failures. - let stderrTail = ""; - let stderrClosed: Promise = Promise.resolve(); - let answered = false; - let conversationMissing = false; - const appendStderr = (text: string) => { - if (answered) return; - stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH); - }; - let refreshDescendants: Effect.Effect = Effect.void; - const spawnProcess = - options.spawnClaudeCodeProcess ?? - ((spawnOptions: ClaudeSpawnOptions) => { - if (platform !== "win32") { - // Node can report "exit" before it has read the stderr the CLI wrote. - let stderrDone = () => {}; - stderrClosed = new Promise((resolve) => (stderrDone = resolve)); - const child = spawnClaudeProcessGroup( - spawnOptions, - stopScope, - appendStderr, - stderrDone, - providerProcesses.register, - ); - if (unit === undefined && child.pid !== undefined) { - const tracker = trackDescendants(child.pid); - const polling = runFork( - tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))), + catch: (cause) => queryRunnerError(cause, "query"), + }).pipe( + Effect.tap((queryRuntime) => + restore( + Effect.gen(function* () { + if (mcpServers !== undefined) { + const timedOut = (phase: ClaudeMcpRegistrationTimeoutError["phase"]) => () => + Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", { + threadId: input.threadId, + providerSessionId: input.providerSessionId, + phase, + }).pipe( + Effect.andThen( + Effect.fail( + queryRunnerError(new ClaudeMcpRegistrationTimeoutError({ phase }), phase), + ), + ), + ); + // The SDK leaves query() boot unbounded, and it takes about a minute on a host + // with CPUs 12x oversubscribed, so it gets its own, longer deadline. + yield* Effect.promise(() => + queryRuntime.initializationResult().catch(() => undefined), + ).pipe( + Effect.timeoutOrElse({ + duration: CLAUDE_BOOT_TIMEOUT, + orElse: timedOut("initialize"), + }), ); - child.once("exit", () => - runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))), + // Errors and mcp_status can echo headers; log only server names. + const failed = yield* Effect.tryPromise({ + try: () => queryRuntime.setMcpServers(mcpServers), + catch: (cause) => queryRunnerError(cause, "setMcpServers"), + }).pipe( + Effect.map((result) => Object.keys(result.errors)), + Effect.orElseSucceed(() => Object.keys(mcpServers)), + Effect.timeoutOrElse({ + duration: CLAUDE_MCP_REGISTRATION_TIMEOUT, + orElse: timedOut("setMcpServers"), + }), ); - refreshDescendants = tracker.refresh; + if (failed.length > 0) { + yield* Effect.logWarning("orchestration-v2.claude-mcp-servers-unavailable", { + threadId: input.threadId, + servers: failed, + }); + } } - return child; - } - const child = SpawnWorker.spawnPiped(spawnOptions.command, spawnOptions.args, { - cwd: spawnOptions.cwd, - env: spawnOptions.env, - signal: spawnOptions.signal, - windowsHide: true, - }); - child.stderr - .setEncoding("utf8") - .on("data", (chunk: string) => options.stderr?.(chunk)); - return child; - }); - let spawnedProcess: ClaudeSpawnedProcess | undefined; - let processExited = false; - let processExit: Promise | undefined; - const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => { - const child = spawnProcess(spawnOptions); - spawnedProcess = child; - // A spawn that fails emits only "error". - const releaseAgent = portDiscovery.trackAgent(); - child.once("exit", releaseAgent); - child.on("error", releaseAgent); - processExited = child.exitCode !== null || child.signalCode != null; - processExit = new Promise((resolve) => { - if (processExited) resolve(); - else - child.once("exit", () => { - processExited = true; - resolve(); + yield* logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.open", + options: loggedClaudeQueryOptions(input.options), + }, }); - }); - return child; - }; - const queryRuntime = yield* Effect.uninterruptibleMask((restore) => - Effect.try({ - try: () => - withoutClaudeCanUseToolShadowedWarning(() => - query({ - prompt, - options: { ...options, spawnClaudeCodeProcess }, - }), - ), - catch: (cause) => queryRunnerError(cause, "query"), - }).pipe( - Effect.tap((queryRuntime) => - restore( - Effect.gen(function* () { - if (mcpServers !== undefined) { - const timedOut = (phase: ClaudeMcpRegistrationTimeoutError["phase"]) => () => - Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", { - threadId: input.threadId, - providerSessionId: input.providerSessionId, - phase, - }).pipe( - Effect.andThen( - Effect.fail( - queryRunnerError( - new ClaudeMcpRegistrationTimeoutError({ phase }), - phase, - ), - ), - ), - ); - // The SDK leaves query() boot unbounded, and it takes about a minute on a host - // with CPUs 12x oversubscribed, so it gets its own, longer deadline. - yield* Effect.promise(() => - queryRuntime.initializationResult().catch(() => undefined), - ).pipe( - Effect.timeoutOrElse({ - duration: CLAUDE_BOOT_TIMEOUT, - orElse: timedOut("initialize"), - }), - ); - // Errors and mcp_status can echo headers; log only server names. - const failed = yield* Effect.tryPromise({ - try: () => queryRuntime.setMcpServers(mcpServers), - catch: (cause) => queryRunnerError(cause, "setMcpServers"), - }).pipe( - Effect.map((result) => Object.keys(result.errors)), - Effect.orElseSucceed(() => Object.keys(mcpServers)), - Effect.timeoutOrElse({ - duration: CLAUDE_MCP_REGISTRATION_TIMEOUT, - orElse: timedOut("setMcpServers"), - }), - ); - if (failed.length > 0) { - yield* Effect.logWarning( - "orchestration-v2.claude-mcp-servers-unavailable", - { - threadId: input.threadId, - servers: failed, - }, - ); - } - } - yield* logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.open", - options: loggedClaudeQueryOptions(input.options), + }), + ).pipe( + Effect.onError(() => + Queue.shutdown(promptQueue).pipe( + // SDK disposal can return before process exit; await the owned child's exit before retrying. + Effect.andThen( + Effect.tryPromise({ + try: async () => { + if (spawnedProcess !== undefined && !processExited) { + spawnedProcess.kill("SIGKILL"); + } + await processExit; }, - }); - }), - ).pipe( - Effect.onError(() => - Queue.shutdown(promptQueue).pipe( - // SDK disposal can return before process exit; await the owned child's exit before retrying. - Effect.andThen( - Effect.tryPromise({ - try: async () => { - if (spawnedProcess !== undefined && !processExited) { - spawnedProcess.kill("SIGKILL"); - } - await processExit; - }, - catch: (cause) => queryRunnerError(cause, "close"), - }).pipe(Effect.timeout("10 seconds")), - ), - Effect.ensuring( - Effect.tryPromise({ - try: () => queryRuntime[Symbol.asyncDispose](), - catch: (cause) => queryRunnerError(cause, "close"), - }).pipe(Effect.orDie), - ), - Effect.orDie, - ), + catch: (cause) => queryRunnerError(cause, "close"), + }).pipe(Effect.timeout("10 seconds")), ), + Effect.ensuring( + Effect.tryPromise({ + try: () => queryRuntime[Symbol.asyncDispose](), + catch: (cause) => queryRunnerError(cause, "close"), + }).pipe(Effect.orDie), + ), + Effect.orDie, ), ), ), - ); + ), + ), + ); - return { - messages: Stream.fromAsyncIterable( - claudeQueryMessages(queryRuntime), - (cause) => cause, - ).pipe( - Stream.catch((cause) => - Stream.fromEffect( - Effect.gen(function* () { - if (!answered) { - yield* Effect.promise(() => stderrClosed).pipe( - Effect.timeoutOption(CLAUDE_STDERR_DRAIN_TIMEOUT), - ); - } - const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL); - return yield* queryRunnerError( - refusedRoot - ? new ClaudeCodeRootRefusalError({ cause }) - : conversationMissing || - (!answered && stderrTail.includes(CLAUDE_CONVERSATION_NOT_FOUND)) - ? new ClaudeConversationNotFoundError({ cause }) - : cause, - "fromAsyncIterable", - ); - }), - ), - ), - Stream.tap((message) => - Effect.sync(() => { - answered = true; - if ( - message.type === "result" && - message.subtype !== "success" && - message.errors.some((error) => error.startsWith(CLAUDE_CONVERSATION_NOT_FOUND)) - ) { - conversationMissing = true; - } - }), - ), - Stream.tap((message) => - logProtocolEvent({ - direction: "incoming", - stage: "decoded", - payload: message, - }), - ), + return { + messages: Stream.fromAsyncIterable( + claudeQueryMessages(queryRuntime), + (cause) => cause, + ).pipe( + Stream.catch((cause) => + Stream.fromEffect( + Effect.gen(function* () { + if (!answered) { + yield* Effect.promise(() => stderrClosed).pipe( + Effect.timeoutOption(CLAUDE_STDERR_DRAIN_TIMEOUT), + ); + } + const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL); + return yield* queryRunnerError( + refusedRoot + ? new ClaudeCodeRootRefusalError({ cause }) + : conversationMissing || + (!answered && stderrTail.includes(CLAUDE_CONVERSATION_NOT_FOUND)) + ? new ClaudeConversationNotFoundError({ cause }) + : cause, + "fromAsyncIterable", + ); + }), ), - offer: (message, onQueued) => - Effect.uninterruptibleMask((restore) => - restore(Queue.offer(promptQueue, message)).pipe( - Effect.tap(() => Effect.sync(() => onQueued?.())), - ), - ).pipe( - Effect.asVoid, - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "prompt.offer", - message, - }, - }), - ), - ), - setModel: (model) => - Effect.tryPromise({ - try: () => queryRuntime.setModel(model), - catch: (cause) => queryRunnerError(cause, "setModel"), - }).pipe( - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.set_model", - model, - }, - }), - ), - ), - applyFlagSettings: (settings) => - Effect.tryPromise({ - try: () => queryRuntime.applyFlagSettings(settings), - catch: (cause) => queryRunnerError(cause, "applyFlagSettings"), - }).pipe( - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.apply_flag_settings", - settings, - }, - }), - ), - ), - setPermissionMode: (mode) => - Effect.tryPromise({ - try: () => queryRuntime.setPermissionMode(mode), - catch: (cause) => queryRunnerError(cause, "setPermissionMode"), - }).pipe( - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.set_permission_mode", - mode, - }, - }), - ), - ), - renameSession: (title) => - Effect.tryPromise({ - try: () => - sendClaudeControlRequest(queryRuntime, { - subtype: "rename_session", - title, - source: "host", - }), - catch: (cause) => queryRunnerError(cause, "renameSession"), - }).pipe( - Effect.asVoid, - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.rename_session", - title, - }, - }), - ), - ), - stopTask: (taskId) => - Effect.tryPromise({ - try: () => queryRuntime.stopTask(taskId), - catch: (cause) => queryRunnerError(cause, "stopTask"), - }).pipe( - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { type: "query.stop_task", taskId }, - }), - ), - ), - backgroundTasks: (toolUseId) => - Effect.tryPromise({ - try: () => queryRuntime.backgroundTasks(toolUseId), - catch: (cause) => queryRunnerError(cause, "backgroundTasks"), - }).pipe( - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { type: "query.background_tasks", toolUseId }, - }), - ), - ), - mcpServerStatus: Effect.tryPromise({ - try: () => queryRuntime.mcpServerStatus(), - catch: (cause) => queryRunnerError(cause, "mcpServerStatus"), + ), + Stream.tap((message) => + Effect.sync(() => { + answered = true; + if ( + message.type === "result" && + message.subtype !== "success" && + message.errors.some((error) => error.startsWith(CLAUDE_CONVERSATION_NOT_FOUND)) + ) { + conversationMissing = true; + } + }), + ), + Stream.tap((message) => + logProtocolEvent({ + direction: "incoming", + stage: "decoded", + payload: message, }), - readMcpResource: ({ server, uri }) => - Effect.tryPromise({ - try: () => queryRuntime.readMcpResource(server, uri), - catch: (cause) => queryRunnerError(cause, "readMcpResource"), + ), + ), + offer: (message, onQueued) => + Effect.uninterruptibleMask((restore) => + restore(Queue.offer(promptQueue, message)).pipe( + Effect.tap(() => Effect.sync(() => onQueued?.())), + ), + ).pipe( + Effect.asVoid, + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "prompt.offer", + message, + }, }), - callMcpTool: (call) => - Effect.tryPromise({ - try: () => - sendClaudeControlRequest(queryRuntime, { - subtype: "mcp_call", - tool: call.tool, - arguments: call.arguments, - result_not_for_model: true, - }), - catch: (cause) => queryRunnerError(cause, "callMcpTool"), + ), + ), + setModel: (model) => + Effect.tryPromise({ + try: () => queryRuntime.setModel(model), + catch: (cause) => queryRunnerError(cause, "setModel"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.set_model", + model, + }, }), - listPermissionRules: Effect.tryPromise({ - try: () => - sendClaudeControlRequest(queryRuntime, { subtype: "list_permission_rules" }), - catch: (cause) => queryRunnerError(cause, "listPermissionRules"), - }).pipe( - Effect.flatMap(decodeClaudePermissionRules), - // A settings file Claude couldn't parse was skipped, so its rules are missing from the list. - Effect.filterOrFail( - ({ state }) => (state.errors ?? []).length === 0, - ({ state }) => new Error(`Claude skipped ${state.errors?.length} settings file(s)`), - ), - Effect.map(({ state }) => state.rules), - Effect.mapError((cause) => queryRunnerError(cause, "listPermissionRules")), ), - interrupt: Effect.tryPromise({ - try: () => queryRuntime.interrupt(), - catch: (cause) => queryRunnerError(cause, "interrupt"), - }).pipe( - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.interrupt", - }, - }), - ), + ), + applyFlagSettings: (settings) => + Effect.tryPromise({ + try: () => queryRuntime.applyFlagSettings(settings), + catch: (cause) => queryRunnerError(cause, "applyFlagSettings"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.apply_flag_settings", + settings, + }, + }), ), - // A job started since the last poll is recorded before the CLI is told to exit. - close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe( - Effect.andThen(Queue.shutdown(promptQueue)), - Effect.andThen(closeClaudeQuery(queryRuntime)), - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.close", - }, - }), - ), + ), + setPermissionMode: (mode) => + Effect.tryPromise({ + try: () => queryRuntime.setPermissionMode(mode), + catch: (cause) => queryRunnerError(cause, "setPermissionMode"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.set_permission_mode", + mode, + }, + }), ), - } satisfies ClaudeAgentSdkQuerySession; - }, - // Fresh IDs may already have a metadata-only transcript; only resumed opens can reuse their ID. - (effect, input) => - effect.pipe( - Effect.retry({ - times: 1, - while: (error) => - input.options.resume !== undefined && - isClaudeMcpRegistrationTimeoutError(error.cause), + ), + renameSession: (title) => + Effect.tryPromise({ + try: () => + sendClaudeControlRequest(queryRuntime, { + subtype: "rename_session", + title, + source: "host", + }), + catch: (cause) => queryRunnerError(cause, "renameSession"), + }).pipe( + Effect.asVoid, + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.rename_session", + title, + }, + }), + ), + ), + stopTask: (taskId) => + Effect.tryPromise({ + try: () => queryRuntime.stopTask(taskId), + catch: (cause) => queryRunnerError(cause, "stopTask"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { type: "query.stop_task", taskId }, + }), + ), + ), + backgroundTasks: (toolUseId) => + Effect.tryPromise({ + try: () => queryRuntime.backgroundTasks(toolUseId), + catch: (cause) => queryRunnerError(cause, "backgroundTasks"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { type: "query.background_tasks", toolUseId }, + }), + ), + ), + mcpServerStatus: Effect.tryPromise({ + try: () => queryRuntime.mcpServerStatus(), + catch: (cause) => queryRunnerError(cause, "mcpServerStatus"), + }), + readMcpResource: ({ server, uri }) => + Effect.tryPromise({ + try: () => queryRuntime.readMcpResource(server, uri), + catch: (cause) => queryRunnerError(cause, "readMcpResource"), + }), + callMcpTool: (call) => + Effect.tryPromise({ + try: () => + sendClaudeControlRequest(queryRuntime, { + subtype: "mcp_call", + tool: call.tool, + arguments: call.arguments, + result_not_for_model: true, + }), + catch: (cause) => queryRunnerError(cause, "callMcpTool"), + }), + listPermissionRules: Effect.tryPromise({ + try: () => sendClaudeControlRequest(queryRuntime, { subtype: "list_permission_rules" }), + catch: (cause) => queryRunnerError(cause, "listPermissionRules"), + }).pipe( + Effect.flatMap(decodeClaudePermissionRules), + // A settings file Claude couldn't parse was skipped, so its rules are missing from the list. + Effect.filterOrFail( + ({ state }) => (state.errors ?? []).length === 0, + ({ state }) => new Error(`Claude skipped ${state.errors?.length} settings file(s)`), + ), + Effect.map(({ state }) => state.rules), + Effect.mapError((cause) => queryRunnerError(cause, "listPermissionRules")), + ), + interrupt: Effect.tryPromise({ + try: () => queryRuntime.interrupt(), + catch: (cause) => queryRunnerError(cause, "interrupt"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.interrupt", + }, }), ), - ), + ), + // A job started since the last poll is recorded before the CLI is told to exit. + close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe( + Effect.andThen(Queue.shutdown(promptQueue)), + Effect.andThen(closeClaudeQuery(queryRuntime)), + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.close", + }, + }), + ), + ), + } satisfies ClaudeAgentSdkQuerySession; + }); + + return ClaudeAgentSdkQueryRunner.of({ + allocateSessionId: random.uuidV4(), + open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(function* ( + input: ClaudeAgentSdkQueryOpenInput, + ) { + // A fresh ID may already have a transcript, so a fresh session retries under a new ID; + // the adapter adopts it from the init message, as it does after /clear. + return yield* openQuery(input).pipe( + Effect.catchIf( + (error) => isClaudeMcpRegistrationTimeoutError(error.cause), + Effect.fnUntraced(function* () { + const { resume, ...options } = input.options; + if (resume !== undefined) return yield* openQuery(input); + const sessionId = yield* random.uuidV4(); + return yield* openQuery({ ...input, options: { ...options, sessionId } }); + }), + ), + ); + }), forkSession: Effect.fn("ClaudeAgentSdkQueryRunner.forkSession")(function* ( input: ClaudeAgentSdkSessionForkInput, ) { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index d185c852bf5b0..f1ef42a005e41 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -510,37 +510,42 @@ it.effect.each([ ["times out a CLI that never boots", "5 minutes", false], ] as const)("%s", ([, bootWait, boots]) => Effect.gen(function* () { - const waiting = Promise.withResolvers(); + const attempts = [Promise.withResolvers(), Promise.withResolvers()]; const booted = Promise.withResolvers(); - const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( - () => - ({ - initializationResult: () => { - waiting.resolve(); - return booted.promise; - }, - // The CLI answers control requests only after it has booted. - setMcpServers: async () => { - waiting.resolve(); - await booted.promise; - return { added: ["t3-code"], removed: [], errors: {} }; - }, - close: vi.fn(), - [Symbol.asyncDispose]: async () => {}, - }) as unknown as ClaudeSdk.Query, - ); + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => { + const waiting = attempts[querySpy.mock.calls.length - 1]!; + return { + initializationResult: () => { + waiting.resolve(); + return booted.promise; + }, + // The CLI answers control requests only after it has booted. + setMcpServers: async () => { + waiting.resolve(); + await booted.promise; + return { added: ["t3-code"], removed: [], errors: {} }; + }, + close: vi.fn(), + [Symbol.asyncDispose]: async () => {}, + } as unknown as ClaudeSdk.Query; + }); yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); const runner = yield* ClaudeAgentSdkQueryRunner; const { resume, ...options } = resumedMcpQueryInput.options; const opening = yield* runner .open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume } }) .pipe(Effect.result, Effect.forkChild); - yield* Effect.promise(() => waiting.promise); + yield* Effect.promise(() => attempts[0]!.promise); yield* TestClock.adjust(bootWait); if (boots) booted.resolve(); + else { + yield* Effect.promise(() => attempts[1]!.promise); + yield* TestClock.adjust(bootWait); + } const result = yield* Fiber.join(opening); assert.equal(result._tag, boots ? "Success" : "Failure"); + assert.equal(querySpy.mock.calls.length, boots ? 1 : 2); if (result._tag === "Success") yield* result.success.close; else assert.equal(