Skip to content

Split completed turn summaries at user boundaries - #320

Merged
ymichael merged 1 commit into
mainfrom
bb/fix-completed-turn-summary-boundaries
Jun 23, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/fix-completed-turn-summary-boundaries

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Summary

  • detect external human new-turn boundaries inside completed turn ranges
  • split completed turn summary groups at those boundaries so later user rows stay in source order
  • constrain source-order sorting to the affected suffix so provisioning rows remain before initial turn summaries

Validation

  • pnpm exec turbo run typecheck --filter=@bb/thread-view
  • pnpm exec turbo run test --filter=@bb/thread-view -- test/completed-turn-summary-rendering.test.ts
  • pnpm exec turbo run test --filter=@bb/thread-view

@ymichael
ymichael force-pushed the bb/fix-completed-turn-summary-boundaries branch from a73b2f9 to 8d016d6 Compare June 23, 2026 16:33
@ymichael
ymichael merged commit a0c5475 into main Jun 23, 2026
6 checks passed
@ymichael
ymichael deleted the bb/fix-completed-turn-summary-boundaries branch June 23, 2026 17:15
SawyerHood added a commit that referenced this pull request Aug 21, 2026
## What was wrong

When a Claude Code Stop hook blocks a stop, Claude Code injects the
hook's reason as a synthetic user message and the model answers again.
That synthetic message never becomes a bb thread event
(`provider-claude-code` only forwards `tool_result` user messages), so
one bb turn ends with two `agentMessage` items back to back: the real
answer, then a one-line reply to the hook. Completed-turn grouping in
`@bb/thread-view` keeps exactly one terminal message per segment
(`findLastTerminalTimelineMessage`) and slices everything before it into
the collapsed `Worked for` summary. The real answer, including any
question for the user, disappears behind a row that reads like a
duration stat, in the app and in `bb thread log`.

Issue: #1355. Report: https://get-bb.github.io/reports/issues/1355.html
(reproduced live on a fresh instance from 16ceb3a; the code at the
root cause is unchanged on current main).

## What changed

`packages/thread-view/src/completed-turn-grouping.ts`: an assistant text
that is directly followed by more assistant text, with no work in
between, is a complete response, not narration about upcoming tool
activity. `groupCompletedTurnSummaryMessages` now promotes such messages
to `ungrouped-message` items (the terminal message counts as the
follower of the last summary message). The existing collapse is
unchanged for text followed by tool activity, so ordinary `text -> tool
-> text` turns still render as `user -> Worked for -> last answer`.

Behavior for the issue's shape (`answer, hook reply`): both assistant
rows are visible at rest and no summary row is emitted. For `narration,
command, answer, hook reply`: `Worked for` holds the narration and the
command, then the answer and the hook reply are both visible.

Deviation from the report's primary proposal: the report suggests
surfacing every top-level assistant text. That changes every agentic
turn (interim narration such as "Let me check X" would leave the
summary), which #320 deliberately collapses, and #1508's review measured
a 1,500-event page producing ~1,500 rows (past the 200-row
completed-timeline cache limit). This change is scoped to the shape that
loses the answer. Remaining gap: a hook that makes the model call a tool
before answering (`answer, [hook], tool, reply`) still folds the answer,
because nothing in the event stream marks the boundary; fixing that
needs `provider-claude-code` to surface the synthetic hook message
through the bridge protocol, which is a contract change and a separate
PR.

No wire change. The app and `bb thread log` share this row builder, so
both pick it up.

## How you verified

New tests, which fail on origin/main and pass with this change:

- `packages/thread-view/test/completed-turn-grouping.test.ts`: `keeps an
assistant response visible when more assistant text follows it
directly`, `folds narration that precedes work and keeps the response
that precedes the terminal text`, `keeps every response in a run of
adjacent assistant texts`. Two existing tests that encoded the old
behavior with two adjacent assistant texts now use a command message as
the folded work.
- `packages/thread-view/test/completed-turn-summary-rendering.test.ts`:
`keeps an assistant answer visible when the provider re-queries and the
model answers again`, `folds narration before work but keeps the answer
that precedes a hook reply`.

With `completed-turn-grouping.ts` checked out from origin/main the
rendering test fails with:

```
- Expected
+ Received
  [
    "conversation:user",
-   "conversation:assistant",
+   "turn:4-4",
    "conversation:assistant",
  ]
```

Commands:

- `pnpm exec turbo run typecheck --filter=@bb/thread-view
--filter=@bb/server --filter=@bb/app --filter=@bb/cli
--filter=@bb/client-core`: 8/8 pass.
- `pnpm exec turbo run test --filter=@bb/thread-view --filter=@bb/server
--filter=@bb/cli --filter=@bb/client-core`: thread-view 21/21 files, cli
48/48, client-core 20/20, server 194/195 (the one failure is
`internal-skill-trees.test.ts` mode 0644 vs 0664, a pre-existing local
umask difference unrelated to this change).
- `apps/app` `vitest run src/components/thread/timeline`: 28/28 files.

