Skip to content

Move new chat and manager actions into sidebar - #5

Merged
SawyerHood merged 5 commits into
mainfrom
bb/move-new-chat-and-manager-buttons-thr_mbvu2u5rzi
May 12, 2026
Merged

SawyerHood merged 5 commits into
mainfrom
bb/move-new-chat-and-manager-buttons-thr_mbvu2u5rzi

Conversation

@SawyerHood

@SawyerHood SawyerHood commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Add matching ghost New Chat and New Manager actions above Projects in the sidebar, aligned with thread row spacing and height through shared row classes.
  • Keep those sidebar actions outside the sticky project stack so the Projects sticky tier cannot clip the New Manager row.
  • Tighten the gap between the sidebar action buttons and the Projects heading with a compact sticky-stack top padding mode.
  • Remove the header New Manager action and route New Manager through the currently selected project by default.
  • Add a Project picker inside the Hire Manager dialog so the manager can be created for a different project before submitting, with project selection derived instead of synchronized through extra effects.
  • Use a shared hire-manager mutation key with useIsMutating so pending hires keep the action disabled after the dialog closes.
  • Add focused tests for sidebar actions, dialog project selection, and shared pending-state behavior.

Validation

  • pnpm exec turbo run typecheck --filter=@bb/app
  • NODE_OPTIONS=--no-experimental-webstorage pnpm exec turbo run test --filter=@bb/app -- src/components/dialogs/HireManagerDialog.test.tsx src/components/sidebar/ProjectList.test.tsx src/components/sidebar/AppSidebar.test.tsx src/hooks/mutations/project-mutations.test.tsx
  • pnpm exec turbo run build --filter=@bb/app
  • git diff --check

@SawyerHood
SawyerHood marked this pull request as ready for review May 12, 2026 22:23
@SawyerHood
SawyerHood marked this pull request as draft May 12, 2026 22:27
@SawyerHood
SawyerHood marked this pull request as ready for review May 12, 2026 22:35
@SawyerHood
SawyerHood merged commit f94cc99 into main May 12, 2026
1 check failed
brsbl referenced this pull request in brsbl/bb Jun 6, 2026
The Loading apps... / Couldn't load apps. notice rendered after the
Create App... row, so Create App was not last while apps were loading or
failed to load. Fold the app-load status above Create App inside the
trailing row group so Create App is always the final row in every app
state. Normal installed-app and no-app ordering and the #5/get-bb#6 ARIA/toolbar
fixes are unchanged. Add tests for the loading and error states asserting
the notice precedes Create App and Create App stays last.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
ymichael added a commit that referenced this pull request Aug 17, 2026
The only provider without an existing bridge, built canonical-only (no
legacy dialect; the legacy in-process adapter stays untouched and live).
Per decision #5 the bridge owns its app-server children: one per bb
thread with #1402 supervision (finalize on close with bounded grace,
pipe destruction, per-callback currency checks, allowlisted child env,
SIGTERM->SIGKILL escalation, kill-all on stdin close). Unexpected child
death settles open turns as failed and the next turn restores from the
rollout with a session/replaced notification.

Translation shared, not duplicated: the adapter's ~1,200 lines of
stateful closures extracted byte-identically into codex/translator.ts +
session-params.ts (adapter 2,255 -> 348 lines); event-translation,
schemas, interactive-requests, permission-mapping imported by both
dialects. Bridge-minted structural ids (bt<entropy>-<serial>-<codexId>)
keep parentToolCallId consistency with no maps and reverse-map for
steer/interrupt/fork including legacy-persisted raw codex ids.
Archived-session resumes reply SESSION_NOT_RESTORABLE with the original
text preserved for the unarchive-retry path. Handshake: sessionRestore,
archiveSync, nameSync, goalState, manualCompaction all true; fork
checkpoint; runtime approval policy.

Conformance 11/11 against real supervised fake-app-server children.
Suites 973 default + 253 isolated, zero legacy assertion changes; the
daemon build produces bb-codex-bridge.mjs, wired into the bundle
manifest, launcher required-artifacts, and the tarball smoke.

Co-Authored-By: Claude Fable 5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 9, 2026
## Human comments

## What was wrong

