Skip to content

A tool call that completes in a later turn shows as pending in its spawning turn's details #1714

Closed

Description

@aemrebarut

⚠ Agent-assisted: an AI agent found, reproduced, and root-caused this
while auditing the turn-summary details round trip around #1510. Details
verified against main at ba426545; please re-verify before acting.

Summary

When an item's item/started is scoped to one turn and its item/completed
is scoped to a later turn — the persisted shape #447 made the projection
support — the spawning turn's summary row renders the item completed
with its output
in its inline children, but expanding the same row
through the turn-summary details route renders the same row id pending
with empty output
. The details response is a 200; nothing errors or logs.
Every expansion of that turn shows the wrong state, permanently, because the
lifecycle is persisted.

This is the cross-turn sibling of #1201 (cross-page), and #1510's
whole-item ownership rule does not cover it: that rule operates within a
scoped item identity, while this lifecycle spans two scopes.

Environment

  • Reproduced at d0e727447; every involved function is unchanged at main
    (ba426545) except the unrelated Fix long streamed messages across timeline completion #1568 hunk in timeline.ts (verified by
    full-file diff — packages/thread-view has no commits in between).
  • Server-side only; no app build needed. Repro is a vitest file over
    createConnection(":memory:") using the same harness shape as
    apps/server/test/services/threads/timeline-in-turn-window.test.ts.

Reproduction

Seven events; the second turn's only purpose is to carry the late completion:

seq  event                          scope    item
 1   turn/started                   turn-1
 2   item/started commandExecution  turn-1   call-1  "npm run dev"
 3   item/completed agentMessage    turn-1   msg-1
 4   turn/completed                 turn-1
 5   turn/started                   turn-2
 6   item/completed toolCall        turn-2   call-1  completed, result "dev server exited with code 0"
 7   turn/completed                 turn-2

Seq 6 is what the claude-code translator emits for a late tool_result once
toolItemsByCallId was cleared at the turn boundary
(packages/agent-runtime/src/shared/tool-item-translation.ts →
{ type: "toolCall", tool: "unknown", … }), matching #447's root-cause
description verbatim.

Drop this file into apps/server/test/services/threads/ and run it — the
first test demonstrates the defect (all four assertions on the final state
fail if the defect is fixed… inverted: they pass today, documenting the
wrong behavior); the control shows that scoping the same completion row to
turn-1 makes both surfaces byte-identical:

/**
 * Repro: a cross-turn item lifecycle renders `completed` in a turn row's
 * inline children but `pending` in the same row's turn-summary details.
 *
 * The item's `item/started` is scoped to turn-1; its `item/completed` arrives
 * scoped to turn-2 — the persisted shape #447 made the projection support
 * (keep first scope, stretch end). The control scopes the same completion row
 * to turn-1 and both surfaces agree.
 */
import { expect, it } from "vitest";
import { turnScope } from "@bb/domain";
import type { Thread } from "@bb/domain";
import {
  createConnection,
  createProject,
  createThread,
  insertEvents,
  migrate,
  noopNotifier,
  upsertHost,
} from "@bb/db";
import type { DbConnection } from "@bb/db";
import type { TimelineRow } from "@bb/server-contract";
import {
  buildThreadTimelineWithProfile,
  buildTimelineTurnSummaryDetails,
} from "../../../src/services/threads/timeline.js";

const providerThreadId = "provider-root";

function setup(): { db: DbConnection; thread: Thread } {
  const db = createConnection(":memory:");
  migrate(db);
  const host = upsertHost(db, noopNotifier, {
    name: "test-host",
    type: "persistent",
  });
  const { project } = createProject(db, noopNotifier, {
    name: "test-project",
    source: { type: "local_path", hostId: host.id, path: "/tmp/test" },
  });
  const thread = createThread(db, noopNotifier, {
    projectId: project.id,
    providerId: "claude-code",
  });
  return { db, thread };
}

type EventInput = Parameters<typeof insertEvents>[2][number];