Manual: on a dev instance built from this branch, a `claude-code` thread
in a scratch repo with a blocking Stop hook (the report's 4a repro)
produced events `agentMessage, agentMessage, turn/completed`. `bb thread
log` now prints the three-bullet answer with its closing question as an
`Assistant` row, followed by the hook reply as a second `Assistant` row,
with no `Worked for` row; the app shows the same two rows at rest.

Fixes #1355

> AGENT GENERATED: by Claude Opus 5


## Independent verification

Verified by a second agent on a fresh checkout of this branch
(`40224ee60`, origin/main is an ancestor; no conflicts) in its own
worktree and dev instance.

Commands:

- `pnpm install --frozen-lockfile --prefer-offline && pnpm exec turbo
run build`
- Fail-before: `git checkout origin/main --
packages/thread-view/src/completed-turn-grouping.ts`, then `pnpm exec
vitest run test/completed-turn-grouping.test.ts
test/completed-turn-summary-rendering.test.ts` in
`packages/thread-view`: 5 failed / 19 passed. The five new tests are
exactly the ones that fail. Rendering test assertion:

  ```
  - Expected
  + Received
    [
      "conversation:user",
  -   "conversation:assistant",
  +   "turn:4-4",
      "conversation:assistant",
    ]
  ```

Grouping test: `expected [ { kind: 'summary', …(5) } ] to deeply equal [
{ kind: 'ungrouped-message', …(1) } ]`.
- Pass-after: restored the PR file, same command: 24/24 pass.
- `pnpm exec turbo run typecheck --filter=@bb/thread-view
--filter=@bb/server --filter=@bb/cli --filter=@bb/client-core
--filter=@bb/app --filter=@bb/mobile`: 9/9 successful.
- `pnpm exec turbo run test --filter=@bb/thread-view --filter=@bb/server
--filter=@bb/cli --filter=@bb/client-core`: thread-view 21/21 files (385
tests), cli 48/48 (453), client-core 20/20 (238). See the server result
note below.
- Ad-hoc probes through `renderTimelineFixture` (not committed):
`reasoning, text, reasoning, text` (extended thinking between the answer
and the hook reply) still renders both assistant rows at rest; `text,
tool, text` still collapses to `user -> Worked for -> assistant` (the
deliberate #320 behavior); a steer between two answers keeps the
existing per-segment preservation; `text, text, text, tool, text` shows
the first two, folds the third with the tool.

Repro on the fixed branch (report section 4a, real `claude-code` turn
with a blocking Stop hook on a scratch repo, own dev instance):
persisted events were `item/completed agentMessage` (seq 22),
`item/completed agentMessage` (seq 29), `turn/completed` (seq 32) with
no hook event between, the same shape as the report. `bb thread log`
(default minimal format) printed `User`, `Provisioned thread`, then the
full three-bullet answer with its closing question as an `Assistant`
row, then the hook reply as a second `Assistant` row, with no `Worked
for` row. `GET /api/v1/threads/:id/timeline` (what the app renders)
returned `conversation:user, system:operation, conversation:assistant,
conversation:assistant` and no `turn` row. The bug no longer reproduces.
The provider still drops the synthetic hook message
(`plugins/provider-claude-code/src/delta-translation.ts`
`translateUserMessage` returns `[]` when there are no tool results), so
the fix is entirely in the shared row builder, as described.

CI: all required checks green on the PR head (Checks, Tests
server/packages/integration/app-1..3, Package Smoke ubuntu+macos,
version check).

Residual risks (agreed with the PR body): `answer, [hook], tool, reply`
still folds the answer because no event marks the hook boundary; that
needs `provider-claude-code` to surface the synthetic user message (wire
change, separate PR). Any provider that emits two adjacent assistant
items for one response now shows both rows. `answer, answer2, error`
shows `answer` at rest but still folds `answer2` before the error row
(pre-existing behavior for error terminals, not made worse). Textual
merge overlap with #2071 in the same loop of
`completed-turn-grouping.ts`.

> AGENT GENERATED: by Claude Opus 5

Co-authored-by: Claude <[email protected]>
ymichael added a commit that referenced this pull request Nov 18, 2026
…7795)

## Human comments

## What was wrong

The timeline had two display orders. It grouped rows turn by turn until
the first user message that landed inside another turn (a message while
a turn was still open, or while a delegated child was still running).
After that "ordering boundary" it sorted every later row by source
sequence. #320 added the switch so a message sent mid-turn shows where
it was sent. Everything downstream then had to reproduce it:

- **Paging:** a whole-thread boundary scan, plus
`timeline-display-ownership.ts` to work out which page shows a row whose
display position differs from its sequence.
- **Server re-sort:** a delegation-span boundary query and a server-side
re-sort.
- **Outline:** the conversation outline checkpoint could never move past
the boundary, so 3 of the 5 largest local threads reproject everything
after it on every rebuild.

The display order itself was also inconsistent before the boundary:
operation notices recorded mid-turn showed after the turn's reply, and
two turns running at once showed one turn whole before the other.
Pending steers were pinned to the bottom on threads without a boundary
but sorted into place on threads with one.

## What changed

**One display rule** (`packages/thread-view`):
- Every row is ordered by where its content starts. A collapsed summary
row starts at its first summarized item, not at the turn's request.
- A completed turn's work collapses into one summary row per run, and a
run ends at any visible user message that lands inside the turn before
its final reply.
- Pages no longer pass split points in; the projection computes them
from the rows it loaded.

**Deleted:**
- the ordering boundary;
- `timeline-display-ownership.ts`;
- the external-user boundary scan in `timeline-context-order.ts` (the
grouping context keeps only request/turn bookkeeping);
- `getFirstParentedTimelineBoundarySequence` and the late-delegation
rows it needed;
- `listStoredStandaloneThreadTimelineRows`, which only display ownership
called;
- `orderTimelineRowsUsingContext`;
- the boundary in the projection cache key;
- the outline checkpoint's boundary cap.

Because display order is now sequence order, a page owns exactly the
rows whose `sourceSeqStart` is in its window.

**Pending steers become live state** (`server-contract`, server, app,
CLI):
- A steer waiting for the running turn is no longer a row on any page.
The latest page returns it in a new `pendingSteers` field, alongside
`activeThinking` and `activeWorkflows`, so push deltas and window reuse
carry it.
- The app's timeline controller and `bb thread log` show pending steers
after the rows, as main does.
- Once accepted, the steer becomes a row with the same id where it was
accepted. Rejected steers stay rows ordered by their request.

**Other:**
- `hasTimelineGroupingContextChangesInRange` replaces the old change
probe, with a query-plan test and query-cost case.
- `docs/timeline-pagination.md` describes the new rule.
- No host-daemon wire change. The timeline response gains
`pendingSteers`, a required array that is empty off the latest page. SDK
types pick it up from the contract.

Visible changes, all toward "in the order it happened":

| Change | Threads affected (of 4,995) |
|---|---|
| A user message moves above a startup warning that fired just after it
| ~186 |
| An operation notice moves to where it happened instead of after the
turn's reply | ~277 |
| Turns that ran at the same time interleave by time | ~12 |
| After a steer, the agent text written before that turn's work shows
above the work summary instead of below it | — |
| A duplicate "interrupted" notice right after an error merges, now that
they're adjacent | 2 |

## How you verified

Real data, from a `VACUUM INTO` copy of a 10.7 GB local bb database:

**Full builds, main vs this branch, all 4,995 threads.** 4,615 are
identical. Every difference is one of the moves in the table above. I
checked each pattern by hand on the threads where it showed up.

**Paged walks.** `test/timeline-history/paged-walk.test.ts` walks a
thread page by page at the default and a 120-event budget and compares
the result with one full build. It passes for 1,000 walks: every thread
whose display changed (380) plus 120 random ones. Main passes the same
set. The deletion was safe because display order now equals page order.
Two intermediate designs broke the walks for exactly that reason (an
in-turn reorder, and pending steers appended after sorting), and both
were fixed by removing the special order, not by adding ownership.

**Outline replay with no boundary cap.**
`test/timeline-history/outline-replay.test.ts` (opt-in,
`BB_TIMELINE_HISTORY_DB`, same harness as #7765) replays the 5 largest
threads plus 7 overlap-heavy ones. It appends events in random chunks,
changes status at random, runs live pruning and switches connections,
and the incremental outline matches a full build at every step (197 s).

**Live.** On a `pnpm start:worktree` instance:
- Seeded real threads showing each change, compared against an
`origin/main` instance.
- Ran a real Codex thread through `sleep 25` and steered it mid-command.
The steer was accepted one event later and renders as a row there,
splitting the turn's summary around it. `pendingSteers` was empty
afterwards.

**Tests:**
- New server test: a pending steer is in no page's rows, only the latest
page carries it in `pendingSteers`, and acceptance turns it into a row
with the same id.
- Boundary-only tests were removed or rewritten as grouping-context
cache tests.
- The CLI snapshot for a pending steer is unchanged from main.

**Commands:**
- `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`
passed (140 tasks).
- `pnpm exec turbo run test --filter=@bb/server --filter=@bb/db
--filter=@bb/thread-view --filter=@bb/server-contract
--filter=@bb/client-core --filter=@bb/cli --filter=@bb/app` passed:
server 4,316, db 718, thread-view 553, server-contract 88, client-core
239, cli 934, app 7,128. One server test timed out while all suites ran
concurrently and passes alone in 7.5 s.
- `pnpm exec turbo run check:query-costs --filter=@bb/db` passed.

> 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