Skip to content

Speed up thread switching, resume, realtime, and composer - #4532

Closed
hemaaanth wants to merge 10 commits into
get-bb:mainfrom
hemaaanth:perf/ten-user-felt-speedups
Closed

hemaaanth wants to merge 10 commits into
get-bb:mainfrom
hemaaanth:perf/ten-user-felt-speedups

Conversation

@hemaaanth

Copy link
Copy Markdown
Contributor

Human comments

What was wrong

Opening a large thread, resuming a suspended tab, archiving, streaming, and typing all did more synchronous work or more network requests than the user action required. Timeline rows remounted or refetched, stale sockets waited for reconnection, realtime events invalidated broad caches, and composer work ran on unrelated renders.

What changed

  • Keep the timeline scroll body mounted across thread switches, render only the first visible window, prefetch thread data on navigation intent, and retain recent timelines for delta refreshes.
  • React immediately to archive/delete and thread creation while preserving server-side child confirmation and rolling back panes, navigation, and cached rows on failure or Undo.
  • Defer nonessential plugin boot until route content paints. Warm composer command and file suggestions without putting plugin draft/selection consumers on every typing render.
  • Probe resumed sockets, pace realtime cache invalidations, move costly sweeps off the active path, and push timeline deltas only to capable viewers of an armed timeline. Older browser/server peers continue to use HTTP updates.
  • Keep the current mainline's manual queued-draft behavior. The removed server draft-save API was not restored. No server/host-daemon wire fields changed; HOST_DAEMON_PROTOCOL_VERSION remains unchanged. No new CLI command or public SDK member was introduced.

How you verified

Performance

The measurements below were collected before the rebase, against baseline 4354b88ce14457fbdf1fc1a8e0db2dd4b5ef90f3. They are not measurements against the current PR base (0067c020591c1873edd4666b95fcfbee67c0a16e). Rebase conflict resolutions preserved current main's composer, runtime, and manual draft contracts. In particular, the old draft-save request measurement no longer applies. Each fix was tested alone on that older baseline, and the integrated variant was tested separately; fix 8 depends on fix 7c. Five browser runs per scenario, medians reported, seeded data with 1,200 threads, 100–150 ms simulated RTT, Chromium 140. Sub-noise gains are not claimed.

Fix / representative metric Older baseline Fix alone All fixes on older baseline
1. Large-thread switch, 1× 468 ms 358 ms 340 ms
2. Thread-open prefetch, switch at 100 ms RTT 531 ms 387 ms 310 ms
3. Reopen after 5.5 min 769 ms / 27 KB 609 ms / 1.1 KB 355 ms / 1.2 KB
4. Archive toast 428 ms 148 ms 145 ms
5. Cold-reload sidebar row 2,758 ms 2,329 ms 1,851 ms
6. Half-dead socket resume to fresh data 8,289 ms 223 ms 213 ms
7a. Idle sidebar refetches per minute 51 0 0
7b. Worst server stall 361 ms 94 ms 82 ms
7c. Typing delay p95 while streaming 27 ms 8.4 ms 12 ms
7d. Cold-reload timeline row at 4× 3,217 ms 3,078 ms 2,590 ms
8. Timeline GETs per stream (on 7c) 81 4 4
9. First / to provider commands, cold 654 ms 213 ms 246 ms
10. First thread key at 4× 222 ms 118 ms 125 ms

Other integrated older-base results: @file reaction 381 → 20 ms; delete dialog 334 → 111 ms; streaming line latency p95 677 → 384 ms. Approve and first diff patch were within measurement noise. The large-thread switch improved 1.4× at 1×, short of the original 2× target. No current-main browser benchmark was run after the rebase.

Correctness

  • pnpm exec turbo run typecheck lint build --filter=@bb/app --filter=@bb/server — 9/9 tasks pass; app lint has 0 errors and 210 warnings.
  • Complete app suite: 584 files passed, 2 skipped; 5,352 tests passed, 5 skipped. Targeted archive rollback, split-layout, composer subscription, and windowing tests also pass.
  • Native plugin loading tests: 3/3 pass without a concurrent full app run. Under simultaneous suites, one 5-second native import timed out.
  • Full server suite: 316 files passed, 3 failed, 3 skipped; five tests failed. The two systemd install tests and the UTC committer-date assertion also failed on the unchanged older baseline. The generator receives +00:00 from Git 2.39.5 while the test expects Z. A daemon-reconnect test and a native import timed out under parallel load; the reconnect test passed in a targeted rerun, and all three native loading tests passed when run alone. The server suite is not reported as green.
  • Rebased plugin checks: pnpm exec turbo run typecheck lint test --filter=bb-plugin-thread-list --filter=bb-plugin-scheduled-send — 12/12 tasks pass (9 cached); thread-list 470/470 tests and scheduled-send 24/24. Plugin lint has 0 errors (9 and 1 warnings, respectively). Older-base integrated verification also covered @bb/db, @bb/domain, @bb/server-contract, and @bb/process-utils.

🤖 Generated with Claude Code

AGENT GENERATED

hemaaanth and others added 10 commits September 29, 2026 23:56
Preload first-screen bundles without evaluating them ahead of the timeline. Reconcile plugin owners after both boot phases, protect local preference edits during hydration, and give thread routes a paint backstop.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Detect half-dead connections after a tab resumes and refresh active queries immediately. Cover initially hidden tabs and clear stale resume state when disconnected.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Avoid rendering every timeline row during switches, prefetch thread data on user intent, and retain timeline windows longer under a bounded cache. Test scroll anchors, prefetch races, and eviction.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Update archive, delete, create, and approval UI optimistically while keeping rollback and Undo intact. Close a pending delete dialog if its preflight is aborted.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Prefetch commands from deliberate editor intent, refine file suggestions in memory, and move draft updates off the per-key render path. Coalesce draft writes and preserve draft presence across sidebar mounts.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Invalidate compacted history only when needed, bound sweep work, and defer redundant thread view updates. Coalesce the initial connection wave after content paint.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Opt capable WebSocket viewers into timeline deltas after a timeline read. Bound pushes to recently viewed windows and keep HTTP refresh as the fallback for old clients or stale subscriptions.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Restore selective draft and selection updates for plugins that read them, while keeping unrelated plugin hooks off the typing path. Remove stale native-draft and reconnecting-state assumptions after the mainline rebase.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Preserve the prior layout and maximized pane until an archive or delete settles. Undo or failure restores them only when the layout has not changed since the optimistic close. Keep archive confirmation tests aligned with the authoritative child check.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
TanStack Virtual keeps a trailing scroll callback after unmount. Keep the jsdom environment alive through its debounce so the complete app suite does not report an uncaught callback after every test passes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Oct 1, 2026
## Human comments

## What was wrong

When a tab or phone resumes, its realtime socket is often half-dead:
still `OPEN` to the browser, but nothing arrives. The app only noticed
after the regular ping cycle and its 5 s pong timeout, then waited out
the reconnect backoff, so the first seconds after resume showed stale
threads.

## What changed

Split out of #4532 (commit 631124e, unchanged). Part 1 of 6.

- `apps/app/src/lib/ws.ts`: on becoming visible or coming back online,
probe the open socket with a 1.5 s pong timeout and reconnect at once if
it does not answer. Tabs that start hidden are tracked too. First
reconnect delay drops from 1 s to 250–500 ms (per-client jitter) with a
growth factor of 2 up to the same 30 s cap. An `online` event in a
hidden tab no longer probes.
- `apps/app/src/hooks/realtime-cache-effects.ts`,
`cache-owners/system-cache-effects.ts`: after a resume of at least 5 s
hidden, refetch the active timeline, thread and sidebar queries right
away instead of waiting for the socket verdict.

No server, host daemon or wire change. Known trade-off: on a link slower
than 1.5 s after wake, the probe reconnects a socket that would have
answered.

## How you verified

- `pnpm exec turbo run typecheck lint --filter=@bb/app`: pass (0 lint
errors).
- `vitest run src/lib/ws.test.ts
src/hooks/realtime-cache-effects.test.ts
src/hooks/system-cache-effects.test.ts`: 104/104 pass, including the new
resume probe, initially-hidden and stale-resume-state cases.
- Not re-measured on this base. #4532 measured half-dead socket resume
to fresh data at 8,289 ms → 223 ms on its older baseline. Not checked on
a real phone.

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

Co-authored-by: hemaaanth <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Oct 1, 2026
## Human comments

## What was wrong

The periodic provider lifecycle sweep started a sweep for every provider
environment in one synchronous pass, including rows that are permanently
parked on a provider-owner mismatch. On installs with many provider
environments that pass held the event loop.

## What changed

Split out of #4532 (the `environment-engine.ts` part of commit
9537a77, re-applied on current main). Part 2 of 6.

- `apps/server/src/services/environments/environment-engine.ts`:
`sweepProviderLifecycles` yields to the event loop after every 25
scheduled sweeps and between providers.
- `packages/db/src/data/environments.ts`:
`listProviderLifecycleEnvironments` excludes rows already marked failed
with the owner-mismatch message, with no owner thread and still owned by
a different plugin. Sweeping them was a no-op that wrote nothing. They
come back as soon as the owning plugin provides them again. (#4532
filtered these after loading; moved into the query after review.)

Not included from #4532: the event-loop stall log threshold change (500
ms → 250 ms). No wire change.

## How you verified

- `pnpm exec turbo run typecheck lint --filter=@bb/server
--filter=@bb/db`: pass.
- `vitest run test/query-plans.test.ts` in `packages/db`: 37/37 pass.
- `vitest run
test/services/environments/provider-orchestration.test.ts`: 64/64 pass,
including the new test that blocked rows are left untouched, a retryable
row is still removed, and a blocked row is picked up again once its
plugin provides it.
- Not re-measured on this base. #4532 reported worst server stall 361 ms
→ 94 ms for its combined server-stall work, of which this is one part.

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

---------

Co-authored-by: hemaaanth <[email protected]>
Co-authored-by: Claude Code <[email protected]>
SawyerHood added a commit that referenced this pull request Oct 1, 2026
## Human comments

## What was wrong

Event pruning and the output-retention sweeps announced their work as
`history-rewritten`. That change kind is broadcast to every connected
client and makes each one refetch thread lists, search, prompt history
and timelines, although compaction only changes stored event bodies.
Idle sidebars refetched continuously while sweeps ran.

Separately, compaction changes timeline rows without advancing the
thread's sequence. The timeline route computes `afterSequence` deltas
against the last rows it served at that sequence, so once one viewer
refetched, a second viewer at the same sequence got an empty delta and
kept the pre-compaction rows. This already happened on main.

## What changed

Split out of #4532 (the compaction part of commit 9537a77) plus a fix
for the second-viewer case. Part 3 of 6.

- `packages/domain/src/change-kinds.ts`: new thread change kind
`history-compacted`.
-
`apps/server/src/services/system/{event-pruning,periodic-sweeps,thread-pruning-sweep}.ts`:
emit `history-compacted` instead of `history-rewritten`; the pruning
sweep sends one notification per thread at the end of the sweep.
- `apps/server/src/ws/hub.ts`: a change that is only `history-compacted`
goes to that thread's detail subscribers, not to every client.
- `apps/app/src/hooks/cache-owners/realtime-cache-registry.ts`:
`history-compacted` refreshes only the thread's timeline window and its
loaded turn details (the second added after review; expired output
otherwise stayed visible in expanded turns).
- `apps/server/src/routes/threads/data.ts` (not in #4532): after a
rewrite or compaction, `afterSequence` requests at or below the sequence
current at that moment get a full window instead of a delta. Compaction
also clears the latest-rows cache as a rewrite does. The global
ordering-context cache is still cleared only for rewrites; its entries
are already keyed by the rewrite generation that pruning bumps.
- `docs/events-table-pruning.md` updated.

Compatibility: an already-open tab running the old bundle drops the
unknown kind (lenient parse) and simply does not refresh after a
compaction. No host daemon wire change. Not included from #4532: moving
`history-rewritten` from immediate to debounced, and invalidation
without cancelling in-flight fetches.

## How you verified

- `pnpm exec turbo run typecheck lint --filter=@bb/app
--filter=@bb/server --filter=@bb/domain`: pass (0 lint errors).
- Server: `vitest run test/system/thread-pruning-sweep.test.ts
test/system/event-pruning.test.ts test/services/periodic-sweeps.test.ts
test/app/hub.test.ts test/public/public-thread-timeline-delta.test.ts`:
51/51 pass.
- New test "answers every viewer of a compacted thread with a full
window at the unchanged sequence" fails without the route change (second
viewer receives `{ upsertRows: [] }`) and passes with it.
- App: `vitest run src/hooks/realtime-cache-effects.test.ts
src/hooks/cache-owners/cache-owner-registry.test.ts`: pass, including
the new test that compaction marks only the timeline and loaded turn
details stale. `@bb/domain` tests: 204/204.
- Not re-measured on this base. #4532 measured idle sidebar refetches at
51 → 0 per minute on its older baseline.

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

---------

Co-authored-by: hemaaanth <[email protected]>
Co-authored-by: Claude Code <[email protected]>
SawyerHood added a commit that referenced this pull request Oct 1, 2026
## Human comments

## What was wrong

Thread timeline and thread-detail bootstrap queries used React Query's
default five-minute cache lifetime. Coming back to a thread after a few
minutes threw away its cached rows and paid for a cold full-page
timeline load, even though the server can answer with a small
`afterSequence` delta when the client still has rows.

## What changed

Split out of #4532 (the retention part of commit dbcbfe1, re-applied
on current main). Part 4 of 6.

- `apps/app/src/hooks/cache-owners/thread-open-cache-owner.ts` (new):
keeps a per-QueryClient recency list of opened threads. Past 20 threads
(8 on coarse pointers) the least recently opened thread's inactive
timeline and bootstrap queries are removed. A thread still mounted in
another pane is never evicted. A deleted thread is dropped from the list
and its bootstrap query removed (added after review).
- `apps/app/src/hooks/queries/thread-queries.ts`: the timeline and
bootstrap queries are kept for one hour after unmount, and
`useThreadTimeline` touches its thread on mount.

Reopening a retained thread shows its cached rows immediately and
refreshes them through the delta read main already has. A cached
bootstrap still triggers the existing `refetchOnMount: "always"` thread
read. Trade-off: rows up to an hour old are visible for one request
round trip.

Not included from #4532: prefetch on hover or focus, keeping the scroll
body mounted, first-window rendering, and timeline push over the socket.
No server change.

## How you verified

- `pnpm exec turbo run typecheck lint --filter=@bb/app`: pass (0 lint
errors).
- `vitest run src/hooks/queries/thread-queries.test.tsx
src/hooks/cache-owners/cache-owner-registry.test.ts`: 34/34 pass. Six
tests are new: a deleted thread frees its slot (fails without the fix),
hour-long retention, eviction past the cap, keeping a thread open in
another pane, the smaller cap on touch devices, and reopening a retained
timeline with a delta from its cached sequence. The other five fail with
main's `thread-queries.ts` restored.
- Full `@bb/app` suite at concurrency 1: 5,180 passed, 3 failed
(`ToolsView.plugin-detail`, `CommandPalette.cold-open`,
`CommandPalette`). Each of those files passes when run alone on this
branch and none touch the changed code; they were not run on clean main.
- Not re-measured on this base. #4532 measured reopen after 5.5 minutes
at 769 ms / 27 KB → 609 ms / 1.1 KB on its older baseline.

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

---------

Co-authored-by: hemaaanth <[email protected]>
Co-authored-by: Claude Code <[email protected]>
SawyerHood added a commit that referenced this pull request Oct 1, 2026
## Human comments

## What was wrong

`usePromptDraftStorage` returned the live draft, so every component that
needed any draft operation re-rendered on each keystroke: the composers,
the plugin composer host with its banners and actions, and, through
draft-presence ids threaded into the group builders, the sidebar tree.
`useComposer()` subscribed every plugin composer contribution to draft
and selection changes whether or not it read them.

## What changed

Split out of #4532 (commits 087cbc3 and aab5c06 together, applied
on current main). Part 6 of 6. Independent of the suggestion warm-up PR;
the two merge cleanly.

- `apps/app/src/hooks/usePromptDraftStorage.ts`: a stable
`usePromptDraftController` plus opt-in `usePromptDraftSnapshot` and
`usePromptDraftInputEmpty`. Debounce, flush on
`pagehide`/`visibilitychange`, the cross-tab `storage` listener,
`clearIfCurrentMatches` and `restoreIfEmpty` are unchanged.
- `apps/app/src/components/plugin/plugin-composer-host.tsx`,
`PluginComposerBanners.tsx`, `PluginComposerActions.tsx`,
`promptbox/PromptBoxActionsMenu.tsx`: static scope/layout/run view split
from the draft context; banner rows and the action list are memoized.
- `apps/app/src/lib/plugin-sdk-hooks.ts`: `useComposer()` subscribes to
the draft only once the caller reads `text`, `draft`, `isEmpty` or
`attachmentCount`, and to selection only once it reads `selection`.
Returned values are unchanged and no public SDK member is added.
- `apps/app/src/components/promptbox/NewThreadComposer.tsx`: only
`LiveDraftNewThreadPromptBox` follows the live draft.
- `plugins/thread-list`: collapsed rows read draft presence from one
published draft-id set (`list/sidebarDraftPresence.ts`) instead of a
`draftThreadIds` argument through every group builder.

Not included from #4532: the re-added `addQuote` (removed on main in
#4474 and unused), the `ThreadDetailPromptArea` memo (needs stable props
from another commit), and the scheduled-send formatter caching.

Review note: lazy tracking writes two refs during the plugin's render,
which adds one `react(refs)` lint warning at `plugin-sdk-hooks.ts`. A
draft change between the render that first reads a field and its commit
is seen on the following change.

## How you verified

- `pnpm exec turbo run typecheck lint --filter=@bb/app
--filter=bb-plugin-thread-list`: pass, 0 lint errors (app warnings 208
vs 207 on main, the one above).
- `pnpm exec turbo run test --filter=@bb/app
--filter=bb-plugin-thread-list --concurrency=1`: `@bb/app` 5,185 passed,
6 skipped; thread-list 443/443.
- Two new tests in `plugin-slot-mounts.test.tsx`: a plugin that starts
reading `text`/`isEmpty` only after a local toggle keeps updating, and a
plugin that reads only `useComposer().selection` re-renders on picker
changes. Both fail with tracking disabled (the state of 087cbc3
alone).
- Not re-measured on this base. #4532 measured the first thread
keystroke at 4× CPU throttle at 222 ms → 118 ms on its older baseline.

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

Co-authored-by: hemaaanth <[email protected]>
Co-authored-by: Claude Code <[email protected]>
@SawyerHood SawyerHood closed this Oct 1, 2026
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.

2 participants