Skip to content

Reconnect the SDK realtime client after a refused connection - #6183

Merged
ymichael merged 1 commit into
mainfrom
bb/sdk-realtime-reconnect-thr_6e9knccemi
Oct 23, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/sdk-realtime-reconnect-thr_6e9knccemi

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

The SDK realtime client (packages/sdk/src/realtime-client.ts) had two failure modes on a refused connection. Its socket.onerror called close(), and undici's close() on a failing connection fires error again synchronously, so the handler recursed until the stack overflowed. And a first connection refused without a close event left the client closed for good, with no reconnect scheduled. Any SDK client that subscribes while the server refuses connections hits both.

What changed

  • socket.onerror closes a failing socket once; a repeated error from close() is ignored.
  • The error path runs the same close handling as onclose, so a refused first connection schedules a reconnect.
  • No wire, CLI or SDK surface change.

How you verified

  • packages/sdk/test/realtime-client.test.ts (new), both failing on main and passing here:
    • "closes a failing socket once even when close reports another error"
    • "reconnects after a first connection fails without a close event"
  • CI on this head.

AGENT GENERATED

🤖 Generated with Claude Code

socket.onerror closes a failing socket once: undici's close() on a failing connection fires error again synchronously, which recursed until the stack overflowed. A first connection refused without a close event now schedules a reconnect instead of staying closed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 96e5c8d into main Oct 23, 2026
49 checks passed
@ymichael
ymichael deleted the bb/sdk-realtime-reconnect-thr_6e9knccemi branch October 23, 2026 23:19
ymichael added a commit that referenced this pull request Oct 24, 2026
## Human comments

## What was wrong

`main` has 14 commits since 0.47.0, including #6195, which fixes the
timeline staying detached at the bottom (a regression from #5951 that
shipped in 0.47.0). `bb-app` and `@bb/desktop` were still at 0.47.0, so
the publish and desktop workflows can't ship them.

## What changed

- `packages/bb-app/package.json`, `apps/desktop/package.json`: 0.47.0 →
0.47.1 (`node scripts/bump-version.mjs --patch`).
- No `CHANGELOG.md` or `RELEASE_META` entry: like earlier fix-only
patches, these changes go into the 0.48.0 notes.