function seed(db: DbConnection, thread: Thread, lateCompletionTurnId: string) {
  const events: EventInput[] = [];
  let sequence = 0;
  const push = (event: Omit<EventInput, "sequence" | "threadId">): void => {
    sequence += 1;
    events.push({ ...event, sequence, threadId: thread.id });
  };

  // turn 1: a command starts, the turn answers and completes
  push({
    type: "turn/started",
    scope: turnScope("turn-1"),
    providerThreadId,
    itemId: null,
    itemKind: null,
    data: JSON.stringify({}),
  });
  push({
    type: "item/started",
    scope: turnScope("turn-1"),
    providerThreadId,
    itemId: "call-1",
    itemKind: "commandExecution",
    data: JSON.stringify({
      item: {
        type: "commandExecution",
        id: "call-1",
        command: "npm run dev",
        cwd: "/tmp/test",
        status: "pending",
        approvalStatus: null,
      },
    }),
  });
  push({
    type: "item/completed",
    scope: turnScope("turn-1"),
    providerThreadId,
    itemId: "msg-1",
    itemKind: "agentMessage",
    data: JSON.stringify({
      item: { type: "agentMessage", id: "msg-1", text: "Dev server is starting." },
    }),
  });
  push({
    type: "turn/completed",
    scope: turnScope("turn-1"),
    providerThreadId,
    itemId: null,
    itemKind: null,
    data: JSON.stringify({ status: "completed", providerThreadId }),
  });

  // turn 2: the same call settles late. In the defect case its completion row
  // is scoped to turn-2 (the adapter's degraded late-result shape); in the
  // control it stays scoped to turn-1.
  push({
    type: "turn/started",
    scope: turnScope("turn-2"),
    providerThreadId,
    itemId: null,
    itemKind: null,
    data: JSON.stringify({}),
  });
  push({
    type: "item/completed",
    scope: turnScope(lateCompletionTurnId),
    providerThreadId,
    itemId: "call-1",
    itemKind: "toolCall",
    data: JSON.stringify({
      item: {
        type: "toolCall",
        id: "call-1",
        tool: "unknown",
        status: "completed",
        result: "dev server exited with code 0",
      },
    }),
  });
  push({
    type: "turn/completed",
    scope: turnScope("turn-2"),
    providerThreadId,
    itemId: null,
    itemKind: null,
    data: JSON.stringify({ status: "completed", providerThreadId }),
  });

  insertEvents(db, noopNotifier, events);
}

function run(lateCompletionTurnId: string) {
  const { db, thread } = setup();
  seed(db, thread, lateCompletionTurnId);

  const build = (includeNestedRows: boolean): TimelineRow[] =>
    buildThreadTimelineWithProfile(db, thread, {
      eventBudget: 1_000_000,
      includeProviderUnhandledOperations: false,
      includeNestedRows,
      maxInlineOutputChars: 32_000,
      maxSeq: 0,
      page: { kind: "latest", segmentLimit: 20 },
    }).response.rows;

  const turnRow = build(false).find(
    (row): row is Extract<TimelineRow, { kind: "turn" }> =>
      row.kind === "turn" && row.turnId === "turn-1",
  );
  expect(turnRow).toBeDefined();

  const inlineTurnRow = build(true).find(
    (row): row is Extract<TimelineRow, { kind: "turn" }> =>
      row.kind === "turn" && row.turnId === "turn-1",
  );
  // Exactly what LazyTurnRowBody sends on expansion: the row's own identity.
  const details = buildTimelineTurnSummaryDetails(db, thread, {
    includeProviderUnhandledOperations: false,
    turnId: turnRow!.turnId,
    sourceSeqStart: turnRow!.sourceSeqStart,
    sourceSeqEnd: turnRow!.sourceSeqEnd,
  });

  const workOf = (rows: readonly TimelineRow[]) =>
    rows.find((row) => row.kind === "work") as
      | (Extract<TimelineRow, { kind: "work" }> & { output?: string })
      | undefined;
  return {
    detailsCommand: workOf(details.rows),
    detailsRows: details.rows,
    inlineChildren: inlineTurnRow?.children ?? [],
    inlineCommand: workOf(inlineTurnRow?.children ?? []),
    turnRow: turnRow!,
  };
}

it("details disagree with inline children when the completion is scoped to the next turn", () => {
  const result = run("turn-2");

  // The turn row's range covers the late completion (seq 6).
  expect(result.turnRow.sourceSeqStart).toBe(1);
  expect(result.turnRow.sourceSeqEnd).toBe(6);

  // Same row id on both surfaces — the same rendered item.
  expect(result.detailsCommand?.id).toBe(result.inlineCommand?.id);

  // Inline: the truth. Details: permanently pending, no output.
  expect(result.inlineCommand?.status).toBe("completed");
  expect(result.inlineCommand?.output).toBe("dev server exited with code 0");
  expect(result.detailsCommand?.status).toBe("pending");
  expect(result.detailsCommand?.output).toBe("");
});

