Skip to content

Build timeline rows for provider items from one record per item - #7754

Merged
ymichael merged 6 commits into
mainfrom
bb/item-records-timeline
Nov 18, 2026
Merged

ymichael merged 6 commits into
mainfrom
bb/item-records-timeline

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

packages/thread-view rebuilt every provider item (commands, tool calls, subagents, file changes, web and file activity, answers, reasoning, background tasks) at read time by stitching its events together. Each kind had its own state machine with its own merge rules, about 3,850 lines in total:

  • tool activity cells and running calls;
  • web activity begin/end;
  • file-edit row matching;
  • assistant text buffers;
  • the reasoning lifecycle;
  • background tasks.

Since 2026-08-19 the daemon writes each finished item whole into its completed event. Most of this merging no longer does anything, but every rule still has to be kept consistent across kinds and across full builds and pushes.

What changed

Rows for provider items now come from one record per item.

  • item-records.ts (new) keeps the records in the projection fold. Each item event updates its record: the current item, start and end points, streamed text and output, and progress. The rules below reproduce today's behaviour; the old merge machinery is not kept.
    • New records. A start, delta or progress event after a completion starts a new record. A later completion, or delegation or background-task progress, continues the same record.
    • Turn changes. Answer, reasoning and file-change records split when the same id shows up in another turn. Command and tool records do not split, so a completion scoped to a later turn still closes the command.
    • Reopened items. A delegation started again in the same turn reopens its record. A background task keeps one record for the whole thread, with its first completion time and its first parent.
    • Final at first completion. Answers and reasoning are final at their first completion. Web search and fetch, image view and generation, file read, search, plan steps and extension items are also final at their first completion; later events for the same id are ignored.
    • Stops. At a stop or turn end, a streaming answer keeps the text it had. Open reasoning keeps the stop time and status, and a later completion only replaces its text.
    • Closed turns. Answer deltas in a closed turn are ignored. Reasoning that starts in a closed turn is not shown.
    • Running output. Running command and file-change output shows complete lines, plus whatever had arrived by the last stop or turn end. A running command interrupted with its turn shows all of its output. Output that arrives after a command finished is appended.
    • Approvals. A command that waited for approval starts when it is approved.
    • Fields. Tool name and arguments come from the first event that had them. A command's description is the latest one given. Presentation falls back to the first one seen.
    • File-change row ids. A file change keeps the row id it had when its file was first named, matched later by path or new path. A file-change id reused in another turn gets that turn in its row id.
    • Reasoning order. Finished reasoning whose summary and content equal what streamed keeps the streamed order.
    • Suppression. Suppressed low-value item events are dropped one at a time, as before.
  • item-record-messages.ts (new) turns a record into projection messages and never reads events. Formatted messages are cached per record version, so a push only reformats the records it touched.
  • build-event-projection.ts sends item events to the records. Compaction items still open and close the turn's compaction row through the existing handlers. Pushes resume the fold for item events as before.
  • event-projection-state.ts: the turn-end rules (interrupting pending tools, finishing operations) work on messages.
  • operation-projection.ts: file-edit merging is removed.
  • Deleted:
    • tool-activity-projection.ts, tool-activity-cells.ts, tool-activity-web-projection.ts;
    • exec-lifecycle.ts, web-activity-lifecycle.ts, file-edit-parsing.ts;
    • assistant-buffering.ts, assistant-event-projection.ts, assistant-stream-projection.ts, buffered-text-projection.ts;
    • reasoning-lifecycle-projection.ts, visible-text-buffer.ts;
    • background-task-projection.ts, tool-call-suppression.ts.
  • Not changed: user messages, client requests and steers, turn grouping, thread operations, interactions, provisioning, errors, head state, and the server's timeline files.

No wire, CLI, guide or settings changes.

How you verified

