Skip to content

Fix env-daemon CI flakes - #1

Merged
ymichael merged 2 commits into
mainfrom
codex/env-daemon-ci-green
Mar 18, 2026
Merged

ymichael merged 2 commits into
mainfrom
codex/env-daemon-ci-green

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Summary

  • bind env-daemon RPCs to the intended provider child instead of the mutable active child
  • stub provider model listing in the env-daemon runtime test so CI does not require a real codex CLI

Validation

  • pnpm exec turbo run typecheck --filter=@bb/environment-daemon
  • pnpm exec turbo run test --filter=@bb/environment-daemon

@ymichael
ymichael merged commit a229058 into main Mar 18, 2026
1 check passed
@ymichael
ymichael deleted the codex/env-daemon-ci-green branch March 18, 2026 02:49
SawyerHood pushed a commit that referenced this pull request Jul 30, 2026
## The problem

When you open a thread through bb connect, your browser has to talk to
your laptop through a long pipe that runs out to Cloudflare and back.
Every single question your browser asks down that pipe takes about **95
milliseconds** to get an answer, no matter how small the answer is.
That's just how long the trip takes.

So if you ask two questions one after the other, you wait ~190 ms. If
you ask them at the same time, you wait ~95 ms. The number of questions
matters way more than how big the answers are.

Opening a thread used to ask more questions than it needed to, and it
asked some of them in a line when they could have been asked all at
once.

## What this changes

**1. Stop waiting in line.** Loading a thread needs two things: the
thread itself, and its timeline. Neither one needs the other. But the
code asked for the thread, waited for the whole answer to come back, and
only then asked for the timeline. Now both go out at the same time.

**2. Stop asking twice.** Right after loading the thread, the app
immediately asked for the same thread again. Now it skips the second ask
if the first one just answered (within 5 seconds).

**3. Stop asking for things nobody looked at.** There's a "Parent"
dropdown in the thread sidebar. The app fetched the list of possible
parent threads on every thread open — even though most people never open
that dropdown. Now it only fetches when you actually click it. You'll
see a brief "Loading threads…" the first time, and a retry option if it
fails.

**4. Let answers be zipped.** The pipe had a rule that said "don't send
me compressed data." That rule made your laptop unzip everything before
pushing it through the pipe, so we shipped big uncompressed answers when
small zipped ones would do. That rule is gone.

## Did it actually work?

Yes for #1, barely for #4. I tested this against the real production
Connect — real Cloudflare, real tunnel, not a simulation.

