Skip to content

Report the environment branch from the daemon instead of on git status reads - #6018

Merged
ymichael merged 6 commits into
mainfrom
bb/git-plugin-pr3-server-primitives-thr_i4jcnrjiv8
Oct 22, 2026
Merged

ymichael merged 6 commits into
mainfrom
bb/git-plugin-pr3-server-primitives-thr_i4jcnrjiv8

Conversation

@ymichael

@ymichael ymichael commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

The environment's stored branch name, which sidebar labels and thread lists use, was refreshed as a side effect of every git status read (workspace-status.ts, recordEnvironmentCurrentBranch). That ties core's branch labels to core's git status route. The git/GitHub plugin plan moves git status into a plugin, so the branch has to reach the server some other way first. This is PR 3 of that plan, decision D6: the daemon reports the branch.

What changed

  • Daemon (watch-manager.ts): while an environment's workspace is watched, the daemon reports branch metadata (current branch and default branch) through the existing environment-metadata-change message:

    • when the watch becomes ready;
    • after git or shared-ref changes, including coalesced git and content batches;
    • on detached HEAD, where the branch is null.

    Unchanged values are not re-sent. A removed watch can't publish a stale observation.

  • Server: the branch write is removed from git status reads, including commit preflight, together with its now-unused argument and normalization helper. Status responses still return the observed status, but they no longer overwrite the stored branch. The separate refresh when an environment is attached or reused (thread-environment-placement.ts) stays, because it runs before any watch exists.

  • Wire: HOST_DAEMON_PROTOCOL_VERSION goes from 249 to 250. Older daemons are rejected at session open and update through the existing path, so branch metadata always comes from a branch-reporting daemon. Main's connect-next, desktop broker proof, and cleanup inspection capability exports are retained.

  • Performance: shared-ref reads now return a typed snapshot containing the fingerprint and default branch. Shared-only events reuse that snapshot and the cached per-worktree current branch, eliminating four redundant Git processes per workspace. Local Git events still reread the current branch. This is an internal host-workspace contract change; no additional wire or database changes.

  • Startup: local-state snapshots now include the current branch and HEAD-derived fingerprint from one porcelain-v2 status read. Initial watcher processing reuses the local and shared snapshots for metadata, eliminating dedicated branch/default-branch queries and a separate HEAD query. Reads run in the serialized watcher event path, normally at readiness. No additional wire/database changes.

  • No SDK, CLI or UI changes.

How you verified

  • Updated against origin/main at cf2018d777b4b7637cdb03492d389b6d36778fc7.
  • pnpm exec turbo run typecheck lint test --filter='...[origin/main]' --concurrency=2: 265/265 tasks passed on startup follow-up head b4b8789d63.
  • Focused daemon/watch and real Git workspace snapshot tests passed. Restoring redundant current-branch reads makes the new shared-ref regression test fail.
  • Formatting and git diff --check passed.
  • GitHub CI on b4b8789d63: all 40 applicable checks passed, with 7 skipped by workflow conditions.
  • New tests:
    • daemon branch reporting at watch ready, after git changes, on detached HEAD, on a default-branch-only change, deduplication, and stale-watch suppression;
    • server: thread-list branch fields update from daemon messages with no status requests;
    • server: status GET and commit preflight leave the stored branch alone.
  • Negative checks: putting the old status-read writes back makes their regression tests fail. Deduplicating on the branch alone fails the default-branch case.
  • Live, in a source dev app, with every browser status fetch blocked:
    • the initial watch stored the branch;
    • a real git switch changed the sidebar label from qa/d6-initial to feature/d6-without-status;
    • detached HEAD stored null, and the label fell back to "Worktree";
    • the daemon received zero workspace.status calls.

Performance measurement

Measured main cf2018d777, pre-fix PR 655739f7db, and fixed PR f0f55ddcd0 on this Mac using an isolated bb clone with 1, 5, and 20 full linked worktrees, each on a separate branch. Five trials per event. The harness runs the real daemon WatchManager, native HostWatcher, and Git implementation; it counts direct Git child processes in memory. Metadata timing ends at the daemon metadata callback, before websocket transport/server persistence. No status requests are made.

