Skip to content

Stream long answers as append-only deltas and stop relaying out the whole timeline per push - #7613

Merged
ymichael merged 6 commits into
mainfrom
bb/stream-long-answers-as-tail-only-deltas-thr_mmg6evy4y9
Nov 17, 2026
Merged

ymichael merged 6 commits into
mainfrom
bb/stream-long-answers-as-tail-only-deltas-thr_mmg6evy4y9

Conversation

@ymichael

@ymichael ymichael commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Streaming a long answer cost more per push the longer the answer got, in three places (perf audit hotspot 1, thr_qgyt9gkt9f):

  • Wire. A timeline delta upserted every changed row whole, so each push re-sent the full accumulated message text (up to ~27 KB per frame).
  • Render. Block-incremental markdown re-cloned every settled piece on every new body, so React re-rendered the entire settled message on each push. Mounting a table also walked its ancestors with getComputedStyle in a layout effect, forcing a style recalc.
  • Layout. The page scrollers (data-page-scroll-viewport) were also @container/page query containers. A scroll container that is a size container makes Blink lay out its whole scrolled subtree on every content change. An append that dirtied 27 layout objects still took ~8–10 ms of layout at 4× CPU, and in the trace that cost grew with the number of mounted objects. scroll-position-keeper apply was the top self-time entry because it was the first to read layout after each commit.

What changed

  • Append-only deltas (packages/server-contract)
    • New optional field delta.patchRows: { id, ops }[] for rows the base window already holds. Ops are ["append", path, text], ["set", path, value] and ["delete", path] on JSON paths inside the row.
    • computeThreadTimelineDelta diffs each changed row. A string that grew at its end becomes an append. upsertRows now carries only rows that are new to the window.
    • applyThreadTimelineDelta applies patches with structural sharing. It returns null, and the client refetches instead of rendering the row, when an op does not fit the held row (a path that does not exist, an append to a non-string, an index past the end) or when the result changes the row's id or kind.
    • The patched row is not re-validated against timelineRowSchema. A delta applies only to the window whose tag it names, so the client patches exactly the row the server diffed against, and full rows in upsertRows are not schema-checked on the client either. Leaving the schema out keeps it off the boot path without a registry, and applying stays synchronous.
    • In a live stream on the built branch, every delta push applied with no timeline refetch, and the rendered message matched the server's text.
    • I chose JSON-path ops over a typed per-field append contract. Every streamed push also changes sourceSeqEnd, createdAt and messageSeq, and streamed output lives under different fields per row kind (message text, command and tool output, delegation output), so a typed contract would need a field list for each row kind.
    • HTTP reads with afterTag and WebSocket pushes share this code. The daemon wire is unchanged, so HOST_DAEMON_PROTOCOL_VERSION is not bumped. Documented in docs/timeline-pagination.md.
  • Settled markdown stays put (markdown-incremental-pieces.ts)
    • Reused pieces keep their elements and directive mounts by identity, so React skips them.
    • MountedMessageDirectiveView is now a memo boundary keyed on the mount.
    • The raw thread-mention hooks used to read the query cache without subscribing and depended on that re-render to pick up titles. They now subscribe to their cache entries. I copied this part verbatim from Make the React Compiler authoritative in apps/app and shared-ui #7603, which makes the same change, so whichever PR lands first, the other rebases cleanly.
  • Table geometry (markdown-preview.tsx): the breakout width adds --page-container-inset-end to 100cqw, because the page container now sits inside the context-card inset. Resolving the clip ancestor lazily instead of in the mount layout effect landed separately in Mount timeline rows without forcing layout from the scroll handler #7612, so this PR no longer changes it.
  • Query containers moved off scrollers
    • bottom-anchored-scroll-body (thread timeline): the container moves to the existing content child. The context-card inset is passed as --page-container-inset-end, so the table breakout's 100cqw math stays identical.
    • Static PageShell, RootComposeHome (non-compact) and the tasks list: a plain container wrapper inside the scroller.
    • Plugin Guide: the size container moves to the existing outer element. The 3cqh stage gap subtracts the scroller padding it no longer sees, so the gap is unchanged.
    • New guard scroll-container-queries.test.ts fails on any class string that makes one element both a scroll container and a query container. It flags all five of these on main. I added the rule to AGENTS.md (UI).