With the selection memo and projection fold both hitting, a push for one
new event still ran several passes over the whole latest window
(timeline perf audit, REPORT #5). On the snapshot threads the biggest
were:
- **Settled delegations.** Their child rows were built and mapped
bottom-up, then thrown away by `deferSettledTimelineRow` (572 of 634
rows on kdrbtee92b).
- **Sent-message detection.** `parseThreadTellCommand` scanned every
command's text several times per build (2 MB per pass on u738kqjs29,
about 14% of a push).
- **Interrupted turns.** Once any turn in the window had been
interrupted, every fold finish ran `structuredClone` on the whole
projection state, because `pendingFinalizationByTurnId` is never cleared
(6 of 150 sampled active threads, 1–1.8 ms per push).
- **Decoding and byte counts.** Every row was decoded and its bytes
counted again.
- **Byte-budget pagination.** It ran `JSON.stringify` on every leaf,
then on every returned segment.
- **Tag and delta.** Every row object was fresh each build, so the tag
and delta hashed and stringified all of them again.

## What changed

- **thread-view.** `buildThreadTimelineFromEvents` takes a new
`omitSettledDelegationChildRows` option. The server sets it when
`deferContent` is on, and settled delegations then skip building their
child rows. Emptiness is still checked lazily, so the output keeps the
exact `null` vs `[]` that deferral produced.
- **thread-view.** `parseThreadTellCommand` results are cached by
command string, bounded the same way as `shellIntentCache` (16k entries,
8M chars), and every call returns a fresh object.
- **thread-view.** `copyProjectionStateForFinish` deep-copies only when
interrupted-turn finalization would actually change something: a running
call, or a pending message or cell scoped to that turn.
`interruptedTurnFinalizationChangesState` implements the check.
- **server.**
- `timeline-selection-decode.ts` / `timeline-selection-memo.ts`: when a
selection extends the previous one, it reuses the decoded prefix and its
byte count. The decoded rows live on the selection memo entry whose rows
they decode, so they have exactly the memo's bounds (16 entries, 4 idle,
16M data chars) and go away wherever the memo drops an entry: thread
delete, rewrite generation or `data_version` change, context-clear epoch
change, and eviction.
- `timeline-content-pagination.ts` / `timeline-pagination.ts`: JSON byte
counts are cached per row object, and array and parent sizes are derived
from their parts (exact for any UTF-8).
- `timeline-window-reuse.ts`: unchanged latest-window rows, and window
fields like todos and provider commands, are reused from the previous
build when they serialize identically, key order included. The tag,
delta and cache accounting then only touch rows that changed.
`getOrBuild` now passes the stale response to the builder for this.
- `timeline-selection-memo.ts`: the previous build's pageable rows,
which the next build reuses rows from, live on the selection memo entry,
one set per `deferContent`/`includeNestedRows` variant. Their JSON bytes
count toward the memo's 16M budget along with the selection's data
chars, and they go away wherever the memo drops an entry. Only rows
whose JSON size pagination already measured are kept, so the size costs
nothing extra (e515883).
- **server, after rebasing onto #7245.** #7245's projection cache shares
built rows between windows and keyed them only by `includeNestedRows`.
Deferred reads now leave out settled delegations' child rows, so a CLI
read after an app read could reuse the app's rows and lose a subagent's
children. `timeline-projection-cache.ts` now keys rows by
`includeNestedRows` and `omitSettledDelegationChildRows`. The first
non-deferred read after an app read builds its own rows; the projection
is still shared. In the selection memo, a selection shared by several
entries counts its data once, and kept pageable rows count per entry. An
entry that adopts a sibling's selection starts with no kept rows instead
of sharing the sibling's map.
- **No contract change.** No wire, CLI, SDK or plugin surface changes.
Output is byte-identical to main.

