#21864·ai

harness-claude-code: a turn after a background task ends empty, because `runTurn` stops on Claude Code's own task-notification `result`

Author: brightironCreated Sep 30, 2026Updated Sep 30, 2026
Labelstask-identify-issue-type-donefactory-activefactory-automaticharness/claude-codetask-identify-harness-labels-done

Description

If a turn ends while a Claude Code background task is still running (Bash with run_in_background: true), the next turn on that session ends in about 2.6s with no answer. The host gets start, start-step, raw, finish, zero tokens, and empty text.

Reproduced on @ai-sdk/harness-claude-code 1.0.139 (Claude Code 2.1.281, Agent SDK 0.3.281) and 1.0.130 (2.1.276 / 0.3.276). Main's src/bridge/index.ts at eb93c81f has the same logic.

Each turn is a new query() resumed on the session. On resume, Claude Code queues its own <task-notification> command for the leftover task ahead of the host's prompt, runs it first, and emits a result for it. The bridge ends the turn there.

SDK messages the bridge received on turn 2, logged from its for await loop. The first line is what the bridge sent. system/init is cut to four keys and the result omits modelUsage, subagent_stats and permission_denials. The rest is verbatim.

// sent by the bridge
{"type": "user", "message": {"role": "user", "content": [{"type": "text", "text": "Run the bash command `date +%s >> /tmp/repro.txt` in the foreground, then reply with exactly the word DONE."}]}, "parent_tool_use_id": null, "uuid": "8465c5a1-88f1-44ff-bf69-91b4b125f5c3"}
{"type": "system", "subtype": "task_notification", "task_id": "bvyx3y08f", "tool_use_id": "toolu_01XA1rXDQWD8K7W2Ape2HwVP", "status": "stopped", "output_file": "", "summary": "Background shell command didn't finish before the previous session ended", "uuid": "d65d343b-b30c-481f-a627-88057d0add3a", "session_id": "749c1baf-b15a-4249-a7b9-8e3b6774674d"}
{"type": "command_lifecycle", "command_uuid": "8465c5a1-88f1-44ff-bf69-91b4b125f5c3", "state": "queued", "uuid": "fa48b00c-a5cd-46b7-bd79-1a33aca571bc", "session_id": "749c1baf-b15a-4249-a7b9-8e3b6774674d"}
{"type": "system", "subtype": "init", "session_id": "749c1baf-b15a-4249-a7b9-8e3b6774674d", "model": "claude-sonnet-4-5", "claude_code_version": "2.1.281"}
{"is_error": false, "duration_api_ms": 0, "num_turns": 0, "stop_reason": null, "session_id": "749c1baf-b15a-4249-a7b9-8e3b6774674d", "total_cost_usd": 0.15733320000000003, "usage": {"output_tokens_details": {"thinking_tokens": 0}, "input_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 0, "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": [], "speed": "standard"}, "fast_mode_state": "off", "fast_mode_disabled_reason": "sdk_opt_in_required", "origin": {"kind": "task-notification"}, "subtype": "success", "result": "", "type": "result", "duration_ms": 66, "uuid": "aff0f8c7-e23a-4e74-b036-52e7019875f1", "queued_turn_count": 0, "result_index": 0}

The notification's result has origin: {kind: "task-notification"}, num_turns: 0, result: "", result_index: 0, and no user_message_uuid. The bridge stops reading there.

With the change below the bridge reads on. The prompt's own result arrives later with result_index: 1 and echoes the sent uuid in user_message_uuid(s). Turn 2 answers DONE in 5.1s and the command runs.

Turn 2 frames with the change applied

Same trimming as above. The 36 frames between the started lifecycle and the final result are omitted: 1 system/init, 2 system/status, 28 system/thinking_tokens, 4 assistant, 1 user.

// sent by the bridge
{"type": "user", "message": {"role": "user", "content": [{"type": "text", "text": "Run the bash command `date +%s >> /tmp/repro.txt` in the foreground, then reply with exactly the word DONE."}]}, "parent_tool_use_id": null, "uuid": "48da386a-a07b-49f9-96cc-fa9753623698"}
{"type": "system", "subtype": "task_notification", "task_id": "bmfl4zexy", "tool_use_id": "toolu_019PWWYDMSxvrjwUMkDChBsd", "status": "stopped", "output_file": "", "summary": "Background shell command didn't finish before the previous session ended", "uuid": "299c2ff1-55f9-43af-92ee-16b6909fb25e", "session_id": "3f484272-5d39-4bc0-bbb4-6cbeeddb2970"}
{"type": "command_lifecycle", "command_uuid": "48da386a-a07b-49f9-96cc-fa9753623698", "state": "queued", "uuid": "52179535-9d49-4b32-9399-646470875755", "session_id": "3f484272-5d39-4bc0-bbb4-6cbeeddb2970"}
{"type": "system", "subtype": "init", "session_id": "3f484272-5d39-4bc0-bbb4-6cbeeddb2970", "model": "claude-sonnet-4-5", "claude_code_version": "2.1.281"}
{"is_error": false, "duration_api_ms": 0, "num_turns": 0, "stop_reason": null, "session_id": "3f484272-5d39-4bc0-bbb4-6cbeeddb2970", "total_cost_usd": 0.0298164, "usage": {"output_tokens_details": {"thinking_tokens": 0}, "input_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 0, "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": [], "speed": "standard"}, "fast_mode_state": "off", "fast_mode_disabled_reason": "sdk_opt_in_required", "origin": {"kind": "task-notification"}, "subtype": "success", "result": "", "type": "result", "duration_ms": 59, "uuid": "ab773d6d-4790-47a7-97e6-cbd122fc9cf9", "queued_turn_count": 0, "result_index": 0}
{"type": "command_lifecycle", "command_uuid": "48da386a-a07b-49f9-96cc-fa9753623698", "state": "started", "uuid": "b567af6c-b020-4710-ba58-9b3adec47154", "session_id": "3f484272-5d39-4bc0-bbb4-6cbeeddb2970"}
// ... 36 frames omitted: 1 system/init, 2 system/status, 28 system/thinking_tokens, 4 assistant, 1 user ...
{"duration_api_ms": 11709, "stop_reason": "end_turn", "session_id": "3f484272-5d39-4bc0-bbb4-6cbeeddb2970", "total_cost_usd": 0.05730615, "usage": {"input_tokens": 18, "cache_creation_input_tokens": 551, "cache_read_input_tokens": 74415, "output_tokens": 203, "output_tokens_details": {"thinking_tokens": 0}, "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": 551}, "inference_geo": "", "iterations": [{"type": "message", "input_tokens": 8, "output_tokens": 32, "cache_creation_input_tokens": 198, "cache_read_input_tokens": 37384}], "speed": "standard"}, "terminal_reason": "completed", "fast_mode_state": "off", "fast_mode_disabled_reason": "sdk_opt_in_required", "is_error": false, "num_turns": 2, "subtype": "success", "api_error_status": null, "result": "DONE", "ttft_ms": 2326, "type": "result", "duration_ms": 4278, "uuid": "d7585b46-10dd-422d-9f28-ba24b16d4e74", "ttft_stream_ms": 970, "time_to_request_ms": 60, "first_content_frame_ms": 971, "user_message_uuid": "48da386a-a07b-49f9-96cc-fa9753623698", "user_message_uuids": ["48da386a-a07b-49f9-96cc-fa9753623698"], "request_sent_wall_ms": 1790794217016, "queued_turn_count": 0, "result_index": 1}

Cause. In packages/harness-claude-code/src/bridge/index.ts, the successful-result branch ends the turn whenever no host steering message is pending, whatever command the result answers:

typescript
queryInput.observeResult();
if (!queryInput.hasActiveUserMessages()) {
  queryInput.close();
  break;
}

hasActiveUserMessages() only counts steering messages. The initial prompt goes out with messageId: randomUUID() and is never recorded, so right after the notification's result nothing is pending and the loop breaks.

The SDK types already say a result can be bound to its send (SDKResultSuccess.user_message_uuids):

so a consumer that sent any of them can bind this result to its own send by finding its uuid anywhere in the list

Expected: the turn ends on the result for the host's prompt.

Actual: the turn ends on the result for Claude Code's own notification, and the host sees an empty turn.

Impact. In the standalone repro the prompt's side effect doesn't happen: /tmp/repro.txt is still empty about 18s after the turn. In our own integration, which keeps the sandbox and session around, we've seen the prompt's tool work land after the empty turn ended, so re-sending the prompt ran it twice. I haven't reproduced that part standalone.

Proposed change

Two ways to fix it. I've implemented the first. The choice is yours.

1. Bind the result to a message the bridge sent. A successful result ends the turn only when its user_message_uuid(s) names a message this turn sent, either the initial prompt or a steering message. This also covers any other command Claude Code queues for itself, without needing a list of origin kinds.

Two edge cases:

  • Older CLIs. The notification's result is the query's first result, so a result-only fallback can't work. The bridge counts the CLI as echoing once it has shown any sent uuid, in a command_lifecycle.command_uuid or a result's user_message_uuid(s). Until then the first successful result ends the turn, same as today. In every run I captured (both 2.1.281 runs above, six earlier 2.1.276 runs) the prompt's queued lifecycle arrived before the notification's result. The change relies on that. If it ever flips, it quietly falls back to today's behaviour.
  • Cancelled prompt. If Claude Code cancels or discards the initial prompt, no result will answer it, so the turn ends anyway.

is_error and non-success results still go to emitTerminalError unchanged. The existing index.test.ts passes as-is (23/23), including the steering test, whose fixtures carry no uuids.

2. Skip results with origin.kind === 'task-notification'. This marks exactly this case and is a smaller change. It doesn't cover other self-queued commands, and it depends on origin being set.

They also combine: use the uuid rule, and skip task-notification origins even before any echo has been seen.

Diff for option 1, against main eb93c81f:

diff
--- a/packages/harness-claude-code/src/bridge/index.ts
+++ b/packages/harness-claude-code/src/bridge/index.ts
@@ -670,6 +670,7 @@
               usage: streamEventState.pendingStepUsage ?? harnessUsage,
             });
           }
