Skip to content

Deliver parent/child notices through the dispatcher - #6728

Merged
ymichael merged 2 commits into
mainfrom
bb/pr-notices-go-through-the-queue-thr_dh3f658scf
Nov 2, 2026
Merged

ymichael merged 2 commits into
mainfrom
bb/pr-notices-go-through-the-queue-thr_dh3f658scf

Conversation

@ymichael

@ymichael ymichael commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Parent/child system notices (a child finished, needs attention, changed owner, a detached tool result, an environment-directory continuation) had their own delivery path in parent-system-messages.ts (queueParentSystemMessage → deliverParentSystemMessage / attemptParentSystemMessageDelivery). It was separate from the dispatcher (attemptDispatch) that every other message has used since #6493, kept its own copies of core's waits, and skipped the message.dispatch plugin hooks. Child turn-end notices were also batched in an in-memory Map flushed by a 2 s setTimeout. A server restart or a failed delivery inside that window lost them.

What changed

Path Before After
Parent/system notices own executor (deliverParentSystemMessage) with its own waits and no plugin hooks; queued only when a question, compaction, /clear or an offline host blocked it saved to the parent's queue first as a deliveryMode: "steer" row, then attempted through the dispatcher as an initiator: "system" turn; execution options resolved from the parent at delivery
Drained notice rows sendClaimedSystemNotice → deliverParentSystemMessage deleted; an ordinary drained row with a typed systemNotice
Child turn-end notices in-memory Map + setTimeout, lost on restart or failure one coalesced queued row per parent (coalesce_key = child-outcomes); sendAt moves 2 s later as each child finishes; a timer wakes the drain (and sets itself again if it fires before the wall clock reaches sendAt, which happens on Windows), and the existing due sweep is the backstop after a restart
Parent with no environment yet delivery threw (requireThreadEnvironment) and the notice was dropped the notice waits for provisioning
Notice whose first attempt never ran on a busy parent a notice row on a busy parent had no recovery path the idle-thread recovery sweep also retries ready notices on busy threads

A notice to a parent that is mid-turn still steers into that turn, the same as on main:

  • an active parent: join-turn attempt, steered with expectedTurnId;
  • a parent starting a turn: parked as turn-starting, then steered into the turn once it starts;
  • a pending question: waits on interaction, then steers into the same turn;
  • an offline host: waits on host-offline, then steers into the same turn on reconnect;
  • a held row is stored with deliveryMode: "steer", so a drain joins the running turn instead of waiting for it to end.

Schema: queued_thread_messages.coalesce_key and coalesce_state (nullable text), with a partial index on (thread_id, coalesce_key). Migration 0149_coalesced_system_notices. No daemon wire change, so HOST_DAEMON_PROTOCOL_VERSION is unchanged.

Plugin SDK: the message.dispatch doc now says core's own notices go through the hook with initiator: "system". SDK 0.6.114 → 0.6.115 (doc-only).

Visible behaviour changes

  1. With Concurrency Limit at its cap, a notice that would start a new turn on an idle parent now waits instead of bypassing the limit. A notice that steers into a running parent turn is unaffected: Concurrency Limit always lets join-turn through.
  2. A third-party plugin with a message.dispatch hook can now hold notices.
  3. A child-finished notice to a parent survives a server restart during its 2 s batching window.
  4. A notice to a parent that has no environment yet waits for provisioning instead of being dropped.

How you verified

  • New apps/server/test/threads/system-notice-dispatch.test.ts (15 tests). Run against main's source, the original 14 gave 10 failures. The 4 that pass on main are the steer and recovery guards (running turn, pending question, offline host, recovery on a busy parent), which pin behaviour main already has.
    • The dispatch hook sees notices as system turns and can hold them.
    • A parent without an environment waits.
    • Child outcomes coalesce into one durable row, which the due sweep delivers as one turn; a later outcome after the window starts a new row; an edited coalesced row (new content, execution options or send time) is left alone.
    • A notice whose hook throws is kept for the retry sweep.
    • A parent that finished provisioning while the hook ran still gets the notice.
    • Execution options are resolved at delivery.
    • The window timer delivers the row even when it fires while the wall clock is still short of sendAt. Without the re-arm this fails. It is the cause of the first CI run's Windows failure in internal-event-append-ownership.test.ts ("notifies a parent when a child provider process exits").
    • A notice whose first attempt never ran on a parent that stays active is recovered.
    • Mid-turn parent: the notice steers into the running turn. A limiter at its cap that only admits join-turn sees the notice as join-turn and lets it steer. A held notice is a steer row that joins the turn when released. A pending question makes it wait, then it steers into the same turn. An offline host makes it wait, then it steers into the same turn on reconnect.
  • The existing "parks a parent system notice with its taxonomy while a turn starts" test (thread-send-dispatch.test.ts) covers the parent-starting-a-turn case. plugins/concurrency-limit/server.test.ts "does not re-admit running threads or join-turn attempts" covers the limiter side.
  • Existing child-notification tests now flush through the queue drain instead of the in-memory timer.
  • pnpm exec turbo run typecheck lint --filter='...[origin/main]': 153/153 tasks passed.
  • pnpm exec turbo run test for @bb/server (3803 passed), @bb/db (634), @get-bb/plugin-sdk (410), @bb/domain (294).
  • node .github/workflows/check-plugin-sdk-version.mjs: passes. drizzle-kit generate after the rebase reports no schema changes.