A real empty commit in another, unwatched worktree changes shared refs. Each cell is Git process count / median completion ms (time from starting the trigger until the last daemon Git child exits; the triggering Git process is excluded from counts).

Watched workspaces Main Pre-fix PR Fixed PR
1 3 / 289 7 / 201 3 / 409
5 15 / 338 35 / 285 15 / 373
20 60 / 1166 140 / 2994 60 / 870

These commits emit no metadata message: branch labels have not changed, so PR versions deduplicate them. Main does not report branch metadata from watches.

To measure actual message latency, a second shared-ref workload changes refs/remotes/origin/HEAD between two default branches. Process counts are identical to the table above. Times are medians in ms to the last workspace's metadata callback; both PR versions emit exactly one message per workspace.

Watched workspaces Main completion (no metadata) Pre-fix PR metadata Fixed PR metadata
1 154 146 218
5 150 194 287
20 1066 3062 808

Appending to tracked README.md in every watched worktree spawns zero Git processes and zero metadata messages on all versions/counts. Median last content-status notifications in ms:

Watched workspaces Main Pre-fix PR Fixed PR
1 82 89 84
5 134 142 146
20 138 143 146

At 20 workspaces the fix removes 80 extra Git processes per shared-ref event, matching main's 60, and lowers median metadata latency from 3062 to 808 ms (~74%). Low-count timing differences reflect system/trigger variability; this does not claim a latency improvement at every count. The preexisting three fingerprint processes per workspace remain. Those shared-ref measurements preceded the startup follow-up below; startup is now 8 processes/workspace.

Harness, per-process traces, and the detailed report are outside the checkout at /Users/michael/.bb/thread-storage/thr_r6a3k624u7/branch-perf/ (measure.mjs, report.md, and {main,branch,fixed}-{1,5,20}.json). Source snapshots for the measured revisions are retained there.

Repeated startup measurement

Measured main cf2018d777, previous PR head f0f55ddcd0, and startup fix b4b8789d63. Five completed fresh-process trials at each count, alternating version order, using the same real bb worktrees/native watcher/Git harness described above. Timing starts before watch-set replacement and includes provisioning, ignore discovery, and initial reads. Observation/quiet windows are excluded.

Git process counts were identical across all five completed trials in each cell:

Watched workspaces Main Previous PR Startup fix
1 10 14 8
5 50 70 40
20 200 280 160

The fix removes 120 processes versus the previous PR at 20 workspaces, and uses 40 fewer than main. Each workspace now uses two provisioning checks, two local-state calls, three shared-ref calls, and one ignore-discovery call.

Startup completion, median (min–max), ms:

Watched workspaces Main Previous PR Startup fix
1 238 (134–457) 272 (152–345) 375 (202–479)
5 1534 (914–3970) 1110 (993–1745) 1081 (1051–3030)
20 4899 (4658–6040) 5376 (4661–22630) 6901 (4573–11398)

Completion is the last daemon Git child exit. Both PR versions emit one metadata message per workspace; their last-metadata medians round to the same millisecond as completion. Main emits no branch metadata.

Timing tradeoff: the process-count target is met, but this is not a demonstrated wall-time improvement. At 20 workspaces the new median is 6.90 s versus main's 4.90 s and the previous PR's 5.38 s. Initial snapshots now run after readiness instead of overlapping setup, and the host timings have wide ranges. All-root-watch-ready medians for 1/5/20 workspaces were main 234/1534/4900 ms, previous PR 239/1087/5356 ms, and startup fix 198/642/6367 ms. Content invalidation still happens immediately at readiness; metadata computation follows asynchronously.

One additional previous-PR 20-workspace attempt failed during the existing root ignore-discovery Git command; its log was retained and the sample rerun. Native Git timeout settings were unchanged. The measurement harness's settling deadline was raised to 60 seconds while completing the series.

