Skip to content

Cut per-thread-open requests behind the surfaces that need them (B9-B13, B16, C5) - #1884

Merged
SawyerHood merged 2 commits into
bb/mobile-perf/ws-liveness-and-resumefrom
bb/mobile-perf/thread-open-query-gating-review
Aug 19, 2026
Merged

SawyerHood merged 2 commits into
bb/mobile-perf/ws-liveness-and-resumefrom
bb/mobile-perf/thread-open-query-gating-review

Conversation

@SawyerHood

@SawyerHood SawyerHood commented Aug 19, 2026 •

Copy link
Copy Markdown
Collaborator

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 (Add WebSocket ping/pong, reconnect watermark and visibility-gated realtime flushes (B2, B3, B4) #1883).
  • Next layer: bb/mobile-perf/list-models-cache (Memoize provider.list_models on the server and key follow-up execution options by host (B6) #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 Opus 5

@SawyerHood SawyerHood changed the title bb/mobile perf/thread open query gating review Cut per-thread-open requests behind the surfaces that need them (B9-B13, B16, C5) Aug 19, 2026
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/thread-open-query-gating-review branch from 5543aad to fa9b8bb Compare August 19, 2026 07:50
@SawyerHood
SawyerHood marked this pull request as ready for review August 19, 2026 08:04
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/thread-open-query-gating-review branch from fa9b8bb to 4df68ee Compare August 19, 2026 15:59
kirbyhood and others added 2 commits August 19, 2026 16:03
Cut the requests every thread open used to issue on mobile:

- B9: thread storage file list loads only when the secondary panel is
  open or a storage tab exists (ThreadDetailView, RootComposeView).
- B10: child threads derive from the sidebar-navigation cache; the
  parent-keyed GET /threads is the fallback without that cache.
- B11: forks list in ThreadDetailSecondaryContent is enabled only while
  the secondary panel is open.
- B12: prompt history (project + thread) waits for a real keydown on
  coarse-pointer devices (usePromptHistoryEnabled).
- B13: NewThreadComposer worktree-reuse options derive from the sidebar
  bootstrap instead of a duplicate project thread list.
- B16: mention candidates derive from the sidebar cache; the command
  catalog is prefetched on composer focus for coarse pointers.
- C5: compact viewports request segmentLimit=8 for the first timeline
  window and keep it for deltas.

Co-Authored-By: Claude <[email protected]>
…strap

Review fixes for the thread-open query gating:

- useChildThreads / useThreadMentionCandidates observed the whole sidebar
  bootstrap payload, so every sidebar patch (any thread's status/title/
  unread change) re-rendered ThreadDetailView with a fresh child array.
  They now select their slice through react-query's structurally shared
  `select`, and only read `isFetching` while the cache is empty.
- On a cold open (deep link) the thread mounted while the app shell's
  bootstrap was still in flight, so the "fallback" list request fired
  anyway. The derived hooks now wait for an in-flight bootstrap and only
  fall back when nothing is fetching it (or it failed).
- The focus-time command catalog prefetch no longer retries three times
  on failure (matches the typeahead observer's no-retry policy).
- Add the missing `handleEditorFocus` dependency flagged by lint.

Co-Authored-By: Claude <[email protected]>
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/thread-open-query-gating-review branch from 4df68ee to c4dd688 Compare August 19, 2026 16:13
@SawyerHood
SawyerHood merged commit faaed7e into main Aug 19, 2026
12 checks passed
@SawyerHood
SawyerHood deleted the bb/mobile-perf/thread-open-query-gating-review branch August 19, 2026 16:23
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]>
SawyerHood added a commit that referenced this pull request Aug 19, 2026
…n options by host (B6) (#1885)

## What was wrong

Every execution-options read (each thread open, window focus, reconnect)
sent a fresh `provider.list_models` RPC to the host, and the host
spawned a provider CLI per request (measured 1-3 s). Nothing cached the
answer on the server, daemon, or bridge. The request carried the
environment's cwd although the Claude Code, Codex, and ACP bridges
ignore it, so every environment probed separately. On the client, the
follow-up composer keyed its query by `environmentId`, so each thread in
a different environment on the same machine issued its own request. On
mobile this put a CLI spawn on the critical path of every thread open.
(Mobile perf sweep finding B6.)

## What changed

- `apps/server`: `listProviderModelsMemoized` runs the probe through a
new `createAsyncTtlMemo` (`services/lib/async-ttl-memo.ts`) held on
`lifecycleDedupers.providerModelList` (10 min TTL, in-flight dedupe,
failures never stored). The key is `[hostId, daemonSessionId,
providerRegistrationRevision, command]`, so a daemon reconnect or a
plugin reload re-probes at once. The probe bypasses the memo only while
no daemon session is registered.
- `packages/domain`:
`providerModelCatalogDependsOnWorkspace(providerId)` states which
first-party bridges read the workspace path (only Pi). The server sends
`cwd` only for those; host-scoped catalogs share one memo entry across
environments.
- `apps/app`: component-local composers (`ThreadDetailPromptArea`,
`EmbeddedThreadChat` via `PluginThreadChat`) receive the environment's
host and `resolveThreadCreationProviderRouting` routes by `hostId` when
the selected provider's catalog is host-scoped. Pi and unknown providers
keep environment routing.
- `plugins/provider-claude-code`: `model/list` goes through
`createClaudeCodeBridgeModelListMemo` (2 min window plus in-flight
dedupe; failures not kept) so bursts share one CLI spawn.

## How you verified

- New tests: `apps/server/test/services/async-ttl-memo.test.ts` (TTL
expiry, in-flight sharing, rejection not stored, clear);
`apps/server/test/system/execution-options.test.ts` "model probe memo"
block (one probe without cwd across two environments plus explicit host;
Pi keeps cwd and keys per workspace; two concurrent readers share one
held RPC; a failed probe is retried and a reconnected daemon session
re-probes); `apps/app/src/hooks/useThreadCreationOptions.test.tsx`
(claude-code component-local routes by host, pi routes by environment);
`plugins/provider-claude-code/src/bridge/__tests__/model-list-memo.test.ts`
(shared probe, window expiry, failure retry). Updated
`provider-routing.test.ts` and `public-threads.defaults.test.ts` for the
host-scoped Codex probe (no cwd, single probe).
- `pnpm exec turbo run typecheck --force` for @bb/domain, @bb/server,
@bb/app, bb-plugin-provider-claude-code: pass. `lint` for @bb/app: 0
errors, 147 warnings (same as baseline). Targeted vitest runs above:
server 54/54, app 134/134, claude plugin 264/264. Full @bb/server suite:
1735 passed, 2 unrelated failures (file-mode umask assertion in
internal-skill-trees, timeout in plugin-service under load).

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


## Stack context

Layer 6 of 22 in the `bb/mobile-perf/*` stack (bottom → top: quick wins
first, big rocks last).
- Prerequisite (layer below):
`bb/mobile-perf/thread-open-query-gating-review` (#1884).
- Next layer: `bb/mobile-perf/workspace-status-and-pr-cache` (#1886).
- Audit findings addressed: see title IDs. Review: approved-with-fixes;
1 review fix commit(s).
- Reviewer notes / follow-ups: Minor (not fixed, low value): on plugin
surfaces (PluginThreadChat) the environment is fetched separately from
the thread, so the follow-up execution-options query can flip its key |
Design note: host-scoped catalogs are reused for up to 10 min (server) +
2 min (Claude bridge) after an account/CLI change on the same daemon
session; the curated Claude catalog is
- Wire/contract: No schema or protocol change.
HOST_DAEMON_PROTOCOL_VERSION not bumped (still 135). The only
wire-visible difference: the server now omits the already-optional `cwd`
field from `provider.list_models` for claude-code, codex, and acp-*
providers (verified their bridges ignore it: Claude `model/list` params
are `z.object({})`, Codex `handleModelList(id)` takes no params, ACP
builds its list from the l

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

---------

Co-authored-by: Claude <[email protected]>
ymichael pushed a commit that referenced this pull request Oct 14, 2026
## Human comments

## What was wrong

The composer `@` picker matches threads against the sidebar's in-memory
thread list, but cut that list to the first 200 entries before matching
(`buildThreadMentionCandidates` in
`apps/app/src/hooks/queries/thread-queries.ts`). The cap came over from
the older `GET /threads?limit=200` fetch when #1884 moved the picker
onto sidebar data. The sidebar list is ordered project by project with
personal threads last, so past 200 active threads, later projects and
all personal threads become unmentionable, even by exact title.

## What changed

- Match against every sidebar thread: the 200-entry slice is removed and
the wrapper folded into `selectThreadMentionCandidates`. The picker
still shows at most 8 thread rows. The short startup fallback fetch
before the sidebar loads keeps its 200 limit.
- One hook-level regression test
(`usePromptMentions.coverage.test.tsx`): 215 sidebar threads; an exact
search for the last one must return it.

Deviations from the issue's proposals, deliberately not included:
- **Refetching the sidebar on every mention open** (`staleTime: 0`): the
rename and new-project cases do not reproduce in the real app. Realtime
delivered both instantly on unfixed `main`, and reconnects already
invalidate the cache. The change would add a full `sidebar-bootstrap`
download on every `@`.
- **Gating path rows on the settled query**: the change lives in the
shared `usePathSuggestions`, which the right-panel file search
(`NewTabFileSearch`) also uses. There it would blank results and show
"Searching files..." on every keystroke. In the `@` picker the stale
rows linger for about 120 ms, so this is left for a picker-scoped
follow-up if wanted.

## How you verified

- The regression test fails on unfixed `main` and passes with the fix.
- `pnpm exec turbo run test --filter=@bb/app --
src/hooks/usePromptMentions src/hooks/usePathSuggestions
src/hooks/queries/thread-queries
src/hooks/queries/sidebar-navigation-query
src/hooks/threadMentionSuggestions src/hooks/pathMentionSuggestions
src/hooks/promptMentionCandidates`: 64 tests across 9 files pass.
- `pnpm exec turbo run lint typecheck --filter=@bb/app` passes.
- Manual, `pnpm start:worktree` with 215 seeded threads: typing `@Bulk
thread 1` in the new-thread composer was missing that thread before
(results started at 199) and lists it first after. On the unfixed build,
a CLI rename (`bb thread update --title`) and a CLI-created project both
appeared in the picker immediately.

Fixes #5475

> AGENT GENERATED

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

---------

Co-authored-by: SawyerHood <[email protected]>
Co-authored-by: qa <qa@x>
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.

2 participants