Same rows as main. I built every thread of a 4,794-thread copy of a production snapshot without caches. The copy was read in process with SQLite only. Each thread was built with origin/main at d89f5ce (this branch's base) and with this branch, in the collapsed, flat and nested displays. All 14,382 responses are byte-identical: rows, head state and page fields. test/timeline-history/paged-walk.test.ts also passes on the same copy (BB_TIMELINE_HISTORY_DB), at both window budgets, for every thread.

Running items, replayed from real threads. I picked 17 real turns from Claude Code, Codex and Pi. They include:

  • subagents and background delegations;
  • stops mid-answer and mid-reasoning;
  • late completions after a stop;
  • a closed turn that keeps streaming;
  • approvals, suppressed tools, long command output and reused ids.

Each thread was cut at the start of the turn and marked running. The remaining events were then inserted one at a time (up to 2,500), and the latest page was read after each insert through the normal resumed-fold push path. Main and this branch were identical at every one of the 30,322 steps.

Running items, live. I ran a dev instance from source with a fresh data dir and six real threads (three Claude Code, three Codex):

  • a Claude Code Task subagent, and a Codex spawned agent;
  • streamed reasoning, answers and command output;
  • stops mid-reasoning (Claude Code), mid-command (Codex), and mid-answer (both).

While they streamed I polled the running server's timeline. All 101 changed responses equal a replay of the same events at the same sequence; sequence numbers are ignored because the live log has gaps. Main and this branch give identical results for those six threads at all 227 steps, in the collapsed and nested displays.

Cost. Same copy, sequential runs, main twice. The table shows the sum over the 8 largest threads of each thread's median, in ms. Rounds ran in the order main, branch, main, branch, then branch, main.

main 1 branch 1 main 2 branch 2 branch 3 main 3
cold latest page 221.6 211.1 220.4 199.7 195.9 208.8
warm latest page 10.9 11.2 10.8 10.0 10.0 10.5
older-page walk 5,827 5,538 5,785 5,205 5,117 5,383
turn details 34.3 32.5 33.8 31.8 30.6 32.8
outline 17.2 15.9 15.5 15.0 15.0 15.1
push, 30 streamed deltas (median) 18.53 18.26 17.59 17.55 17.36 17.26
push p90 20.64 20.55 19.40 19.56 19.13 19.09

A long running turn replayed one event at a time (1,200 pushes on each of two threads; median push ms, then total ms):

main 1 branch 1 main 2 branch 2 branch 3 main 3
thr_xhbjjkf7u2 median 2.31 2.21 2.07 2.00 2.00 2.04
thr_xhbjjkf7u2 total 2,928 2,829 2,611 2,522 2,519 2,590
thr_79dqcxvx2i median 1.88 1.82 1.71 1.73 1.69 1.69
thr_79dqcxvx2i total 2,289 2,191 2,041 2,042 2,006 2,016

Size. Non-blank lines, not counting tests:

before after
packages/thread-view/src 16,305 13,676 (−2,629)
server timeline files (apps/server/src/services/threads/timeline*, thread-timeline*, 19 files) 6,486 6,486 (unchanged)

Tests.

  • tool-activity-projection.test.ts and file-edit-row-placement.test.ts drove the deleted handlers directly, so they are removed.
  • item-record-rows.test.ts covers what users see instead: running output a line at a time, flushed at a stop; reset output; output after a command finished; an answer stopped mid-stream; and pushes equal to a full build through a stop, a subagent and late completions. It passes on main too.

Commands:

  • pnpm exec turbo run typecheck lint:type-aware --filter=@bb/thread-view --filter=@bb/server
  • pnpm exec turbo run test --filter=@bb/thread-view: 541 passed.
  • apps/server vitest test/services/threads/ and test/timeline-history: 394 passed, plus the real-history walk above. This includes timeline-read-cost and all four timeline-read-equivalence files.

Behaviour changes

  • Command output that arrives before the command's start event used to be joined with output carried on the start event. Now the start event's output is not added while the command runs. No thread in the 4,794-thread copy has this shape: the daemon opens an item before its deltas.

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael
ymichael merged commit cb991e3 into main Nov 18, 2026
39 checks passed
@ymichael
ymichael deleted the bb/item-records-timeline branch November 18, 2026 21:10
ymichael added a commit that referenced this pull request Nov 18, 2026
## Human comments

## What was wrong

A provider can stop waiting on a request it raised: a Claude
`PermissionRequest` hook answers it and the SDK aborts the
`can_use_tool` request, Codex sends `serverRequest/resolved`, a Pi
dialog reaches its `timeout`, or an ACP/Pi session ends with a
permission open. In each case the bridge dropped its local waiter
(Claude's `onAbort` only answered `deny` locally; Codex ignored
`serverRequest/resolved`) and nothing reached the runtime, daemon, or
server. The interaction row stayed `pending`, so the card stayed up and
every later message queued behind it (#6966). The wire had no way to say
a request was withdrawn: `notifications/cancelled` existed only for ACP
tool calls, and the server only closed interactions per thread (provider
exit) or on reconnect.

Pointed at by T3 Code's fix for the same bug, pingdotgg/t3code#27320.

## What changed

- **Bridge → runtime:** `BRIDGE_NOTIFICATION_METHODS.requestCancelled`
(`notifications/cancelled { requestId }`) now covers
`interaction/request` as well as tool calls. Every bridge that stops
waiting sends it:
- Claude: the SDK abort for permission requests and user questions, and
session close/replace/stream end.
- Codex: `serverRequest/resolved` for a request bb has not answered,
plus child exit and session release. These apply to forwarded tool calls
too.
- ACP: `cancelPendingPermissions`, which covers stop, release, steer
cancel, policy change, and agent exit.
  - Pi: dialog `timeout` and session close/replace.
- **Runtime:** `RuntimeToolCalls` → `RuntimeProviderRequests`, also used
for interactive requests. `onInteractiveRequest(request, signal)` gets
an abort signal. A withdrawn request is never answered.
- **Daemon:** `InteractiveRequestRegistry.registerAndWait(request,
signal)` rejects a withdrawn wait. Once registration settles, it reports
the withdrawal through the existing retrying interrupt queue to a new
`POST /session/interactive-request/withdraw` route, so a withdrawal that
races registration cannot leave a row behind.
- **Server:** `interruptWithdrawnProviderRequest` closes the matching
row as `interrupted` with the reason "The agent stopped waiting for this
answer". The next queued message then dispatches. It writes the
lifecycle record but not the approval's `item/completed: interrupted`.
Writing that item made the projection drop the real result Claude sends
after the hook allows the tool; the first live re-run caught this.
- **Projection (`thread-view`):** a call that its turn ends without
settling no longer keeps `approvalStatus: waiting_for_approval` (in
`interruptPendingToolMessages`, `event-projection-state.ts`). This
affects a provider that withdraws and never settles the item.
- **On top of #7723:** ACP's `withdrawPendingQuestions` (bb answers on
its own when a new prompt starts) now also aborts the forwarded request,
so that card closes too. Codex and Pi keep #7723's
unanswered-interaction warnings and add the withdrawal on top.
- **Wire:** `HOST_DAEMON_PROTOCOL_VERSION` 268 → 269 (new route). Plugin
SDK 0.6.160 → 0.6.161 (new `BRIDGE_NOTIFICATION_METHODS` key,
bridge-grammar snapshot). Docs: `docs/provider-bridge-protocol.md`,
`docs/provider-plugin-api.md`.
- **Test fixtures:** the scripted-echo bridge gets `withdraw_approval`,
and the fake Codex app-server gets `withdrawAfterMs`.

## How you verified

**Live repro, before (origin/main 502cf5a, `pnpm start:worktree`,
claude 2.1.325).** I used a project `.claude/settings.json`
`PermissionRequest` hook (matcher `Bash`) that returns `allow`, and a
`claude-code` thread in `accept-edits` that runs two unsandboxed `curl`
commands. Both commands completed (`HTTP/2 200`) and the turn finished
with `DONE.`. Then:

```text
bb thread interactions list   -> pint_2dsywi5jzf pending, pint_r4b2sui9p5 pending
bb thread list --json         -> {"status":"idle","hasPendingInteraction":true}
bb thread tell 'Reply OK.'    -> message queued (waiting for a pending interaction); it dispatches when that clears
```

**Same steps, after:**

```text
pending_interactions -> both interrupted, "The agent stopped waiting for this answer" (rows from the first after-run, which still used the earlier wording)
command items        -> completed, exitCode 0, "HTTP/2 200"; timeline rows status completed, no approval state
bb thread list       -> idle, hasPendingInteraction false
bb thread tell       -> dispatched; agent replied "OK."
```

I also stopped a thread with a genuinely pending approval (no hook). The
card closed and the command row shows `interrupted` with no lingering
"waiting for approval".

After rebasing onto #7754 (timeline rows rebuilt from item records) and
#7723, I re-ran both live cases. The hook case shows both commands
`completed`, exit 0, `HTTP/2 200`, `approvalStatus: null`, both cards
`interrupted`, and the follow-up dispatched. The stop-while-pending case
shows the card `interrupted` and the command row `interrupted` with no
approval state.

**Tests:**
- New tests:
- Integration:
`tests/integration/fake/smoke/withdrawn-approvals.test.ts`, full server
+ daemon + runtime + scripted bridge. The card closes, the row is not
left waiting, and the follow-up message dispatches.
  - Runtime: abort on withdraw.
- Daemon registry: withdraw after registration, during registration,
never registered, and after the answer.
  - Daemon app: posts the withdraw route.
  - Server: route, idempotence, and the item left to the provider.
- Bridges: Claude (approval + user question), Codex
`serverRequest/resolved` (no late answer reaches Codex), ACP stop, Pi
timeout/answer/close.
  - thread-view: the turn-end approval state.
- They fail without the fix. With the runtime's interactive cancel
disabled, the integration test fails with `expected [ { id:
'pint_nk2fcgcggg', … } ] to deeply equal []`. Without the projection
change, the thread-view test fails.
- `pnpm exec turbo run typecheck` and `test` pass for
`@bb/agent-runtime`, `@bb/host-daemon`, `@bb/server`,
`@bb/host-daemon-contract`, `@bb/provider-bridge-protocol`,
`@bb/provider-bridge-acp`, `@bb/thread-view`, the Claude, Codex, and Pi
plugins, and the scripted-echo bridge. `lint` passes on the touched
packages.

Fixes #6966

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 19, 2026
## Human comments

## What was wrong

The timeline build in `@bb/thread-view` had no check against cost
growing faster than the data. #7754 replaced an indexed lookup with a
per-file scan of every row. Behavior tests passed, and the regression
stayed in until #7835. Adding a growth check found two more quadratic
paths in `group-event-projection-turns.ts`:

- `applyExternalUserBoundaries` filtered every root user message in the
thread once per turn (turns × messages).
- `findRootTurnRunningAtSequence` scanned every turn once per
thread-scoped warning or interaction prompt (turns × prompts).

## What changed

- **New test,
`packages/thread-view/test/timeline-build-growth.test.ts`.** It builds
timelines for 16 thread shapes at 100 and at 400 units: files in one
edit (same and reversed completion order), file changes, commands,
command output deltas, assistant messages and deltas, reasoning deltas,
tool calls, reads and searches, web searches, plan updates, delegations,
user messages sent during a running turn, turns, and turns that each
raise a thread-scoped permission prompt.
- It counts work during the build: array callback, scan and copy
methods, plus Array/Map/Set iteration and `Object.keys/values/entries`.
- It requires 4× the input to cost less than 6× the work. Linear code
measures about 4×; quadratic code about 16×.
- It counts work rather than timing it, so it is deterministic and
cannot flake under load.
- The prototype wrappers exist only during the synchronous build and are
restored in `finally`.
- **`applyExternalUserBoundaries`:** sorts the boundary sequences once,
then binary-searches each turn's window. The output is already
ascending, so the per-turn sort is gone.
- **Thread-scoped messages:** a single sweep resolves the running turn
for all of them (`findRootTurnsRunningAtThreadMessages`). It walks turns
sorted by start and keeps a stack that discards turns completed before
the current message.
- No wire, protocol, CLI, persisted-data or UI changes.

## How you verified

- The new test fails on the code it guards:
  - `item-records.ts` from before #7835: 11.4× and 13.7×.
- `group-event-projection-turns.ts` from before this PR: 6.97× for
turns, 9.41× for per-turn thread-scoped prompts.
  - After this PR, every scenario measures 3.5–4.0×.
- Real data, read-only export of 7 local threads (the four with the most
turns, 1,370/798/641/720, plus the three with the most thread-scoped
interaction prompts):
- `JSON.stringify(buildThreadTimelineFromEvents(...))` hashes are
identical before and after, for `completedTurnDisplay` collapse/expand ×
`includeNestedRows` true/false.
  - Full-build medians:

    | thread | turns | before | after |
    |---|---:|---:|---:|
    | `thr_cdfq9maj8q` | 1,370 | ~395 ms | ~345–357 ms |
    | `thr_d5ej4e2gtv` | 798 | ~357 ms | ~303–322 ms |

    Smaller threads show no measurable change.
- `pnpm exec turbo run test typecheck lint:type-aware lint
--filter=@bb/thread-view` passes.
- `pnpm exec turbo run test --filter=@bb/server --
test/services/threads/timeline test/public/public-thread-timeline
test/timeline-history` passes: 263 passed, 2 skipped. The skipped tests
are history replays that need `BB_TIMELINE_HISTORY_DB`.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant