Skip to content

Tune realtime invalidations: PR key, work-status debounce, branch list, send path, search, archived (B8, K5, B14, B15, B17, B18, B24) - #1882

Merged
SawyerHood merged 4 commits into
bb/mobile-perf/secondary-panel-gatingfrom
bb/mobile-perf/invalidation-tuning
Aug 19, 2026
Merged

SawyerHood merged 4 commits into
bb/mobile-perf/secondary-panel-gatingfrom
bb/mobile-perf/invalidation-tuning

Conversation

@SawyerHood

@SawyerHood SawyerHood commented Aug 19, 2026 •

Copy link
Copy Markdown
Collaborator

What was wrong

Realtime and query policies on the client did more network and git work than the UI needed, which is expensive on phones and through bb connect:

  • work-status-changed fired on every file-change burst. It refetched (and aborted) the in-flight git status probe every flush and also refetched the pull request, which a local edit cannot change. The PR query itself refetched on every focus ("always") and polled every 5 s while checks were pending; each lookup spawns gh pr view.
  • The root-compose branch list (a daemon git RPC) went stale after 5 s and refetched on every foreground.
  • After a send succeeded, the client prepended the prompt-history entry locally and then invalidated the same query; it also refetched default execution options that consumers read only as initial values, and a queued send refetched thread detail although queue-changed arrives over realtime.
  • Every events-appended flush from any thread invalidated (cancelling) the open thread search and ran the timeline pacing machinery for threads nobody was viewing.
  • Every status/title/environment change refetched every open archived settings page (100-row un-windowed pages).

What changed

  • PR query: refetchOnWindowFocus: true, 30 s pending-check poll, PR key dropped from the work-status handler. turn/completed and the poll keep it current.
  • Branch list: REALTIME_OWNED_NO_FOCUS_QUERY_POLICY + 30 s stale; picker open still refetches. Removed the now-unused FAST_FOCUS_OWNED_LIVE_QUERY_POLICY.
  • Work status: marked stale immediately, active observers refetched at most once per second per environment with cancelRefetch: false; changes inside the interval coalesce into one trailing refetch; timers cleared on dispose.
  • Send success: prompt history is prepended locally on both paths, default-exec marked stale with refetchType: "none", queued sends refetch only the queue list while realtime is connected. History rewrites still refetch prompt history explicitly.
  • Search: goes stale only when a batch contains turn/completed, once per flush (flushOnce on ThreadRealtimeDirtyContext), with cancelRefetch: false.
  • Timelines without an active observer are only marked stale (refetchType: "none").
  • Archived list keys are marked stale, not refetched, by status/title/environment handlers (dirtyActiveThreadListQueries); archived-changed still refetches. Archived page size 100 -> 50.

How you verified

  • pnpm exec turbo run typecheck --filter=@bb/app and pnpm exec turbo run lint --filter=@bb/app pass (lint: 0 errors, pre-existing warnings only).
  • New tests fail on origin/main and pass on this branch (verified by stashing the source changes):
    • apps/app/src/hooks/realtime-cache-effects.test.ts: search invalidated only on turn/completed; once per flush without aborting the in-flight search; unviewed timeline marked stale with refetchType: "none" while the viewed one refetches; archived lists not refetched on status/title but refetched on archived-changed; PR not refetched on work-status-changed; work-status refetch paced to one per second without aborting the probe.
    • apps/app/src/hooks/cache-owners/thread-runtime-cache-owner.test.ts: accepted send keeps prompt history local and only marks default-exec stale; queued send refetches only the queue list.
    • apps/app/src/hooks/queries/project-queries.test.tsx: branch list has no focus refetch and 30 s stale.
    • apps/app/src/hooks/queries/environment-queries.test.tsx: updated for refetchOnWindowFocus: true and 30 s poll.
  • pnpm exec turbo run test --filter=@bb/app -- src/hooks src/components/settings src/views/thread-detail src/components/thread/timeline src/components/promptbox src/lib/query-client: 134 files, 1018 tests pass.

Fixes: part of the mobile / iOS Safari performance program (verified sweep report in the bb thread; no single issue).