Not changed: how TimelineWindowedItems mounts rows. #7612 has since changed that path; this PR does not touch it.

Old tabs: a tab still running the previous app ignores patchRows. That is acceptable because AppUpdateHost reloads the page when the server's version or commit changes, and the mobile and desktop apps load the app from the server.

Refs #6816.

How you verified

Benchmark. Production builds of main (da3e60b81d) and this branch, each served by pnpm start:worktree with the same seeded 500-thread fixture and stream provider. The stream was 4 × 24 KB markdown messages with 3 streamed commands (stream:120:40 rep:8) into the 2.9k-item thread, with 48 characters typed during the stream. Headless Chrome 145 at 1600×1000. Three rounds, alternating main and branch run by run on a loaded machine. Medians of 3:

main 1× branch 1× main 4× branch 4×
Typing 48 chars during the stream 3.37 s 3.12 s 5.51 s 4.18 s
Long animation frames (count / total) 3 / 243 ms 3 / 223 ms 187 / 17.9 s 78 / 6.9 s
Frames > 100 ms 0 0 55 10
Forced style + layout in LoAF 92 ms 83 ms 9.8 s 3.3 s
Layout time (Performance.getMetrics) 2.78 s 0.83 s 10.4 s 3.6 s
WebSocket bytes received 3.48 MB 0.55 MB 3.51 MB 0.55 MB
  • After the rebase onto Keep timeline pushes from re-rendering the thread view #7599 and Mount timeline rows without forcing layout from the scroll handler #7612, without patched-row validation (echo provider streaming 199 chunks of paragraphs, links, inline code, tables and code blocks, about 25 KB, every 40 ms, into a thread with 8 earlier answers of that size; headless Chrome 1600×1000 at 4× CPU, typing 48 characters during the stream; main measured before those PRs landed, so this is not a strict A/B):
    • Timeline WebSocket bytes 1.46 MB → 0.15 MB; the last push 27.5 KB → 1.3 KB.
    • Layout 3.8 s → 0.33–0.35 s; long animation frames 68–72 → 4; forced style and layout 2.9 s → 40–48 ms; typing 5.7–6.0 s → 2.4–2.5 s.
  • Wire. Timeline frames for the same stream fell from 3.50 MB to 0.47 MB of deltas, with the same final text length. About 210 KB of the rest is timelinePage.olderCursor and historySnapshot. Both embed maxSeq, so they change on every push (~760 B each time). That cost is constant per push and does not grow with the answer, so I left it.
  • Layout probe. Appending text to the last paragraph of a 24 KB message and then reading layout costs 6–10 ms at 4× with the container on the scroller, and 1.4 ms with it on the child. contain: layout on rows, blocks or the preview, and replacing the flex columns with blocks, made no difference.
  • iOS 18.4 Simulator Safari (iPhone 16 Pro, same stream, alternating; noisy because another simulator was running on the same CPU):
    • Painted frames over the stream went from 352–468 to 548–612. Frame p95 went from 230–507 ms to 186–196 ms, and typing p95 from 243–1,187 ms to 275–353 ms.
    • Frames over 100 ms did not change (44–53).
    • WebKit does not have the container cost: both placements laid out in under 1 ms.
  • Layout parity. I compared the bounding rect of every text-bearing element on main and on this branch: a thread, Settings, Settings › Appearance, home, Tasks and the Plugin Guide, at 1600×1000, plus home, a thread and Settings at 500×900. They are identical except timestamp and relative-date text, because the two fixtures were seeded minutes apart.

Tests. Each new test fails on main and passes here.

  • thread-timeline-delta.test.ts
    • A grown message row is sent as an append of only the new text; the delta does not contain the old text.
    • 300 random steps of growth, rewrites, added and removed keys and nested arrays round-trip exactly.
    • Patches that do not fit (append to a non-string, a missing key, an unknown row) return null.
    • A __proto__ key stays data.
    • A patch that changes a row's id or kind returns null.
  • thread-timeline-push.test.tsx: a pushed row patch is applied, and a patch that does not fit the held row leaves the cache unchanged and refetches with the held tag.
  • markdown-incremental-pieces.test.ts: settled pieces keep their elements and directive mounts by identity when the body grows.
  • markdown-preview.incremental.test.tsx
    • While content grows, the DOM only gains nodes for new blocks; nothing inside a settled block is mutated or removed. On main, settled links get attribute rewrites on every body.
    • A settled plugin directive renders once and does not re-run its attribute effect.
  • scroll-container-queries.test.ts (the guard above).