The detailed report, raw traces, and source snapshots remain outside the checkout in /Users/michael/.bb/thread-storage/thr_r6a3k624u7/branch-perf/: startup-report.md, startup.mjs, run-startup-samples.py, and startup-{main,fixed,startup}-{1,5,20}-{0..4}.json.

AGENT GENERATED

Remove status-read branch writes, retain the attachment refresh, and observe default-branch changes. Defer the AI text-task API and revert its SDK bump until Git Commit supplies the first plugin caller.
ymichael and others added 4 commits October 21, 2026 11:07
Main kept 246 daemons compatible for connect next. This PR moves branch
reporting to the daemon, so only 248 daemons are accepted and the
connect-next version gate, now always true, is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael marked this pull request as ready for review October 22, 2026 20:17
@ymichael
ymichael merged commit 10b410f into main Oct 22, 2026
47 checks passed
@ymichael
ymichael deleted the bb/git-plugin-pr3-server-primitives-thr_i4jcnrjiv8 branch October 22, 2026 20:17
ymichael added a commit that referenced this pull request Oct 22, 2026
## Human comments

## What was wrong

GitHub pull request status was core. The daemon ran `gh`, the server
assembled and watched the status, and the app, SDK, CLI and Tasks and
GitHub plugins each reached it through core routes and commands. Core's
PR UI couldn't leave core because there was nothing outside core to read
from.

## What changed

**New bundled, default-enabled plugin: `plugins/github-pr-status`
(`bb--github-pr-status`)**
- `host.ts` / `host/git-host.ts`: the in-worktree lookup moved from
`packages/host-workspace/src/git-host.ts`. It covers the current branch,
upstream and fork remotes (`getPullRequestTarget`), the merge-queue
GraphQL query, and `gh pr ready|ready --undo|merge`. It runs on the
environment's own machine with the daemon's shell `PATH`.
- `server.ts`:
  - resolves the environment;
- serves a keyed `pullRequests` read, one row per environment id (up to
200), so a list of rows loads in one request;
- serves `markReady`, `markDraft` and `merge`, each of which re-checks
state before acting;
  - registers `bb pull-request show|ready|draft|merge <environment-id>`.
- `store.ts` is the single place reads are cached (10 s), re-checked
while watched, and published when they change.
- PR snapshots are kept by PR URL, so environments sharing a PR share
one snapshot. Persistence, cross-row reuse and webhooks can feed this
one place later.
- While a row is watched (`bb.rpc.experimental_whileWatched`), it
re-checks every 30 s when checks are pending, auto-merge is on, the PR
is queued or mergeability is unknown. That is the same rule as core's
`pull-request-watch.ts`.
  - Other triggers match main's:
    - `status-changed` and environment create/delete fetch fresh;
    - a completed turn re-checks through the 10-second cache;
    - `git-refs-changed` only marks the cached row stale;
- `metadata-changed` re-checks only when the environment's branch
actually changed (one environment read, no `gh`);
- in the app, a cached row is re-fetched on mount, and again when the
page is shown if it's older than 30 s (1 h once merged or closed). Main
got this from TanStack's `refetchOnMount: "always"` and focus refetch.
Here it uses only the public read hook's `refetch`, in
`pull-request-queries.ts`.
- It invalidates the row's tag only when the row changed, and never for
a result a viewer is already receiving.
- `contract.ts` is the public contract. The read returns the fully
assembled shape the UI renders: state, attention, checks, review,
mergeability, auto-merge and merge queue.

**Watched reads**
- `bb.rpc.experimental_whileWatched` comes from `bb/5939-recut`,
mechanism only: the `plugin-read` subscription target, the server
registry and producer lifecycle, app query hooks holding the
subscription, per-target subscribe validation, and fake-host support.
- Left out: the SDK `experimental_watchRpc` /
`experimental_watchDiscovery`, the CLI `--watch` flags, and
plugin-signal scoping.