it("control: the same completion row scoped to turn-1 keeps both surfaces identical", () => {
  const result = run("turn-1");
  expect(result.inlineCommand?.status).toBe("completed");
  expect(result.detailsCommand?.status).toBe("completed");
  expect(JSON.stringify(result.detailsRows)).toBe(
    JSON.stringify(result.inlineChildren),
  );
});

Both tests pass today, which is the bug: the first documents the divergence,
the control shows the completion row's turn scope is the only causal
variable. Item kind (toolCall vs commandExecution), accepted input, and
the presence of an assistant message make no difference (variants checked).

Expected vs. actual

Expected: buildTimelineTurnSummaryDetails(row.turnId, row.sourceSeqStart, row.sourceSeqEnd).rows equals the same row's children from an
includeNestedRows: true build — the property #1510 restored for byte-page
cuts. Concretely: one command row, completed, with its output.

Actual: the details command row is status: "pending", output: "",
completedAt: null, sourceSeqEnd pinned to the item/started row. The
inline child is completed with the output. Same row id. HTTP 200.

Root cause

Line references at ba426545 (thread-view files are identical at
d0e727447).

The inline path merges the cross-turn lifecycle on purpose:
onExecEnd looks up the running call by bare call id in thread-level state
(packages/thread-view/src/tool-activity-projection.ts:1082) and
upsertRunningExecCall keeps the first scope while merging terminal
state/output and stretching sourceSeqEnd (:497-550; the comment at
:518-520 — "provider background work can outlive its spawning turn, and a
late terminal event for the same call id may arrive scoped to a later turn"
— is #447's fix). The turn's bounds stretch over member-message ends
(packages/thread-view/src/group-event-projection-turns.ts:115-157), which
is why the turn-1 row spans [1,6], past its own turn/completed at 4.

The details path re-projects the row's sequence window but filters by
turn scope:

  1. The window [1,7) fetch does select the completion row
    (apps/server/src/services/threads/timeline.ts:1953-1982 at main).
  2. filterExactEventRowsForRequestedTurn drops every turn-scoped row whose
    turnId differs from the requested turn (timeline.ts:619, drop at
    :625). The completion is scoped turn-2 → gone. This filter is [codex] Fix turn detail hydration for overlapping turns #164's
    deliberate fix for overlapping-turn detail ranges, so it cannot simply be
    removed.
  3. Because rows were removed, the effective range is re-derived from the
    surviving rows (resolveTurnSummaryDetailsSourceRange, :647), which is
    why the exact-bounds matcher still matches and the response is a silent
    200 rather than a missing-match error.
  4. No closure step can restore the row. ensureSequenceWindowWholeItemRows
    (:828) — added by [issue sweep] Give timeline turn details the whole-item ownership rule #1510 for exactly this symptom in the byte-cut case —
    cannot see it: the item's span is computed per scoped identity
    (scopedItemRefKey = scopeKind + turnId + itemId,
    packages/db/src/data/events.ts:1448-1450; predicate :1475-1510,
    hardened in Fix timeline failures for large scoped item windows #1398 for ACP item-id reuse), so the turn-2 completion is a
    different identity from the turn-1 start; and its lifecycle backfill only
    fetches rows below the window start (timeline.ts:904), never forward.
    The parented-rows, turn-started, and background-task helpers select other
    row classes entirely.
  5. The re-projection therefore holds item/started with no terminal row:
    the cell renders pending with empty output, and the matched row's
    children are returned as the expansion result.

In one sentence: the projection's ownership model is "an item belongs to the
turn it started in, wherever its rows are scoped" (#447, keyed by bare call
id), the details route's model is "a turn's rows are the rows scoped to that
turn, whole-item-closed per scoped identity" (#164 + #1510 + #1398), and a
cross-turn lifecycle satisfies the first while violating the second — each
surface renders its own model.

Where the shape comes from

  • [codex] Show background subagent tasks #447's root cause records it on a real thread, and the projection merge
    exists because of it. Any thread that persisted such a lifecycle renders
    wrong on every expansion of the spawning turn — persisted data, not a
    transient state.
  • The claude-code translator still scopes a late tool_result to whichever
    turn is open (translate-message.ts, tool_result path), degrading it to
    a generic toolCall once the boundary cleared toolItemsByCallId. Since
    Keep Claude child threads active while subagents run #633 the common background flows hold the logical turn open across
    intermediate SDK results, so new claude-code occurrences should be rare
    — which makes the historical rows the main carriers, plus providers that
    scope items by their own turn ids (codex event translation).

Impact

The main timeline is right and nothing is lost — but the details surface
contradicts it, and in the app the expansion surface is the only place a
finished turn's work rows are readable. Unlike #1201 (oldest byte slice of a

4 MiB turn), this affects every expansion of an affected turn at any
size, silently, forever.