The release commit sits directly on `b17bfc8fdd` (#6217). Everything
below was tested on `22d41249ee`, and the sidebar was tested again on
`b17bfc8fdd`. This release includes the daemon protocol bump from #6185
(251 → 252), so enrolled machines will update their daemon.

## How you verified

- `node .github/workflows/check-version-lockstep.mjs`: `bb-app=0.47.1
@bb/desktop=0.47.1`.
- Typecheck, tests and the `bb-app` tarball smoke run in CI on this PR,
instead of locally.
- `git diff --check`, and `oxfmt --check` on the changed files: clean.
- Manual QA of `22d41249ee` with `pnpm start:worktree` (production
bundle) and headless Chrome, on a fresh data dir:
- **Timeline (#6195):** a long unread reply stops at NEW, detached. A
short unread reply opens at the end with no jump arrow. Scrolling up 150
px and growing the viewport 900 → 1200 attaches. Scrolling up 400 px and
growing it stays detached. Sending after scrolling up 1,800 px jumps to
the end and follows the streamed Claude Code reply. The view is still at
the end after a reload.
- **Docs (#6146):** typing in a note while `bb docs pull`/`push`
appended a paragraph kept both edits on disk and in the editor. A stale
push after a UI edit was refused as a conflict. A new note was renamed
from its first line and kept its Markdown after a reload.
- **Skills (#6185):** `bb project commands` lists project skills from
the documented roots for Claude Code and Codex, with no duplicate names.
A Codex `/skill` turn ran the skill.
- **Storage & retention (#6190, #6205):** two outside worktrees were
listed. Bulk removal removed the clean one, kept its branch, and kept
the dirty one. The table fits a 390 px viewport.
- **Sidebar multi-select (#6191, #6217), on `b17bfc8fdd`:** with the
experiment on, Cmd+Shift-click selected a second thread without
navigating ("Actions for 2 threads"). Pressing it again on the same
thread deselected it. Shift-click selected a range of 4. Escape cleared
the selection. Cmd-click cleared the selection and opened a split. Bulk
Pin applied to the two selected threads (checked with `bb thread list`).
With the experiment off, Cmd-click opens a split.
- **omp (#6186):** the picker labels GPT-5.6 Terra rows `openai` and
`openai-codex`.

Not exercised: the Ultrafast icon (#6198), because no Codex model on the
test account offers Ultrafast. Also not exercised: the Android
touch-drag attach, the desktop app, the SDK realtime reconnect (#6183)
and retryable host RPCs (#6184). Those last two are covered by unit
tests only.

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

## What was wrong

Core owns every git read: the daemon's `workspace.status` /
`workspace.diff*` / branch commands, the server's
`/environments/:id/status`, `/diff*` and `/diff/branches` routes with
their read cache, diff tiering and result adapters, and the CLI's `bb
environment` diff commands. Plugins can't replace or build on any of it.
This PR moves the read side into a bundled Git plugin. Core's Diff tab,
Info git rows, composer segment, Commit dialog and `bb thread show
--git-diff` keep their UI and read through the plugin's RPCs; #6157
moves that UI into the plugin.

Based on `main`, which now has #6183 (SDK realtime reconnect) and #6184
(`experimental_retryable`) that this PR uses.

## What changed

**Git plugin (`plugins/git`, id `bb--git`, bundled and enabled by
default, no app entry yet)**

- **Host** (`host.ts`, `host/*`): status, diff, files with initial
patches, patches and branch options.
- `packages/host-workspace/src/workspace.ts` moves (`git mv`) to
`host/workspace-reads.ts`. Its byte-budget and commit caches and their
tests move with it, as does the server's diff tiering.
- Git code only the plugin calls (`runGitWithNullRecordLimit`, the raw,
numstat and name-status parsers, `readMergeBaseRef`) lives in
`host/git.ts`. The record-limited listing is a record parser over the
shared runner's streaming `onStdout`, which stops git once the limit is
reached.
- Reads run in the plugin host worker, with its own VCS process pool.
Diff, file, patch and branch reads run at interactive priority: the
handler sets it in a plugin-local store, and the plugin's git calls pass
it explicitly to `experimental_runVcsProcess`. The read methods are
`experimental_retryable`.
- One `WorkspaceReads` is kept per path, capped at 64, so the repo
probes core repeated on every read run once per workspace.
- A reference-counted index copy keeps the real index's times and never
writes a split index. It lives in the worker's temp directory and is
removed when the last reader releases it.
- A racy-untracked guard re-reads only when the work generation changed
within the mtime granularity window.
- Patch batches are capped at 6 MiB and return the rest as `deferred`;
the server loops until every requested path is answered.
- **Server** (`server.ts`, `server/*`):
- Reads: keyed `status` and `patches`, plus `workspaceStatus`, `diff`,
`files`, `fileSide`, `branches`.
- Mutations: `viewed`, `markViewed`, `clearViewed`, `setMergeBase` and
`refresh`.
- `status` and `files` share in-flight reads and keep results for 3 s
(`createAsyncTtlMemo` from `@bb/async-cache`). Generation tokens are
unique per process and change on every environment change. Unwatching an
environment drops its caches.
- Invalidation comes from `environment:changed` while a client watches,
coalesced per environment. The turn-end status heal subscribes only
while something is watched, checks the watch first, caches thread →
environment, and unsubscribes on dispose.
- `fileSide` reads through `bb.sdk.files.read({ ref })`, core's
`host.read_file`, so its limits and `ENOENT` / `invalid_path` /
`file_too_large` outcomes are core's.
- CLI: `bb git status|branches|diff|files|file|patch|viewed`. Output,
error codes and stderr (including the `Error: ` prefix) match what the
old `bb environment` commands printed.
- **Types**: the plugin's own shapes (workspace status, diff response,
file stats, the host contract) live in `plugins/git/contract.ts`; the
RPC contract in `plugins/git/rpc-contract.ts`. Core keeps its schemas
where they are on main (`@bb/domain`, `@bb/host-daemon-contract`,
`@bb/server-contract`). The few the plugin host needs at runtime (diff
target, branch options, checkout ref, resolution failure, branch list
limits) have plugin-side copies, and
`plugins/git/contract-copies.test.ts` checks each copy's
`z.toJSONSchema` against core's.

**Shared between the daemon and the plugin
(`bb-environment-provider-host`)**

Only code both still call:
- `workspace-git.ts`: the one git runner, on the public host process
APIs. It spawns with `experimental_spawnPortableOutputProcess`, or with
the provider-bridge entry's `experimental_spawnPortableProcess` (and
`experimental_killPortableProcess`) for the six reads that feed git
stdin (`log --stdin`, `patch-id`, `hash-object --stdin(-paths)`). It
admits each run through `experimental_runVcsProcess` with an explicit
priority, and keeps the byte caps, truncated stdout, timeouts with a 1 s
force kill, the Windows startup-crash retry and process-group kill. It
also holds `WorkspaceError` and its failure mapping,
`parsePorcelainV2StatusZ`, and `createGitQueries`, the repository,
branch and default-branch queries. Environment providers'
`bb-environment-provider-host/git` is now a wrapper that runs it at
background priority.
- `branch-options.ts`: branch listing, used by the daemon's
`host.list_branch_options` and the plugin's `branches`.
- `git-types.ts`: zod-only schemas for the above, safe in the plugin
host and app bundles.

Core-only git code stays in `@bb/host-workspace/src/git.ts`, as on main.
Code that lost its last caller is deleted.

**Core on the plugin's reads**

- **Daemon**: the git read commands are gone and
`HOST_DAEMON_PROTOCOL_VERSION` goes 254 → 255 (only 255 is compatible,
as on main: the server now sends a git `ref` to `host.read_file`).
Workspace resolution collapses to `requireResolvedWorkspaceForCommand`.
- **Server**:
- The status, diff and branch read routes are gone, along with the
workspace read cache, diff tiering and RPC result adapters.
- Commit reads its status and diff through the plugin
(`git-plugin-reads.ts`) and calls `refresh` afterwards. With the plugin
off it fails with 409 `git_plugin_unavailable`, and the message names
the plugin's state.
  - `files.read` accepts a git `ref` (with `rootPath`).
- The plugin CLI output cap is 32 MiB, so `bb git diff` and `bb git
file` print what `bb environment diff` and `diff-file` printed.
- **App**:
- The environment query hooks keep their keys, placeholders and cache
owners. Their fetchers call the plugin through
`hooks/queries/git-plugin-reads.ts`.
- Each hook watches the environment's plugin `status` read, so the
plugin shares its cache across them.
- The live plugin-frontend reconcile that runs on every WebSocket
connect marks frontends as pending only when a frontend actually loads,
changes or leaves. Before, every reconnect flipped "settled" true →
false → true about 250 ms after boot. With the bundled Git plugin's
frontend on that path, the flip swapped the secondary panel surface and
remounted every Diff card (code → skeleton → code). A card probe on this
PR over 10 reloads: 10 of 10 doubled before, 0 of 10 after.
- Core UI is unchanged: every component stays in `apps/app` as on
`main`, and `@bb/shared-ui` is untouched. The only app changes are the
read path above and the type imports that follow the workspace and diff
types this PR moves out of `@bb/domain` and `@bb/server-contract` into
`plugins/git/contract.ts` (test builders into
`bb-plugin-bb--git/testing`).
- **CLI**: `bb thread show --git-diff` reads through the plugin. The old
`bb environment
status|branches|diff|diff-files|diff-file|diff-patch|diff-viewed`
commands still run and print the `bb git` command that replaced them.
`bb plugin build` prints server build warnings.
- **MCP**: read mode allows the bundled plugin's read-only `bb git`
commands.

**Retired SDK environment reads**

- `environments.status`, `diff`, `diffFiles`, `diffPatch`, `diffFile`
and `diffBranches` leave the public typings and docs.
- Runtime adapters
(`packages/sdk/src/areas/retired-environment-reads.ts`) keep their old
shapes, limits and error codes over `plugins.callRpc`.
- `bb-plugin-build` warns on calls to them. It detects optional,
aliased, bracket and destructured calls, and never fails the build.

**Plugin SDK 0.6.83 → 0.6.84**: the fake host's `experimental_watchRpc`
and the 32 MiB `PLUGIN_CLI_OUTPUT_MAX_BYTES`, both in
`docs/api_to_audit.md`. No new process primitives: the git runner uses
the existing public host APIs.

**Docs**: the bb-cli skill and command index, the backend SDK and CLI
guides, the new `references/git-reads.md`, the vcs-process-admission and
manual-runbook docs, the verify-bb feature map, and the plugin's
`PLUGIN_OVERVIEW.md`, README and `git` skill.

**With the Git plugin disabled** in this PR, core's Diff tab, Info git
rows and composer segment show their read errors, and Commit returns
409. #6157 hides them instead.

**Production lines** (excluding tests, stories, fixtures and docs):
+8,540 / −7,483, net +1,057. #6157 then moves the UI (net −676), so the
stack is net +381.

| Area | Added | Removed | Net |
|---|---:|---:|---:|
| `plugins/git/host` (workspace reads moved from `@bb/host-workspace`,
plugin-only git code) | 3,154 | 0 | +3,154 |
| `plugins/git` root (contract, RPC contract, host and server entries) |
1,297 | 0 | +1,297 |
| `plugins/git/server` (reads, generations, invalidation, Viewed, CLI) |
1,272 | 0 | +1,272 |
| `bb-environment-provider-host` (shared runner, branch listing,
git-types) | 1,256 | 560 | +696 |
| `apps/app` (read path, live reconcile) | 247 | 119 | +128 |
| `@bb/plugin-build` (retired-read build warnings) | 87 | 4 | +83 |
| `@bb/sdk` (retired-read adapters) | 273 | 193 | +80 |
| other (`plugins/mcp`, `turbo.json`, `plugin-sdk`) | 50 | 26 | +24 |
| `@bb/host-workspace` (workspace reads moved out) | 228 | 3,975 |
−3,747 |
| `apps/cli` | 87 | 577 | −490 |
| `apps/server` (routes, read cache, tiering) | 279 | 719 | −440 |
| `apps/host-daemon` | 58 | 436 | −378 |
| `@bb/server-contract` | 229 | 535 | −306 |
| `@bb/host-daemon-contract` | 18 | 179 | −161 |
| `@bb/domain` | 5 | 103 | −98 |
| `@bb/test-helpers` | 0 | 57 | −57 |
- `getDiff` stays, at about 211 lines: rebuilding diffs from files plus
patches would lose binary patches, name-status rename scores and the
total byte budget across files.

## Git reads on the host

#### Git reads on the host: what is shared per change

- **One status snapshot per change.** The plugin server keeps a work
generation per watched environment. Each `environment:changed`, turn
end, refresh or merge-base change starts a new one, and a generation
also expires after 3 s. `status`, `files` and `patches` reads in the
same generation share one `git status` run and its untracked list. Reads
without a watch, and CLI and commit reads, get a unique generation and
share nothing.
- **Ref-derived values cached per refs generation and HEAD.** This
covers the merge base, the base commit and origin/HEAD. Only
`git-refs-changed`, environment status changes, refresh and merge-base
changes bump the refs generation, and it also expires after 30 s. An
edit therefore runs no `merge-base`, `rev-parse` or `symbolic-ref`.
- **Untracked line stats and blob ids cached per file signature** (mode,
size, mtime, ctime, inode). Only new or changed untracked files go
through `add --intent-to-add` plus one `diff --raw --numstat`. Status,
files and patches share the result.
- **One combined diff for the file list.** `diff --raw --numstat -M -z`
against the base replaces the separate raw, numstat and name-status
calls. With Ignore whitespace on, raw and numstat stay two calls,
because git 2.55 drops whitespace-only files from `--raw -w`. Patches
reuse the file list's rename pairs, and a single path skips the numstat.
- **The real index is never written.** Porcelain `git diff` refreshes
and rewrites `.git/index` even with `--no-optional-locks` /
`GIT_OPTIONAL_LOCKS=0`. That write fed the gitdir watcher and is what
drove the idle Diff loop on main. Worktree diffs therefore run against a
copy of the index, reused until the real index changes. The copy is
reference-counted, so a reader never loses it mid-diff, keeps the real
index's times, never writes a split index, and lives in the worker's
temp directory. Every other read sets `GIT_OPTIONAL_LOCKS=0`, and status
passes `--no-optional-locks`.
- **Tests pin this down.** `plugins/git/host/git-process-budget.test.ts`
uses a PATH shim that logs every git process and asserts the exact
commands per change:
  - 8 for an edit that adds an untracked file with Diff open,
  - 5 for a tracked edit with Diff open,
  - 2 for a tracked edit with Diff closed.

It also checks that `.git/index` is byte-identical after reads, even
when the stat data in the index is stale.

#### Index copy vs alternatives (bb clone, 3.4 GB `.git`, 0.99 MB index)

Each change appends to `README.md` and runs the three worktree diffs a
change triggers. Times are per change, as the median of 10 changes.
Bytes are per change, averaged over the 10. "Stat-dirty" means 500
tracked files had their mtime bumped without a content change.

| Strategy | Clean: ms | Clean: bytes written | Stat-dirty: ms |
Stat-dirty: bytes written | Writes `.git/index` | Same output as main |
|---|---:|---:|---:|---:|---|---|
| Real index (main) | 45.0 | 0 | 98.8 | 97 KB (one rewrite of
`.git/index`) | yes | yes |
| Fresh copy per change | 45.7 | 968 KB | 133.1 | 1935 KB | no | yes |
| Copy reused until the index changes (#6165) | 44.7 | 97 KB (one 0.99
MB copy, then 0) | 98.9 | 194 KB (the copy plus one refresh of the copy,
then 0) | no | yes |
| Plumbing `diff-index` | 44.4 | 0 | 160.0 | 0 | no | no (raw lists
stat-dirty files; ignores `diff.*` config) |

The reused copy costs the same time as main, writes nothing in steady
state, and leaves `.git/index` alone. It re-copies about 1 MB only when
the real index changes, that is, on the user's own `git add` or
checkout. Plumbing `diff-index` writes nothing, but it is slower once
entries are stat-dirty, because it re-reads them on every call and never
refreshes. It is also wrong for the file list: `--raw` reports
stat-dirty files as modified, and plumbing ignores `diff.*` config,
which would change patches compared with main.

#### Missed watcher events heal at turn end

On main, git reads rewrote `.git/index`, and the gitdir watcher turned
each rewrite into another status check. That hid gaps in the
workspace-root watcher. During the first PR-state branch runs, reps 1
and 2, the daemon's root watcher reported 1 to 7 of 15 edits in some
scenarios.
- Now, when a thread's turn ends (status becomes `idle` or `error`) and
a client watches its environment, the Git plugin starts a new generation
for that environment, clears its caches and reads status once. With
nothing watched it subscribes to no thread events at all. It invalidates
`status` and `files` only when the result differs from what it last
served.
- A missed edit therefore shows up at the latest when the turn ends,
without polling.
- Test: `refreshes status when a turn ends even if the watcher missed
the edit` in `plugins/git/server.test.ts`.

The dropouts happened in one early PR-state run (reps 1–2, between 23:40
and 23:55):
- The daemon emitted 1, 5, 6 or 7 of 15 `work-status-changed` events in
some edit scenarios. Its logs had no watcher errors for that window.
- In every run after that (PR-state rerun, even state, base, and the
final edit reruns), the daemon reported all 15 edits.
- An independent `@parcel/watcher` subscription on the same repository
ran alongside the reruns. It saw the same 15 change batches per run,
with no errors.
- The dropouts did not recur, so whether FSEvents or the daemon caused
them is not established.

## How you verified

- New tests, each failing without its fix:
- Index copy times, reference counting, no split index, racy untracked:
`plugins/git/host/index-copy.test.ts`.
- The patch byte budget: `host.test.ts`. The deferred loop, generations
and rewatch, and turn-end only while watched: `server.test.ts`.
- CLI output, error codes and the exact `Error: ` stderr:
`server/cli.test.ts`.
- Core's schemas and the plugin's copies stay identical:
`contract-copies.test.ts`.
- Retired adapter codes and limits: `retired-environment-reads.test.ts`.
- `plugin-frontend-live-reconcile.test.ts`: the reconcile reports
changes on first load, on a hash change and on a removal, and not for an
unchanged list.
- Build warnings: `retired-sdk-members.test.ts`. MCP read mode:
`policy.test.ts`. Commit errors by plugin state:
`git-plugin-reads.test.ts`.
- The moved git tests pass from their new homes:
`bb-environment-provider-host` (`workspace-git`), `@bb/host-workspace`
(`git`) and `plugins/git/host` (`git`, `git-admission`, workspace
reads).
- Git processes and requests, measured at the top of the stack: see
#6157.
- `node .github/workflows/check-plugin-sdk-version.mjs`.
- CI on this head.

> 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