Not changed:
- **Push pacing** still waits the last build's duration (capped at 1 s).
Cheaper builds shorten it directly.
- **Remaining u738kqjs29 cost.** Most of its remaining push cost is the
fold finish over completed turn t3 (7.4k events). The window loads t3
only as context and the page doesn't return it. Removing that needs
page-bounded reads (#4674 / S6), not hit-path work.
- **kdrbtee92b grouping-context SQL.** About 10% of its push is still
`getTimelineGroupingContext` running again whenever child (parented)
events are appended.

## How you verified

**Before/after.** Harness push scenario: warm latest read with
`afterTag` after appending one `item/started`. In-process on a clone of
the Nov 7 snapshot. 4 alternating main/branch pairs × 12 appends, load
average 14–19 (other slices were benchmarking at the same time). Median
of per-run medians:

| thread | main ms | branch ms | Δ |
|---|---|---|---|
| kdrbtee92b (active) | 4.0 (3.5–4.4) | 2.8 (2.8–3.0) | −30% |
| u738kqjs29 (forced active) | 15.4 (14.3–16.2) | 9.8 (9.4–10.6) | −36%
|
| 8nnix6m53a (forced active) | 5.9 | 3.0 | −48% |
| gyi25h9awq (forced active) | 10.6 | 4.7 | −56% |
| wg5iwwrezi (forced active) | 10.9 | 4.3 | −61% |
| txqr3djnmd (forced active, interrupted turn) | 8.0 | 2.5 | −69% |
| mwktgwihcc (forced active, interrupted turn) | 8.1 | 3.2 | −60% |

An earlier round of 3 pairs at load average 37–58 showed the same
direction, with −16% to −61% and much wider spread.

**Memory.** The first version of this PR kept decoded selections in a
separate per-connection cache: 4 per thread for 64 threads, bounded by
count only, never dropped on thread delete, rewrite or idle. It retained
rows the memo and the stored-event decode cache had already released.
They now live on the memo entries (49f4151). Retained `heapUsed`
after one instance reads the app, phone, CLI and nested windows of each
thread, after a forced GC, on a clone of the snapshot:

| scenario | main | c381f52 | 49f4151 |
|---|---|---|---|
| 12 harness threads | +63 MB | +321 MB (261 MB in the decoded-selection
cache) | +67 MB |
| 12 harness + 293 most recent threads | +109 MB | +295 MB | +108 MB |
| 12 harness threads, forced active | – | – | +74 MB |

Push and warm timings for 49f4151 vs c381f52: harness `push` +
`warm`, 9 alternating pairs × 12 appends (3 of them reversed-order, 3
interleaved), load average 7–9. Median of per-run medians:

| case | c381f52 | 49f4151 |
|---|---|---|
| warm push, kdrbtee92b | 2.5 ms | 2.4 ms |
| warm push, u738kqjs29 (forced active) | 8.8 ms | 9.1 ms (last 3
interleaved pairs: 8.8 vs 8.8) |
| cold after append, kdrbtee92b / u738kqjs29 | 33.4 / 207.8 ms | 34.0 /
207.4 ms |
| warm cache hit, all 12 threads | 0.0–0.1 ms | 0.0–0.1 ms |

Rows read, decoded and folded per push are identical, and
`event-json-decode` stays under 0.1 ms on both, so the prefix is still
reused.

**Memory, kept pageable rows (e515883).** Before this commit the
reused rows sat in a separate per-connection map of the last 32 windows.
The bound was a count, and nothing dropped a thread's windows on
rewrite, compaction or memo eviction. Same measurement as above. In
brackets: heap freed by dropping the kept rows once the windows instance
is gone.

| read set | 49f4151 | e515883 |
|---|---|---|
| 12 harness threads | +66.5 MB (5.9) | +66.5 MB (1.0) |
| 305 threads (12 harness + 300 most recent) | +108.3 MB (3.2) | +108.4
MB (1.2) |
| the same 305, harness threads read last | +128.6 MB (5.9) | +112.4 MB
(1.0) |
| 318 threads, the 17 largest read last | +149.1 MB (14.4) | +140.3 MB
(0.0) |

On this branch alone the old map stayed small in the default read order,
because the last 32 windows read were small threads. With the larger
merged integration branch (#7250) it measured 33 MB at 305 threads.

The first version of this commit charged every pageable row. That
stringified the older context rows pagination never measures, and it
doubled u738kqjs29's first CLI, nested and summary reads after an app
read (27 → 57 ms). Keeping only measured rows removed that cost.

Timings for e515883 vs 49f4151: harness `cold`, `warm`,
`variants`, `capacity` and `push`. Push threads were kdrbtee92b plus
u738kqjs29, wg5iwwrezi and txqr3djnmd forced active, 12 appends, 5
repeats. 4 alternating pairs, each started at load below 8 (4.3–6.3).
Median of per-run medians:

| case | 49f4151 | e515883 |
|---|---|---|
| warm push, kdrbtee92b / txqr3djnmd / wg5iwwrezi / u738kqjs29 | 1.9 /
2.05 / 3.55 / 8.6 ms | 1.9 / 2.1 / 3.6 / 8.15 ms |
| cold after append, u738kqjs29 | 205.8 ms (202.5–212.5) | 210.8 ms
(206.6–220.3) |
| cold app latest, sum of 12 threads | 567.7 ms | 570.7 ms |
| first variant read after app, sum of 48 | 782.8 ms | 788.5 ms |
| u738kqjs29 CLI log after app | 26.85 ms | 27.15 ms |
| capacity reopen | 19.3 ms | 19.35 ms |
| warm cache hit, all 12 threads | 0.0–0.1 ms | 0.0–0.1 ms |

Every rows-read, decoded, bytes and response-bytes metric is identical
between the two.

**Parity.** Responses were hashed on main and on the branch over a
read-only clone of the snapshot:
- All 947 threads with ≥1,000 events, six window variants each: app
latest, phone (segmentLimit 8), CLI, nested, nested+deferred,
summaryOnly.
- Up to three older pages per thread.
- A 13-step incremental replay on 112 threads (the 12 harness threads
plus 100 sampled), app and CLI params. Each step compares warm memo,
fold and row-reuse builds against a cold build at the same maxSeq, and
also hashes the delta from the previous step.

Result: 9,723 / 9,723 hashes identical to main, and warm equals cold at
every replay step. Retained-output availability, which depends on
`Date.now()`, was normalized before hashing. Re-run on 49f4151 with
the same script on a fresh clone: 9,723 / 9,723 identical to main and to
c381f52, warm equals cold at every replay step.

e515883 vs 49f4151, using the integration's parity and
append-replay scripts on fresh clones:
- 162 threads × 8 variants, older pages, turn details and outlines:
4,652 forward-order and 2,462 reverse-order hashes, all identical.
- Append replay over 64 thread-runs: 1,024 steps and 5,120 deltas, 0
warm-vs-cold mismatches on both.

**Tests added.** I ran the `structuredClone` test against the old
condition, where it fails. The others test code paths that don't exist
on main, so they weren't run there.
- `thread-view/test/settled-delegation-child-rows.test.ts`: omitted
child rows equal deferring the full rows, including nested, childless
and pending delegations.
- `thread-view/test/event-projection-fold.test.ts`: fold matches cold
after every event for an interrupted turn with nothing pending, and
finishing does not call `structuredClone`.
- `thread-view/test/tool-call-parsing*.test.ts`: cached results are
independent objects, repeated parses are reused, and the existing
linearity benchmarks now use unique commands so the cache can't mask
them.
- `server/test/services/threads/timeline-selection-decode.test.ts`:
prefix reuse and byte count. The memo entry carries the decoded rows and
a reused selection extends them. Decoded rows are dropped on history
rewrite and thread forget, and when the memo evicts the entry for its
data-char budget or its entry cap.
- `server/test/services/threads/timeline-selection-decode.test.ts`, kept
pageable rows (e515883). A build reuses no row objects after the memo
forgets the thread. Kept rows count toward the memo budget, so a second
thread of the same size evicts the first. Both tests fail on 49f4151,
where the rebuilt rows are still the old objects.
- `server/test/services/threads/timeline-window-reuse.test.ts`:
unchanged rows keep identity across an append and serialize like a fresh
build; reuse only happens on exact JSON equality, including key order.
- `server/test/services/threads/timeline-content-pagination.test.ts`:
derived byte counts equal `Buffer.byteLength(JSON.stringify(rows))` for
nested multibyte rows.
- `server/test/services/threads/timeline-window-sharing.test.ts`: the
CLI window built after the app window keeps a settled subagent's child
rows. It fails without the cache-key change (`[null]` instead of `[1]`).
The existing sharing test now expects a row rebuild for each new row
shape (`includeNestedRows` × `deferContent`).

**Commands run.**
- e515883: `turbo run typecheck lint --filter=@bb/server`, plus
vitest on `test/services/threads` and `test/provider-corpus` (34 files,
293 tests pass, 1 skipped). All with `env -u BB_ACCOUNT_POOL_PARENT_URL
-u BB_SERVER_URL -u BB_CLI`.
- `pnpm exec turbo run typecheck test --filter=@bb/server
--filter=@bb/thread-view --filter=@bb/provider-parity`
- 49f4151: `turbo run typecheck lint --filter=@bb/server`, plus
vitest on `test/services/threads/timeline*`, `thread-events`,
`conversation-outline*`, `test/provider-corpus`, `event-pruning` and
`internal-event-append-ownership` (25 files, 241 tests pass, 1 skipped)

**After rebasing onto main at 226d128** (#7245, #7238, #7254, #7284):
`turbo run typecheck lint --filter=@bb/server`, `turbo run typecheck
test --filter=@bb/thread-view --filter=@bb/provider-parity`, and vitest
on `test/services/threads` and `test/provider-corpus` (38 files, 312
tests pass, 1 skipped). Push harness, 4 threads × 12 appends, rebased
branch vs main at be3ca2c: warm push −37% to −64%, identical response
bytes (load average 12–38, so the exact numbers are noisy).

Refs #4674 (does not fix it)

> 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

Refreshing branches (`GET /projects/:id/branches`, used by the picker's
Refresh, `bb project branches` and `sdk.projects.branches`) chained its
two host RPCs: the server sent `host.inspect_git_source` with a blocking
remote fetch, waited for the reply, and only then sent
`host.list_branch_options` so the list would include fetched branches.
On a remote host that is two serial round trips. This is finding #5 of
the server→daemon RPC audit.

## What changed

- **Wire change, `HOST_DAEMON_PROTOCOL_VERSION` 281 → 282.**
`host.list_branch_options` takes `remoteRefresh: "background" |
"blocking"`, the same values as `host.inspect_git_source`. The server
only ever sent `"none"`, which is gone. A 281 daemon rejects
`"blocking"`, so the bump is required.
- **Server** (`apps/server/src/routes/projects.ts`): both branch routes
send the two RPCs together with the same `remoteRefresh`. `/branches` is
now one round trip.
- **Daemon** (`bb-environment-provider-host` `listBranchOptions`):
`"blocking"` awaits `refreshRemoteBranches` before reading refs. That
function keeps one in-flight fetch per repo, so the two blocking RPCs
share a single `git fetch` and both read after it. The git plugin's
local `"none"` call is unchanged.
- No response-shape, CLI or SDK change. Picker reads (open and
keystrokes) keep main's parallel pair.

Removing `git status` from every keystroke, which an earlier revision
did with a server-side inspection cache, is left out. It needs either
that cache, whose search responses carry state up to 30 s stale, or a
change to the response shape.

## How you verified

**Live A/B on the host-RPC latency rig.** A second daemon reached
through a proxy adding 100 ms each way (~200 ms RTT). The proxy decodes
WebSocket frames to log every `host-rpc.request`, and the remote daemon
logs every git spawn. The project is a clone of this repo (9,101 files,
1,730 remote branches); 10 rounds each of open, four keystrokes and
`/branches`.

| `/branches`, remote (n=10) | main | this PR |
|---|---|---|
| median | 531 ms | **270 ms** |
| second RPC starts after the first | 286 ms (serial) | **0 ms**
(together) |
| `git fetch` per refresh | ≤1 | ≤1 (shared, never 2) |

- Responses are byte-identical to main for open, search, search with
`selectedBranch`, and `/branches` with and without a query. Also
identical for a repo mid-merge with conflicts plus a dirty tree, and for
a non-git folder.
- Background fetches: 6 in both runs.
- Open and keystroke requests send the same two parallel RPCs as main.

**Tests:**
- `host-branches-dispatch.test.ts`: a blocking
`host.list_branch_options` sent while a background fetch is held open
waits for it and lists the fetched branch. It fails if `"blocking"`
behaves like `"background"`.
- `public-project-workspace-routing.test.ts`: `/branches` has both
blocking RPCs in flight before either replies.
- Contract and provider-host suites pass. `turbo run typecheck lint`
passes for `@bb/server`, `@bb/host-daemon`, `@bb/host-daemon-contract`,
`bb-environment-provider-host` and `bb-plugin-bb--git`.

🤖 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.

1 participant