Skip to content

[codex] Update sidebar manager row presentation - #6

Merged
SawyerHood merged 2 commits into
mainfrom
bb/update-sidebar-manager-row-icon-thr_aj9cjrxpyq
May 14, 2026
Merged

SawyerHood merged 2 commits into
mainfrom
bb/update-sidebar-manager-row-icon-thr_aj9cjrxpyq

Conversation

@SawyerHood

Copy link
Copy Markdown
Collaborator

Summary

  • Removes the visible manager label/pill from sidebar manager rows.
  • Moves the manager user icon into the leading slot and swaps it to the expand/collapse indicator on hover/focus for managers with children.
  • Indents manager rows so the leading icon aligns with the parent project label.
  • Removes the managed-child count badge from the right side of manager rows.

Validation

  • PASS: pnpm exec turbo run test --filter=@bb/app -- src/components/sidebar/ThreadRow.test.tsx
  • PASS: pnpm exec turbo run test --filter=@bb/app -- src/components/sidebar/ProjectRow.test.tsx
  • PASS: pnpm exec turbo run typecheck --filter=@bb/app
  • PASS: git diff --check
  • CAVEAT: pnpm exec turbo run lint --filter=@bb/app fails on apps/app/src/components/dialogs/HireManagerDialog.tsx:216 with react-hooks/exhaustive-deps.
  • Confirmed unrelated: latest origin/main at cbe708b7 fails the same @bb/app lint command with the same HireManagerDialog.tsx:216 error.

@SawyerHood
SawyerHood force-pushed the bb/update-sidebar-manager-row-icon-thr_aj9cjrxpyq branch 2 times, most recently from 8eb5982 to 321ca80 Compare May 13, 2026 21:42
@SawyerHood
SawyerHood force-pushed the bb/update-sidebar-manager-row-icon-thr_aj9cjrxpyq branch from 7110df6 to d617985 Compare May 14, 2026 18:59
@SawyerHood
SawyerHood marked this pull request as ready for review May 14, 2026 19:02
@SawyerHood
SawyerHood merged commit d2a9509 into main May 14, 2026
1 check failed
brsbl added a commit to brsbl/bb that referenced this pull request 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]>
SawyerHood added a commit that referenced this pull request Jul 31, 2026
## The bug

