Skip to content

[codex] Route new manager flow - #7

Merged
SawyerHood merged 8 commits into
mainfrom
bb/route-new-manager-flow-thr_un9smztivd
May 14, 2026
Merged

SawyerHood merged 8 commits into
mainfrom
bb/route-new-manager-flow-thr_un9smztivd

Conversation

@SawyerHood

Copy link
Copy Markdown
Collaborator

Summary

  • Replace the sidebar New Manager dialog launch with navigation to /projects/:projectId/managers/new.
  • Move the hire-manager form into NewManagerView, preserving project selection, provider/model/host selection, hire mutation handling, error display, pending state, and navigation to the created manager thread.
  • Update route metadata, app route matching, story coverage, and focused tests for the routed page and sidebar action.

Validation

  • env -u NODE_ENV NODE_OPTIONS=--no-experimental-webstorage pnpm exec turbo run test --filter=@bb/app -- src/views/NewManagerView.test.tsx src/components/sidebar/AppSidebar.test.tsx
  • env -u NODE_ENV pnpm exec turbo run typecheck --filter=@bb/app
  • env -u NODE_ENV pnpm exec turbo run lint --filter=@bb/app

SawyerHood and others added 5 commits May 14, 2026 12:23
Add a short intro line above the configuration card so the routed page
clarifies what hiring does, and tighten the action footer: a ghost
Cancel button (returns to the project) sits next to the primary Hire
Manager button, which now carries a UserRoundPlus icon and a spinner
glyph during the in-flight state.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Reframe the New Manager routed page as a focused "hire a colleague"
moment rather than a generic settings-style form. Centers a narrow
column with an identity avatar, an explanatory blurb sourced from the
manager system prompt, a friendly name input, a compact Project / Model
/ Host config card, and a full-width primary Hire Manager button. Empty,
loading, and missing-project states all flow through the same shared
primitives.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Split the dash-joined clause into two sentences so the blurb reads
plainly without the visual weight of an emdash.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Center-aligning a multi-line paragraph gives both edges a jagged break
and makes it harder to scan. Switch the blurb to text-left so the
sentences read naturally; the avatar and heading stay centered.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@SawyerHood
SawyerHood marked this pull request as ready for review May 14, 2026 22:41
SawyerHood and others added 3 commits May 14, 2026 15:42
Mirrors the description landed on main in HireManagerDialog (bcaf1dd)
so the routed page and the dialog stay in sync, then appends the
project-thread context that the routed page needs.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Resolves conflicts in NewManagerView.tsx and NewManagerView.test.tsx
by adopting main's ProviderInfo / useSystemExecutionOptions API while
keeping the routed-page header (centered hero, avatar, blurb) and
react-router wiring.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@SawyerHood
SawyerHood merged commit be35574 into main May 14, 2026
1 check failed
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
## Human comments

## What was wrong

Every worktree create checks that the source repository has a commit
(`readGitRepositoryState` in
`packages/environment-provider-host/src/git.ts`). It did this with `git
rev-list --all --max-count=1`. Even with `--max-count=1`, git has to
load and date-sort the tip commit of every ref before it can print one.
On a checkout with thousands of branches, that is the slowest git call
in thread creation, and the caller only needs to know whether any commit
exists. This is finding #7 of the Nov 4 hot-path audit.

## What changed

- `readGitRepositoryState` now runs `git rev-parse --verify --quiet
HEAD^{commit}` first. If HEAD resolves to a commit, it returns
`has_commits` straight away.
- It falls back to `rev-list --all` only when HEAD is unborn. That keeps
the existing result for an orphan HEAD when other branches have commits.
- No visible behaviour change. Each state (`not_git`, `no_commits`,
`has_commits`) still maps to the same result and the same error.
- No wire change, so no `HOST_DAEMON_PROTOCOL_VERSION` bump. No plugin
SDK change.

## How you verified

Real data: `~/Projects/bb` (4,477 local branches, 2,671 remote refs, 123
worktrees, git 2.50.1). I called the real `readGitRepositoryState` from
this branch and compared it with main's function body, run through the
same `detectGitSource`/`runGit` runner. Runs were interleaved, after one
warm-up each.

