Repository navigation
Add WebSocket ping/pong, reconnect watermark and visibility-gated realtime flushes (B2, B3, B4) - #1883
Merged
SawyerHood merged 6 commits intoAug 19, 2026
Conversation
SawyerHood
marked this pull request as ready for review
August 19, 2026 08:04
SawyerHood
force-pushed
the
bb/mobile-perf/ws-liveness-and-resume
branch
from
August 19, 2026 15:59
6edb892 to
b5fd08c
Compare
Browsers cannot send WebSocket-level pings, and the server never pings browser sockets, so a half-open realtime socket (Wi-Fi/LTE switch, iOS background suspend, tunnel hiccup) stays OPEN and silent forever. The app then sits on stale data behind a green connection badge, and the refetch fallbacks that gate on "connected" never fire. Add a `ping` client message to `clientMessageSchema` and a strict `pong` server message (plus a lenient inbound counterpart) in @bb/domain, re-exported from @bb/server-contract. The server answers a ping with a pong on the same socket only; nothing is broadcast and no state changes. This is browser <-> server only. `clientMessageSchema` is not used on the host-daemon wire, so HOST_DAEMON_PROTOCOL_VERSION is unchanged. Co-Authored-By: Claude <[email protected]>
`WebSocketManager` only handled onopen/onmessage/onclose. A dead but OPEN socket was never detected, and after a drop partysocket's backoff (up to 30 s) ran even when the browser had just told us the network was back or the tab was visible again. While the document is visible the manager now sends `ping` every 25 s (skipped when a frame arrived within the last 5 s) and treats any inbound frame as proof of life; a probe with no answer within 5 s forces a reconnect. On visibilitychange/pageshow/focus and on `online`, a closed socket reconnects immediately, an OPEN one is probed, and an attempt in flight is left alone. Hidden documents send nothing. `reconnectNow()` replaces the partysocket instance instead of calling `reconnect()`, which is a no-op while a backoff wait holds its connect lock. The onopen event now carries `disconnectedAt` for reconnects: the close time for a natural close, or the last inbound frame for a socket that failed its probe, so reconnect catch-up can use it as a watermark. Co-Authored-By: Claude <[email protected]>
On a phone every app switch reconnects the socket. The reconnect wave invalidated ~30 query prefixes with the default cancelRefetch, aborting partially downloaded responses, and a separate browser-resume wave had just invalidated the active thread bundle, so each foreground cost two overlapping waves. Realtime change events also flushed while the tab was hidden, refetching every active observer nobody could see. - `invalidateRealtimeQueriesAfterServerReconnect` takes `disconnectedAt` and, like the initial-connect path, only invalidates queries whose `dataUpdatedAt` predates it (errored/never-loaded queries have 0 and are included), with `cancelRefetch: false` so in-flight fetches keep going. The system version re-check and diff-patch eviction are kept. - `createRealtimeCacheEffects` merges thread, environment, host, project and system changes while the document is hidden and applies them as one wave on the next visible; a debounce that elapses hidden is held. - The browser-resume invalidation of the active thread bundle is removed: the realtime layer now owns catch-up (immediate reconnect or probe on visible, watermarked reconnect wave, hidden-merged flush), so the bundle wave only duplicated it. Suspend still cancels fetches. Co-Authored-By: Claude <[email protected]>
…eout On iOS resume the visibility handler typically fires first and sends the liveness ping; the browser then reports the socket close a moment later. onclose only recorded the loss and let partysocket wait out its first 1 s backoff, and it watermarked the loss at the close time even though the unanswered probe already proved the socket was dead before the ping. When a close arrives while a probe is outstanding, replace the socket right away (same path as a probe timeout) and watermark from the last inbound frame. Co-Authored-By: Claude <[email protected]>
Removing the browser-resume bundle invalidation left a hole: the suspend handler still cancels every in-flight fetch with revert, which puts a first load back to pending/idle with no data. A realtime-owned query with refetchOnWindowFocus: false (thread default execution options, pending interactions) then had nothing that restarted it while the socket stayed healthy: no focus refetch, no realtime change for it, no reconnect wave. Open a thread, switch tab/app while the 1-3 s execution-options probe is in flight, come back: the composer stayed on its loading gate until the next mount. Remember the queries cancelled at suspend and refetch exactly those on resume (cancelRefetch: false, so a fetch already restarted by a focus refetch or realtime flush is reused). Settled queries are untouched, so this does not bring the resume wave back. Co-Authored-By: Claude <[email protected]>
The realtime ping/pong message kinds land in @bb/domain, which the published @get-bb/plugin-sdk bundles (dist/provider-bridge.js and bundled types). The npm version guard refuses content drift under an already published version, so the SDK version moves with the first layer of the mobile performance stack that changes it. Co-Authored-By: Claude <[email protected]>
SawyerHood
force-pushed
the
bb/mobile-perf/ws-liveness-and-resume
branch
from
August 19, 2026 16:13
b5fd08c to
450af53
Compare
SawyerHood
added a commit
that referenced
this pull request
Aug 19, 2026
…t, send path, search, archived (B8, K5, B14, B15, B17, B18, B24) (#1882) ## 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` (#1881). - Next layer: `bb/mobile-perf/ws-liveness-and-resume` (#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 Code (claude-mangosteen-eap) --------- Co-authored-by: Claude <[email protected]>
SawyerHood
added a commit
that referenced
this pull request
Aug 19, 2026
…13, B16, C5) (#1884) ## What was wrong Opening a thread on a phone issued ~17 requests. Several of them served surfaces that were not on screen: the thread-storage file list (`host.list_files`, limit 1000) for the secondary panel, the forks list for the info tab, 50 full prompt-history entries that only ArrowUp consumes, a child-thread subset that the sidebar bootstrap already holds, a duplicate `GET /threads?projectId=` for worktree-reuse options, and a 200-thread `@`-mention candidate list that duplicates the sidebar cache. The first timeline window also always used the 20-segment server default on a 390 px viewport (B9, B10, B11, B12, B13, B16, C5). ## What changed - The thread-storage file list loads only while the secondary panel is open or a storage tab exists. - The child-thread subset and the `@`-mention candidates derive from the cached sidebar bootstrap (via `select` with structural sharing) and fall back to the network only when the project is absent from the cache. On cold deep-link opens the hooks wait for the in-flight bootstrap instead of racing it. - The forks list query is enabled only while the secondary panel is open. - Prompt history (thread and project) is enabled on fine pointers, or on coarse pointers after the first non-IME keydown, so iPad + keyboard still works. - The worktree-reuse options in the new-thread composer derive from the sidebar bootstrap the composer already observes. - The `/` command catalog is prefetched on the first composer focus on coarse pointers (`retry: false`). - Compact viewports request `segmentLimit=8` for the first timeline window and on the full-refetch path; the server timeline cache is keyed by segment limit so deltas keep working. ## How you verified - New tests: query gates (enabled/disabled per surface), fallback vs derived child/mention lists, in-flight bootstrap wait, viewport-dependent `segmentLimit` including the delta path, IME handling for the keyboard-seen flag, focus-time command prefetch (coarse) vs none (fine). - `pnpm exec turbo run typecheck --filter=@bb/app`, `pnpm exec turbo run lint --filter=@bb/app`, targeted `pnpm exec turbo run test --filter=@bb/app -- src/hooks/queries src/components/promptbox src/views/thread-detail`. - Measured on the seeded perf fixture at 390 px: thread-open API requests 17 → 8 (with the other layers of this stack). Fixes: part of the mobile / iOS Safari performance program (verified sweep report in the bb thread; no single issue). ## Stack context Layer 5 of 22 in the `bb/mobile-perf/*` stack (bottom → top: quick wins first, big rocks last). - Prerequisite (layer below): `bb/mobile-perf/ws-liveness-and-resume` (#1883). - Next layer: `bb/mobile-perf/list-models-cache` (#1885). - Audit findings addressed: see title IDs. Review: approved-with-fixes; 2 review fix commit(s). - Reviewer notes / follow-ups: The requested branch bb/mobile-perf/thread-open-query-gating is checked out in worktree /home/sawyer/projects/bb/.claude/worktrees/wf_dec7ce2a-e37-8 and still points at dde6cdd w | B16 prefetch nuance (not a bug): useProjectCommands keeps staleTime 0, so on coarse-pointer devices the first '/' still issues a background refetch after the focus-time prefetch. T | B12 nuance (by design, matches the audit's proposed fix): on an iPad with a hardware keyboard the very first keydown enables the prompt-history fetch, so an ArrowUp pressed as the | Derived child/mention lists depend on the sidebar bootstrap being kept fresh by another active observer (AppLayout's useSidebarNavigation, always mounted). If a sibling package (e. > AGENT GENERATED: by Claude Code (claude-mangosteen-eap) --------- Co-authored-by: Sawyer Hood <[email protected]> Co-authored-by: Claude <[email protected]>
ymichael
added a commit
that referenced
this pull request
Sep 21, 2026
## Human comments ## What was wrong Backgrounding the app on a phone kills the realtime socket. Recovery runs through `invalidateRealtimeQueriesAfterServerReconnect`, which refetches any realtime-owned query whose `dataUpdatedAt` predates `disconnectedAt`. Two independent defects stopped that from happening, so a thread that finished while the app was backgrounded kept spinning in the sidebar indefinitely. `setQueryData` always stamps `dataUpdatedAt` with the write time, so the local cache patches that realtime pushes apply (#2169) moved the sidebar's watermark forward. `disconnectedAt` is always pinned at or before the moment the page resumes — the app cannot notice the drop while suspended — while the hidden-change flush stamps the sidebar at resume time. The strict comparison therefore always failed and the catch-up fetch was skipped. The skip required that patches landed during the gap, which required that a thread was running: the wave was suppressed precisely when it was needed. Separately, `probeOrReconnect` took ~30s rather than 5s to notice the dead socket. `sendPing` skips the probe when a frame arrived within `REALTIME_PONG_TIMEOUT_MS`, but `lastServerActivityAt` records when the app *read* the bytes, not when they crossed the network. On resume the OS delivers everything it buffered during the freeze, so the guard saw fresh activity from stale data and suppressed the very probe that exists for that transition, deferring detection to the next 25s interval tick. ## What changed `cache-owners/cache-effect-utils.ts`: `patchCachedQueryData` writes cache patches without advancing `dataUpdatedAt`, keeping that timestamp meaning "when this data last came from the server" as the reconnect watermark assumes. `query-cache.ts`, `thread-list-cache-data.ts` and `project-cache-owner.ts` route the sidebar navigation, thread list and timeline patch helpers through it, which covers the realtime and optimistic-mutation writers that funnel through them. Status pushes still patch one row instead of refetching the bootstrap document, so #2169's optimization is unaffected. `lib/ws.ts`: `probeOrReconnect` passes `ignoreRecentActivity`, since frame recency is only evidence of liveness if the page was awake for that window. The 25s interval keeps the guard. `lib/ws.ts`: only a `pong` now clears an outstanding probe. Frames are ordered on one connection, so a frame the server sent after our ping cannot overtake the pong; a non-pong frame arriving with the probe still outstanding was therefore sent before the ping landed and proves nothing about the socket now. The server answers every ping unconditionally (`ws/client-protocol.ts`) and serves the app bundle, so the two cannot be version-skewed. This narrows the "any inbound frame is liveness" rule from #1883 to the probe window and updates its test accordingly. Without it, a straggler buffered frame cancels the reconnect and detection falls back to ~30s, which is browser-ordering-dependent and would have made the probe fix land only about half the time. No wire change: `HOST_DAEMON_PROTOCOL_VERSION` is untouched, and no CLI or configuration surface is affected. Perf notes, since both mechanisms here were tuned for mobile foreground cost in #1883 and #2435: the added traffic is one `GET /api/v1/sidebar-bootstrap` per reconnect where realtime activity happened during the gap — the fetch the design always intended and the one that corrects the stale row — plus one ping frame per foreground. `cancelRefetch: false` and the default `refetchType: 'active'` are untouched, so in-flight downloads still are not aborted and inactive queries are still marked stale without fetching. Preserving `dataUpdatedAt` cannot add sidebar refetches because that query is `staleTime: Infinity`; the queries where it could are the thread list (10s, mounted only for the forks panel) and the timeline (2s, effectively always stale), and focus refetches are gated on the socket being disconnected. ## How you verified - `pnpm exec turbo run typecheck lint test --filter=@bb/app`: 552 files, 4959 tests pass, 0 lint errors (191 pre-existing warnings in untouched files). - Three regression tests, each confirmed failing before its fix: a hidden flush followed by a reconnect still invalidates the sidebar (`realtime-cache-effects.test.ts`); the resume probe fires despite buffered frames (`ws.test.ts`); a stale frame does not answer a probe (`ws.test.ts`). - Not verified on a real device. The ~30s-to-~5s detection improvement and the browser task ordering behind the third change are reasoned from the code and the ping/pong protocol, not observed in iOS Safari. Fixes # > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What was wrong
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)invalidateQueriesrefetched every active observer nobody could see. (B4)What changed
@bb/domain/@bb/server-contract:pingclient message andpongserver message.apps/server/src/ws/client-protocol.tsanswers a ping with a pong on the same socket only. Browser-server only;HOST_DAEMON_PROTOCOL_VERSIONis unchanged becauseclientMessageSchemais 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 andonline: a closed socket reconnects immediately (reconnectNow()replaces the partysocket instance becausereconnect()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 carriesdisconnectedAtfor reconnects (close time, or last inbound frame when a probe failed).system-cache-effects.ts:invalidateRealtimeQueriesAfterServerReconnect({ disconnectedAt })invalidates only queries withdataUpdatedAt < disconnectedAt(errored/never-loaded queries have 0 and are included) withcancelRefetch: 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 andactive-thread-lifecycle-cache-owner.tsis 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.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).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) #1882).bb/mobile-perf/thread-open-query-gating-review(Cut per-thread-open requests behind the surfaces that need them (B9-B13, B16, C5) #1884).