Stack context

Layer 3 of 22 in the bb/mobile-perf/* stack (bottom → top: quick wins first, big rocks last).

  • Prerequisite (layer below): bb/mobile-perf/secondary-panel-gating (Gate closed secondary-panel diff queries and keep the compact terminal mounted (G1, G4) #1881).
  • Next layer: bb/mobile-perf/ws-liveness-and-resume (Add WebSocket ping/pong, reconnect watermark and visibility-gated realtime flushes (B2, B3, B4) #1883).
  • Audit findings addressed: see title IDs. Review: approved-with-fixes; 1 review fix commit(s).
  • Reviewer notes / follow-ups: Client-side only: the PR query is no longer refreshed by any realtime signal other than turn/completed (git-refs-changed does not touch it, and it never did). A PR created/pushed f | Archived settings pages go stale (not refetched) on status/title/environment changes until the settings route remounts or a focus refetch; archived-changed still refetches. Accepte | K5 is a leading-edge throttle with a coalesced trailing refetch (first change after a quiet period refetches immediately) rather than a pure 1 s debounce; the trailing refetch sche
  • Wire/contract: None. All changes are client-side (apps/app) query policy and cache-invalidation behavior; no server routes, host daemon RPCs, WebSocket messages, or session payloads changed, so HOST_DAEMON_PROTOCOL_VERSION is unchanged.

AGENT GENERATED: by Claude Opus 5

@SawyerHood SawyerHood changed the title bb/mobile perf/invalidation tuning Tune realtime invalidations: PR key, work-status debounce, branch list, send path, search, archived (B8, K5, B14, B15, B17, B18, B24) Aug 19, 2026
@SawyerHood
SawyerHood marked this pull request as ready for review August 19, 2026 08:04
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/invalidation-tuning branch from 2d9a6db to bb1d3d0 Compare August 19, 2026 15:59
SawyerHood and others added 4 commits August 19, 2026 16:03
Each pull-request lookup spawns `gh pr view` on the host and each branch
list is a daemon git RPC (throttled fetch plus several git commands).
The PR query refetched on every window focus (`"always"`) and polled every
5 s while checks were pending; the root-compose branch list used the 5 s
FAST_FOCUS_OWNED policy and refetched on every foreground. On a phone that
is a subprocess per app switch for data that rarely changes.

- PR query: `refetchOnWindowFocus: true` (only when stale) and a 30 s
  pending-check poll.
- Branch list: 30 s stale, no focus refetch. Realtime
  `project-sources-changed` and the picker's open-refetch keep it current.
  FAST_FOCUS_OWNED_LIVE_QUERY_POLICY had no other users and is removed.

Co-Authored-By: Claude <[email protected]>
After a send was accepted the client prepended the prompt-history entry
locally and then invalidated the same query, and it refetched the thread's
default execution options even though consumers only read them as initial
values. A queued send refetched thread detail, the queue and prompt
history although `queue-changed` arrives over realtime.

- Accepted send: prepend prompt history locally (unchanged), mark default
  execution options stale with `refetchType: "none"`, no prompt-history
  refetch. The no-realtime path keeps its detail/timeline/list refetches.
- Queued send: prepend the prompt-history entry locally and refetch only
  the queue list while realtime is connected; fall back to the full queue
  invalidation when it is not.
- History rewrites (edit/fork/retry) still refetch prompt history
  explicitly, since a rewrite can drop or reorder prompts.

Co-Authored-By: Claude <[email protected]>
Every client's thread-list subscription receives every streaming thread's
`events-appended` batches, and every file edit sends `work-status-changed`.
The registry turned those into work that mostly benefits nobody on a phone:

- Search was invalidated (cancelling the request in flight) on every
  50-100 ms flush from any thread; on a slow link the open search could be
  aborted forever. It now goes stale only on `turn/completed`, once per
  flush, with `cancelRefetch: false`.
- Timelines of unviewed threads went through the fetch pacing/cancel
  machinery. Without an active timeline observer they are now only marked
  stale (`refetchType: "none"`) so a remount refetches.
- `work-status-changed` refetched (and aborted) the work-status probe on
  every burst and also refetched the pull request, which a local edit
  cannot change. Work status is now marked stale immediately and refetched
  at most once per second per environment without cancelling the probe in
  flight (changes inside the interval coalesce into one trailing refetch);
  the PR key is no longer touched (turn/completed and the check poll cover
  it).
- Status/title/environment changes refetched every open archived settings
  page. Archived list keys are now only marked stale by those handlers;
  `archived-changed` still refetches them. Archived page size drops from
  100 to 50 rows.

`ThreadRealtimeDirtyContext` gains `flushOnce` so global handlers can run
once per flush of batched thread changes.

Co-Authored-By: Claude <[email protected]>
The comments claimed the realtime queue-changed handler refreshes the
thread record; it only refetches the queue list and prompt history. The
thread detail refetch was dropped because an enqueue never writes the
thread row, so state the actual reason.

Co-Authored-By: Claude <[email protected]>
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/invalidation-tuning branch from bb1d3d0 to 7b0ef3d Compare August 19, 2026 16:13
@SawyerHood
SawyerHood merged commit 69f049b into main Aug 19, 2026
12 checks passed
@SawyerHood
SawyerHood deleted the bb/mobile-perf/invalidation-tuning branch August 19, 2026 16:23
SawyerHood added a commit that referenced this pull request Aug 19, 2026
…l mounted (G1, G4) (#1881)

## What was wrong

The secondary panel keeps its content mounted while closed so the next
open is instant (compact drawers retain the panel off-screen; desktop
keeps the subtree). But its data stayed live: the diff tab TOC query,
the toolbar's shared TOC observer, visible-row patch requests, and every
file-preview query kept running behind a closed panel. Each workspace
write emits `work-status-changed`, which invalidates the diff TOC and
previews and evicts the patch cache, so a hidden panel refetched the
TOC, re-requested patches, and remounted the highlighted preview on
every fs event (audit G1). Terminals were gated on `isPanelOpen`, but on
compact that meant every drawer close disposed xterm and its socket, and
every reopen re-created xterm/WebGL and replayed up to the full
scrollback (audit G4).

## What changed

- `ThreadSecondaryPanel` derives `isDiffPanelLive = isDiffPanelActive &&
isLayoutOpen` and uses it for the toolbar TOC observer and the
diff-target work-status query.
- `GitDiffTabContent` and `DiffFilesPanel` take `isPanelOpen`. The TOC
query is enabled only while the panel is open. `requestPaths` is skipped
while closed and re-fires for the current visible set on reopen (dedupes
against the cache).
- Workspace / project / host / thread-storage preview tab bodies take
`isPanelOpen` and pass `enabled` to their preview queries.
`ThreadDetailView` and `RootComposeView` pass `isSecondaryPanelOpen`.
The DOM stays mounted; an invalidated query refetches once on reopen.
- Terminal controller exposes `shouldMountTerminalView = isPanelOpen ||
(isPanelPersistedOpen && hasPanelOpened)`. `ThreadTerminalContent`
mounts on it. A compact drawer close keeps an already-mounted terminal
alive; a persisted-open tab synced from another device does not start
xterm on a phone that never opened the drawer; closing the persisted
panel releases the view. Desktop is unchanged (`isPanelOpen ===
isPanelPersistedOpen`).

## How you verified

- New `ThreadSecondaryPanelTabContent.panelGate.test.tsx`: with the real
query hooks and a mocked sdk, the diff TOC and workspace preview do not
fetch while `isPanelOpen` is false, do not refetch after
`invalidateQueries` while closed, and refetch exactly once on reopen.
Fails before, passes after.
- New `useThreadTerminalController.mount.test.tsx` and extended
`ThreadTerminalContent.test.tsx`: view is retained (same DOM node)
across a hidden-but-persisted panel, unmounts when persisted state
closes, and never mounts for a persisted-open panel this client has not
shown. Fail before, pass after.
- `pnpm exec turbo run typecheck --filter=@bb/app`, `pnpm exec turbo run
lint --filter=@bb/app` (147 warnings, same as baseline, 0 errors),
targeted vitest for `src/components/secondary-panel`,
`src/components/thread/terminal`, `src/views/thread-detail`,
`src/views/RootComposeView` (50 files, 408 tests pass).

Fixes: part of the mobile / iOS Safari performance program (verified
sweep report in the bb thread; no single issue).


## Stack context

Layer 2 of 22 in the `bb/mobile-perf/*` stack (bottom → top: quick wins
first, big rocks last).
- Prerequisite (layer below): `bb/mobile-perf/css-paint-ios` (#1880).
- Next layer: `bb/mobile-perf/invalidation-tuning` (#1882).
- Audit findings addressed: see title IDs. Review: approved.
- Deliberately not done here: G4 optional 'smaller replay tail for
compact clients': not done. It requires a client hint on the terminal
WebSocket URL plus server/daemon handling (wire chang
- Reviewer notes / follow-ups: Minor test gap (not blocking):
DiffFilesPanel's `requestPaths` early-return while `isPanelOpen ===
false` and its re-fire on reopen is untested; no existing jsdom harness
renders D | Trade-off to be aware of (by design, per G4): on compact a
hidden-but-persisted terminal keeps its WebSocket and xterm/WebGL
context alive off-screen while the drawer is closed; xt
- Wire/contract: None. No server, daemon, protocol, CLI, config, or
plugin API changes. HOST_DAEMON_PROTOCOL_VERSION untouched.

> AGENT GENERATED: by Claude Code (claude-mangosteen-eap)

---------

Co-authored-by: Claude <[email protected]>
SawyerHood added a commit that referenced this pull request Aug 19, 2026
…ltime flushes (B2, B3, B4) (#1883)

## What was wrong

- The realtime WebSocket had no liveness probe. Browsers cannot send
WebSocket pings and the server never pinged browser sockets, so a
half-open socket (Wi-Fi/LTE switch, iOS background suspend, tunnel
hiccup) stayed OPEN and silent. The app showed stale data with a green
connection badge, and refetch fallbacks gated on "connected" never
fired. After a drop, partysocket's backoff (up to 30 s) ran even when
the browser had just reported the tab visible or the network online.
(B3)
- On a phone every app switch reconnects the socket. The reconnect wave
invalidated ~30 query prefixes with the default `cancelRefetch: true`,
which aborted partially downloaded responses, and a separate
browser-resume wave had just invalidated the 8-key active thread bundle.
Each foreground cost two overlapping waves. (B2)
- Realtime change events flushed while the document was hidden, so
`invalidateQueries` refetched every active observer nobody could see.
(B4)

## What changed

- `@bb/domain` / `@bb/server-contract`: `ping` client message and `pong`
server message. `apps/server/src/ws/client-protocol.ts` answers a ping
with a pong on the same socket only. Browser-server only;
`HOST_DAEMON_PROTOCOL_VERSION` is unchanged because
`clientMessageSchema` is not on the daemon wire.
- `apps/app/src/lib/ws.ts`: pings every 25 s while visible (skipped when
a frame arrived in the last 5 s), treats any inbound frame as liveness,
and forces a reconnect when a probe gets no answer within 5 s. On
visibilitychange/pageshow/focus and `online`: a closed socket reconnects
immediately (`reconnectNow()` replaces the partysocket instance because
`reconnect()` is a no-op while a backoff wait holds its lock), an OPEN
socket is probed, an attempt in flight is left alone. Hidden documents
send nothing. The onopen event carries `disconnectedAt` for reconnects
(close time, or last inbound frame when a probe failed).
- `system-cache-effects.ts`:
`invalidateRealtimeQueriesAfterServerReconnect({ disconnectedAt })`
invalidates only queries with `dataUpdatedAt < disconnectedAt`
(errored/never-loaded queries have 0 and are included) with
`cancelRefetch: false`. System version re-check and diff-patch eviction
are kept.
- `realtime-cache-effects.ts`: while hidden, thread, environment, host,
project and system changes are merged (deduplicated) and applied as one
wave on the next visible; a debounce that elapses hidden is held.
- `query-client.ts`: the browser-resume active-thread-bundle
invalidation is removed and `active-thread-lifecycle-cache-owner.ts` is
deleted. The realtime layer now owns catch-up: immediate reconnect or
probe on visible, watermarked reconnect wave, hidden-merged flush.
Suspend still cancels in-flight fetches.

## How you verified

- `pnpm exec turbo run typecheck --filter=@bb/domain
--filter=@bb/server-contract --filter=@bb/server --filter=@bb/app
--filter=@bb/sdk --filter=@bb/cli`: pass.
- `pnpm exec turbo run lint --filter=@bb/app` (and the other changed
packages): 0 errors, only pre-existing warnings in unrelated files.
- `pnpm exec turbo run test --filter=@bb/server --
test/app/client-protocol.test.ts`: 9 passed (new: ping answered with
pong on the same socket only).
- `pnpm exec turbo run test --filter=@bb/app -- src/lib/ws.test.ts
src/lib/ws.plugin-signal.test.ts src/hooks/system-cache-effects.test.ts
src/hooks/realtime-cache-effects.test.ts src/lib/query-client.test.ts
src/hooks/cache-owners/cache-owner-registry.test.ts
src/hooks/environment-cache-effects.test.ts
src/hooks/cache-owners/environment-workspace-cache-owner.test.ts
src/hooks/mutations/thread-runtime-mutations.test.tsx
src/hooks/cache-owners/thread-runtime-cache-owner.test.ts
src/lib/system-config-atoms.local-access.test.ts
src/views/thread-detail/SplitThreadArea.test.tsx
src/components/dialogs/AddMachineDialog.test.tsx
src/components/settings/MachinesSettingsSection.test.tsx
src/views/MachineSettingsView.test.tsx`: 15 files, 160 tests passed.
- New tests: ws liveness (interval ping, pong/any-frame clears probe,
no-pong reconnect with last-activity watermark, no pings while hidden
and one probe on visible, immediate reconnect on visible/online when
closed, subscriptions re-sent on the replacement socket); reconnect
watermark predicate with a real QueryClient (stale invalidated, fresh
left alone, in-flight fetch not cancelled, errored query refetched);
hidden-flush gating (thread status/events merged and flushed once on
visible; debounce elapsing hidden, environment/host/system changes held
until visible); handleConnected passes the watermark.

Fixes: part of the mobile / iOS Safari performance program (verified
sweep report in the bb thread; no single issue).


## Stack context

Layer 4 of 22 in the `bb/mobile-perf/*` stack (bottom → top: quick wins
first, big rocks last).
- Prerequisite (layer below): `bb/mobile-perf/invalidation-tuning`
(#1882).
- Next layer: `bb/mobile-perf/thread-open-query-gating-review` (#1884).
- Audit findings addressed: see title IDs. Review: approved-with-fixes;
2 review fix commit(s).
- Reviewer notes / follow-ups: Reconnect wave
(invalidateRealtimeQueriesAfterServerReconnect) is still not
visibility-gated: a hidden desktop tab that reconnects after a server
restart refetches ~30 prefixes whi | Zombie-socket iOS resume: NO_FOCUS
realtime-owned queries (pending interactions, default execution options,
sidebar) catch up only after the 5 s pong timeout + reconnect; useThread
| Watermark heuristic (dataUpdatedAt < disconnectedAt,
cancelRefetch:false) can keep a fetch that started before the socket
died and resolved after; self-heals on the next change (im |
system-config-atoms.ts still refetches config on every reconnect
(unchanged, flagged by implementer).
- Wire/contract: Browser<->server WebSocket only: new client message
{type:"ping"} added to clientMessageSchema (packages/domain), new server
message {type:"pong"} (pongMessageSchema strict,
pongMessageLenientSchema for clients), both re-exported from
@bb/server-contract. Not on the host-daemon wire (clientMessageSchema is
used only by apps/server/src/ws/client-protocol.ts and
apps/app/src/lib/ws.ts), so HOST_DAEM

> AGENT GENERATED: by Claude Code (claude-mangosteen-eap)

---------

Co-authored-by: Claude <[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