Skip to content

Watch plugin reads through the core watched-target registry - #5939

Closed
ymichael wants to merge 6 commits into
mainfrom
bb/watched-plugin-reads-registry-thr_mwyzuec25q
Closed

ymichael wants to merge 6 commits into
mainfrom
bb/watched-plugin-reads-registry-thr_mwyzuec25q

Conversation

@ymichael

@ymichael ymichael commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Plugins had no way to run work only while someone looks at its result. Provider usage measured on client timers whether or not any surface showed it, and the server couldn't tell which plugin reads were live. Core already starts and stops its own watchers (daemon git and thread-storage watching, timeline pushes, PR checks) through the hub's watched-target registry. Plugins didn't share that path, and the SDK and CLI couldn't follow a plugin read live.

What changed

  • One watched-target path for plugins and core. A plugin-read subscription target is registered in the hub's watched-target registry. bb.rpc.experimental_whileWatched(method, handler) starts one producer per distinct watched {input} or {key} read and aborts it when the last watcher leaves or the plugin unloads.
  • Every live read subscribes. App query hooks (plain and keyed) and SDK watchers hold a plugin-read subscription for each live read, whether or not the method has a producer. RPC responses stay exactly { ok, result } (Return only ok and result from plugin RPC responses #6073), so no response field says whether a read is watched, and a failed first read still starts the producer.
  • SDK and CLI:
    • plugins.experimental_watchRpc reads immediately and re-reads after any change to its plugin and after reconnect. The SDK has no contract to compute tags from.
    • plugins.experimental_watchDiscovery follows plugin lifecycle changes.
    • bb plugin rpc call --watch and bb plugin rpc list --watch stream snapshots.
  • Provider usage is the first producer. getUsage measures only while a surface or CLI watch reads it, and it follows usage sources with experimental_watchDiscovery. Its provider sources (Codex, Claude Code, ACP) invalidate their inventory on host and provider changes.
  • Fault isolation: the server drops an oversized subscribe target and keeps the rest of the message, instead of closing the socket. The app doesn't send oversized targets.
  • Plugin signals go only to subscribers of that plugin.
  • Plugin SDK 0.6.68; provider usage requires it. Audit entries are updated. No host-daemon wire changes.

Not in this PR (each becomes its own PR from main, measured against main):

  • moving connect and bb-account onto watchRpc;
  • plugin mutation toasts.

The earlier head (39d8771a6b) and the worker's unpushed dedupe commits are kept on local branches.

How you verified

Same headless-Chrome scripts against start:worktree builds of main (8160529994) and this branch on one data dir:

main this PR
Provider-usage reads, 150 s idle, card closed 1 (inventory at load) 0
Provider-usage reads, 150 s with the card open 3 3
All /api/ requests, 150 s idle 79 76

The card renders the same on both builds.

  • bb plugin rpc call push-notifications threadNotifications.keyed --watch printed the first snapshot. After a threadNotifications.set from another shell it printed the new level within 4 s.
  • pnpm exec turbo run typecheck lint --filter='...[origin/main]': 142/142 tasks passed.
  • Tests passed:
    • turbo run test for the plugin SDK, SDK, domain, CLI and provider plugins;
    • server hub and plugin tests, 603 (one install-jobs test timed out under load and passed alone, 11/11);
    • app src/lib and src/hooks, 1,702.

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael
ymichael force-pushed the bb/watched-plugin-reads-registry-thr_mwyzuec25q branch from dcdb86e to 5c0d533 Compare October 21, 2026 03:47
@ymichael
ymichael force-pushed the bb/watched-plugin-reads-registry-thr_mwyzuec25q branch from 5c0d533 to b1d2347 Compare October 21, 2026 04:05
Base automatically changed from bb/unify-core-watching-git-status-timelines-pr-stat-thr_mwyzuec25q to main October 21, 2026 04:15
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
ymichael force-pushed the bb/watched-plugin-reads-registry-thr_mwyzuec25q branch from b1d2347 to 6a94370 Compare October 21, 2026 04:22
ymichael and others added 6 commits October 21, 2026 21:37
A plugin-read subscription target starts each experimental_whileWatched
producer when its first watcher subscribes and aborts it when the last
one leaves, through the registry core uses for daemon workspace watching,
timeline pushes and PR status. Every live app query hook and SDK watcher
holds the subscription for its read, whether or not the method has a
producer, so a failed first read still starts it.

The SDK gains plugins.experimental_watchRpc, which reads immediately and
re-reads after any change to its plugin and after reconnect (RPC
responses carry no tags, and the SDK has no contract to compute them),
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. Plugin
signals go only to plugin subscribers. Also fixes a recursive close after
a failed WebSocket handshake in the SDK realtime client.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Port #5677's provider-usage migration onto the watched-read registry as the
first experimental_whileWatched caller. getUsage registers a producer that
re-measures at the reader's maxAgeMs only while settings, the sidebar
footer or a CLI watch reads it, replacing the frontend refresh and
countdown timers, the external store and manual cache publication. A
plugin-local resource cache owns measurement freshness, errors, forced
collection and cancellation, and the plugin follows usage sources with
experimental_watchDiscovery.

Settings and the footer read through tagged queries with the contract the
merged hooks require, moved into contract.ts so the app imports it
without server code. Reload writes through the new refreshUsage mutation.
The Codex, Claude Code and ACP usage sources tag their inventory and
invalidate it on host, config and provider-registration changes.

Behaviour as in #5677: reads refresh at the requested cadence only while
watched; refresh errors keep previous values with Retry; a later success
clears earlier errors; host and config changes refresh inventory; Reload
is disabled while pending and the footer countdown follows shared
refreshes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A plugin read over the 16 KiB cap failed the whole subscribe message, and
the server closed the socket with 1008. The app resends every target in one
batch on reconnect, so a single oversized read could keep core's realtime
socket dropping. Subscribe and unsubscribe messages now drop each target
that fails validation, the way unknown kinds were already dropped, and keep
the rest. The app also refuses to send a target that fails validation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The watched-reads entry said core controls and the CLI share one realtime
subscription implementation; the app uses its own WebSocketManager and the
SDK and CLI use BbRealtimeClient. The tagged-mutation entries said core uses
useTaggedMutation and optimistic descriptors; core has no caller of either.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/watched-plugin-reads-registry-thr_mwyzuec25q branch from 39d8771 to e98cc48 Compare October 22, 2026 04:38
@ymichael

Copy link
Copy Markdown
Collaborator Author

Superseded by #6125, which landed the part of this PR that was needed: bb.rpc.experimental_whileWatched on the hub's watched-target registry. experimental_watchRpc, experimental_watchDiscovery and the CLI --watch flags were dropped because no plugin needs them.

AGENT GENERATED

@ymichael ymichael closed this Oct 22, 2026
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