| run | load avg | main p50 | main p90 | main max | branch p50 | branch
p90 | branch max |
|---|---|---|---|---|---|---|---|
| n=20 | ~27 | 813 ms | 1,042 ms | 1,066 ms | 36 ms | 49 ms | 52 ms |
| n=30 | 23→38 | 2,716 ms | 11,478 ms | 16,073 ms | 66 ms | 120 ms | 154
ms |

Both columns include the shared `rev-parse --is-inside-work-tree`
detection spawn. In both runs the branch took one fast spawn where main
took a ref walk whose cost grows with load.

Tests:
- Added `packages/environment-provider-host/test/git.test.ts`. It covers
a plain directory, an empty repository, a commit on HEAD, an unborn HEAD
with commits on another branch (the fallback path), and a bare clone.
- `pnpm exec turbo run typecheck lint
--filter=bb-environment-provider-host` passes.
- Full suites are left to CI.

> 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 9, 2026
… on outline loads (#7243)

## Human comments

## What was wrong

Two read paths re-projected whole turns or whole histories on every
request (REPORT #7 of the Nov 7 timeline audit):

- **Turn summary details.** `buildTimelineTurnSummaryDetails` read,
decoded and projected the entire turn, then paginated it. Every "load
earlier" page and every re-expand paid the full projection again.
6e9knccemi turn t2 (7,563 events) took 13 pages × ~150 ms.
- **Conversation outline.** `conversation-outline-cache.ts` refused to
keep a checkpoint once any `backgroundTask` or `delegation` item
appeared in the projected history (`hasBackgroundState`). Every outline
load of a thread that had ever run a background command therefore
reprojected its whole epoch. 11 of the 12 audit threads have such items;
d5ej4e2gtv paid ~140–290 ms per load.

## What changed

- `timeline-turn-details-cache.ts` (new) keeps the scoped turn-details
projection in a per-connection LRU (32 entries, 32 MiB, 8 MiB per
entry).
- Slot: thread plus the snapshot surface, which already encodes every
request input except the cursor.
  - Revision: snapshot key plus the thread's rewrite generation.
- An entry also expires when a retained-output preview it contains would
flip to `retention-expired`, since that preview depends on `Date.now()`.
- Pages paginate the cached rows. `paginateTimelineContents` accepts
precomputed leaf sizes (`measureTimelineContentLeafBytes`) so they are
measured once.
- `conversation-outline-cache.ts` drops the blanket background guard.
Background and delegation item ids join the checkpoint's referenced item
set, exactly like tool-call ids, so a later selected event for a
retained item rebuilds from scratch.
- The outline SQL selection already drops a task's normal `completed`
completion and never selects delegation rows, so the full build never
depended on those events.
- Failed or interrupted completions and progress events are selected,
and they trigger the rebuild.
- `docs/timeline-pagination.md` documents both behaviours.

No wire, CLI or SDK changes.

## How you verified

Benchmarks used the shared audit harness, in-process against an APFS
clone of the Nov 7 production snapshot. Runs were 3 alternating base/fix
pairs on the same machine, each the median of 3 samples. Load average
was 12–69 because other slices were benchmarking at the same time, so
absolute numbers are noisy; the pairs alternate.

**Turn summary details** (app parameters: `deferContent`, whole turn,
walk every `beforeCursor` page):

| thread / turn | events | pages | whole walk ms (before → after) |
re-expand ms (before → after) |
|---|---|---|---|---|
| 6e9knccemi t2 | 7,563 | 13 | 1913 → 155 | 1914 → 4.2 |
| 6e9knccemi t3 | 4,212 | 8 | 643 → 83 | 627 → 1.5 |
| u738kqjs29 t3 | 7,407 | 4 | 859 → 221 | 886 → 0.7 |
| avim9t7kpe t1 | 5,886 | 6 | 824 → 140 | 840 → 1.2 |
| kdrbtee92b t1 | 7,335 | 3 | 659 → 213 | 594 → 0.3 |
| wg5iwwrezi t1 | 1,914 | 4 | 178 → 48 | 177 → 0.5 |

First pages and single-page turns cost the same as before. Parity: every
page of 23 turns on 12 threads hashes identically between base and fix.

**Conversation outline**, thread forced active, second load after the
first:

| thread | background events | before → after ms |
|---|---|---|
| d5ej4e2gtv | 5,262 | 286 → 116 |
| 6e9knccemi | 276 | 34 → 1.4 |
| kdrbtee92b | 779 | 12.6 → 2.6 |
| ymhw6pktq4 | 198 | 12.1 → 1.0 |
| y6xhxw8t8w | 168 | 18.9 → 7.9 |

Outline parity replay:
- For each thread, the replay moves the tail of its last 25 root turns
out of `events` and re-appends it step by step: at turn ends, mid-turn,
and at random background-task events.
- At every step it compares `loadThreadConversationOutline`
(incremental) with `buildThreadConversationOutline` (independent full
builder).
- Coverage: 107 threads (the 12 audit threads, the 60 threads with the
most background events, and recent threads with ≥1,000 events), 4,573
steps.
- Result: **0 mismatches**.
- Median incremental cost per append, before → after: yvsvx8anai 18.4 →
2.1 ms, dwzy4aij2h 16.5 → 2.3 ms, 3wbmnrdpap 30.9 → 2.5 ms.

Tests added:
- `timeline-turn-details-cache.test.ts`
- One projection serves all pages and a repeat expand. Fails before: 2
extra projections.
- A gap-fill below the latest sequence (rewrite generation bump,
unchanged maxSeq) rebuilds. Fails if the generation is dropped from the
revision.
- A preview flips to `retention-expired` once its retention passes.
Fails if the expiry is ignored.
- `conversation-outline-incremental.test.ts`
- Only the live tail is read after background tasks that finished after
their turns. Fails before: 403 rows read vs < 25.
- Matches the full rebuild when a retained background task later reports
`completed`, `failed` or progress.

Commands:
```sh
pnpm exec turbo run typecheck lint --filter=@bb/server
pnpm exec turbo run test --filter=@bb/server -- test/services/threads/ test/public/public-thread-data.test.ts test/public/public-thread-timeline-completed-turn-display.test.ts   # 358 passed
pnpm exec turbo run test --filter=@bb/server -- test/public/public-thread-timeline* test/public/public-thread-cleared-context-history.test.ts test/public/public-thread-shell-command-summaries.test.ts   # 73 passed
```

Not changed:
- Measured but left alone: `GET /threads/:id/messages/:seq`,
empty-latest-window retries, `bb thread wait` polling, github-pr-status
`turnRanGh`, fork history copy.
- Remaining outline fallbacks: a nested child of a kept tool call still
writing (gcuc46ug4j, kbjzy5zdu7), and threads whose turns never all
settle (d5ej4e2gtv).

Refs #4674

> 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 24, 2026
## Human comments

## What was wrong

`serveDaemonFileStream`
(`apps/server/src/services/hosts/daemon-file-stream.ts`) always sent a
`host.read_file_chunk` with `length: 0` to get metadata, then
`createFileStreamResponse` read the first chunk with a second RPC. Every
un-ref'd raw host file request therefore cost two serial daemon round
trips: image previews, the file viewer's 64 KiB sample, thread-storage
files and project/environment files. Only a `304` took one. This is
finding #7 of the server→daemon RPC audit. I checked the call pattern in
the code and on a running server before changing anything: main makes 2
RPCs per small file.

## What changed

- **Server** (`daemon-file-stream.ts`): the first read is `offset 0,
length 64 KiB`. The daemon returns the metadata together with `min(64
KiB, size)` bytes, and the stream source uses those bytes as its first
chunk when the response starts at byte 0. A file up to 64 KiB, or a
preview sample of any file, now takes one RPC. Files over 64 KiB save
one RPC but still take two waves (first chunk, then the rest in
parallel).
- The first read stays metadata-only (`length: 0`) for HEAD,
`If-None-Match: *`, and ranges that don't start at byte 0 (video seeks,
suffix ranges), so those requests don't ship 64 KiB that would be thrown
away.
- The prefetched bytes are used only when they cover the stream's first
read exactly. Any mismatch falls back to a normal chunk read, so the
choice of first read can cost an extra RPC but can't change the
response.
- **Wire change, `HOST_DAEMON_PROTOCOL_VERSION` 281 → 282:**
`host.read_file_chunk` gains a required `knownRevisions: revision[]`
(max 16). The server fills it from the request's `If-None-Match` tags
(`W/"file-<revision>"`). When the file's current revision is in the
list, the daemon returns the metadata with no bytes, and the server
answers `304` from that same read.
- Without this field, every image revalidation would ship up to 64 KiB
for nothing. The alternative, probing with `length: 0` whenever
`If-None-Match` is present, would bring back the second RPC for files
that changed.
  - Chunk reads after the first send `[]`.
- **Daemon** (`file-read.ts`): reads 0 bytes when the revision is known.
The revision check and the read are otherwise unchanged.
- **Docs:** updated the streaming paragraph in
`docs/debugging-and-qa.md`.

## How you verified

**Real running servers, main vs this branch, same inputs.** I ran `pnpm
start:worktree` (its own dev data dir, not `~/.bb`) on main, then
rebuilt and restarted it on this branch. There were two hosts:
- the local primary daemon;
- a second dev daemon enrolled via `POST /hosts/join-codes`, whose
`BB_SERVER_URL` pointed at a TCP proxy that delays each direction by 100
ms (**~200 ms RTT**).

I counted host RPCs on the remote daemon with an `--import` preload that
logs every `fs.open` of the test directory. Each `host.read_file_chunk`
opens the file exactly once. Each cell below is the median of 8 requests
to `GET /api/v1/hosts/:id/files/<path>`.

Remote host (200 ms RTT):

| request | file | main RPCs | branch RPCs | main ms | branch ms |
|---|---|---|---|---|---|
| GET | 2.7 KB txt | 2 | **1** | 411 | **208** |
| GET | 12 KB png | 2 | **1** | 411 | **206** |
| GET | 48 KB png | 2 | **1** | 411 | **206** |
| GET | 300 KB jpg | 6 | 5 | 412 | 412 |
| file-viewer sample `Range: bytes=0-65535` | 12 KB png | 2 | **1** |
410 | **207** |
| file-viewer sample `Range: bytes=0-65535` | 300 KB jpg | 2 | **1** |
410 | **208** |
| revalidation, stale ETag (file changed) → 200 | 48 KB png | 2 | **1**
| 410 | **206** |
| revalidation, matching ETag → 304 | all | 1 | 1 | ~206 | ~206 |
| HEAD | all | 1 | 1 | ~206 | ~208 |
| seek `Range: bytes=100000-` | 300 KB jpg | 5 | 5 | 414 | 421 |

- **Per action:** opening an image in the file viewer is the 64 KiB
sample request plus the image GET (`loadFilePreview` in
`apps/app/src/lib/api.ts`). For a ≤64 KiB image that drops from 4 RPCs /
~820 ms to 2 RPCs / ~410 ms on the remote host. Each image rendered from
the file URL saves ~200 ms.
- **Local host:** every request is 2–5 ms on both builds, with no
measurable change.
- **Correctness on both hosts:** full and ranged bodies are
byte-identical to the files on disk (sha1 compared). A file appended
between requests revalidates to a full `200` with the new bytes in one
RPC.

**Tests:**
- New route test in
`apps/server/test/files/file-content-routes.test.ts`. It asserts the
daemon command sequence (offset, length, `knownRevisions`) for GET, the
preview Range, matching and stale `If-None-Match`, HEAD, a multi-chunk
file (no duplicate offset-0 read), and a seek. It fails on main, which
sends a `length: 0` probe and then re-reads offset 0.
- New daemon test in `host-files.test.ts`: the first chunk comes back
with metadata, and a known revision returns no bytes.
- Ran locally: `turbo run typecheck --filter=@bb/server
--filter=@bb/host-daemon`. Vitest for `file-content-routes`,
`host-file-routes`, `daemon-file-stream`, `file-stream-response` (77
passed), and `host-files` plus `server-connection` in the daemon (60
passed). `packages/host-daemon-contract/test/contract.test.ts` now pins
protocol 282 and rejects a missing, malformed or over-long
`knownRevisions` (56 passed). 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 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.

1 participant