Commands.

  • pnpm exec turbo run typecheck --filter=@bb/app --filter=@bb/server-contract --filter=bb-plugin-tasks --filter=bb-plugin-plugin-api-docs
  • pnpm exec turbo run lint on the same packages: no new findings.
  • pnpm exec turbo run test --filter=bb-plugin-tasks --filter=bb-plugin-plugin-api-docs
  • Targeted vitest: the server timeline delta, push, scrollback, event-budget and pruning tests (78 passed); app markdown, timeline-push, scroll-keeper, page-shell, RootComposeHome and ThreadTitleMentions tests; and client-core timeline-merge.

🤖 Generated with Claude Code

AGENT GENERATED

@ymichael
ymichael force-pushed the bb/stream-long-answers-as-tail-only-deltas-thr_mmg6evy4y9 branch 2 times, most recently from d70b7d1 to 9c04c33 Compare November 17, 2026 03:47
ymichael and others added 5 commits November 16, 2026 19:55
…hole timeline per push

Timeline deltas now patch rows already on the client instead of re-sending
them: streamed text, reasoning and command output travel as appended text.
Settled markdown pieces keep their React elements, so a push re-renders only
the live tail, and table geometry resolves its clip ancestor from the
ResizeObserver instead of a mount-time getComputedStyle walk.

The page scrollers were also container-query containers, which made Blink
lay out the whole scrolled subtree on every content change. The query
container now sits on the scroller's content child in every shell, with a
source guard so it cannot come back.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pplier now validates with

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… budget raise

Boot code applies deltas through a row-patch dispatcher that the timeline
controller's chunk registers on load; timeline subscriptions only start there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/stream-long-answers-as-tail-only-deltas-thr_mmg6evy4y9 branch from 9c04c33 to fec48f9 Compare November 17, 2026 03:57
…istry