`experimental_NewThreadComposer` exposed only `defaultProjectId` and
`initialPrompt` as seeds. A plugin that stores the submitted
`NewThreadRequest` and re-opens it for editing (e.g. bb-plugin-slopcop's
`RuleEditor`, where the composer's submit IS the save) got a composer
reset to project defaults on every mount — so re-saving after an
unrelated edit silently overwrote the stored provider, model, permission
mode, and environment. No warning, no diff.

## The fix

Additive, optional seed props on `NewThreadComposerProps`:

- `defaultProviderId`, `defaultModel`, `defaultReasoningLevel`,
`defaultServiceTier`, `defaultPermissionMode` — fed into
`useThreadCreationOptions` as initial values, taking precedence over the
project's remembered defaults and falling back to today's behavior when
omitted.
- `defaultEnvironment` — a new pure mapping
(`new-thread-environment-seed.ts`) inverts
`resolveRootComposeThreadEnvironment`: args → encoded environment-picker
selection + branch pick, including the managed-worktree base branch and
unmanaged existing/new branch specs. Unrepresentable variants are
documented on the prop (`project-default` seeds nothing; `personal`
without `hostId` and an `unmanaged` non-null `path` cannot be encoded).

Semantics (documented in the prop doc comments): they are seeds, not
controlled values; the props are value-compared each render, and any
change re-seeds every selection — including user-touched ones — via the
creation-options `resetKey`, following the established
`defaultProjectId` re-seed-during-render pattern. So switching between
two saved records in one mounted composer reloads that record's values.

Supporting fix in `useThreadCreationOptions`: a `resetKey` change
cleared touched fields in a layout effect *after* the render's
`executionInputSources` had been computed, so the reset render reported
stale `explicit` provenance. The provenance memo now treats a pending
reset as "nothing touched", mirroring the render-time rule
`renderedThreadSelections` already applies.

`RootComposeView` is untouched. The SDK testing harness's fake composer
now echoes the seeds back on submit so plugin tests can cover
store-then-restore.

## Round-trip test

The property that prevents the data loss: feeding a submitted request
back in as the `default*` props and submitting untouched must reproduce
an equivalent request.

- `new-thread-environment-seed.test.ts` — pure round trip of every
environment variant (reuse, managed worktree named/default base,
unmanaged existing/new/no branch) plus the documented unrepresentable
cases.
- `PluginNewThreadComposer.test.tsx` — renders the real composer (prompt
box + query hooks mocked) and asserts: (1) a seeded, untouched submit
`toEqual`s the stored request; (2) after a user touches the model,
swapping in a second record's seeds re-seeds everything and submits that
record exactly; (3) with no seed props, behavior is unchanged (project
defaults).

## Also

- Bundled type declarations regenerated via the repo scripts
(`build-bundled-dts.mjs`, `generate-templates.mjs`).
- bb-plugin-authoring skill: new props + store-then-restore pattern
documented.
- `docs/api_to_audit.md`: audit entry #6 for the seeding props.

`turbo lint`/`typecheck` clean for app, plugin-sdk, server, templates;
full `@bb/app` (2197 tests) and `@bb/plugin-sdk` suites pass.

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

`experimental_NewThreadComposer` exposed only `defaultProjectId` and
`initialPrompt` as seeds. A plugin that stores the submitted
`NewThreadRequest` and re-opens it for editing (e.g. bb-plugin-slopcop's
`RuleEditor`, where the composer's submit IS the save) got a composer
reset to project defaults on every mount — so re-saving after an
unrelated edit silently overwrote the stored provider, model, permission
mode, and environment. No warning, no diff.

## The fix

Additive, optional seed props on `NewThreadComposerProps`:

- `defaultProviderId`, `defaultModel`, `defaultReasoningLevel`,
`defaultServiceTier`, `defaultPermissionMode` — fed into
`useThreadCreationOptions` as initial values, taking precedence over the
project's remembered defaults and falling back to today's behavior when
omitted.
- `defaultEnvironment` — a new pure mapping
(`new-thread-environment-seed.ts`) inverts
`resolveRootComposeThreadEnvironment`: args → encoded environment-picker
selection + branch pick, including the managed-worktree base branch and
unmanaged existing/new branch specs. Unrepresentable variants are
documented on the prop (`project-default` seeds nothing; `personal`
without `hostId` and an `unmanaged` non-null `path` cannot be encoded).

Semantics (documented in the prop doc comments): they are seeds, not
controlled values; the props are value-compared each render, and any
change re-seeds every selection — including user-touched ones — via the
creation-options `resetKey`, following the established
`defaultProjectId` re-seed-during-render pattern. So switching between
two saved records in one mounted composer reloads that record's values.

Supporting fix in `useThreadCreationOptions`: a `resetKey` change
cleared touched fields in a layout effect *after* the render's
`executionInputSources` had been computed, so the reset render reported
stale `explicit` provenance. The provenance memo now treats a pending
reset as "nothing touched", mirroring the render-time rule
`renderedThreadSelections` already applies.

`RootComposeView` is untouched. The SDK testing harness's fake composer
now echoes the seeds back on submit so plugin tests can cover
store-then-restore.

## Round-trip test

The property that prevents the data loss: feeding a submitted request
back in as the `default*` props and submitting untouched must reproduce
an equivalent request.

- `new-thread-environment-seed.test.ts` — pure round trip of every
environment variant (reuse, managed worktree named/default base,
unmanaged existing/new/no branch) plus the documented unrepresentable
cases.
- `PluginNewThreadComposer.test.tsx` — renders the real composer (prompt
box + query hooks mocked) and asserts: (1) a seeded, untouched submit
`toEqual`s the stored request; (2) after a user touches the model,
swapping in a second record's seeds re-seeds everything and submits that
record exactly; (3) with no seed props, behavior is unchanged (project
defaults).

## Also

- Bundled type declarations regenerated via the repo scripts
(`build-bundled-dts.mjs`, `generate-templates.mjs`).
- bb-plugin-authoring skill: new props + store-then-restore pattern
documented.
- `docs/api_to_audit.md`: audit entry get-bb#6 for the seeding props.

`turbo lint`/`typecheck` clean for app, plugin-sdk, server, templates;
full `@bb/app` (2197 tests) and `@bb/plugin-sdk` suites pass.

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

---------

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

## What was wrong

Prompt Library searches kept the browse layout: a **Starred** section
ranked by fuzzy score, then a **Recent** section ranked by fuzzy score.
A starred prompt therefore beat a better match, prompts that start with
the query could be buried under weaker substring matches (`Deploy
later…` and `deploy the preview…` were 6th and 7th of 8 for `deploy`),
and starred prompts appeared twice (once per section). Separately, each
search inserted a "Searching prompts…" row above the list, so the list
jumped down and back on every keystroke.

## What changed

- `plugins/prompt-library/ranking.ts`: `rankByQuery` marks prefix
matches (case-insensitive, whitespace-collapsed) and sorts prefix
matches first, then fuzzy score, keeping input order (recency) for ties.
`compareRank` is exported for merging.
- `plugins/prompt-library/server.ts`: with a query, starred and history
matches are merged into one list ranked by prefix, then score, then
starred, then recency; history rows whose text is starred are dropped so
each prompt appears once. Browsing (empty query) is unchanged: starred,
then recent.
- `plugins/prompt-library/contract.ts`: **`search` output changed** from
`{ starred, recent }` to `{ prompts }`, each row with `kind: "starred" |
"recent"`. This also changes `bb prompts search --json`. Text output
follows the same order.
- `plugins/prompt-library/app.tsx`: while searching, section headers are
hidden and rows are keyed by prompt text, so the selection follows a
prompt when starring/unstarring moves it. The status row is gone:
results stay in place during a search, the search icon becomes a spinner
only for searches slower than 300 ms, and the first "Loading prompts…"
message renders inside the empty list.
- CLI help, the skill (`SKILL.md`) and `PLUGIN_OVERVIEW.md` describe the
ranking and the new output shape.

## How you verified

- `pnpm exec turbo run test typecheck lint --filter='...[origin/main]'`
(prompt library and bundled plugins), plus `turbo run test
--filter=@bb/web -- src/marketplace`.
- New tests:
- `server.test.ts`: one test checks the full order (prefix + starred,
prefix + newer, prefix + older, fuzzy + starred, fuzzy + newer, weak
fuzzy match), including a capitalised prefix and removal of the
duplicate starred row.
- `app.test.tsx`: no section headers while searching, and the selection
follows an unstarred prompt. This test fails without the text-keyed
rows.
- `app.test.tsx`: results stay in place with no status row while a
search is pending, and the spinner appears only after 300 ms. This test
fails against the old status row.
- Manual QA on a `pnpm start:worktree` instance with seeded history:
- Source CLI: `bb prompts search` checks ranking, project and thread
scopes, multi-word queries, extra whitespace, no-match queries, the flag
constraint, and star/unstar round trips. Unstarring moves a prompt from
#4 to #6 and re-starring moves it back.
- Headless Chrome: the popup shows one list without headers. With
Ctrl+S, the selection follows the moved row; Tab switches scope; Enter
inserts the prompt.
- A per-frame sampler ran over 166 frames of typing and deleting: the
list's top never moved, and the old status text never appeared.

> AGENT GENERATED

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

Co-authored-by: qa <qa@x>
Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 5, 2026
…7103)

## Human comments

## What was wrong

Sometimes an environment provider answers attach with a path that an
existing ready environment already holds. This happens for threads in
the project's own checkout, or for a worktree thread pointed at an
existing worktree. Core then adopts that row (`bindEnvironmentPath`) and
calls `refreshAttachedEnvironmentBranch` before the first turn. That
function used `host.inspect_git_source` with `remoteRefresh:
"background"`. The daemon then ran:

- a full `git status --porcelain=v1 --untracked-files=all`
- the default-branch ref reads (`symbolic-ref origin/HEAD`,
`for-each-ref`, `show-ref`, `rev-parse` ×2)
- the operation and linked-worktree probes
- a background `git fetch --all --prune`

The refresh only needs the branch currently checked out. Finding #6 in
the Nov 4 hot-path audit.

## What changed

- `apps/server/src/services/threads/thread-environment-placement.ts`:
`refreshAttachedEnvironmentBranch` now calls `host.inspect_git_checkout`
(repo check, `symbolic-ref HEAD`, `rev-parse HEAD`) and records only
`branchName`. No fetch.
- `packages/db/src/data/environments.ts`:
`recordEnvironmentCurrentBranch` no longer accepts `defaultBranch`,
because its only caller no longer passes it.
- No wire change: `host.inspect_git_checkout` already exists, so
`HOST_DAEMON_PROTOCOL_VERSION` is unchanged.

Left out, and why:

- **Refreshing `defaultBranch` on reuse.** The row keeps the value set
at provisioning. The daemon workspace watch reports `defaultBranch`
changes while the environment is watched, and the git plugin reads the
default branch live (`workspaceDefaultBranch` before the row value).
Re-reading it here would need the extra ref reads or a new daemon field.
The old code also wrote the current branch into `defaultBranch` when no
default could be found.
- **The refresh runs twice per thread.** On main, every probe in the
trace appears twice at the same timestamps, including two concurrent
`git status` runs. The branch build still shows two copies of the
checkout read (2 × `symbolic-ref` + `rev-parse`). The fix for that is in
the advancement scheduling and is out of scope here. At about 8 ms per
process it is now cheap.
- **Live measurement of the existing-worktree case.** It uses the same
function. I measured only the project-checkout case.

## How you verified

Measured on the real `~/Projects/bb` (4,489 local branches, 1 remote).
Two source servers, origin/main `fa30b0a7dc` and this branch, each on a
fresh data dir and run at the same time. `GIT_TRACE2_EVENT` recorded
every git process. Each sample creates a thread with `environment:
{type: "provider", environmentProviderId: "project-checkout"}` (what the
composer sends) against an existing ready project-checkout row. Wall
time runs from the thread's `created_at` to its `turn/started` event.
There were 10 interleaved pairs, with a 16 s gap so main's background
fetch finished before the next sample.

| | main | branch |
|---|---|---|
| git processes before the first turn | 34–37 | 12 |
| `git status -uall` before the first turn | 2 (60–920 ms each) | 0 |
| create → provisioning done (median) | 365 ms | 155.5 ms |
| create → turn started (median, min–max) | 410 ms (352–1,219) | 196.5
ms (184–584) |
| `fetch --all --prune` started | 6 / 10 (others hit the 30 s throttle)
| 0 / 10 |

When the fetch ran on main, it took about 3.3 s in the background, plus
a `rev-list --objects --all` child (~1 s) and `maintenance run --auto`.
Load average during the series fell from 31 to 4. The branch outliers
(338 ms, 584 ms) came at the highest load.

Branch correctness, live on the branch server: in a scratch repo project
I created thread 1, ran `git switch -c feature/live-check`, then created
thread 2. The reused row changed to `branch_name = feature/live-check`
and `default_branch` stayed `main`.

Tests:
- `apps/server` `test/threads/environment-providers.test.ts`: the
reused-row refresh test now asserts that exactly one
`host.inspect_git_checkout` runs, that no `host.inspect_git_source`
runs, and that `defaultBranch` is preserved. This fails on main. The
ordering test and the merge-base reuse tests now observe the checkout
read.
- `apps/server` `test/threads/`, `test/environments/`,
`test/public/public-threads.project-default.test.ts`,
`test/public/public-project-workspace-routing.test.ts`: 678 passed.
- `packages/db` `test/data/environments.test.ts`: 16 passed.
- `pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/db`:
passed.

> 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