🤖 Generated with Claude Code

AGENT GENERATED

ymichael added a commit that referenced this pull request Nov 2, 2026
## Human comments

## What was wrong

After a server restart, the GitHub PR Status plugin restores each
environment's PR from its database and serves it right away. It also
starts a background re-check right away, often before the host daemon
has reconnected. That re-check returned `unavailable` ("machine isn't
available"), and `store.load` replaced the environment's known PR link
with that result. The sidebar row badge disappeared and stayed gone
until something re-read that row, such as opening the thread or
refocusing the page. Observed on prod: the server restarted at 13:04:14
and the daemon reconnected at 13:04:20. Afterwards the sidebar showed
only #6849 (the thread that was opened). Six other inbox threads with
open PRs (#6760, #6755, #6736, #6728, #6727, #6734) showed no badge,
although their links and snapshots were still in the plugin database.

## What changed

- `plugins/github-pr-status/store.ts`: when a re-check of a known PR URL
comes back `unavailable`, the environment's link is no longer replaced,
so the last snapshot keeps being served. The snapshot's `fetchedAt` is
still bumped, so the regular poll retries it. Discovery reads (no known
URL) behave as before.
- Behaviour change: `bb pull-request show` for an environment whose
machine is offline now prints the last PR bb saw, or `unavailable` when
it has none. Actions (`ready`/`draft`/`merge`) still refuse with the
machine message. The skill doc and README are updated.

## How you verified

- New store test, "keeps serving a restored PR when its machine is
unreachable after a restart": it restores a persisted PR, makes the
first re-check return `unavailable`, and checks that the PR is still
served, nothing is published, and the next successful check publishes
the update. It fails without the fix (`expected { outcome: 'unavailable'
} to deeply equal { outcome: 'available' }`) and passes with it.
- `pnpm exec turbo run test typecheck lint
--filter=bb-plugin-bb--github-pr-status`: 183/183 tests pass, typecheck
and lint clean.

> 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/pr-notices-go-through-the-queue-thr_dh3f658scf branch 2 times, most recently from 84d56c3 to 6487a3e Compare November 2, 2026 23:00
ymichael and others added 2 commits November 2, 2026 15:33
Parent/system notices are written to the parent's queue and attempted
through attemptDispatch as initiator "system" turns, so they pass the
message.dispatch hooks and share core's waits. Child turn-end notices
coalesce into one durable queued row per parent instead of an in-memory
timer, so a restart inside the 2 s window no longer loses them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On Windows a setTimeout can fire while Date.now() is still a few
milliseconds short of the row's sendAt, so the time-reached drain found
nothing due and the notice waited for the periodic sweep.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/pr-notices-go-through-the-queue-thr_dh3f658scf branch from 6487a3e to 55cff69 Compare November 2, 2026 23:35
@ymichael
ymichael merged commit 7aec8a1 into main Nov 2, 2026
51 checks passed
@ymichael
ymichael deleted the bb/pr-notices-go-through-the-queue-thr_dh3f658scf branch November 2, 2026 23:42
ymichael added a commit that referenced this pull request Nov 4, 2026
…rns (#7028)

## Human comments

## What was wrong

Two separate causes produced noisy child → parent completion notices.

1. **Notices piled up while the parent was blocked.** A child's turn-end
notice only coalesced into a queued row that was still inside its 2 s
scheduled window
([`getPendingCoalescedQueuedThreadMessage`](https://github.com/get-bb/bb/blob/4f973b851a/packages/db/src/data/queued-thread-messages.ts#L885-L906)
required `state = 'scheduled'` and `send_at > now`). Once that row moved
to `waiting` (pending question, starting turn, offline host), every
later outcome created another row. On 2026-11-03 a parent blocked on an
AskUserQuestion from 22:23 to 04:31 received ten separate "completed"
notices from one child, all steered in within two seconds of the answer.
The same pile-up existed before #6728 (pairs from one child appear in
the event log since September); this is the first time a parent stayed
blocked long enough for it to reach ten.
2. **`/compact` turns were reported as completions.** A `/compact` on a
child runs as its own turn whose only root item is the context
compaction. Its turn end notified the parent with "No final output was
recorded." just before the queued message behind it started the real
work. All 7 "No final output" child notices since #6821 were these
turns. Before #6821 the same turn re-sent the previous turn's output.

## What changed

| Area | Change |
|---|---|
| `packages/db` `getPendingCoalescedQueuedThreadMessage` /
`updateCoalescedQueuedThreadMessageInTransaction` | Match any
undelivered coalesced row (`queued`, `scheduled`, `waiting`). Only a row
still inside its time window has `send_at` pushed back; a waiting row
keeps its wait. |
| `apps/server` `postCoalescedSystemNotice`, child notifications |
Return the row as stored; arm the dispatch timer only for a scheduled
row. |
| `packages/db` `isStoredTurnContextCompactionOnly` | New: true when a
turn's completed root items are all `contextCompaction`. |
| `apps/server/src/internal/events.ts` | A completed child turn that
only compacted context does not notify the parent. A turn that compacts
and then answers still does. |
| `bb guide threads` | `--parent-notifications` text says
compaction-only turns are not reported. |

No daemon wire change, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged.
No schema change.

## How you verified

- `apps/server/test/threads/system-notice-dispatch.test.ts`: "merge
later outcomes into a row still waiting on the parent" (parent on a
pending question, two outcomes from one child plus one from another →
one waiting row, latest status per child). Fails on main, passes here.
It replaces "start a new row once the earlier window has expired", which
pinned the pile-up.
- `apps/server/test/threads/child-completion-turn-output.test.ts`: "does
not notify the parent for a turn that only compacted context"
(compaction-only turn → no notice; compaction + answer → notice with the
answer). Fails without the `events.ts` change. The existing turn-scoping
test now records the parent's latest notice per child turn, because its
harness parent never accepts a turn and the old assertion counted the
pile-up.
- `pnpm exec turbo run typecheck lint --filter=@bb/server
--filter=@bb/db` passes.
- `pnpm exec turbo run test --filter=@bb/server --filter=@bb/db`: 3857
passed / 1 skipped, and 653 passed. One run hit a 40 s timeout in
`builtin-plugins.test.ts` under load ~14; that file passes on its own
(27/27).
- Live QA against a `pnpm start:worktree` server: to follow in a
comment.

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

> AGENT GENERATED

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 4, 2026
…eue drawer (#7029)

## Human comments

## What was wrong

**Ownership notices were one turn per child.** `thread-ownership.ts`
debounced each child separately with an in-memory `WeakMap` + 2 s
`setTimeout`, then called `queueParentSystemMessage` once per child.
Unassigning N threads together sent the parent N separate notices, each
its own steer or turn. In production, thr_bgwkk8ing5 got 6 within one
minute on 2026-10-22. A server restart inside the 2 s window lost the
notice. Child turn-end notices had the same design until #6728 moved
them to one durable coalesced queue row per parent.

**Queued bb notices were noisy in the queue drawer and sidebar.**
- The drawer rendered their raw prompt text ("[bb system] These threads
are now children…") with a "From System" label.
- They offered every user-message action (edit, reschedule, drag).
- They appeared for their 2 s coalescing window and then vanished.
- They turned the sidebar's queued clock on even when nothing of the
user's was queued.
- The collapsed summary could show a notice's schedule as if it were the
user's.
- The drawer was capped at 198 px, so a third row sat under a fade.

## What changed

**Ownership notices go through the coalesced queue**
(`thread-ownership.ts`). The WeakMap/timer path is gone. Each change
posts to `postCoalescedSystemNotice` with a `thread-ownership` key and a
2 s window. All changes to one parent become one durable queued row with
a typed, zod-parsed `coalesceState`, listing every child assigned or
unassigned. The timer's per-child behaviour is kept:
- A move undone before the parent is told is withdrawn. If the row ends
up empty, it is deleted (`message.cancelled` is emitted to plugins).
- An `assigned` entry remembers the parent the child had before the
window, so A→B→C notifies only A and C, and A→B→A notifies nobody, even
with `parentNotifications` `stuck`/`off`.
- Removal notices are still skipped unless `parentNotifications` is
`auto`.
- Once a row is delivered, the next change starts a new one.
- Works with main's current coalescing. #7011 reverted #7028's "merge
into rows waiting on the parent", so today a row can only be merged into
or withdrawn from during its 2 s window. If #7028 is restored, ownership
notices pick that up with no change here.
- `postCoalescedSystemNotice`'s `merge` may return `null` to withdraw,
using the new `deleteCoalescedQueuedThreadMessageInTransaction`, which
only deletes a row that is still waiting to be sent.
- A single change renders exactly as before. Two or more use the new
`system-message-thread-ownership-batch` template and `ownership-batch`
kind with a `thread-batch` subject; the timeline titles it "Ownership
changed for N threads".
- Deliberate change: the old timer skipped a notice if the child was
archived or deleted inside the 2 s window. The row's content is fixed
when it is posted, so that narrow case now still notifies.

**The queue drawer shows notices usefully.**
- `ThreadQueuedMessage` gains `systemNotice`. Notice rows use the
timeline's own title and icon ("3 threads updated", "X assigned to you")
and show only their wait reason underneath.
- Notice rows offer only send-now and delete: no edit, no send-time
change, no drag. The server reports them `editable: false` and the
update route refuses a rewrite with 409, so the CLI and SDK follow the
same rule.
- Notices still collecting or being delivered (time wait or no wait) are
left out of the drawer, so they no longer flicker. Held, failed and
stuck notices still show.
- The sidebar's queued-waiting status counts only non-notice rows; a
failed notice still shows as failed.
- The collapsed header adds "· N from bb" and prefers the user's own
wait line over a notice's.
- The drawer cap is 30% of the window height, between 198 and 360 px. A
short queue still fits its content exactly.

**Other**
- `@get-bb/plugin-sdk` bumped to 0.6.124. The bundled types inline
`SystemMessageKind` and `ThreadQueuedMessage`.
- No daemon wire change, no CLI/config surface change.

## How you verified

**Tests**
- New `thread-ownership-notices.test.ts` replaces the timer-mock
debounce test and runs against real queue rows. It covers:
- Bulk unassign: one row, one delivered `ownership-batch` turn. This
**fails on main** with `expected [] to have a length of 1 but got +0`.
With a 2.3 s wait added on main, the same three unassigns produce 1
delivered turn plus 2 more queued notices.
  - The row is persisted and scheduled before the window elapses.
- Same-child flip; intermediate parent never notified; withdrawing one
child keeps the others.
  - Delivered-parent baseline.
  - `stuck`/`off` handling; single change keeps today's exact text.
- Server: queued-work status for notice-only and mixed threads; a notice
row reported `editable: false` with `systemNotice`, and a rewrite
refused with 409.
- App: notice-row title and actions, collapsed summary, transient-notice
filter, drawer-cap math. Existing drawer tests that encoded "From
System", a system second line and the 198 px cap are updated.
- Targeted runs: server 99, app 452; `turbo run test` for domain,
server-contract, cli and client-core. `turbo run typecheck` passes
across server, app, db, cli, demo-server, plugin-sdk and test-helpers;
app lint has no errors.

**Live** on `pnpm start:worktree`, with Claude Haiku managers and
children, driven with the source CLI:
- Ownership:
- Three concurrent assigns and three concurrent unassigns: one notice
each.
- SIGKILL inside the window: the row was on disk and was delivered after
the automatic restart.
  - Assigning then unassigning the same child withdrew the row.
  - A single change kept the old wording.
- Notices held by the concurrency limit (global limit 0):
- The drawer shows "Ownership changed for 4 threads · Held by
Concurrency limit" next to the user's own scheduled message. That's two
unassigns plus two assigns sent 10 s later, merged into the held row.
  - Hovering a notice offers only Send now and Delete.
  - Collapsed: "Queue · 1 from bb" with the user's own schedule.
  - Same at 390 px.
- A MutationObserver on an idle manager saw no queue row or card while
three children reported, and the notice was delivered as one turn.
- With only notices queued, the thread list API reported `queuedWork:
none` and the sidebar clock went away.

> 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