A patch only applies to the row the server diffed against (afterTag), and its
ops already refuse paths and value types that do not fit the held row. Full
rows are not schema-checked on the client either, so the patched row now keeps
only the id and kind checks. That removes the boot-path patcher registry, the
second delta-apply entry point and the timeline-controller registration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 14eeb50 into main Nov 17, 2026
97 of 98 checks passed
@ymichael
ymichael deleted the bb/stream-long-answers-as-tail-only-deltas-thr_mmg6evy4y9 branch November 17, 2026 05:02
smsunarto added a commit to smsunarto/bb-plugins that referenced this pull request Nov 19, 2026
…3) (#187)

* fix(scott-tasks): return a saved comment before agent delivery finishes

Port of upstream get-bb/bb#4679. The app's createComment waited for the
thread lookup and send before answering, so a slow or stuck worker
held the composer. The app now returns the saved comment at once and
delivers in the background; the CLI still waits so it can report the
notified count.

* feat(scott-tasks): move a task and its sub-tasks to another project

Port of the server and CLI half of upstream get-bb/bb#4100. A moved
task gets a fresh number in the target project, lands at the end of its
status column, and keeps its old key as an alias, so mentions and agent
instructions that name the old key still resolve. Labels are remapped
by name and created when missing. A sub-task moved on its own leaves
its parent. New: moveTaskToProject RPC and bb tasks move.

* feat(scott-tasks): move tasks from the detail page and the list's context menu

The UI half of upstream get-bb/bb#4100. The properties rail and inline
chips get a project picker, and a list row's context menu gets Move to
project. Opening a task by a key it had before a move asks the server
and follows the task to its current key.

* feat(scott-tasks): keep New task drafts and cap the dialog's height

The dialog half of upstream get-bb/bb#4100. Title, description and
attributes save to localStorage as they change, so an outside click,
Escape or reload no longer throws a long task away; Discard draft
clears it. The dialog is capped at 85dvh with the description
scrolling, so Create task stays reachable.

* fix(scott-tasks): port upstream touch, embed and download fixes

- get-bb/bb#5097: label and preset row actions stay visible on screens
  without hover, such as a 13-inch iPad.
- get-bb/bb#5157: a narrow desktop pane keeps the compact topbar; only
  touch screens get the taller one.
- get-bb/bb#5903: the whole task embed card opens the task, and a
  loading card no longer highlights on hover.
- get-bb/bb#5508: attachment downloads go through bb's saveFile, which
  the iOS shell implements with WebKit's native download.

* docs(scott-tasks): document bb tasks move; drop unused hono and cron-parser

hono 4.11.9 was a vulnerable pin that nothing imports; cron-parser is unused too.

* feat(scott-tasks): delegate as a child thread from a chosen base branch

bb tasks delegate takes --parent-thread, --parent-notifications auto|stuck|off and --base-branch, passed to threads.spawn. An orchestrating agent dispatches its crew as children so bb reports their turns to it, and starts each worktree from its own branch. --base-branch always means a new worktree, whatever the preset names, and leaves the preset unchanged.

* fix(scott-tasks): let the attachment preview's img own its object URL

Attachment chips set state in an effect to hold the preview URL; the <img> ref callback now creates and revokes it. Clears a react(set-state-in-effect) lint error.

* feat(scott-tasks): owned fields, crew snapshot and parent wakes for Captain

- defineField/setField: typed fields only the owning plugin may write; a write
  bumps the task's updated_at.
- crewSnapshot({threadIds, changedSince}): one read of task, parent, fields,
  preset, live status and the last notifying comment with its delivery state.
- bb tasks comment --notify-parent sends a one-line wake to the commenting
  thread's parent and retries from the database (1, 2, 5, 15 min; 6 attempts),
  then marks it undeliverable; --attach puts files on the comment first.
- delegate takes reportContract and drops its built-in contract under stuck;
  taskThreadsAttach keeps presetName; plugin callers may author comments.
- Task threads get an archived live status that unarchive reverses.

* perf(scott-tasks): drop unused toolbar and command exports

Cuts 10 KB of app.css that Tailwind generated for components nothing imports.

* fix(scott-tasks): let the list's empty state fill the scroller

Port of get-bb/bb#7613's Tasks part: the list's size container moves inside the scroller, and the empty state grows to fill it.

* fix(scott-tasks): resolve CLI file paths with the target host's path rules

Port of get-bb/bb#6760: file flags resolve with the SDK's host-path parser, so Windows drive and UNC paths from a remote thread resolve on that machine instead of with the server's node:path.

* refactor(scott-tasks): drop store inputs nothing passes

Port of the Tasks part of get-bb/bb#4606: create inputs no longer take an id, comment updates take only notifiedCount, attachment updates only blobPath, and new comments rely on the column's 0 default. The tie-break test sets its ids with SQL, as upstream's does. Skipped: upstream blanking the is_image migration (it already ran here), and displayWidth and the description saver's schedule option, which fork tests still use.

* test(scott-tasks): cover list scope switches while reads are pending

Ports get-bb/bb#7056's regression tests. Upstream fixed a list stuck behind placeholders when it switched scope to a cached list; the fork's collection-backed list already passes them, so no code change was needed. All shows every task the shared collection holds, so the All step checks no absent row.

* fix(scott-tasks): apply resize-measured layout in the resize frame

Port of get-bb/bb#7635's Tasks part. The board-width check and the list's row window read their size in a shared ResizeObserver and write it inside flushSync, so a resize never paints one frame of the old layout. lib/shared-resize-observer.ts is vendored from upstream's registry, which the desktop-v0.49.0 pin predates. The row window measures through a plain function of the element so the mount read stays a ref-derived layout measurement.

* docs(scott-tasks): record the upstream sync to get-bb/bb 48c3a78

Names the new upstream base and every change the fork holds, with the reason for each.

* fix(scott-tasks): settle the list's scroll scope during render, not from a ref

ListView read settledScope.current during render, the one oxlint error left in scott-tasks (react(refs)), so bunx oxlint on the plugin failed. The settled scope is now state set during render, like the saved preference above it, and settles in the same render its rows finish loading.

* fix(scott-tasks): stop an expired wake attempt from sending after a retry

Promise.race ended the 30s wait but not the attempt, so a stalled thread lookup could resume after a retry had delivered and wake the parent twice. The deadline now aborts the attempt's signal, and the attempt re-checks right before threads.send (and before recording a target) that it is unexpired and still the latest claim on a pending record. Review's deterministic repro is the regression test; it fails on the old code.

* chore(scripts): prune the resolved scott-tasks list refs baseline entry
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