Skip to content

Watch live plugin reads from the server, SDK and CLI - #5661

Closed
ymichael wants to merge 24 commits into
mainfrom
bb/live-data-stack-3-watching-connect-bb-account-thr_79u87xmcbx
Closed

ymichael wants to merge 24 commits into
mainfrom
bb/live-data-stack-3-watching-connect-bb-account-thr_79u87xmcbx

Conversation

@ymichael

@ymichael ymichael commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Server-side consumers had no way to follow live plugin data, and neither did the CLI or the desktop app's Node SDK. So plugins built their own ways to wait for changes:

  • bb-account exposed bb-account.v1.waitForStatusChange for connect to long-poll;
  • both plugins' login UIs polled every 2 s;
  • connect carried its own synchronization retry, ordering and generation machinery.

Separately, plugin-signal events went to every socket through broadcastToAllClients.

Stack 3 of 13, stacked on #5658. #5640 is merged and #5688 is folded into #5658. Review only this PR's commits. Merge order: #5658 → #5661 → #5669 → #5666 → #5659 → #5660 → #5663 → #5667 → #5668 → #5677 → #5673 → #5670.

What changed

  • 16f7779d47 SDK WebSocket fix: Node can emit a second error from close() and skip the close event after a failed handshake. Error handling now joins the shared close and reconnect path instead of recursing. The CLI watches exposed this, and the regression test fails before the fix.
  • 57c8d41c2a Watched reads (server, SDK, plugin SDK):
    • A {kind:"plugin-read", pluginId, method, read:{input}|{key}} subscription target, capped at 16 KiB of encoded read.
    • The hub runs one producer per distinct read and stops it when the last socket leaves.
    • bb.rpc.experimental_whileWatched(method, (read, signal) => …) registers that producer and aborts it on unwatch or disposal.
    • The app query hooks hold watched interests for as long as they are mounted.
    • bb.sdk.plugins.experimental_watchRpc({…, prepare?, onChange, onError}):
      • re-reads on matching tags and on reconnect, and recovers from a 404 so a consumer survives the producer plugin loading later;
      • runs prepare serially for each distinct value before onChange, retrying with backoff (1 s doubling to 30 s);
      • drains a pending prepare when the watch is stopped.
    • experimental_watchDiscovery emits each distinct method list.
    • Watched calls keep the verified plugin caller identity.
    • plugin-signal now goes only to plugin subscribers, and broadcastToAllClients is deleted. useRealtime subscribes automatically, so existing delivery callers keep working.
    • Plugin SDK 0.6.63.
  • a82fe26cfc CLI:
    • bb plugin rpc call --watch and bb plugin rpc list --watch print one compact JSON value per line.
    • Permanent 4xx errors other than 408 and 429 end the watch with exit 1; transient errors retry.
    • The guide, skill and command index are updated.
  • dcb74f7975 bb-account and connect:
    • Account status and login reads declare contract tags, and the UIs write through experimental_useRpcMutation.
    • Connect follows bb-account through watchRpc, with credential sync done in prepare.
    • Removed: bb-account.v1.waitForStatusChange, connect's long-poll loop, account signal payloads, both 2 s login polls, and connect's retry, generation and ordering code.
    • The hosted device-approval producer still polls getbb.app as before.
  • No host-daemon wire fields change, so HOST_DAEMON_PROTOCOL_VERSION is unchanged.

Behaviour changes:

  • Account and login state refresh on tagged invalidation and reconnect instead of long-polls and 2 s polls.
  • The versioned bb-account.v1.waitForStatusChange RPC is removed. Connect was its only caller.
  • A sign-in code replaced by another client is retired, and Try again shows a new code.
  • First-load errors show Retry. Background read errors keep the loaded content, including the phone-pairing code and countdown, and show an inline Retry.
  • CLI --watch streams snapshots. SDK consumers keep retrying through a missing plugin or method.
  • Watched producers run only while someone watches.

How you verified

  • pnpm exec turbo run build typecheck lint test --filter='...[origin/main]' --continue: 315/318.
    • All builds, typechecks and lints passed.
    • Of the three failed test tasks, the connect assertion was fixed. The MCP child-pid timeout and the builtin build-failure watcher tests are timing tests that pass when rerun on their own.
  • Focused runs after the fixes:
    • SDK, Plugin SDK, CLI, connect and bb-account: 18/18 tasks passed (SDK 137, Plugin SDK 378, CLI 870, bb-account 59, connect 133 tests).
    • Server hub, protocol, wire, caller-identity and builtin-plugin suites: 106/106.
    • The Plugin SDK version check passes.
  • Live checks in an isolated source app with the source CLI:
Behaviour Result
Replaced sign-in code is retired, Try again shows a new one Passed (browser sign-in, replaced through CLI)
Connect recovers after a bb-account 404 or disable Passed (SDK watch gets 404, then data after reload; disable clears pairing, enable restores it)
Earlier sync completing can't restore unavailable account state Passed
Fresh status read after a failed sync, obsolete sign-outs discarded Passed
Abort drains pending sync with no later publish or retry Passed
Two CLI watchers share one producer; the last one leaving aborts it Passed
16,384-byte read accepted; 16,385 closes with 1008 Passed
CLI error matrix: 400/401/403/404/422 exit 1; 408/429 retry 14/14 passed
Failed reads keep the code and show Retry Passed (HTTP 503 injection)

Part of #4944

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael
ymichael force-pushed the bb/live-data-stack-3-watching-connect-bb-account-thr_79u87xmcbx branch from dcb74f7 to 4f93ad4 Compare October 17, 2026 01:24
@ymichael
ymichael force-pushed the bb/live-data-stack-3-watching-connect-bb-account-thr_79u87xmcbx branch from 5febb34 to edaecd9 Compare October 17, 2026 04:51
@ymichael
ymichael changed the base branch from bb/live-data-stack-2-plugin-reads-and-writes-on-cor-thr_agngjehcrj to bb/live-data-stack-2b-typed-rpc-refusals-4944-item-thr_d3hsq48cy6 October 17, 2026 04:51
@ymichael
ymichael force-pushed the bb/live-data-stack-2b-typed-rpc-refusals-4944-item-thr_d3hsq48cy6 branch from 2255258 to 79960f7 Compare October 17, 2026 05:19
@ymichael
ymichael force-pushed the bb/live-data-stack-3-watching-connect-bb-account-thr_79u87xmcbx branch from edaecd9 to 19a7a80 Compare October 17, 2026 05:19
@ymichael
ymichael force-pushed the bb/live-data-stack-2b-typed-rpc-refusals-4944-item-thr_d3hsq48cy6 branch from 79960f7 to 00a947c Compare October 19, 2026 22:20
@ymichael
ymichael force-pushed the bb/live-data-stack-3-watching-connect-bb-account-thr_79u87xmcbx branch from 19a7a80 to 463e8a9 Compare October 19, 2026 22:20
@ymichael
ymichael force-pushed the bb/live-data-stack-2b-typed-rpc-refusals-4944-item-thr_d3hsq48cy6 branch from 00a947c to 278cc78 Compare October 19, 2026 22:49
@ymichael
ymichael force-pushed the bb/live-data-stack-3-watching-connect-bb-account-thr_79u87xmcbx branch from 463e8a9 to f68b674 Compare October 19, 2026 22:49
ymichael added a commit that referenced this pull request Oct 20, 2026
…mutations (#5640)

## Human comments

## What was wrong

**Stack 1 of 14.** Merge order: #5640 → #5658 → #5688 → #5661 → #5669 →
#5666 → #5659 → #5660 → #5663 → #5667 → #5668 → #5677 → #5673 → #5670.

When a core write changes data that other screens or clients show,
someone has to remember to refresh every query that depends on it. Today
each write does this by hand: a cache-owner module plus a system change
kind (for UI preferences, `ui-preferences-changed`, routed through the
realtime registry). Plugins have no equivalent at all, which is #4944.

This is step 1 of a stack that replaces #5582. Here, a contract declares
what a read depends on and what a write changes, and the client
refreshes from those declarations. The plugin hooks in later steps will
be thin wrappers over this same core path.

## What changed

- **`@bb/domain`:** a new `ContractTagDeclarations` type with
`tags(input, output)` and `invalidates(input, output)`. It contains
types only.
- **`@bb/hono-typed-routes`:**
  - `defineRoute` accepts these declarations.
- After a 2xx JSON response, `typedRoutes` publishes the route's
`invalidates` tags through a new `invalidateTags` option.
- Registering a route that declares `invalidates` throws if that option
is missing.
- **Server:** `hub.notifyTags` batches tags within a microtask and sends
`{type:"changed", entity:"tags", tags}` to every connected client. This
is a new message between the server and the app; the daemon is
untouched, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged.
- **New `@bb/query-tags` package:**
  - Tags are registered on queries through `meta`.
- `invalidateTags` refreshes the queries whose data carries a matching
tag, within a scope. Core uses `core`.
- A read that is in flight restarts only if an overlapping invalidation
arrives during it.
- `runTaggedMutation` settles only after the affected active reads have
re-read. That includes a first load whose tags aren't known yet, which
the reference branch got wrong.
- **App:**
- The realtime cache effects pass `tags` messages to `invalidateTags`,
and hold them while the tab is hidden.
- A small `route-tags.ts` adapter connects route contracts to these
reads and mutations.
- **UI preferences, which prove the mechanism:**
- The read declares `ui-preferences`, and update and reset invalidate
it.
  - The sync engine saves through `runRouteMutation`.
- `ui-preferences-cache-owner.ts`, the `ui-preferences-changed` change
kind and its registry entry are deleted.
- The sync keeps each acknowledged entry, so a failed re-read neither
reverts the preference nor bases the next write on a stale revision.

Not in this PR: plugin SDK hooks, plugin RPC, plugin WebSocket targets
and the CLI. Those come in later steps of the stack, each with its first
caller.

## How you verified

- `pnpm exec turbo run build typecheck lint test
--filter='...[origin/main]' --continue`: 296/296 tasks passed.
  - Lint has no errors, and the app's warnings match `origin/main`.
- New tests in `@bb/query-tags` cover tag matching, scope isolation,
stale inactive queries, in-flight races, and refresh failure and
recovery.
  - The first-load race test fails against the reference implementation.
- `@bb/hono-typed-routes` tests: invalidations are published only after
2xx JSON responses, and registration fails without the publisher.
- Two isolated browser profiles against a source server: a preference
write in one refreshed the footer preferences in the other, and a
composer draft survived the refresh.
- Two WebSocket clients with no subscriptions both received the `tags`
message after an HTTP write.
- Sidebar perf, five paired samples per checkout with 3,000 threads,
against `origin/main`:

| Metric | Main median (range) | Branch median (range) |
| --- | ---: | ---: |
| Mount, ms | 410 (404–419) | 408 (359–412) |
| Pin, ms | 72 (71–73) | 71 (70–73) |
| Status patch, ms | 69 (69–71) | 70 (69–73) |
| Membership refresh, ms | 103 (103–107) | 107 (103–108) |
| Query observers | 13 | 13 |

The ranges overlap and the number of query observers is unchanged. These
samples were taken before the unused pieces were removed; removing them
deleted code paths without changing the read path.

Part of #4944

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@ymichael
ymichael force-pushed the bb/live-data-stack-3-watching-connect-bb-account-thr_79u87xmcbx branch from f68b674 to 07740bd Compare October 20, 2026 19:46
@ymichael
ymichael changed the base branch from bb/live-data-stack-2b-typed-rpc-refusals-4944-item-thr_d3hsq48cy6 to bb/live-data-stack-2-plugin-reads-and-writes-on-cor-thr_agngjehcrj October 20, 2026 19:47
@ymichael
ymichael force-pushed the bb/live-data-stack-2-plugin-reads-and-writes-on-cor-thr_agngjehcrj branch from bfcb5a1 to 5ce7d56 Compare October 20, 2026 21:00
@ymichael
ymichael force-pushed the bb/live-data-stack-3-watching-connect-bb-account-thr_79u87xmcbx branch from 07740bd to 7734268 Compare October 20, 2026 21:19
@ymichael
ymichael force-pushed the bb/live-data-stack-2-plugin-reads-and-writes-on-cor-thr_agngjehcrj branch from 2fb8cbe to 4431e9f Compare October 20, 2026 22:37
Base automatically changed from bb/live-data-stack-2-plugin-reads-and-writes-on-cor-thr_agngjehcrj to main October 20, 2026 22:56
ymichael added a commit that referenced this pull request Oct 21, 2026
Rebuild #5661's watched plugin reads on the registry core uses for daemon
workspace watching, timeline pushes and PR status. A plugin-read
subscription target starts each experimental_whileWatched producer when its
first watcher subscribes and aborts it when the last one leaves; the hub no
longer keeps a separate plugin-read map or listener set.

The SDK gains plugins.experimental_watchRpc, which reads immediately,
refreshes on matching tags and reconnect, runs an optional prepare step
before onChange and recovers from 404/503, and
plugins.experimental_watchDiscovery. `bb plugin rpc call --watch` and
`bb plugin rpc list --watch` stream compact JSON snapshots.

Connect follows bb-account's status through watchRpc and syncs its
credential copy in prepare, replacing bb-account.v1.waitForStatusChange,
connect's long-poll loop and its retry and ordering code. Both login UIs
use tagged reads and mutations instead of 2 s polls, passing the contract
the merged live-data hooks require. Plugin signals go only to plugin
subscribers. Also fixes a recursive close after a failed WebSocket
handshake in the SDK realtime client.

Plugin SDK 0.6.64; connect requires it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Oct 21, 2026
Rebuild #5661's watched plugin reads on the registry core uses for daemon
workspace watching, timeline pushes and PR status. A plugin-read
subscription target starts each experimental_whileWatched producer when its
first watcher subscribes and aborts it when the last one leaves; the hub no
longer keeps a separate plugin-read map or listener set.

The SDK gains plugins.experimental_watchRpc, which reads immediately,
refreshes on matching tags and reconnect, runs an optional prepare step
before onChange and recovers from 404/503, and
plugins.experimental_watchDiscovery. `bb plugin rpc call --watch` and
`bb plugin rpc list --watch` stream compact JSON snapshots.

Connect follows bb-account's status through watchRpc and syncs its
credential copy in prepare, replacing bb-account.v1.waitForStatusChange,
connect's long-poll loop and its retry and ordering code. Both login UIs
use tagged reads and mutations instead of 2 s polls, passing the contract
the merged live-data hooks require. Plugin signals go only to plugin
subscribers. Also fixes a recursive close after a failed WebSocket
handshake in the SDK realtime client.

Plugin SDK 0.6.64; connect requires it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael

Copy link
Copy Markdown
Collaborator Author

Closing as superseded. Plugin watching was rebuilt on core's watched-target registry in #5929 + #5939. The plugin migrations will be rebuilt one at a time from main on the merged #5658 API. This branch stays available for reference.

@ymichael ymichael closed this Oct 21, 2026
ymichael added a commit that referenced this pull request Oct 21, 2026
…ver (#5929)

## Human comments

## What was wrong

The server kept two separate records of who is watching what.
`WatchInterestCoordinator` (`apps/server/src/ws/watch-interests.ts`)
kept its own maps of sockets and interests to drive daemon git and
workspace status watching from `environment-detail` and `thread-detail`
subscriptions. Next to the socket subscriptions, the hub
(`apps/server/src/ws/hub.ts`) also kept a `threadTimelineTargetsByKey`
map. Separately, every client polled environment PR status
(`useEnvironmentPullRequest`) every 30 s while a PR was active, so one
more poll ran for every open thread header, and for every thread row the
tasks plugin shows through `experimental_useSidebarThreadPullRequest`.

Moving that check to the server exposed a gap: a hidden tab keeps its
socket and all of its subscriptions, and the server never times idle
clients out. Main's PR polling paused in hidden tabs, because TanStack
pauses `refetchInterval` there, but a server-side watch would keep
running for a tab nobody is looking at. Git status watching and timeline
pushes already behaved this way on main.

The plugin watch API (`whileWatched`, `watchRpc`, in the unmerged #5661)
would have added a third record. The plugin API rule requires plugin
APIs to use core's path, so this PR first gives core a single
watched-target mechanism. A follow-up PR rebuilds plugin watching on top
of it.

## What changed

- **One watched-target registry**
(`apps/server/src/ws/watched-targets.ts`, hub). The hub's existing
socket subscriptions are the only record of realtime subscription
targets. Terminal attachments still keep their own socket maps in the
hub. Listeners register for one or more target kinds and get batched `{
started, stopped }` changes. Closing a socket emits one batch, so the
cost doesn't grow with how many subscriptions it held. A listener that
registers late is told about the targets already being watched.
- **`WatchInterestCoordinator`** drops its own socket maps and its
`subscribe`/`unsubscribe`/`releaseSocket` methods, and listens to the
registry instead. Host resolution, fingerprints and generations are
unchanged. `client-protocol.ts` now only talks to the hub.
- **Thread timelines:** `threadTimelineTargetsByKey` and
`listThreadTimelineTargets` are removed. Timeline windows and turn
traces read the registry.
- **PR status is read on the server**
(`services/environments/pull-request-watch.ts`):
- There is a new realtime target, `{ kind: "environment-pull-request",
environmentId }`.
- The server checks once per environment while anyone watches it, and
re-checks every 30 s only while the PR is active. The rule for "active"
is the one the client used: auto-merge, merge queue, pending checks or
unknown mergeability.
- When any read returns a different result, it sends the route's new
`environment-pull-request` tag.
- The route delegates to this reader. The app hook is a tagged read with
no `refetchInterval`, and still refetches on mount and on window focus.
- **Hidden tabs don't watch** (`a647740f56`):
- After a tab has been hidden for 5 s (the app's existing resume
threshold), it sends `{ type: "visibility", visible: false }`, and
`visible: true` when it is shown again. After a reconnect while hidden,
it re-sends `false` before resubscribing.
- The hub still routes broadcasts to hidden sockets, so the favicon
attention dot, the page title, `bb thread open` and plugin signals still
reach background tabs. Only visible sockets count as watchers in the
registry, so daemon git watches, timeline pushes and PR checks stop when
the last visible tab lets go.
- On resume, the app refreshes the git status and PR status of the
targets it released, alongside the existing thread and timeline refetch.
CLI and SDK clients never send `visibility`, so they always watch.
- **Reconnect refresh** (`23faeff9f1`): a reconnected app re-reads every
core tagged read (PR status and UI preferences), the way it already
re-read plugin tag scopes. Without it, a PR change made while the app
was disconnected was never fetched: the PR key isn't in the reconnect
refresh list, and the server watch's first check after a restart has
nothing to compare against.
- **Compatibility:** no host-daemon wire change, so
`HOST_DAEMON_PROTOCOL_VERSION` is unchanged. Older servers close the
socket on the new `visibility` message. Servers without #5658, which
includes every release so far, also close it on the new
`environment-pull-request` target; servers with #5658 skip unknown
target kinds. The app always connects to the server that serves it, so
the two ship together.

## How you verified

- `pnpm exec turbo run typecheck lint test --filter='...[origin/main]'
--continue`: 233/233 tasks passed before the hidden-tab commit. With
that commit, on this branch alone: typecheck and lint for `@bb/app`,
`@bb/server` and `@bb/domain`, and the hub, client-protocol, ws,
realtime-cache-effects, watch-interest and PR-watch tests (118 app, 59
server) pass. The full app suite also passes on the stacked #5939.
- **New tests:**
- hub registry: a target starts with its first subscriber, stops when
the last one leaves, closing a socket sends one batch, and late
listeners get the existing targets;
- PR watcher, on the real server test harness: two sockets share one
check, nothing changed sends no refresh, a change sends one, there are
no timed checks once the PR has settled, and no checks after the last
watcher leaves. Removing the timer cleanup makes the last case fail;
- app: the PR query refetches only when its own environment's tag is
invalidated;
- hidden tabs: a target stays watched while any visible socket holds it
and stops when the last one is hidden; hidden sockets still get
broadcasts; showing a tab restarts its targets. The ws manager sends
`visibility` only after 5 s hidden, again after a reconnect, and reports
the released targets on resume. Resume refreshes only the environments
(direct or via a thread) and PRs that were released.
- The watch-interest and client-protocol tests now drive the coordinator
through the hub.
- **Live check** in a source dev app:
  - adding a file sent `work-status-changed` in about 0.7 s;
- with no `environment-detail` watcher the daemon stopped watching, and
resubscribing brought the updates back;
- switching a worktree to a PR's head branch refreshed a subscriber by
tag in the same millisecond;
  - the open thread page showed and dropped "PR #5923" without a reload.
- **Hidden-tab live check** in a headless browser on a thread page,
faking the tab's visibility:
  - visible: adding a file sent `work-status-changed` within a second;
- hidden: `visibility: false` went out after 5 s, and adding a file sent
nothing;
- visible again: `visibility: true` went out, the server re-read git
status, and the page showed "Uncommitted · 2 files".
- **Not checked live:** the 30 s re-check of an active PR, because no PR
with running checks was available. The harness tests cover 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 Oct 21, 2026
Rebuild #5661's watched plugin reads on the registry core uses for daemon
workspace watching, timeline pushes and PR status. A plugin-read
subscription target starts each experimental_whileWatched producer when its
first watcher subscribes and aborts it when the last one leaves; the hub no
longer keeps a separate plugin-read map or listener set.

The SDK gains plugins.experimental_watchRpc, which reads immediately,
refreshes on matching tags and reconnect, runs an optional prepare step
before onChange and recovers from 404/503, and
plugins.experimental_watchDiscovery. `bb plugin rpc call --watch` and
`bb plugin rpc list --watch` stream compact JSON snapshots.

Connect follows bb-account's status through watchRpc and syncs its
credential copy in prepare, replacing bb-account.v1.waitForStatusChange,
connect's long-poll loop and its retry and ordering code. Both login UIs
use tagged reads and mutations instead of 2 s polls, passing the contract
the merged live-data hooks require. Plugin signals go only to plugin
subscribers. Also fixes a recursive close after a failed WebSocket
handshake in the SDK realtime client.

Plugin SDK 0.6.64; connect requires it.

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