**Core reads and acts only through the plugin's public contract**
- The composer banner segment, Info row and thread view use
`experimental_useRpcKeyedQuery` / `experimental_useRpcMutation` with
`pluginId: "bb--github-pr-status"`
(`apps/app/src/hooks/queries/pull-request-queries.ts`). These are the
same calls another plugin makes, so moving the UI later is a cut and
paste.
- The app's RPC hook host now allows those hooks outside a plugin slot
when `pluginId` is explicit.
- `bb thread show`, Tasks (`listTaskPullRequests`, now one batched read)
and the GitHub plugin's `pullForThread` call the same RPC.

**Deleted from core**
- The server PR watcher, route, cache, `environment-pull-request` tag
and subscription target, and the PR action branches.
- The SDK `environments.pullRequest` / `markPullRequestReady` /
`markPullRequestDraft` / `mergePullRequest`, and `bb environment
pull-request …`.
- The `ThreadPullRequest` / `GitHostPullRequest` domain schemas.
- The daemon's `workspace.pull_request` and
`workspace.pull_request_action`. **`HOST_DAEMON_PROTOCOL_VERSION` 250 →
251**, compatible `[250, 251]`. 250 stays compatible because the server
no longer sends either command. 246–249 stay removed, as #6018 intended.

**`experimental_useSidebarThreadPullRequest`**
- Removed from `@get-bb/plugin-sdk/app`, the Plugin Guide and the docs.
- Published bundles keep working: the app installs
`retiredPluginSdkAppMembers` on the plugin runtime, backed by the
plugin's read. It returns `{ isLoading: false, pullRequest: null }` when
the plugin is disabled.
- **Builds never fail on it.** bb builds git-sourced marketplace plugins
at install and update, and rebuilds path and builtin plugins when the
SDK changes. So the `bb-plugin-build` runtime shim keeps the name in its
`@get-bb/plugin-sdk/app` export list. Importing it is a build warning
with the replacement call, which `bb plugin build`/`dev` print and the
server writes to the plugin's log.
- Migration guide:
`bb-plugin-authoring/references/frontend-pull-requests.md`. The runtime
shim is recorded in `docs/api_to_audit.md`.
- Plugin SDK 0.6.72.

**No wake.** Plugin host calls never wake a suspended host. A read on an
asleep or offline machine returns `unavailable`, which the UI renders as
no PR. Ready, Draft and Merge fail with "<machine> isn't available …".
**Behaviour change:** reads no longer wake a suspended host. On main,
`workspace.pull_request` used the `work` wake policy, so opening a
thread whose machine was suspended woke it.

## How you verified

**Request measurement in the real app.** Main and this branch ran as two
`pnpm start:worktree` instances side by side. Each had a thread on a
project checkout of PR #6117's branch while its checks were pending
(`checks_pending`, 0 failed). In each, a headless page opened the thread
and every `/api` request was recorded for 3 minutes, both runs at the
same time:

| | PR requests | when (s) | all `/api` requests |
|---|---|---|---|
| main | 6 × `GET /environments/:id/pull-request` | 1, 32, 64, 95, 127,
158 | 84 |
| branch | 6 × `POST /plugins/bb--github-pr-status/rpc/pullRequests` |
1, 33, 64, 96, 127, 159 | 88 |

The other `/api` differences changed from run to run (hosts, server-move
and execution-options in this run; system config, providers and timeline
in another). They come from background activity in the freshly restarted
branch instance and its extra sidebar threads, not PR traffic. An
earlier run found two bugs that are fixed here with tests:
- a re-check right after open published a result the opening read was
already fetching, costing one extra request;
- a watch that went idle when checks finished never resumed when a new
CI run started.

**Busy thread.** Main and this branch ran side by side again, each with
a thread on its own scratch PR in a private test repo
(`ymichael/test-project` #303 and #304, both closed and their branches
deleted afterwards). Each thread was open in a page. Both received the
same agent turn at the same moment: three commits, a `git fetch`, a
third commit between them, and a `git push`, which also started the
repo's CI. Over 5 minutes, a process monitor counted every `gh` started
by each instance, attributed by process ancestry and confirmed by
working directory. The page counted PR read requests. Two runs gave
identical counts:

| | `gh` calls | PR read requests |
|---|---|---|
| main | 7 (4 `pr view`, 3 merge-queue `api graphql`) | 4 |
| branch | 5 (3 `pr view`, 2 merge-queue `api graphql`) | 2 |

Before this fix the branch also re-checked with `gh` on every
`git-refs-changed` and `metadata-changed`, so a thread that commits and
pushes would have exceeded main.

**Focus refresh.** Main (`f909788625`) and this branch ran side by side
with the same open PR. A page on each hid and showed itself 5 times over
4 minutes, with gaps from 20 s to 60 s, so some shows were under the 30
s stale time and some over. A process monitor counted `gh` per instance:

| | `gh` calls | PR read requests |
|---|---|---|
| main | 5 | 5 |
| branch | 5 | 6 |

The extra read is the realtime connection resuming at the same moment
the page showed. Both reads hit the plugin's 10 s cache, so there's no
extra `gh`.

**Published plugins that use the retired hook.** On the review app, I
installed four git-sourced Community marketplace plugins that call
`experimental_useSidebarThreadPullRequest`. Each went through `bb plugin
install <plugin>@bb-community`, so bb cloned and built it at its
published commit. Each was then used as the sidebar thread list:

| Plugin | Commit | Builds | Warning in `plugin.log` | Renders PR badges
|
|---|---|---|---|---|
| t3sidebar | `8b535729dd` | ✅ | ✅ `src/ThreadCard.tsx:6` | ✅ |
| dockside | `e8736f3858` | ✅ | ✅ `components/inbox/thread-card.tsx:7` |
✅ |
| radar-sidebar | `9a20bfab7e` | ✅ | ✅
`components/radar/RadarThreadRow.tsx:23` | ✅ |
| thread-inbox | `c0981fb6fe` | ✅ | ✅ `src/ThreadCard.tsx:18` | ✅ |

gtd-sidebar fails to install on main too ("Could not resolve
@get-bb/plugin-sdk"), so it's unrelated. This test caught a real bug: T3
Sidebar crashed with a React hook-order error. React Compiler only
treats `use…` names as hooks, so it cached the
`experimental_useRpcKeyedQuery` call inside `useEnvironmentPullRequest`
and skipped it on re-renders with unchanged arguments. Core's own
callers pass a fresh options object on every render, which hid it. The
hooks are now imported under `use`-prefixed local names, and all four
plugins render.

**UI parity.** Screenshots of the same thread on main and on the branch
show the same composer banner segment (PR #6117 with the Merge split
button) and the same Info row (#6117, Open, Checks running). `bb thread
show` printed the PR through the plugin. On this PR, `bb pull-request
draft <env>` converted it to draft. The banner then showed "PR #6125 ·
Draft" with Mark ready, and clicking Mark ready showed the loading
toast, made the PR ready on GitHub, and returned the banner to the open
state with Merge.

**Tests**
- New plugin tests (75):
- host-entry fork, upstream and detached cases using a fake `gh`, moved
from host-workspace;
  - the parse, action-argument and merge-queue table;
  - the assembly table, moved from the server;
  - store polling, publish-on-change and the viewer race;
  - server reads, refusals, the no-wake refusal and the CLI.
- Also added: the `bb-plugin-build` retired-import warning test, the
focus-refresh staleness table and refetch tests, Tasks batched reads and
the disabled-plugin case, CLI `thread show` through RPC, and a hub test
for the `plugin-read` target.
- After merging #6135: `pnpm exec turbo run typecheck lint
--filter='...[origin/main]'` passes 162/162, and `turbo run test
--filter='...[origin/main]'` passes 115/115. That includes #6135's
host-workspace default-branch tests and the host-daemon
`watch-manager-startup` setup-window test. The host-workspace merge kept
#6135's code. This branch only removes the PR lookup from it.

**Not covered**
- `gh` ran only on a local host. Remote hosts use the same plugin
host-artifact path as the other host plugins but weren't exercised.
- Merge wasn't run against a real PR. It uses the same `gh pr merge
--<method>` arguments, covered by the host tests.

> 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