+          if (!queryInput.answersSentMessage(msg)) continue;
           queryInput.observeResult();
           if (!queryInput.hasActiveUserMessages()) {
             queryInput.close();
@@ -764,12 +765,26 @@
   close(error?: unknown): void;
   handleLifecycle(message: ClaudeMessage): void;
   hasActiveUserMessages(): boolean;
+  answersSentMessage(result: ClaudeMessage): boolean;
   observeResult(): void;
   readonly hasObservedResult: boolean;
 } {
   let closed = false;
   let observedResult = false;
   const submittedMessages = new Map<string, Experimental_BridgeUserMessage>();
+  const initialMessageId = randomUUID();
+  const sentMessageIds = new Set<string>([initialMessageId]);
+  // Whether the CLI has shown it tracks the uuids we send (in a
+  // `command_lifecycle` or a result's `user_message_uuid(s)`). Until it has,
+  // results are not attributed and the first successful one ends the turn.
+  let cliEchoesMessageIds = false;
+  const noteEcho = (ids: readonly unknown[]): boolean => {
+    const echoed = ids.some(
+      id => typeof id === 'string' && sentMessageIds.has(id),
+    );
+    if (echoed) cliEchoesMessageIds = true;
+    return echoed;
+  };
   const close = (error?: unknown): void => {
     if (closed) return;
     closed = true;
@@ -808,6 +823,14 @@
         state?: 'queued' | 'started' | 'completed' | 'cancelled' | 'discarded';
       };
       if (lifecycle.command_uuid == null || lifecycle.state == null) return;
+      noteEcho([lifecycle.command_uuid]);
+      if (
+        lifecycle.command_uuid === initialMessageId &&
+        (lifecycle.state === 'cancelled' || lifecycle.state === 'discarded')
+      ) {
+        // No result will ever answer the prompt; let the turn end.
+        observedResult = true;
+      }
       const submitted = submittedMessages.get(lifecycle.command_uuid);
       if (submitted == null) return;
       if (lifecycle.state === 'queued' || lifecycle.state === 'started') {
@@ -823,6 +846,22 @@
     },
     hasActiveUserMessages: () =>
       submittedMessages.size > 0 || userMessages.pendingCount > 0,
+    // Claude Code also runs commands it queued itself (e.g. the
+    // `<task-notification>` for a background task a previous query left
+    // running, `origin.kind: 'task-notification'`) and emits a result for
+    // each, ahead of the host's prompt. Only a result naming a message this
+    // turn sent may end the turn.
+    answersSentMessage: result => {
+      const { user_message_uuid, user_message_uuids } = result as {
+        user_message_uuid?: unknown;
+        user_message_uuids?: unknown;
+      };
+      const ids = [
+        user_message_uuid,
+        ...(Array.isArray(user_message_uuids) ? user_message_uuids : []),
+      ];
+      return noteEcho(ids) || !cliEchoesMessageIds;
+    },
     observeResult: () => {
       observedResult = true;
     },
@@ -845,7 +884,7 @@
               return {
                 value: toUserMessage({
                   text: initialUserMessage,
-                  messageId: randomUUID(),
+                  messageId: initialMessageId,
                 }),
                 done: false,
               };
@@ -861,6 +900,7 @@
               nextMessage.value.messageId,
               nextMessage.value,
             );