**Asking both questions at once (change #1):**

| | how long |
|---|---:|
| Before (one after the other) | **255 ms** |
| After (both at once) | **141 ms** |

That's **114 ms faster, about 45%**. This is the change that matters.

**Zipping the answers (change #4):** barely moves the needle, ~0–10 ms.

The reason is boring: the answers are already small. Earlier work capped
how much timeline gets sent at once, so even the biggest threads on my
machine only produce 15–61 KB. Zipping shrinks that by 3–4×, which
sounds great, but the pipe moves data fast enough (~18 MB/s) that 40 KB
was never the problem. The 95 ms trip was.

Zipping still earns its place in two spots, though:
- On a slow connection (say hotel wifi at 10 Mbps), that same 40 KB *is*
worth ~35 ms per request.
- It turns the app's precompressed asset files back on. Those had been
silently disabled over Connect this whole time by the "don't send me
compressed data" rule, and they're much bigger than any API response.

**Bottom line: don't expect to feel the zipping on fast internet. Do
expect thread opens to feel snappier.**

## Things that will look different

- **A new "Parent: None" row.** If you have a project with only one
thread, the Parent row used to be hidden — the app knew there was
nothing to pick. Now it can't know that without asking, and asking is
the thing we're trying to avoid. So the row is always there for root
threads.
- **The Parent dropdown can be tabbed to** in a couple of cases where it
previously couldn't.
- **Re-opening a thread you've seen before** now asks "what's new since
X?" instead of "give me everything," and falls back to asking for
everything if the server can't answer that.

## The part to be careful about

To let zipped data through the pipe, I rewrote the piece of code that
forwards requests, swapping `fetch` for Node's lower-level HTTP client.
This touches **every** thing that goes through the tunnel — including
any dev server you've shared with `bb connect expose <port>`, not just
BB itself. It's the riskiest part of this PR.

Things that could have broken, and why they didn't:

- **Garbled responses.** Raw headers now get forwarded as-is, which is
dangerous if a "this data is chunked" header rides along with data
that's already been un-chunked. The relay already throws those headers
away (`apps/connect/src/tunnel-do.ts:44`), so it can't happen.
- **Wrong length.** A "this is 500 bytes" header on a body that isn't
500 bytes would break things. Checked both places that set it — they
always match what actually gets sent.
- **Redirects.** The old code told `fetch` not to follow them. Node's
client doesn't follow them anyway. Same behavior.
- **Reused memory.** The new code hands out views into Node's internal
buffer. Safe here, because it's copied out synchronously before Node can
reuse it.

No daemon protocol version bump needed — the wire format didn't change,
no worker code changed, and the already-deployed relay handles these
headers fine.

**One thing tests can't cover:** whether Cloudflare's runtime passes a
zipped response through untouched. I confirmed it by hand (step 2
below). Running it locally uses the same runtime but skips Cloudflare's
CDN layer, so local testing isn't a full substitute.

## How to check it yourself

Node 22, pnpm 9, clean checkout:

```bash
pnpm install --offline --frozen-lockfile
pnpm run ensure-native-modules
pnpm exec turbo run test typecheck --filter=@bb/tunnel-client --filter=bb-plugin-connect --force
pnpm exec turbo run test --filter=@bb/app --force -- src/hooks/cache-owners/cache-owner-registry.test.ts src/hooks/queries/thread-queries.test.tsx src/components/secondary-panel/ThreadMetadataContent.test.tsx src/views/thread-detail/ThreadDetailSecondaryContent.test.tsx
pnpm exec turbo run typecheck --filter=@bb/app --force
```

Then open DevTools → Network and load a thread through bb connect:

1. The thread and timeline requests start together, and the thread isn't
requested twice.
2. The timeline response has `content-encoding: gzip` and a
`server-timing: bb_connect_origin` header.
3. The Connect host log prints timing (`originTtfbMs`, `originBodyMs`,
`responseBytes`, `contentEncoding`).
4. Nothing requests parent candidates until you click **Parent**. First
click shows "Loading threads…", then the list.
5. A root thread in a project with no other threads shows the **Parent:
None** row.

## Tests

All green. Tunnel client 6/6, connect plugin 65/65, four focused app
suites 28/28, plus typechecks. The full GitHub matrix passes — app,
server, integration, packages, checks, and macOS/Linux smoke.

The new tests are the interesting ones. They check that the timeline
request really does leave before the thread request comes back, that a
warm cache asks for a delta and merges the answer correctly, that the
duplicate thread request is skipped when fresh but still happens when
stale, and that zipped bytes cross the tunnel byte-for-byte identical.
SawyerHood added a commit that referenced this pull request Aug 10, 2026
…lection listeners (#1285)

Follow-up #1 from the #1269 tap-freeze diagnosis (primary fix: #1281).
Two re-render/tap amplifiers on the thread timeline.

## Root cause

**1. Every realtime event re-rendered every timeline row.**
`useSenderThreadMetadataById` rebuilt a fresh `Map` on every matching
query-cache event with no equality check, and its predicate also fired
on `observerResultsUpdated` (observer churn with no data change). The
map fed `TimelineRendererStaticContext`, and context identity changes
bypass `React.memo` — so every `sidebarNavigation`/`threads`/`thread`
cache event re-rendered all rows of the un-virtualized timeline, keeping
style/layout dirty and amplifying any main-thread work on mobile.

**2. Per-tap handler work was O(N messages).** Each
`SelectableMessageProse` (one per assistant message) registered 6
document-level listeners, so every tap and every `selectionchange`
dispatched N sets of handlers and scheduled up to N rAF callbacks.

## Fix

Commit 1 (`useSenderThreadMetadataById` + `ThreadTimelineRows`):
- The hook keeps the previous map reference when the rebuild is
value-equal (all metadata fields are primitives, so shallow per-entry
compare is exact).
- The sync predicate drops `observerResultsUpdated` — the map is built
exclusively from `query.state.data`, which only changes via `updated`
dispatches.
- The map moves out of the wide static context into a dedicated
`SenderThreadMetadataContext`, so a *genuine* metadata change (any
thread title anywhere in the cache) re-renders only the conversation
rows that resolve sender labels, not every row.

Commit 2 (`SelectableMessageProse`):
- One module-level registry owns a single shared set of 6 document
listeners and one shared report frame. Each instance keeps its own
selection state machine (the `hadSelection` null-once gate,
pending/last-release anchors, multi-click timer) and its node-scoped
`click`/`dblclick` listeners. An instance inside its multi-click delay
is skipped by shared report passes and reports when its own timer fires,
preserving double/triple-click semantics.

## Measurement

React Profiler over a 21-row timeline in jsdom, 10 value-equal `threads`
cache events (the shape realtime refetches produce):

| | full-timeline commits | React update work |
|---|---|---|
| before | 11 | ~136 ms |
| after | **0** | **0 ms** |

Document listeners for N assistant messages: before 6·N, after 6 total.

## Validation

- `pnpm exec turbo run typecheck --filter=@bb/app` — pass
- `pnpm exec turbo run test --filter=@bb/app --force` — 328 files, 2472
tests, all pass (including the 51 pre-existing selection/timeline
behavior tests, unchanged)
- `pnpm exec turbo run lint --filter=@bb/app` — pass
- New regression tests were each verified to fail against the pre-fix
code:
- `useSenderThreadMetadataById.test.tsx` — stable reference on equal
rebuilds, new reference + value on real changes, stability across
unrelated query keys
- `ThreadTimelineRows.render-stability.test.tsx` — profiler-counted zero
commits on equal cache events; sender title updates flow through to the
DOM
- `SelectableMessageProse.events.test.tsx` — mounting additional
messages adds zero document listeners; a selection moving between two
messages clears the old one exactly once

Timeline virtualization remains explicitly out of scope.

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
amadad pushed a commit to amadad/bb that referenced this pull request Aug 14, 2026
## The problem

When you open a thread through bb connect, your browser has to talk to
your laptop through a long pipe that runs out to Cloudflare and back.
Every single question your browser asks down that pipe takes about **95
milliseconds** to get an answer, no matter how small the answer is.
That's just how long the trip takes.

So if you ask two questions one after the other, you wait ~190 ms. If
you ask them at the same time, you wait ~95 ms. The number of questions
matters way more than how big the answers are.

Opening a thread used to ask more questions than it needed to, and it
asked some of them in a line when they could have been asked all at
once.

## What this changes

**1. Stop waiting in line.** Loading a thread needs two things: the
thread itself, and its timeline. Neither one needs the other. But the
code asked for the thread, waited for the whole answer to come back, and
only then asked for the timeline. Now both go out at the same time.

**2. Stop asking twice.** Right after loading the thread, the app
immediately asked for the same thread again. Now it skips the second ask
if the first one just answered (within 5 seconds).

**3. Stop asking for things nobody looked at.** There's a "Parent"
dropdown in the thread sidebar. The app fetched the list of possible
parent threads on every thread open — even though most people never open
that dropdown. Now it only fetches when you actually click it. You'll
see a brief "Loading threads…" the first time, and a retry option if it
fails.

**4. Let answers be zipped.** The pipe had a rule that said "don't send
me compressed data." That rule made your laptop unzip everything before
pushing it through the pipe, so we shipped big uncompressed answers when
small zipped ones would do. That rule is gone.

## Did it actually work?

Yes for get-bb#1, barely for get-bb#4. I tested this against the real production
Connect — real Cloudflare, real tunnel, not a simulation.

**Asking both questions at once (change get-bb#1):**

| | how long |
|---|---:|
| Before (one after the other) | **255 ms** |
| After (both at once) | **141 ms** |

That's **114 ms faster, about 45%**. This is the change that matters.

**Zipping the answers (change get-bb#4):** barely moves the needle, ~0–10 ms.

The reason is boring: the answers are already small. Earlier work capped
how much timeline gets sent at once, so even the biggest threads on my
machine only produce 15–61 KB. Zipping shrinks that by 3–4×, which
sounds great, but the pipe moves data fast enough (~18 MB/s) that 40 KB
was never the problem. The 95 ms trip was.

Zipping still earns its place in two spots, though:
- On a slow connection (say hotel wifi at 10 Mbps), that same 40 KB *is*
worth ~35 ms per request.
- It turns the app's precompressed asset files back on. Those had been
silently disabled over Connect this whole time by the "don't send me
compressed data" rule, and they're much bigger than any API response.

**Bottom line: don't expect to feel the zipping on fast internet. Do
expect thread opens to feel snappier.**

## Things that will look different

- **A new "Parent: None" row.** If you have a project with only one
thread, the Parent row used to be hidden — the app knew there was
nothing to pick. Now it can't know that without asking, and asking is
the thing we're trying to avoid. So the row is always there for root
threads.
- **The Parent dropdown can be tabbed to** in a couple of cases where it
previously couldn't.
- **Re-opening a thread you've seen before** now asks "what's new since
X?" instead of "give me everything," and falls back to asking for
everything if the server can't answer that.

## The part to be careful about

To let zipped data through the pipe, I rewrote the piece of code that
forwards requests, swapping `fetch` for Node's lower-level HTTP client.
This touches **every** thing that goes through the tunnel — including
any dev server you've shared with `bb connect expose <port>`, not just
BB itself. It's the riskiest part of this PR.

Things that could have broken, and why they didn't:

- **Garbled responses.** Raw headers now get forwarded as-is, which is
dangerous if a "this data is chunked" header rides along with data
that's already been un-chunked. The relay already throws those headers
away (`apps/connect/src/tunnel-do.ts:44`), so it can't happen.
- **Wrong length.** A "this is 500 bytes" header on a body that isn't
500 bytes would break things. Checked both places that set it — they
always match what actually gets sent.
- **Redirects.** The old code told `fetch` not to follow them. Node's
client doesn't follow them anyway. Same behavior.
- **Reused memory.** The new code hands out views into Node's internal
buffer. Safe here, because it's copied out synchronously before Node can
reuse it.

No daemon protocol version bump needed — the wire format didn't change,
no worker code changed, and the already-deployed relay handles these
headers fine.

**One thing tests can't cover:** whether Cloudflare's runtime passes a
zipped response through untouched. I confirmed it by hand (step 2
below). Running it locally uses the same runtime but skips Cloudflare's
CDN layer, so local testing isn't a full substitute.

## How to check it yourself

Node 22, pnpm 9, clean checkout:

```bash
pnpm install --offline --frozen-lockfile
pnpm run ensure-native-modules
pnpm exec turbo run test typecheck --filter=@bb/tunnel-client --filter=bb-plugin-connect --force
pnpm exec turbo run test --filter=@bb/app --force -- src/hooks/cache-owners/cache-owner-registry.test.ts src/hooks/queries/thread-queries.test.tsx src/components/secondary-panel/ThreadMetadataContent.test.tsx src/views/thread-detail/ThreadDetailSecondaryContent.test.tsx
pnpm exec turbo run typecheck --filter=@bb/app --force
```

Then open DevTools → Network and load a thread through bb connect:

1. The thread and timeline requests start together, and the thread isn't
requested twice.
2. The timeline response has `content-encoding: gzip` and a
`server-timing: bb_connect_origin` header.
3. The Connect host log prints timing (`originTtfbMs`, `originBodyMs`,
`responseBytes`, `contentEncoding`).
4. Nothing requests parent candidates until you click **Parent**. First
click shows "Loading threads…", then the list.
5. A root thread in a project with no other threads shows the **Parent:
None** row.

## Tests

All green. Tunnel client 6/6, connect plugin 65/65, four focused app
suites 28/28, plus typechecks. The full GitHub matrix passes — app,
server, integration, packages, checks, and macOS/Linux smoke.

The new tests are the interesting ones. They check that the timeline
request really does leave before the thread request comes back, that a
warm cache asks for a delta and merges the answer correctly, that the
duplicate thread request is skipped when fresh but still happens when
stale, and that zipped bytes cross the tunnel byte-for-byte identical.
amadad pushed a commit to amadad/bb that referenced this pull request Aug 14, 2026
…lection listeners (get-bb#1285)

Follow-up get-bb#1 from the get-bb#1269 tap-freeze diagnosis (primary fix: get-bb#1281).
Two re-render/tap amplifiers on the thread timeline.

## Root cause

**1. Every realtime event re-rendered every timeline row.**
`useSenderThreadMetadataById` rebuilt a fresh `Map` on every matching
query-cache event with no equality check, and its predicate also fired
on `observerResultsUpdated` (observer churn with no data change). The
map fed `TimelineRendererStaticContext`, and context identity changes
bypass `React.memo` — so every `sidebarNavigation`/`threads`/`thread`
cache event re-rendered all rows of the un-virtualized timeline, keeping
style/layout dirty and amplifying any main-thread work on mobile.

**2. Per-tap handler work was O(N messages).** Each
`SelectableMessageProse` (one per assistant message) registered 6
document-level listeners, so every tap and every `selectionchange`
dispatched N sets of handlers and scheduled up to N rAF callbacks.

## Fix

Commit 1 (`useSenderThreadMetadataById` + `ThreadTimelineRows`):
- The hook keeps the previous map reference when the rebuild is
value-equal (all metadata fields are primitives, so shallow per-entry
compare is exact).
- The sync predicate drops `observerResultsUpdated` — the map is built
exclusively from `query.state.data`, which only changes via `updated`
dispatches.
- The map moves out of the wide static context into a dedicated
`SenderThreadMetadataContext`, so a *genuine* metadata change (any
thread title anywhere in the cache) re-renders only the conversation
rows that resolve sender labels, not every row.

Commit 2 (`SelectableMessageProse`):
- One module-level registry owns a single shared set of 6 document
listeners and one shared report frame. Each instance keeps its own
selection state machine (the `hadSelection` null-once gate,
pending/last-release anchors, multi-click timer) and its node-scoped
`click`/`dblclick` listeners. An instance inside its multi-click delay
is skipped by shared report passes and reports when its own timer fires,
preserving double/triple-click semantics.

## Measurement

React Profiler over a 21-row timeline in jsdom, 10 value-equal `threads`
cache events (the shape realtime refetches produce):

| | full-timeline commits | React update work |
|---|---|---|
| before | 11 | ~136 ms |
| after | **0** | **0 ms** |

Document listeners for N assistant messages: before 6·N, after 6 total.

## Validation

- `pnpm exec turbo run typecheck --filter=@bb/app` — pass
- `pnpm exec turbo run test --filter=@bb/app --force` — 328 files, 2472
tests, all pass (including the 51 pre-existing selection/timeline
behavior tests, unchanged)
- `pnpm exec turbo run lint --filter=@bb/app` — pass
- New regression tests were each verified to fail against the pre-fix
code:
- `useSenderThreadMetadataById.test.tsx` — stable reference on equal
rebuilds, new reference + value on real changes, stability across
unrelated query keys
- `ThreadTimelineRows.render-stability.test.tsx` — profiler-counted zero
commits on equal cache events; sender title updates flow through to the
DOM
- `SelectableMessageProse.events.test.tsx` — mounting additional
messages adds zero document listeners; a selection moving between two
messages clears the old one exactly once

Timeline virtualization remains explicitly out of scope.

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
SawyerHood added a commit that referenced this pull request Aug 19, 2026
## What was wrong

The host daemon is supposed to keep the native `@parcel/watcher` addon
out of the parent process (parcel runs in a forked child). The
in-process fallback in
`packages/host-watcher/src/parcel-watcher-backend.ts` reached the addon
through `await import("./real-parcel-watcher.js")`. esbuild inlines a
dynamic import of an internal module and hoists that module's static
`import parcelWatcher from "@parcel/watcher"` to the top level of
`dist/daemon-bundle.mjs`. The daemon therefore loaded `watcher.node`
(built with `NAPI_DISABLE_CPP_EXCEPTIONS`) before `pty.node`
(`NAPI_CPP_EXCEPTIONS`) at startup. On macOS, dyld coalesces the
identical weak `Napi::details::CallbackData<...>::Wrapper` symbol across
images to watcher.node's try/catch-less copy. When `PtyFork` throws
`Napi::Error` on a failed spawn, nothing catches it, `std::terminate`
runs, and the app dies with SIGABRT.

Issue: #1873. Investigation report:
https://get-bb.github.io/reports/issues/1873.html

## What changed

- `packages/host-watcher/src/parcel-watcher-backend.ts`: the in-process
fallback now does `const { default: parcelWatcher } = await
import("@parcel/watcher")`. A dynamic import of the external package
stays a real `import("@parcel/watcher")` in the esbuild ESM bundle, so
`watcher.node` loads only when a watcher is needed in-process.
- `packages/host-watcher/src/real-parcel-watcher.ts`: kept for the
forked watcher child entry; its comment now explains why daemon-bundle
code must not dynamically import it.
- `apps/host-daemon/test/parcel-watcher-not-loaded-in-parent.test.ts`
(new): bundles `@bb/host-watcher` with the daemon bundle's esbuild
settings, then asserts (1) the output has no static top-level
`@parcel/watcher` import and still has a dynamic
`import("@parcel/watcher")`, and (2) importing that bundle in a child
`node` with a `process.dlopen` hook loads no `@parcel/watcher` addon.

No wire shapes changed, so `HOST_DAEMON_PROTOCOL_VERSION` was not
bumped. No CLI/guide/doc surfaces are affected.

## How you verified

**The new test fails before the fix** (both assertions, for the right
reason):

```
 ❯  @bb/host-daemon  test/parcel-watcher-not-loaded-in-parent.test.ts (2 tests | 2 failed) 175ms
     × does not hoist a static import of @parcel/watcher 36ms
     × does not dlopen a @parcel/watcher addon when the bundle is imported 137ms

AssertionError: static top-level import(s) of @parcel/watcher found in the bundle; watcher.node would load at daemon startup:
import parcelWatcher from "@parcel/watcher";: expected [ Array(1) ] to be null

AssertionError: @parcel/watcher addon loaded on import:
[dlopen] <repo>/node_modules/.pnpm/@parcel[email protected]/node_modules/@parcel/watcher-linux-x64-glibc/watcher.node: expected [ Array(1) ] to deeply equal []
```

**After the fix:**

```
 Test Files  1 passed (1)
      Tests  2 passed (2)
```

**Real daemon bundle, rebuilt with the fix** (`pnpm exec turbo run build
--filter=@bb/host-daemon`), then run with the report's `process.dlopen`
logger and `NODE_PATH` unset:

```
$ grep -c 'from"@parcel/watcher"' dist/daemon-bundle.mjs
0
$ node --require log-dlopen.cjs dist/daemon-bundle.mjs --definitely-not-a-flag
[dlopen #1] <repo>/node_modules/.pnpm/[email protected]/node_modules/node-pty/build/Release/pty.node
[exit] code=1 addons loaded=1
```

Before the fix the same bundle contained `import VYr
from"@parcel/watcher"` and the report's
`daemon-bundle-addon-load-order.log` shows `watcher.node` as dlopen #1
and `pty.node` as #2.

**Package suites and typecheck:** `pnpm exec turbo run test typecheck
--filter=@bb/host-daemon --filter=@bb/host-watcher --force` → 5/5 tasks
successful; `@bb/host-watcher` 45 tests passed, `@bb/host-daemon` 585
tests passed.

**macOS was not re-run.** This was verified on Linux only. On Linux the
symptom differs (the report shows the same symbol coalescing produces a
SIGSEGV analog under `RTLD_GLOBAL`, and Node's default `RTLD_LOCAL`
dlopen avoids it), so the macOS SIGABRT itself was not reproduced here.
The fix is still correct because the crash requires `watcher.node` to be
resident in the daemon process before `pty.node` loads, and the root
cause of that is the static import in the bundle. The test and the
dlopen log above show that with this change the daemon process loads no
`@parcel/watcher` addon at startup, so dyld has no watcher.node copy of
the `Wrapper` symbol to coalesce with when node-pty's image loads;
node-pty then uses its own exception-aware copy, which catches the
`Napi::Error` as intended. The forked watcher child
(`bb-parcel-watcher-child.mjs`) still loads `watcher.node`, which is the
intended isolation.

Fixes #1873

> AGENT GENERATED: by Claude Opus 5

---------

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

## What was wrong

bb cloud (the `bb-ai` plugin, #4254) only served thread titles and
commit messages. Voice input had no hosted option, so a bb without a
Codex login had no microphone. The plan left voice as phase 2
(`plans/bb-account-and-hosted-generation.md`, Part 8). The bb side
already had everything voice needs: the plugin SDK's `transcribe` hook,
the Voice input row in Settings → AI services, the server's transcribe
route, `bb voice transcribe`, and the mic's readiness check. The missing
pieces were a hosted endpoint and bb-ai implementing `transcribe`.

## What changed

- **bb-ai-gateway** (`apps/ai-gateway`): new `POST
/api/ai/v1/transcribe`.
- Takes `{audio, format, hint}` with base64 audio, capped at 10 MB, and
forwards it to OpenRouter's `POST /api/v1/audio/transcriptions` with
`provider: {zdr: true, data_collection: "deny"}`.
- Metering is shared with `/complete` through one `handleMetered` path:
the same auth, rate limit, daily budget and request log. Transcription
reserves 2¢ per call and settles to the reported cost.
- `AI_TRANSCRIBE_MODELS` (new, required var, set in `wrangler.jsonc` for
production and staging) lists the models in order. OpenRouter's
transcription endpoint has no `models` fallback, so the gateway moves to
the next model when one answers with an HTTP error, all within an 8 s
deadline. It never retries after a timeout.
- The vocabulary `hint` goes to `provider.options.groq.prompt`, the only
hint option OpenRouter documents.
- Default models: `microsoft/mai-transcribe-2`, then
`openai/whisper-large-v3-turbo`. Both have ZDR endpoints.
- **bb-account**: `bb-account.v1.fetch` accepts request bodies up to 16
MB instead of 1 MB, since base64 recordings didn't fit. Responses stay
capped at 1 MB.
- **bb-ai**: registers `transcribe`.
- It sends the recording through `bb-account.v1.fetch` with a 10 s
timeout.
- It maps the MIME type or file extension to an OpenRouter format, so
Chrome's `audio/webm;codecs=opus` becomes `webm` and Safari's
`audio/mp4` becomes `m4a`.
- It refuses recordings over 10 MB or in unknown formats without
contacting getbb.app.
- The opt-in, sign-in and used-up-budget checks are shared with
`complete`.
- bb cloud now appears for Voice input, and Automatic tries Codex, then
bb cloud.
- **Copy and docs**: `bb ai` help, the plugin README, overview and
skill, `docs/configuration.md`, and the verify-bb feature map now cover
voice input and say recordings are never stored. (Merged with #4522,
which made bb cloud on by default and removed its settings page and
disclosure, and #4525, which deleted the plan doc. The model comparison
that was going into the plan is below.)

**Model choice** (OpenRouter transcription models with ZDR endpoints,
2026-09-29): `microsoft/mai-transcribe-2` (Azure, about $0.0017/min at a
launch price that ends 2026-12-31, #1 on FLEURS and #2 on Artificial
Analysis's word-error-rate board), `openai/whisper-large-v3-turbo`
(Groq/DeepInfra, $0.0002–0.0007/min, takes a vocabulary prompt on Groq),
and Voxtral Mini Transcribe, Deepgram Nova-3 and AssemblyAI
Universal-3.5 Pro. `openai/gpt-transcribe`,
`google/gemini-3.5-transcribe` and `x-ai/grok-stt-1.0` have no ZDR
endpoint.

- **Stale docs from #4522**: the `bb-cloud-ai` skill, plugin overview,
README, `docs/configuration.md` and the verify-bb feature map still
described the removed opt-in and settings page. They now say bb cloud is
on by default once you sign in, `bb ai off` turns it off, and disabling
the plugin also stops it. The skill also covers voice input: accepted
formats, the 10 MB limit, the 10 s timeout, and `bb voice transcribe`.

No server, daemon or SDK changes. No `HOST_DAEMON_PROTOCOL_VERSION`
bump.

**Known issue, not addressed here:** through OpenRouter, MAI-Transcribe
2 answers 400 for WebM and MP4 audio but accepts the same speech as Ogg
or MP3. Chrome and Safari recordings therefore get transcribed by
Whisper after one refused MAI call. The follow-up is either to put
Whisper first in `AI_TRANSCRIBE_MODELS` (config only) or to convert
recordings to Ogg before upload.

## How you verified

- `pnpm exec turbo run typecheck test lint --filter=@bb/ai-gateway
--filter=bb-plugin-bb-ai --filter=bb-plugin-bb-account`: pass (gateway
32 tests, bb-ai 28, bb-account 59).
- New gateway tests cover:
- the exact OpenRouter request, including ZDR and the Groq hint, and the
metering and request log, which never contains audio or text;
  - falling back on an HTTP error but not on a timeout;
  - charging nothing when every model refuses;
  - input validation (base64, the 10 MB cap, format, hint size);
- the 2¢ reserve, so a nearly spent budget still allows a title but not
a recording;
  - 401 without a credential;
- a Miniflare test that sends a 4 MB body through the real Workers
runtime and D1.
- New bb-ai tests cover the fetch payload and timeout, refusals that
send nothing (off, too large, unknown format), budget exhaustion from a
transcription answer, and MIME/extension mapping.
- Local end to end against real OpenRouter (`pnpm cloud:dev` with a key,
plus `pnpm dev` signed in to a local account, `bb ai on`, and `bb
settings ai-services set voice bb`):
- `bb voice transcribe` on WebM, MP3 and M4A clips returned correct
transcripts in 1.0–1.6 s. The gateway log showed MAI answering MP3 and
Whisper answering WebM and M4A.
  - `bb ai usage` counted the requests.
- After merging `main`: typecheck, test and lint pass again (bb-ai 24
tests, gateway 32, bb-account 59).
  - Recording with the mic in the app worked.

## Rollout

Deploy the gateway (**Deploy AI Gateway**) before releasing bb-ai. A
released bb-ai against an old gateway would show the mic and fail every
recording with a 404.

> AGENT GENERATED

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

---------

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

## What was wrong

Several cache owners wrote a server reply or the thread-detail bootstrap
straight into the React Query cache with `setQueryData` while a fetch of
the same key could still be in flight. React Query writes fetch results
without checking whether they're older than what's cached (query-core
`query.ts`), so the older fetch landed last and put stale data back.
Effects included: an environment or host status that stayed stale after
opening a thread, a plugin settings form resetting its draft to the old
value, a cancelled plugin install flipping back to running, new plugin
update jobs dropping out of the list, an `idle` app update phase
switching off the progress poll, and the AI service selection flickering
back. These are items #2–#10 from the direct cache write audit
(@thread:thr_fjr5x8dzaz). #1 (thread tabs) is fixed separately in #6611.

## What changed

Two fixes, depending on whether the data has a version field:

- **Environment and Host keep the newer copy by `updatedAt`** (#2, #3,
#10). The bootstrap ingest (`thread-detail-cache-owner.ts`), the rename
reply (`applyEnvironmentUpdateResult`), and the
`useEnvironment`/`useHosts` fetches all compare `updatedAt`. The
fetch-side check is what catches a fetch that started before the write
and lands after it. To make it testable, those fetches now live in
`environmentQueryOptions` and `hostsQueryOptions`. Host `status` comes
from live daemon sessions and a disconnect doesn't change `updatedAt`,
so on a tie the cached copy wins over the bootstrap. The bootstrap only
fills an empty cache or replaces strictly older data. Rename replies and
fetch results still win ties.
- **`setQueryDataOverInFlightFetch`** (`cache-effect-utils.ts`) for data
with no version (#4–#9): it writes the value, and if a fetch of the key
is in flight it cancels that fetch (the cache keeps the written value)
and refetches. With nothing in flight it's a plain write. Used by
`applyPluginSettingsView`, `applyPluginInstallJob`,
`applyPluginUpdateJob`, `hydrateAppUpdateStatus`,
`hydrateSystemVersionCache` and `writeCachedAiServices`, so every caller
gets the fix. Where the audit suggested an unconditional
cancel-write-invalidate (#7) or a cancel before the write (#8, #9), this
helper refetches only when a fetch was actually in flight. That avoids
an extra request on every write. Forced version and app-update checks
update the server's cache, so the trailing unforced refetch returns the
forced result.

No wire, CLI or plugin API changes.

Not covered here: audit items #11 (plugin safe mode) and #12 (prompt
history), both low risk. Also not covered: a lint rule restricting
direct `setQueryData` calls to the helper, which would stop new call
sites from bringing the race back.

## How you verified

- New tests use real `QueryClient`/`QueryObserver` instances: start a
fetch that resolves late with older data, do the write, let the fetch
land, then check that the newer value survives (and, for the helper,
that the trailing refetch runs).
- `thread-detail-cache-owner.test.ts` (new): late environment and
host-list fetches after a bootstrap, an older bootstrap over a newer
cache, and the equal-`updatedAt` host status case.
- `environment-workspace-cache-owner.test.ts`: a late environment fetch
after a rename, and an older rename reply over a newer cache.
- `in-flight-fetch-writes.test.ts` (new): one row per cache-owner write
for #4–#9, plus helper tests for the no-fetch case (no extra request)
and a fetch of an unobserved query.
- With each source change reverted, every race test failed on the stale
data and passed once the fix was restored.
- `pnpm exec turbo run typecheck lint test --filter=@bb/app`: passed
(647 files, 6515 tests; 0 lint errors, no new warnings). After rebasing
onto `0472409243` I re-ran the three changed test files (21 tests
passed).

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

> AGENT GENERATED

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 5, 2026
…ately, and read shared refs once per repo (#7082)

## Human comments

## What was wrong

Every watched environment ran its own full `git for-each-ref refs/heads
refs/remotes` whenever any ref in the repository was written, and
fingerprinted the whole listing (`packages/host-workspace/src/git.ts`,
`apps/host-daemon/src/watch-manager.ts`). On `~/Projects/bb` (4,474
local branches, 2,672 remote refs) that listing is about 1 MB and takes
about 200–300 ms. Because the fingerprint covered every ref, any ref
write in the repository changed every watched environment's fingerprint,
whether it was a commit in one worktree, a new thread's branch or a
`fetch --prune`. Each environment then emitted `git-refs-changed`, which
refetches git status, files and the branch list in the git plugin and
makes the PR plugin run `inspectRefs`. This is finding #1 ("Ref watch
fan-out") of the Nov 4 hot-path overreach audit.

## What changed

- **One listing per repository.** `WatchManager.readSharedGitRefs` keeps
one pending listing per common git dir. Requests join it until the read
starts, after a 25 ms join window. A ref change that arrives after a
read has started gets a fresh read, so no environment acts on a listing
taken before its own event. The listing runs from the worktree that
started it. If it rejects (for example, that worktree was removed), each
joined environment retries with its own read instead of failing with it.
- **`git-refs-changed` now means "a ref this environment uses moved".**
`SharedGitRefsSnapshot.fingerprintFor({ branchName, mergeBaseBranch })`
covers only the oids of:
  - the HEAD branch, plus its `%(upstream)` and `%(push)` refs
- every remote-tracking ref named after the branch
(`refs/remotes/*/<branch>`). bb creates worktrees with `--no-track`, and
a plain `git push fork <branch>` leaves both `%(upstream)` and `%(push)`
empty, so a push to a fork remote still refreshes PR status.
  - the default branch, local and `origin/`
  - `origin/HEAD` and its target
- the environment's merge-base branch (`refs/heads/<base>` and
`refs/remotes/<base>`). The server resolves it per watched environment
with the rule the git plugin reads status with (`mergeBaseBranch ??
baseBranch ?? defaultBranch`, `resolveEnvironmentMergeBaseBranch`) and
sends it as `mergeBaseBranch` on each `watch-set.replace` workspace
target. That covers envs started from a non-default branch and a base
picked from any surface (Diff tab, Info tab, context banner), all of
which persist through the git plugin's `setMergeBase`. A merge-base
change already emits `metadata-changed`, so the server re-sends the
target; the daemon updates the running watch in place (no re-provision)
and rereads its refs, so the env refreshes once against the new base.
- **New `git-branches-changed` environment change kind.**
`SharedGitRefsSnapshot.branchNamesFingerprint` hashes the repository's
branch-name set. When it changes, the daemon emits
`git-branches-changed` instead of `git-refs-changed`. Each consumer
handles it as follows:
- **git plugin** (`plugins/git/server/invalidation.ts`): invalidates
only the branch list (`refs:` tag, the `branches` RPC). It keeps the
status/files caches and does not bump the refs generation. `refsChanged`
is now set per change kind rather than inferred from the refs tag, so a
batch that mixes the new kind with `work-status-changed` doesn't bump
refs either.
- **github-pr-status**: `environmentChangeEffect` returns `null`, so the
kind is ignored; PR status doesn't depend on other branches existing.
Added to its mapping table test.
- **App cache registry** (`realtime-cache-registry.ts`): `dirty: []`,
the same as `git-refs-changed`. Neither is in the app's watched-kinds
list or the server's watch-target kinds.
- **Server** (`notifyDaemonEnvironmentChange`): forwards the new kind
unchanged. The existing internal test now covers it.
- **Supporting changes.** `inspectGitRepository` already read
`--git-common-dir`; it now returns it, and `HostWorkspace` exposes it as
`gitCommonDir`. The listing format drops `%(refname:short)` (local names
are now sliced from `refs/heads/`) and adds `%(upstream)` and `%(push)`.

**Why the bumps are needed**
- **`HOST_DAEMON_PROTOCOL_VERSION` 262 → 263:** `git-branches-changed`
is a new value in the daemon's `environment-change` WebSocket message
(`hostDaemonEnvironmentChangeSchema`). A 262 server would reject it, and
a 262 daemon would keep emitting `git-refs-changed` for branch-name
changes. The same bump covers the new required `mergeBaseBranch` field
on `watch-set.replace` workspace targets.
- **`@get-bb/plugin-sdk` 0.6.125 → 0.6.126**
(`scripts/bump-plugin-sdk.mjs --patch`): the new kind widens the
`changes` union of the SDK's `environment:changed` event
(`ENVIRONMENT_CHANGE_KINDS` → `ChangedMessage`), which changes the
published bundled types.

**No visible behaviour change.** Every env still refreshes when its own
branch, upstream, push target, default branch or merge base moves, and
its branch list refreshes when a branch is created or deleted. The
branch list is not ordered by commit, so moves of unrelated branches
can't change it.

## How you verified

**Real data, main vs branch.** I wrote a harness outside the checkout.
It runs the real `WatchManager` with the subprocess parcel watcher on 20
real `~/Projects/bb` worktrees, with a `git` PATH shim that logs every
spawn. It then writes a probe branch (`refs/heads/bench-refwatch-probe`)
in the real repo: create, 5 moves, delete. Before and after each step it
diffs every other ref, so writes by other agents can be attributed. To
show what each env refetches, it maps the kinds each env emitted through
that checkout's own git-plugin `tagsForEnvironmentChanges` and
github-pr-status `environmentChangeEffect`. For the main run, every
non-test file in this PR is checked out from origin/main.

Probe branch **create and delete**, 20 watched worktrees, final run
(load 5–10):

| | main | branch |
|---|---|---|
| `for-each-ref` spawns | 20 (15.2 s / 19.5 s summed) | 1 (0.20 s / 0.24
s) |
| envs emitting `git-refs-changed` | 20 | 0 |
| envs emitting `git-branches-changed` | — | 20 |
| git plugin refetch per env | status + files + branch list, caches
cleared | branch list only, caches kept |
| PR plugin per env | `invalidate` (`inspectRefs` → `upstream` host
call) | none |

One env on the branch also had an unrelated `work-status-changed` during
the delete step (its own files changed), and refetched status and files
for that.

Probe branch **moves**: main spawned 20 `for-each-ref` per move and all
20 envs emitted `git-refs-changed` (more when other agents' writes
overlapped). The branch spawned 1 per move and 0 envs emitted anything.
Earlier runs across load 5–45 gave the same counts:
- moves reached 0 envs whenever nothing else moved (16 of 16 such steps)
- 1 env when a watched worktree switched its own HEAD branch mid-step
(verified in its reflog)
- `for-each-ref` at watch startup: main 20–28, branch 11–17, because
provisioning is serial so only part of it joins

How often name changes happen on `~/Projects/bb`. These now trigger only
a branch-list refetch instead of a full refresh of every env:
- Live 29-minute sample: 18 ref-write bursts, 7 of which changed the
name set (2 local creates, 5 remote creates, 2 remote prunes).
- Reflogs, last 7 days: about 105 ref creations a day against 253 moves.
That is a lower bound, since deleted refs lose their reflogs.

Costs:
- A single listing with the new format, 15 interleaved runs: median 259
ms and 0.90 MB, against 286 ms and 1.09 MB for the old format.
- `%(push)` adds about 18 ms (190 ms against 172 ms at low load).
- Each env now keeps a short fingerprint string instead of a ~1 MB copy
of the listing.

**Tests**

- `packages/host-workspace/test/host-workspace.test.ts`, for both files
and reftable:
- creating a branch changes `branchNamesFingerprint` but not the `main`
env's fingerprint.
- moving an unrelated branch leaves the `main` env's fingerprint
unchanged.
- moving the env's own branch, its upstream, its
`refs/remotes/fork/<branch>` (no config), a renamed `%(push)`
destination, or the default branch changes it.
- with an env on `main`, moving its merge base changes the fingerprint
for a local base (`feature`) and a remote one (`fork/feature`). This
fails if the merge base is left out of the watched set.
- `apps/host-daemon/src/watch-manager.test.ts`:
- a branch-name change emits only `git-branches-changed`, and an own-ref
move emits only `git-refs-changed`.
- an env reports its merge base moving and the other env doesn't.
Changing a merge base through `watch-set.replace` keeps the watch
running (no re-provision), refreshes that env once, and later base moves
reach it. This fails without the in-place update.
- two worktrees of one repo share one read, and only the one whose refs
moved reports.
- a change that arrives while a shared read is running starts a fresh
read. This test fails if a started read can be joined.
- when the shared read rejects, joined envs fall back to their own read.
This test fails without the fallback.
- `plugins/git/server/invalidation.test.ts`: `git-branches-changed` →
refs tag only, caches kept, no refs-generation bump, also when mixed
with `work-status-changed`.
- `plugins/github-pr-status/server.test.ts`: `git-branches-changed` → no
effect.
- `packages/host-daemon-contract/test/contract.test.ts`: protocol 263
(262 no longer compatible), and the new kind parses in
`environment-change`.
- `apps/server/test/internal/internal-environment-change.test.ts`: the
server forwards the new kind to clients.
- `apps/server/test/app/watch-interests.test.ts`: workspace targets
carry the resolved merge base (`null`, then `baseBranch`, then a
`setMergeBase`-style override, then back to `baseBranch` when cleared),
re-sent on each `metadata-changed`.
- **Live check on a `pnpm start:worktree` dev server** with a scratch
repo and 4 worktree threads, watching the client WebSocket's environment
events:
- moving `origin/feature/beta`: only the env started from `feature/beta`
gets `git-refs-changed` (before this commit, none did).
- setting Worktree A's merge base to `origin/feature/alpha`: A gets
`metadata-changed` + `git-refs-changed`, and its watch isn't restarted.
Moving `origin/feature/alpha` afterwards reaches A only.
- after clearing A's merge base, moving `feature/alpha` again reaches no
env.
- Commands:
- `pnpm exec turbo run typecheck` for `@bb/host-daemon-contract`,
`@bb/host-workspace`, `@bb/host-daemon`, `@bb/server`, `@bb/app`,
`bb-environment-provider-host` and the git and github-pr-status plugins:
all pass.
- Targeted `vitest run` for those packages: all pass. CI runs the full
suites.

> AGENT GENERATED

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 25, 2026
…ed (#8126)

## Human comments

## What was wrong

While an agent works, the Diff panel cost two host round trips a second,
whether or not the diff changed. The daemon reports
`work-status-changed` for every workspace write without fingerprinting
it (`apps/host-daemon/src/watch-manager.ts`), including identical
rewrites and writes to ignored output. The git server marked both the
`status` and `files` tags stale on every such event and flushed at most
once a second (`plugins/git/server/invalidation.ts`). Each flush made
the client refetch both reads, and each refetch was one
`plugin.host.call`. Every host `files` call also re-ran `diffPatch` for
up to 10 inline patches and shipped them again, though the server and
client already had them at the same revision. This is finding #1 of the
server→daemon RPC audit.

## What changed

The change stays inside the git plugin (server and host ship as one
plugin artifact). There is no daemon wire change, so no
`HOST_DAEMON_PROTOCOL_VERSION` bump.

- **New host method `snapshot`** (`plugins/git/host.ts`, `contract.ts`).
It reads status and every watched file list in one call, sharing one
`git status`.
  - Each part carries a sha256 fingerprint of its result.
- When the server passes the fingerprint it already holds
(`statusUnless`, `files[].unless`) and the result still matches, that
part comes back as `{ outcome: "unchanged" }`. An unchanged file list
also skips `diffPatch`.
- **`knownPatches` on `files` and `snapshot`.** The server names the
inline patches it holds, by path and blob revision. The host reads only
the others and lists the reused paths, and the server fills them back
in. The client contract (`files.initialPatches`) is unchanged.
- **Server flush becomes a probe** (`server.ts`).
- A coalesced `status`/`files` invalidation for a watched environment
now makes one `snapshot` call with the status and the watched file-list
queries.
- The server compares the result with what it served while those reads
were watched, and invalidates only the tags whose result changed. Other
tags (refs, viewed) still publish directly.
- The snapshot replaces the read memo entries, so the client's refetch
is served without another host call.
- Probes for an environment run one at a time; tags that arrive during a
probe go through the coalescer again.
- The turn-end check uses the same probe, and now compares the file
lists as well as status.
- **Several repos (#8062).** The snapshot follows the Changes panel's
repo list: one `snapshot` call per repo folder, carrying that repo's
watched file lists (with each extra repo's own target) and its status,
plus the environment folder's status when no repo is rooted there. A
single-repo environment still makes one call. The merged, repo-grouped
result is compared with what was served, so a changed repo list also
refreshes the panel.
- **Watched file lists keep their memo on change events.** Unwatched
file-list queries are evicted when the workspace changes or their last
watcher leaves. The probe owns their freshness: it drops any in-flight
read and replaces the entry, so a read that started before a change
can't stand in for the check after it. Unwatched environments still
clear on every change. If a probe fails or can't cover a tag, the server
clears the memo before invalidating.
- **Shorter quiet period** (`server/invalidation.ts`). A probe now waits
50 ms of quiet instead of 250 ms, with a 250 ms max wait instead of 500
ms. The 1 s minimum spacing per environment stays, so there is still at
most one host call a second. The long debounce existed to batch client
refetches; a no-op probe now costs a 275 B reply and no refetch, so it
only delayed real edits.
- `server/invalidation.ts` passes the environment id to `publish`.
`DIFF_FILES_INLINE_PATCH_MAX_FILES` moved to `contract.ts`, the schema
that uses it. The README and `PLUGIN_OVERVIEW.md` describe the new
refresh.

Not changed: no-op writes still cost one background `snapshot` per
second. It is answered `unchanged` in 275 B and causes no client
refetch. Filtering earlier would mean host-side change detection. The
daemon's `work-status-changed` has to stay unfiltered, because core's
environment file previews depend on it for ignored files too.

## How you verified

**Real servers, same input** (`af25b0b5a60` vs this branch, fresh `/tmp`
data dirs):
- The workspace was a 9,101-file clone of this repo on a **second
enrolled daemon**. It connected through a WebSocket-aware proxy that
adds **100 ms each way (200 ms RTT)** and logs every daemon↔server frame
by request id.
- The Diff panel was open in headless Chrome: "All changes", 3 changed
files, inline patches.
- Each run lasts 60 s and makes 11 real edits: append a line to one of 3
tracked files, every 5 s plus a random 0–1 s offset. The churn scenario
also writes every 250 ms, alternating an identical rewrite of
`package.json` and a write to a `.git/info/exclude`d directory, which is
about 230 `work-status-changed` events a minute.
- Latency is measured from the edit to the new `+N` count in the panel.
Latency cells are means over the listed runs (each run is 11 edits).
Host-call counts and bytes were identical across runs to within 1 call.
The branch numbers in this table were measured at f0d08f9.

| per minute | main, churn | branch, churn | main, edits only | branch,
edits only |
|---|---|---|---|---|
| git host calls | 122 (61 `status` + 61 `files`) | **61 `snapshot`**
(~50 answered `unchanged`) | 24 (12 + 12) | **12 `snapshot`** |
| git host request bytes | 365 KB | 219 KB | 72 KB | 43 KB |
| git host response bytes | 224 KB | **45 KB** | 44 KB | 32 KB |
| client `status` + `files` refetches | 122 | **22** | 24 | 22 |
| edit → panel, mean (runs) | 603 ms (667, 669, 693, 382) | 625 ms (680,
570) | 744 ms (740, 748) | **590 ms** (590, 589) |

Per action:
- **A real edit:** 2 host calls → **1**, and it shows up **~150 ms
sooner** (744 → 590 ms with 200 ms RTT).
- **A burst of no-op writes:** 2 host calls with full payloads plus 2
client refetches per flush → **1** `snapshot` with a 275 B `unchanged`
reply and no client refetch.

About 3.4 KB of each host request is core's `contributedEnv`, sent on
every `plugin.host.call` (audit finding #9); it is out of scope here.

Latency phases for edits only, mean of 22 edits:

| phase | main | branch |
|---|---|---|
| write → daemon event at proxy | 90 ms | 90 ms |
| event → host request (quiet period + 100 ms one-way) | 362 ms | **158
ms** |
| host round trip | 210 ms | 209 ms |
| host response → panel | 82 ms | 134 ms |

The last row is ~52 ms longer on the branch: after the probe
invalidates, the client makes one more client→server→plugin request,
which the snapshot-seeded memo answers. That cost is fixed and doesn't
grow with host RTT, and the shorter quiet period more than covers it.

Under churn, latency is set by where an edit lands against the 1 s
minimum spacing, which both builds share. Run-to-run spread (382–693 ms
on main) is larger than the difference between builds.

**Tests:**
- `plugins/git/server/invalidation.test.ts`: covers the 50 ms quiet
period, the 250 ms max wait and the unchanged 1 s spacing.
- `plugins/git/server.test.ts` (new "workspace change refreshes" block,
each failing on main):
- one `snapshot` and no invalidation for unchanged bursts, with later
reads served from it;
- only the changed tag is invalidated, and its refetch is served from
the snapshot;
  - the host answers `unchanged` for parts the server holds;
  - a read in flight across a change does not stand in for the probe;
- the host is asked only for patches the server doesn't hold, and the
client still gets the full `initialPatches`.
- `plugins/git/host.test.ts`: against a real repo, `files` and
`snapshot` re-read only patches whose revision changed, and a matching
fingerprint yields `unchanged`.
- Existing turn-end, invalidation and CLI tests are updated for the new
`publish` signature and host output shape.
- `pnpm exec turbo run typecheck test lint:type-aware
--filter=bb-plugin-bb--git` passes locally. Full suites are left to CI.

**Review follow-up (6fbb7c1):** A previously read alternate whitespace
view now returned the new file 1.45 s after the edit, before the 3 s
cache expiry. A rejected host snapshot now sends both reads through the
fallback without an unhandled rejection. Both regression cases failed on
the prior revision. All 301 git plugin tests, typecheck and type-aware
lint passed. With the 200 ms RTT proxy, the updated branch made 61 host
snapshots and 22 client status/files refetches in one minute of churn.
All 11 edits reached the panel, averaging 685 ms.

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

> AGENT GENERATED

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael pushed a commit that referenced this pull request Nov 25, 2026
…lability read (#8187)

## Human comments

## What was wrong

A nested bb whose Account Pooler proxies to a parent pool decides per
turn whether it can route through the parent, using `ParentAvailability`
in `plugins/account-pool/src/parent-pool.ts`. `load()` gives the
parent's `/availability` 2 s, and on any error or non-OK status returns
`UNAVAILABLE_POOL`. `get()` caches that result for the full 30 s TTL,
the same as a good answer. So one slow read from a busy parent takes the
child off the pool for 30 s, and every turn that starts in that window
runs with no pool credentials. On a child with no Claude login of its
own, Claude Code answers `Not logged in · Please run /login` and
Provider Retry skips the turn as not retryable. On one child this
happened three times in a day, each time the parent's host was under
heavy load.

## What changed

- `plugins/account-pool/src/parent-pool.ts`: `ParentAvailability`
remembers the last good availability.
- A failed read keeps serving it, and the next read is tried after 5 s
instead of 30 s.
- Once reads have failed for 60 s in a row, the parent is reported
unavailable and that answer is cached for the normal TTL, as before. A
parent that has never answered is reported unavailable, and the read is
retried after 5 s.
  - The read timeout goes from 2 s to 5 s.
- `plugins/account-pool/src/parent-pool.test.ts`: three cases, all of
which fail on `main`:
  - one failed read keeps the last good value and retries after 5 s;
- a parent that stays down is reported unavailable after 60 s, then
cached for the TTL;
  - a failed first read is retried after 5 s.
- No wire, CLI or doc changes.

## How you verified

- New tests on `main`'s `parent-pool.ts`: the 3 new tests fail with
`expected { claude: false, codex: false } to deeply equal { claude:
true, codex: false }`, and the other 13 pass. With the change: 16/16.
- After the final commit: `pnpm exec turbo run typecheck lint test
--filter=bb-plugin-account-pool --force` passed 10/10 tasks, with 14
test files and 402 tests passing. Lint reported 3 warnings, all in
`app.tsx`, which this PR does not touch. `pnpm exec turbo run
lint:type-aware --filter=bb-plugin-account-pool --force` passed 7/7
tasks with 0 warnings. `pnpm exec turbo run prepare:bundled
--filter=bb-plugin-account-pool` passed 7/7 tasks. `oxfmt --check`
passes on both files.
- Standalone reproduction with real HTTP and the real clock.
`ParentAvailability` uses the real `fetch` and the shipped TTL and
timeouts against a local HTTP parent, and one `get()` per second stands
in for a turn start. `main` and this branch ran side by side.

  One slow answer (request #2 answers in 8 s, then normal), on `main`:

  ```
  [  0.0s] parent: request #1 -> 200 {claude:true}
  [  0.1s] child:  turn start -> ROUTED (claude via parent pool)
  [ 30.2s] parent: request #2 answering in 8s
[ 32.2s] child: warn could not read parent availability: The operation
was aborted due to timeout
[ 32.2s] child: turn start -> NOT ROUTED (turn runs with no login) after
waiting 2003ms
  [ 62.3s] parent: request #3 -> 200 {claude:true}
  [ 62.3s] child:  turn start -> ROUTED (claude via parent pool)
  summary: 43 turn starts routed, 30 not routed, 3 parent requests
  ```

  With the change:

  ```
  [  0.0s] parent: request #1 -> 200 {claude:true}
  [  0.1s] child:  turn start -> ROUTED (claude via parent pool)
  [ 30.2s] parent: request #2 answering in 8s
[ 35.2s] child: warn could not read parent availability: The operation
was aborted due to timeout
[ 35.2s] child: turn start -> ROUTED (claude via parent pool) after
waiting 5003ms
  [ 40.2s] parent: request #3 -> 200 {claude:true}
  [ 70.4s] parent: request #4 -> 200 {claude:true}
  summary: 70 turn starts routed, 0 not routed, 4 parent requests
  ```

  A parent that stays down (503 from 25 s on), on `main`:

  ```
  [  0.0s] parent: request #1 -> 200 {claude:true}
  [  0.1s] child:  turn start -> ROUTED (claude via parent pool)
  [ 30.2s] parent: request #2 -> 503 (down)
[ 30.2s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 30.2s] child:  turn start -> NOT ROUTED (turn runs with no login)
  [ 60.4s] parent: request #3 -> 503 (down)
[ 60.4s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 90.5s] parent: request #4 -> 503 (down)
[ 90.5s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [120.7s] parent: request #5 -> 503 (down)
[120.7s] child: warn could not read parent availability: parent
availability returned HTTP 503
  summary: 30 turn starts routed, 100 not routed, 5 parent requests
  ```

With the change, the child keeps routing for 60 s after the first
failure, then reports the parent unavailable and goes back to reading
every 30 s:

  ```
  [  0.0s] parent: request #1 -> 200 {claude:true}
  [  0.1s] child:  turn start -> ROUTED (claude via parent pool)
  [ 30.2s] parent: request #2 -> 503 (down)
[ 30.2s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 35.2s] parent: request #3 -> 503 (down)
[ 35.2s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 40.2s] parent: request #4 -> 503 (down)
[ 40.2s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 45.3s] parent: request #5 -> 503 (down)
[ 45.3s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 50.3s] parent: request #6 -> 503 (down)
[ 50.3s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 55.3s] parent: request #7 -> 503 (down)
[ 55.3s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 60.3s] parent: request #8 -> 503 (down)
[ 60.3s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 65.3s] parent: request #9 -> 503 (down)
[ 65.3s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 70.3s] parent: request #10 -> 503 (down)
[ 70.3s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 75.3s] parent: request #11 -> 503 (down)
[ 75.3s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 80.3s] parent: request #12 -> 503 (down)
[ 80.3s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 85.4s] parent: request #13 -> 503 (down)
[ 85.4s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 90.4s] parent: request #14 -> 503 (down)
[ 90.4s] child: warn could not read parent availability: parent
availability returned HTTP 503
  [ 90.4s] child:  turn start -> NOT ROUTED (turn runs with no login)
  [120.5s] parent: request #15 -> 503 (down)
[120.5s] child: warn could not read parent availability: parent
availability returned HTTP 503
  summary: 90 turn starts routed, 40 not routed, 15 parent requests
  ```

<details><summary>repro.mts (run from the repo root as
<code>node_modules/.bin/tsx repro.mts
$PWD/plugins/account-pool/src/parent-pool.ts
slow-once|down</code>)</summary>

  ```ts
  import { createServer } from "node:http";
  import type { AddressInfo } from "node:net";
  
const [modulePath, scenario] = process.argv.slice(2) as [string,
"slow-once" | "down"];
  const { ParentAvailability } = await import(modulePath);
  
  const TOKEN = "vqMIj4xUiI3PyvKS2SllSKHsOfxLF_sAZwzNAAvV9TQ";
  const started = Date.now();
const t = () => ((Date.now() - started) / 1000).toFixed(1).padStart(5);
  let request = 0;
  
  const server = createServer((req, res) => {
    request += 1;
    const n = request;
    const elapsed = (Date.now() - started) / 1000;
    if (req.headers["x-bb-account-pool-token"] !== TOKEN) {
      res.writeHead(401).end();
      return;
    }
    const answer = () => {
      res.writeHead(200, { "content-type": "application/json" });
      res.end(JSON.stringify({ claude: true, codex: false }));
    };
    if (scenario === "slow-once" && n === 2) {
      console.log(`[${t()}s] parent: request #${n} answering in 8s`);
      setTimeout(() => { if (!res.destroyed) answer(); }, 8_000);
      return;
    }
    if (scenario === "down" && elapsed > 25) {
      console.log(`[${t()}s] parent: request #${n} -> 503 (down)`);
      res.writeHead(503).end();
      return;
    }
    console.log(`[${t()}s] parent: request #${n} -> 200 {claude:true}`);
    answer();
  });
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1",
resolve));
  const { port } = server.address() as AddressInfo;
  
  const availability = new ParentAvailability({
parent: { baseUrl:
`http://127.0.0.1:${port}/api/v1/plugins/account-pool/http`, token:
TOKEN },
    fetch,
    now: Date.now,
    onError: (error: unknown) =>
console.log(`[${t()}s] child: warn could not read parent availability:
${error instanceof Error ? error.message : String(error)}`),
  });
  
  const durationS = scenario === "slow-once" ? 75 : 130;
  let last: string | null = null;
  let routed = 0;
  let unrouted = 0;
  while ((Date.now() - started) / 1000 < durationS) {
    const before = Date.now();
    const value = await availability.get();
    const waited = Date.now() - before;
    if (value.claude) routed += 1; else unrouted += 1;
const state = value.claude ? "ROUTED (claude via parent pool)" : "NOT
ROUTED (turn runs with no login)";
    if (state !== last || waited > 500) {
console.log(`[${t()}s] child: turn start -> ${state}${waited > 500 ? `
after waiting ${waited}ms` : ""}`);
      last = state;
    }
    await new Promise((r) => setTimeout(r, 1_000));
  }
console.log(`summary: ${routed} turn starts routed, ${unrouted} not
routed, ${request} parent requests`);
  server.close();
  process.exit(0);
  ```

  </details>

- **Not checked:** an isolated nested bb against a slow parent bb end to
end. The reproduction drives the same class the server constructs, with
the same options except `onError`.

Fixes #8188

> AGENT GENERATED

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

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