From 96b4071cdb721b13a5a16fa5ecc5ebdda4286df7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 1 Jul 2026 09:43:43 -0700 Subject: [PATCH] Fix Claude task turn mapping Co-authored-by: codex --- .../Adapters/ClaudeAdapterV2.ts | 140 +++++++++++++----- .../claude_transcript.ndjson | 12 ++ .../fixtures/claude_local_bash_task/input.ts | 7 + .../fixtures/claude_local_bash_task/output.ts | 58 ++++++++ .../testkit/fixtures/index.ts | 17 +++ .../testkit/fixtures/shared.ts | 2 + 6 files changed, 202 insertions(+), 34 deletions(-) create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/claude_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/input.ts create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/output.ts diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 325715cf07..2740ceff6d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1311,6 +1311,18 @@ function commandInputFromClaudeTool(toolName: string, input: ClaudeNativeToolInp ); } +function claudeTaskTypeFromSdkMessage(message: SDKMessage): string | null { + if (typeof message !== "object" || message === null) { + return null; + } + const taskType = Reflect.get(message, "task_type"); + return typeof taskType === "string" ? taskType : null; +} + +function isClaudeNonSubagentTask(message: SDKMessage): boolean { + return claudeTaskTypeFromSdkMessage(message) === "local_bash"; +} + function fileNameFromClaudeTool(toolName: string, input: ClaudeNativeToolInput): string { return ( firstStringInputField(input, ["file_path", "path", "filename", "fileName"]) ?? @@ -1753,10 +1765,12 @@ interface ActiveClaudeTurnContext { readonly providerTurnOrdinal: number; readonly startedAt: DateTime.Utc; readonly assistant: { - text: string; - nativeItemId: string; + fallbackText: string; + fallbackNativeItemId: string; + emittedNativeItemIds: Set; }; readonly toolCalls: Map; + readonly ignoredTaskIds: Set; readonly subagentsByTaskId: Map; readonly subagentsByToolUseId: Map; readonly subagentNodesByTaskId: Map; @@ -2549,17 +2563,20 @@ export function makeClaudeAdapterV2( } input.context.toolCalls.clear(); - if (input.context.assistant.text.length > 0) { + if ( + input.context.assistant.emittedNativeItemIds.size === 0 && + input.context.assistant.fallbackText.length > 0 + ) { const ordinal = yield* resolveItemOrdinal( input.context, - input.context.assistant.nativeItemId, + input.context.assistant.fallbackNativeItemId, ); const artifacts = buildAssistantArtifacts({ idAllocator, turnInput: input.context.input, providerTurnId: input.context.providerTurnId, - nativeItemId: input.context.assistant.nativeItemId, - text: input.context.assistant.text, + nativeItemId: input.context.assistant.fallbackNativeItemId, + text: input.context.assistant.fallbackText, ordinal, startedAt: input.context.startedAt, completedAt: input.completedAt, @@ -2658,6 +2675,49 @@ export function makeClaudeAdapterV2( }); }); + const emitAssistantTextArtifacts = Effect.fnUntraced(function* (input: { + readonly context: ActiveClaudeTurnContext; + readonly nativeItemId: string; + readonly text: string; + }) { + if (input.context.assistant.emittedNativeItemIds.has(input.nativeItemId)) { + return; + } + input.context.assistant.emittedNativeItemIds.add(input.nativeItemId); + const now = yield* DateTime.now; + const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); + const artifacts = buildAssistantArtifacts({ + idAllocator, + turnInput: input.context.input, + providerTurnId: input.context.providerTurnId, + nativeItemId: input.nativeItemId, + text: input.text, + ordinal, + startedAt: now, + completedAt: now, + }); + yield* Effect.all( + [ + emitProviderEvent({ + type: "node.updated", + driver: CLAUDE_PROVIDER, + node: artifacts.node, + }), + emitProviderEvent({ + type: "message.updated", + driver: CLAUDE_PROVIDER, + message: artifacts.message, + }), + emitProviderEvent({ + type: "turn_item.updated", + driver: CLAUDE_PROVIDER, + turnItem: artifacts.turnItem, + }), + ], + { concurrency: 1 }, + ); + }); + const finalizeActiveTurnAfterQueryExit = Effect.fnUntraced(function* ( cause?: Cause.Cause, ) { @@ -2715,19 +2775,23 @@ export function makeClaudeAdapterV2( } if (message.type === "system" && message.subtype === "task_started") { - yield* updateClaudeSubagentNode({ - context, - taskId: message.task_id, - ...(message.tool_use_id === undefined ? {} : { toolUseId: message.tool_use_id }), - ...(message.prompt === undefined ? {} : { prompt: message.prompt }), - title: message.description, - status: "running", - }); + if (isClaudeNonSubagentTask(message)) { + context.ignoredTaskIds.add(message.task_id); + } else { + yield* updateClaudeSubagentNode({ + context, + taskId: message.task_id, + ...(message.tool_use_id === undefined ? {} : { toolUseId: message.tool_use_id }), + ...(message.prompt === undefined ? {} : { prompt: message.prompt }), + title: message.description, + status: "running", + }); + } } if (message.type === "system" && message.subtype === "task_progress") { const progress = message.description.trim(); - if (progress.length > 0) { + if (progress.length > 0 && !context.ignoredTaskIds.has(message.task_id)) { yield* updateClaudeSubagentNode({ context, taskId: message.task_id, @@ -2739,18 +2803,20 @@ export function makeClaudeAdapterV2( } if (message.type === "system" && message.subtype === "task_notification") { - yield* updateClaudeSubagentNode({ - context, - taskId: message.task_id, - ...(message.tool_use_id === undefined ? {} : { toolUseId: message.tool_use_id }), - result: message.summary, - status: - message.status === "completed" - ? "completed" - : message.status === "stopped" - ? "cancelled" - : "failed", - }); + if (!context.ignoredTaskIds.has(message.task_id)) { + yield* updateClaudeSubagentNode({ + context, + taskId: message.task_id, + ...(message.tool_use_id === undefined ? {} : { toolUseId: message.tool_use_id }), + result: message.summary, + status: + message.status === "completed" + ? "completed" + : message.status === "stopped" + ? "cancelled" + : "failed", + }); + } } for (const toolUse of claudeToolUseBlocksFromAssistantMessage(message)) { @@ -2812,19 +2878,23 @@ export function makeClaudeAdapterV2( const assistantText = assistantTextFromSdkMessage(message); if (assistantText !== null && assistantText.text.length > 0) { - context.assistant.text += assistantText.text; - context.assistant.nativeItemId = assistantText.nativeItemId; + yield* emitAssistantTextArtifacts({ + context, + nativeItemId: assistantText.nativeItemId, + text: assistantText.text, + }); return; } const resultText = resultTextFromSdkMessage(message); if ( - context.assistant.text.length === 0 && + context.assistant.emittedNativeItemIds.size === 0 && + context.assistant.fallbackText.length === 0 && resultText !== null && resultText.text.length > 0 ) { - context.assistant.text = resultText.text; - context.assistant.nativeItemId = resultText.nativeItemId; + context.assistant.fallbackText = resultText.text; + context.assistant.fallbackNativeItemId = resultText.nativeItemId; } if (message.type === "result") { @@ -3067,10 +3137,12 @@ export function makeClaudeAdapterV2( providerTurnOrdinal, startedAt, assistant: { - text: "", - nativeItemId: `assistant:${turnInput.runId}`, + fallbackText: "", + fallbackNativeItemId: `assistant:${turnInput.runId}`, + emittedNativeItemIds: new Set(), }, toolCalls: new Map(), + ignoredTaskIds: new Set(), subagentsByTaskId: new Map(), subagentsByToolUseId: new Map(), subagentNodesByTaskId: new Map(), diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/claude_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/claude_transcript.ndjson new file mode 100644 index 0000000000..a8c1603a95 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/claude_transcript.ndjson @@ -0,0 +1,12 @@ +{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"claude_local_bash_task","metadata":{"prompts":["Run a local Bash typecheck command, then answer exactly: claude local bash task fixture complete"],"model":"claude-sonnet-4-6","nativeSessionId":"6a8f8455-10bc-4e31-8e30-b0ea9f88b911","queryMode":"streaming","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"manual-replay-from-thread-7f1dfff1"}} +{"type":"expect_outbound","label":"query.open","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"6a8f8455-10bc-4e31-8e30-b0ea9f88b911"}}} +{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Run a local Bash typecheck command, then answer exactly: claude local bash task fixture complete"},"parent_tool_use_id":null}}} +{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.183","cwd":"/tmp/claude-replay-claude_local_bash_task","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"af3bf4cc-1385-4e19-a5fa-fcbe2a0ca001","session_id":"6a8f8455-10bc-4e31-8e30-b0ea9f88b911"}} +{"type":"emit_inbound","label":"assistant:commentary","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01localbashfixture1","type":"message","role":"assistant","content":[{"type":"text","text":"I'll run the typecheck command now."}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"6a8f8455-10bc-4e31-8e30-b0ea9f88b911","uuid":"97898e28-ee4e-4fcf-80c3-5c790c502a42"}} +{"type":"emit_inbound","label":"assistant:bash","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01localbashfixture1","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01QHaWEM6vnYqxYPvpqv6Xq4","name":"Bash","input":{"command":"vp run --filter @t3tools/web typecheck 2>&1 | tail -30"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"6a8f8455-10bc-4e31-8e30-b0ea9f88b911","uuid":"1d21fda6-13b4-4229-aa5c-c7c92bdca799"}} +{"type":"emit_inbound","label":"task_started:local_bash","frame":{"type":"system","subtype":"task_started","task_id":"bw28jiyac","tool_use_id":"toolu_01QHaWEM6vnYqxYPvpqv6Xq4","description":"vp run --filter @t3tools/web typecheck 2>&1 | tail -30","task_type":"local_bash","uuid":"4873c95b-1aa9-44a5-9783-dc56dac734e6","session_id":"6a8f8455-10bc-4e31-8e30-b0ea9f88b911"}} +{"type":"emit_inbound","label":"task_notification:local_bash","frame":{"type":"system","subtype":"task_notification","task_id":"bw28jiyac","tool_use_id":"toolu_01QHaWEM6vnYqxYPvpqv6Xq4","status":"completed","output_file":"","summary":"vp run --filter @t3tools/web typecheck 2>&1 | tail -30","uuid":"5af2cb9e-6c69-4b5c-a935-2dfba519a773","session_id":"6a8f8455-10bc-4e31-8e30-b0ea9f88b911"}} +{"type":"emit_inbound","label":"user:bash_result","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01QHaWEM6vnYqxYPvpqv6Xq4","type":"tool_result","content":"~/apps/web$ tsgo --noEmit cache disabled","is_error":false}]},"parent_tool_use_id":null,"session_id":"6a8f8455-10bc-4e31-8e30-b0ea9f88b911","uuid":"2820be54-3f9f-4f82-b677-fe11a2e44e3a","timestamp":"2026-07-01T15:51:27.047Z","tool_use_result":{"stdout":"~/apps/web$ tsgo --noEmit cache disabled","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false}}} +{"type":"emit_inbound","label":"assistant:final","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01localbashfixture2","type":"message","role":"assistant","content":[{"type":"text","text":"claude local bash task fixture complete"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"6a8f8455-10bc-4e31-8e30-b0ea9f88b911","uuid":"89be9e65-097b-47e8-849b-be723386b72f"}} +{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":4000,"duration_api_ms":3500,"num_turns":2,"result":"claude local bash task fixture complete","stop_reason":"end_turn","session_id":"6a8f8455-10bc-4e31-8e30-b0ea9f88b911","total_cost_usd":0.001,"usage":{"input_tokens":2,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":2,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":1,"output_tokens":1,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":2,"outputTokens":2,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.001,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"7ff94c9f-194c-4c2e-85ae-6ea81aa6ff16"}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/input.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/input.ts new file mode 100644 index 0000000000..19b15de262 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/input.ts @@ -0,0 +1,7 @@ +import { CLAUDE_LOCAL_BASH_TASK_PROMPT, type OrchestratorFixtureInput } from "../shared.ts"; + +export function claudeLocalBashTaskInput(): OrchestratorFixtureInput { + return { + steps: [{ type: "message", text: CLAUDE_LOCAL_BASH_TASK_PROMPT }], + }; +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/output.ts new file mode 100644 index 0000000000..c51a428148 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_local_bash_task/output.ts @@ -0,0 +1,58 @@ +import { assert } from "@effect/vitest"; +import type { ProviderReplayTranscript } from "@t3tools/contracts"; + +import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts"; +import { + assertBaseProjection, + assertSemanticProjectionIntegrity, + assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, + CLAUDE_LOCAL_BASH_TASK_PROMPT, + projectionFor, +} from "../shared.ts"; + +export function assertClaudeLocalBashTaskOutput( + result: OrchestratorV2ScenarioResult, + transcript: ProviderReplayTranscript, +) { + assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] }); + + assert.lengthOf( + result.projections, + 1, + "Claude local_bash task lifecycle events must not create child app threads", + ); + + const projection = projectionFor(result, transcript.scenario); + assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); + assertUserMessagesInclude(projection, [CLAUDE_LOCAL_BASH_TASK_PROMPT]); + assert.deepEqual( + projection.turnItems.filter((item) => item.type !== "checkpoint").map((item) => item.type), + ["user_message", "assistant_message", "command_execution", "assistant_message"], + ); + + assert.lengthOf( + projection.subagents, + 0, + "Claude local_bash task lifecycle events must not project subagents", + ); + assert.lengthOf( + projection.nodes.filter((node) => node.kind === "subagent"), + 0, + "Claude local_bash task lifecycle events must not project subagent nodes", + ); + + const assistantTexts = projection.turnItems.flatMap((item) => + item.type === "assistant_message" ? [item.text] : [], + ); + assert.deepEqual(assistantTexts, [ + "I'll run the typecheck command now.", + "claude local bash task fixture complete", + ]); + + const command = projection.turnItems.find((item) => item.type === "command_execution"); + assert.isDefined(command); + assert.include(JSON.stringify(command ?? null), "vp run --filter @t3tools/web typecheck"); + assert.include(JSON.stringify(command?.output ?? null), "tsgo --noEmit"); +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts index 562abbb1fa..1d252be087 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts @@ -1,5 +1,7 @@ import { ProviderDriverKind } from "@t3tools/contracts"; +import { claudeLocalBashTaskInput } from "./claude_local_bash_task/input.ts"; +import { assertClaudeLocalBashTaskOutput } from "./claude_local_bash_task/output.ts"; import { grokSubagentLineageInput } from "./grok_subagent_lineage/input.ts"; import { assertGrokSubagentLineageOutput } from "./grok_subagent_lineage/output.ts"; import { assertClaudeMessageSteeringOutput } from "./message_steering/claude_output.ts"; @@ -78,6 +80,21 @@ import { } from "./shared.ts"; export const ORCHESTRATOR_REPLAY_FIXTURES = [ + { + name: "claude_local_bash_task", + buildInput: claudeLocalBashTaskInput, + providers: [ + { + driver: ProviderDriverKind.make("claudeAgent"), + transcriptFile: new URL( + "./claude_local_bash_task/claude_transcript.ndjson", + import.meta.url, + ), + modelSelection: CLAUDE_MODEL_SELECTION, + assertOutput: assertClaudeLocalBashTaskOutput, + }, + ], + }, { name: "grok_subagent_lineage", buildInput: grokSubagentLineageInput, diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts index be63aead8d..08ab813fdf 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts @@ -36,6 +36,8 @@ export const PROVIDER_THREAD_RESUME_SECOND_PROMPT = "Using the conversation history available in this resumed thread, first repeat the exact final answer you gave in the previous turn. Then on a new line write exactly: provider thread resume fixture second turn complete"; export const TOOL_CALL_READ_ONLY_WORKSPACE_ROOT = "/tmp/claude-replay-tool_call_read_only"; export const TOOL_CALL_READ_ONLY_PROMPT = `Read ${TOOL_CALL_READ_ONLY_WORKSPACE_ROOT}/package.json and ${TOOL_CALL_READ_ONLY_WORKSPACE_ROOT}/tsconfig.json, then answer exactly: read only tool fixture complete`; +export const CLAUDE_LOCAL_BASH_TASK_PROMPT = + "Run a local Bash typecheck command, then answer exactly: claude local bash task fixture complete"; export const TOOL_CALL_WRITE_PROMPT = "Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP."; export const MESSAGE_STEERING_INITIAL_PROMPT =