+            sentMessageIds.add(nextMessage.value.messageId);
             return {
               value: toUserMessage({
                 text: nextMessage.value.text,

Accounting is unchanged. The notification's usage is still added to the turn, which is right since it's per turn (all zeros here). Separately, total_cost_usd is a running total but the bridge sums it across results, so costUsd is over-reported. I'll file that separately.

Related

#21694 keeps the query open after a successful result while background tasks are active. This change is about results before the turn's own. They compose: the turn becomes eligible to end once a result answers a sent message, and #21694's wait sits on top. A notification during the wait is still delivered as a step. This change only skips ending on one.

A bounded wait alone doesn't close this. A task that outlives the wait limit still leaves a task for the next query to resume into, and so does a turn the host aborts while waiting on TaskOutput. In our runs, a host abort during TaskOutput produced the same empty next turn.

What I did not check

  • Claude Code versions other than 2.1.276 and 2.1.281.
  • Whether the queued lifecycle always comes before a self-queued command's result. Every run I captured had it first, but I haven't found that ordering documented.
  • A real cancelled / discarded lifecycle for an initial prompt. That case is only scripted in the test.
  • The test inside the vercel/ai monorepo. I ran it in a standalone copy of packages/harness-claude-code/src from main eb93c81f with vitest 3.

Reproduction

Failing test. src/bridge/task-notification-result.test.ts, in the shape of index.test.ts: it mocks the Agent SDK, the MCP server and @ai-sdk/harness/bridge, then imports ./index. Fixtures are the frames above, trimmed to the fields the bridge reads.

typescript
import { afterEach, beforeEach, expect, test, vi } from 'vitest';

type QueryArgs = {
  prompt: AsyncIterable<unknown>;
  options: Record<string, unknown>;
};

const state = vi.hoisted(() => ({
  emitted: [] as Record<string, unknown>[],
  /** Frames the fake query yields; `$PROMPT` becomes the uuid the bridge sent. */
  frames: [] as Record<string, unknown>[],
  /** The index of the last frame the bridge asked for. */
  lastReadFrame: -1,
  originalArgv: [] as string[],
}));

vi.mock('@anthropic-ai/claude-agent-sdk', () => ({
  query: (args: QueryArgs) =>
    (async function* () {
      const initial = await args.prompt[Symbol.asyncIterator]().next();
      const promptUuid = Reflect.get(initial.value as object, 'uuid') as string;
      for (const [index, frame] of state.frames.entries()) {
        state.lastReadFrame = index;
        yield JSON.parse(
          JSON.stringify(frame).replaceAll('$PROMPT', promptUuid),
        );
      }
      // A real query stays open waiting for more input.
      await new Promise(() => {});
    })(),
}));

vi.mock('@modelcontextprotocol/sdk/server/mcp.js', () => ({
  McpServer: class {
    registerTool(): void {}
  },
}));

vi.mock('@ai-sdk/harness/bridge', () => ({
  runBridge: async ({
    onStart,
  }: {
    onStart: (start: unknown, turn: unknown) => Promise<void>;
  }) => {
    await onStart(
      { prompt: 'Run `date +%s >> /tmp/repro.txt`, then reply DONE.' },
      {
        abortSignal: new AbortController().signal,
        experimental_userMessages: {
          pendingCount: 0,
          close: () => {},
          [Symbol.asyncIterator]: async function* () {},
        },
        firstTurn: false,
        emit: (event: Record<string, unknown>) => state.emitted.push(event),
        emitWarning: () => {},
        emitError: () => {},
        requestToolResult: async () => ({ output: {} }),
        requestToolApproval: async () => ({ approved: true }),
      },
    );
  },
}));

const SESSION = '3f484272-5d39-4bc0-bbb4-6cbeeddb2970';

// Frames from one real run (Claude Code 2.1.281, bridge 1.0.139), trimmed to
// the fields the bridge reads: the turn after one that left a
// `run_in_background` Bash task running. The prompt's uuid is substituted.
const taskNotification = {
  type: 'system',
  subtype: 'task_notification',
  task_id: 'bmfl4zexy',
  tool_use_id: 'toolu_019PWWYDMSxvrjwUMkDChBsd',
  status: 'stopped',
  output_file: '',
  summary:
    "Background shell command didn't finish before the previous session ended",
  uuid: '299c2ff1-55f9-43af-92ee-16b6909fb25e',
  session_id: SESSION,
};
const promptQueued = {
  type: 'command_lifecycle',
  command_uuid: '$PROMPT',
  state: 'queued',
  uuid: '52179535-9d49-4b32-9399-646470875755',
  session_id: SESSION,
};
const promptStarted = {
  ...promptQueued,
  state: 'started',
  uuid: 'b567af6c-b020-4710-ba58-9b3adec47154',
};
const init = {
  type: 'system',
  subtype: 'init',
  session_id: SESSION,
  model: 'claude-sonnet-4-5',
  claude_code_version: '2.1.281',
};
const zeroUsage = {
  input_tokens: 0,
  cache_creation_input_tokens: 0,
  cache_read_input_tokens: 0,
  output_tokens: 0,
};
/** Claude Code's result for its own queued notification: no user_message_uuid. */
const notificationResult = {
  type: 'result',
  subtype: 'success',
  is_error: false,
  duration_ms: 59,
  duration_api_ms: 0,
  num_turns: 0,
  result: '',
  stop_reason: null,
  total_cost_usd: 0.0298164,
  usage: zeroUsage,
  origin: { kind: 'task-notification' },
  uuid: 'ab773d6d-4790-47a7-97e6-cbd122fc9cf9',
  queued_turn_count: 0,
  result_index: 0,
  session_id: SESSION,
};
/** The result that answers the host's prompt. */
const promptResult = {
  type: 'result',
  subtype: 'success',
  is_error: false,
  duration_ms: 4278,
  duration_api_ms: 11709,
  num_turns: 2,
  result: 'DONE',
  stop_reason: 'end_turn',
  terminal_reason: 'completed',
  total_cost_usd: 0.05730615,
  usage: {
    input_tokens: 18,
    cache_creation_input_tokens: 551,
    cache_read_input_tokens: 74415,
    output_tokens: 203,
  },
  uuid: 'd7585b46-10dd-422d-9f28-ba24b16d4e74',
  user_message_uuid: '$PROMPT',
  user_message_uuids: ['$PROMPT'],
  queued_turn_count: 0,
  result_index: 1,
  session_id: SESSION,
};

const finish = () =>
  state.emitted.find(event => event.type === 'finish') as
    | { totalUsage: { outputTokens: { total?: number } } }
    | undefined;

beforeEach(() => {
  state.emitted = [];
  state.frames = [];
  state.lastReadFrame = -1;
  state.originalArgv = [...process.argv];
  process.argv.splice(
    0,
    process.argv.length,
    'node',
    'bridge.mjs',
    '--workdir',
    '/tmp/harness-clau