Suggested fix direction

The invariant worth enforcing (it is the one #1510 restored for byte cuts):
for every turn summary row the timeline emits, the details route returns the
same rows as that row's inline children.

Two directions, either keyed to the projection's own ownership rule:

  1. Forward whole-item closure across scopes. After the requested-turn
    filter, for each retained non-background item/started without a terminal
    row in the retained set, re-admit (or fetch, when outside the window) the
    first later item/completed carrying the same item id, provided no other
    item/started for that id sits in between — the same row the projection's
    runningCallsById merge would have consumed, so the guard preserves
    Fix timeline failures for large scoped item windows #1398's id-reuse isolation. This mirrors what
    ensureTimelineWindowBackgroundTaskStateRows already does for background
    tasks (carrying later state into the window) and what
    ensureTimelineWindowParentedRows already does across sequence bounds.
  2. Scope-aware filtering. Teach filterExactEventRowsForRequestedTurn
    to keep another turn's item/* rows when the item id belongs to an item
    the requested turn started (same in-between-restart guard). Smaller
    change, same semantics.

One trap for either direction: the exact-bounds match in
buildThreadTimelineTurnDetailsFromEvents currently succeeds because the
re-derived range and the completion-less re-projection shrink in lockstep
(resolveTurnSummaryDetailsSourceRange / findMatchingTurnSummaryRow).
Re-admitting the completion stretches the re-projected row back to the
requested sourceSeqEnd, so the match range must account for the re-admitted
rows (the way projectionSourceSeqStart already widens the start for
backfilled turn/started rows) or the fix converts the silent wrong answer
into a missing-match 500.

A regression test asserting the invariant for this fixture — details rows
byte-equal to inline children — belongs next to #1510's test in
apps/server/test/services/threads/timeline-in-turn-window.test.ts; the two
tests above can seed it.

Activity

  1. added theissue type on Aug 18, 2026
  2. added
    threads
    on Aug 18, 2026
  3. SawyerHood commented on Aug 18, 2026

    @SawyerHood
    Collaborator

    Reproduction & root-cause report: https://get-bb.github.io/reports/issues/1714.html

    • Verdict: REPRODUCED · root-cause confidence: high
    • Root cause (short): buildTimelineTurnSummaryDetails drops every turn-scoped row whose turnId differs from the requested turn (filterExactEventRowsForRequestedTurn), so a late item/completed scoped to the next turn is discarded and neither the scoped-identity whole-item closure ([issue sweep] Give timeline turn details the whole-item ownership rule #1510) nor any backfill restores it, while the timeline projection merges the same lifecycle by bare call id ([codex] Show background subagent tasks #447) — details render the call unfinished (pending, or interrupted on an idle thread) with no output.
    • Proposed fix: In apps/server/src/services/threads/timeline.ts filterExactEventRowsForRequestedTurn, track item ids that the requested turn item/started inside the window and keep another turn's non-backgroundTask item/* rows for those ids, dropping ownership if another turn emits its own item/started for the same id (preserves Fix timeline failures for large scoped item windows #1398 id-reuse isolation). Prototype patch (1714/repro/prototype-fix.patch) makes the invariant test (details.rows toEqual inline children) pass and keeps the other 115 apps/server thread tests green. Before shipping: also fetch the completion when it lies beyond sourceSeqEnd (byte-cu…
    • Caveats: Did not provoke a real late tool_result from a live provider; the persisted event shape was seeded directly (unit test with in-memory SQLite, and @bb/db insert into the dev instance DB) — that shape is exactly what the claude-code translator emits per code reading. Correction to the issue: on a real idle thread the wrong details row reads 'interrupted' / 'Tool execution interrupted' rather than 'p…

    The report has copy-paste repro steps, screenshots where the bug is visual, code permalinks at 16ceb3a54, and repro artifacts. It was independently re-run by a second agent (see its Verification section).

    AGENT GENERATED: by Claude Opus 5

  4. added
    confirmed-repro
    on Aug 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-reprothreads

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions