Repository navigation
Notify parents when delegated child work ends unexpectedly - #4356
Merged
ymichael merged 5 commits intoSep 26, 2026
Merged
Conversation
ymichael
deleted the
bb/investigate-missing-project-thread-thr_jt92nirtrh
branch
September 26, 2026 04:21
3 tasks done
ymichael
added a commit
that referenced
this pull request
Sep 28, 2026
## Human comments ## What was wrong Since #421 the server takes a host's liveness from whether the hub has a daemon socket registered. Nothing acted on a connection that stayed open while the daemon went silent. When a laptop host slept, its socket could stay half-open, so the server kept reporting the host `connected` and kept sending it work, and each command waited out the full 30s `command_timeout`. On 2026-09-23 M5 (`host_stzudmkj6u`) went to sleep at 20:10:44 (`pmset -g log`). Its session `hses_e4xcqe579w` stayed `active` with a lease that expired at 20:11:14, `bb host list` still showed it `connected, 12m ago` at 20:22, and thread provisioning on it failed with `Timed out waiting for command result`. Simply closing silent sockets would have exposed a second problem. Every disconnect ran timers that settled the lost host's work: after 5s they cancelled pending approvals/questions and marked background tasks finished, and after 30s they interrupted running turns and workspace setup. A sleeping laptop's work is only suspended, so every lid-close would have errored its turns and permanently thrown away its open questions. ## What changed **1. Silent daemons are closed (`ws/hub.ts`, `ws/daemon-protocol.ts`, `start-server.ts`).** Every incoming daemon frame marks the connection as heard from. A check runs once per heartbeat interval (5s) and closes a connection after `LEASE_TIMEOUT_MS / HEARTBEAT_INTERVAL_MS` = 6 quiet checks in a row, which is 30–35s after the daemon's last message. It sends the existing `session-close` `expired` (daemons already reconnect on it), closes the socket, and records close reason `expired`. It counts missed checks rather than comparing wall-clock times, so the *server's* own sleep counts as at most one quiet check, which avoids #421's problem where every host was dropped at once after the server woke. **2. A disconnect no longer settles work; the reconnect does (`internal/session-owner-side-effects.ts`).** On any disconnect (socket close or lease expiry) the host goes offline and nothing is cancelled or interrupted on a timer; the 5s and 30s disconnect timers are removed. The reconnect decides what happens to the work, as it already did: - **Same daemon instance** (sleep, network drop): `reconcileDaemonReportedThreads` carries on with the threads the daemon still reports, and interrupts those it doesn't (`host-connection-lost`). - **New instance** (daemon or machine restarted): `handleHostSessionOpened` interrupts turns, pending interactions, background tasks and workspace setup, unchanged. The imported sessions of an experimental server move still settle their hosts' work at boot, as before (`settleLostHostWork`). **2b. Display: only the thread notice waits, no `host-reconnecting` (`949d7760b0`, `5e3b305bff`, `1b97f8224e`, `8632254074`).** A host's `status` everywhere (API, CLI, SDK, machine labels, pickers, thread info panel) is its real connection. The one thing that waits out a brief drop is a running thread's "<host> disconnected" notice (`waiting-for-host`), shown only once a socket has been closed for `HOST_RECONNECT_GRACE_MS` (30s); a session the server ended itself (silent daemon, removed host) shows it immediately. `closeSession` no longer stamps `lastSeenAt`, so "last seen" is the last time the daemon was actually heard from. The unreachable `host-reconnecting` display status and the `hostReconnectGraceExpiresAt` field are removed from the domain, SDK, client-core, app and thread-list plugin (plugin SDK version bumped). **3. Answering a question whose host is offline fails up front (`services/interactions/pending-interactions.ts`).** Before, the answer marked the interaction `resolving` and was sent once; that send failed and the answer was never re-sent, so the agent stayed blocked. Now the request fails with `502 host_unavailable` ("Host is not connected") and the question stays `pending`, so it can be answered once the host is back. **4. Remote terminals survive a same-instance reconnect (`683d232a2a`).** A running terminal keeps its owning daemon session when the socket drops. When a socket opens, disconnected terminals owned by the same daemon instance move onto the new session and go back to `running`; a restarted daemon's terminals, and terminals that were still starting, expire as before. The server records how far it has forwarded each terminal's output, asks the daemon to replay from there after reattaching, and holds live output until the replay arrives, so browsers see one continuous stream. The daemon now buffers `terminal.exited` across a disconnect so an exit during the drop is still reported. **Wire change: `HOST_DAEMON_PROTOCOL_VERSION` 219 → 220.** **5. Host calls wait briefly for a reconnecting daemon (`b2b97cdbce`, `services/hosts/online-rpc.ts`).** Before sending, every online host RPC (including plugin host calls) waits up to 5s for the host's daemon when a reconnect is plausibly under way: the host is `active` and its newest session is either open but not yet on a socket (within its lease) or was closed by its socket dropping within the reconnect grace. Nothing has reached the daemon before the wait, so it is safe for every command. Silent-expired, long-gone, suspended or removing hosts still fail fast. Requests whose socket drops after sending are still retried only for idempotent commands. This also fixes the stop the server re-sends during `/internal/session/open`, which used to run before the new socket registered. **6. Stop settles immediately when the host is offline (`8467cb0bd3`, `threads/thread-lifecycle.ts`).** A stop the host can't receive (`host_unavailable`) now settles the thread on the server the way `unknown_environment` already did: the active turn is interrupted, pending interactions and background tasks are settled, and the thread goes idle. If the same daemon later reconnects still running that thread, the server sends it the stop instead of reviving it; that applies to a thread whose latest run marker is a manual-stop interruption with no turn started since (`listThreadIdsStoppedSinceLastTurnStart`). **7. Daemon reconnect backoff capped at 10s (`d8c367fd25`, `apps/host-daemon/src/server-connection-support.ts`).** The ladder was ~1, 3, 7, 15, 31, 61s, so after a tunnel outage of 20–27s (where outages on this instance cluster) the next attempt landed just past the 30s reconnect grace, so running threads showed "<host> disconnected" and host calls stopped waiting for it. With a 10s cap it is ~1, 3, 7, 15, 25, 35s. Taken from the Modal mid-turn disconnect investigation; that investigation's 90s interruption grace is superseded by item 2. No test: it is a single constant whose target (the server's 30s window) the daemon cannot import. **8. Bugs found by end-to-end QA against a `pnpm start:worktree` server** (a disposable daemon reached through a TCP proxy that can drop or black-hole its connection): - `0685d228d5`: an open thread page kept the "<host> disconnected" notice after the host came back, until reload. The server now publishes the host's thread status when a daemon socket opens, not only when it closes. - `14df3f2653`: a browser that attached a terminal while its host was reconnecting (after a server restart, or opening the page during an outage) was dropped as a client and showed a dead terminal. It now stays registered and gets the reattach and the replay of missed output. - `4bd5fafb86`: typing in or resizing a disconnected terminal returned `terminal_not_running`, which the app treats as the terminal ending, so it stopped reconnecting. Those inputs are now dropped quietly while the host is away. - `eb01a96829` (app): the terminal panel force-closed disconnected terminals that weren't on screen, hid their tabs, and offered a "Start new terminal" replacement that closed them first. Loading a page during an outage, or any second terminal tab during a brief drop, killed live terminals and orphaned their processes on the host. Disconnected terminals are now shown and kept until their host returns; the retained-terminal tracking, auto-close effects and replacement flow are removed. - `5deced4c62`: earlier on this branch a host was reported connected for 30s after its socket closed, and the send path read that status to decide whether to queue on `host-offline`. A follow-up sent during that window returned `HTTP 502: Host is not connected` instead of queueing (reproduced live 8s into a drop). Sends and queued-message drain failures now decide by whether a daemon socket is registered, so a message sent during a drop queues and goes out on reconnect. - `8632254074`: the same mistake applied anywhere that read `host.status` to decide what to do, e.g. the CLI's and app's reconnect checks, which believed a dropped host was still connected for 30s. The server now reports the real connection everywhere; only the thread notice waits (item 2b). **9. A turn that finishes while its host is away completes normally (`376defc50f`).** When a daemon reconnected, the server interrupted every active thread it no longer reported as running. A turn that finished during the outage was in that set: its final events were still queued on the daemon, which only delivers them once the new session is open, so they arrived after the thread had been set to `error` ("Thread interrupted because the connection to the host was lost"); the turn's success was rejected and the agent's final reply was lost. Session open now carries `undeliveredEventThreadIds`, the threads the daemon still holds events for; the server leaves those running and the held events settle the turn as usual. **Wire change** (same unreleased 220 bump as item 4). **10. The composer can send while its thread waits for the host (`ccfcecdff6`, client-core).** With "Enter steers the active thread" on (the default), Enter sends the draft as a steer, and the composer only allowed that for `active` / `provisioning` / `starting`. Once a host had been gone for 30s and the thread showed `waiting-for-host`, the send button went grey and Cmd+Enter did nothing. A draft can now be sent then; the server queues it (`delivery: queued`, item 8) and steers it in on reconnect. Sending an already-queued message immediately stays disabled while the host is away. The placeholder, which only said "Host disconnected", now says "Queue a message for when the host reconnects". Items 1–3, 5–8 and 10 change no wire contract; items 4 and 9 share the protocol bump. ### Reviewer attention - **A host that never comes back** (dead machine) leaves its running threads `active` / "<host> disconnected" until someone stops them; there is deliberately no timed cap. Stop now settles them immediately (item 6), and removing the machine settles everything on it. - **Protocol version:** 219 → 220 (items 4 and 9); plugin SDK 0.5.30 → 0.5.31 (item 2b). Enrolled daemons will self-update. - **Parent notices for children on a lost host (#4356):** #4356 notified a parent when the 30s disconnect timer interrupted its child. That timer is gone (item 2), so the notice now comes when the reconnect interrupts the child (the daemon no longer reports it, or a restarted daemon) — and not at all while the host stays away. #4356's two host-loss tests are rewritten to interrupt the child on reconnect. - **Wait on calls:** during a socket drop, a host call can now take up to 5s before failing instead of failing immediately. ## How you verified Tests (each new or changed test fails with its fix removed): - `test/hosts/daemon-liveness.test.ts` (new): a silent daemon is still connected at 30s and closed at 35s (`session-close` `expired`, close `1000 expired`, session `closed/expired`, a later real `onClose` is a no-op); a daemon sending one message every 25s stays connected. - `test/public/public-thread-interactions.test.ts`: a pending approval survives a 10-minute disconnect; answering while offline returns 502 `host_unavailable` and leaves it `pending`; answering after reconnect gives `resolving`. - `test/internal/session-owner-runtime-status.test.ts`: a closed socket stays hidden until the reconnect grace ends, then clients get `waiting-for-host` while the thread stays `active`; a daemon that reconnects within the grace never shows a disconnect. - `test/internal/background-task-reconciliation.test.ts`, `test/threads/thread-provisioning-recovery.test.ts`: background tasks, running turns and workspace setup are untouched after a 10-minute disconnect. The existing tests for same-instance vs restarted-instance reconnect still pass. - `test/services/threads/thread-runtime-display.test.ts`: an active thread stays `active` while its host's closed socket is within the grace or its reconnecting daemon hasn't registered yet; a server-expired (silent) session shows `waiting-for-host` at once. - `test/public/public-terminals.test.ts`: a same-instance reconnect reattaches the terminal, sends no `terminal.close`, asks for a replay from the forwarded position and holds live output until it arrives (browser sees 0,1,2,3,4); a restarted instance still expires terminals. `apps/host-daemon/src/server-connection.test.ts`: a `terminal.exited` sent while disconnected is delivered after reconnect. - `test/internal/background-task-reconciliation.test.ts`: a same-instance reconnect that reports a thread in `undeliveredEventThreadIds` leaves it `active`, and the held `item/completed` + `turn/completed` then settle it `idle` (fails without item 9: `error`). `event-sink.test.ts`: held events report their threads until delivered. - `test/hosts/online-rpc.test.ts`: an RPC waits for a daemon reconnecting after its socket dropped; a silent-expired host fails without waiting. `test/internal/background-task-reconciliation.test.ts`: a stop while offline settles the thread idle with the turn interrupted, and a same-instance reconnect sends the daemon `thread.stop` instead of reviving; a thread that started a new turn after its last stop is still revived. - Rebased on `origin/main` `f3b2460b81`. Latest full run on this head `ccfcecdff6` (`turbo typecheck lint test --filter=...[origin/main]`): typecheck and lint clean; tests all pass (`@bb/server` 3281, `@bb/app` 5120, `@bb/host-daemon` 734, `@bb/db` 583, `@bb/client-core` 281, integration 79) except load flakes that pass when their file is run alone (`install-machine-script` "restarts its own running daemon…", `plugin-native-server-loading` ×2, host-daemon `workspace-path-list` "does not overflow the call stack…", `CommandPalette` "opens only the selected result in a split…", agent-runtime `runtime.acp-topology`). Live QA (scenarios run on `8632254074` before the last rebase; the held-events row re-run on `376defc50f`): an isolated `pnpm start:worktree` instance (its own data dir), plus a disposable second daemon (`host_vmi9qdpe65`) that reaches the server through a TCP proxy, so its connection can be dropped (proxy down) or left open but silent (`SIGSTOP`). The base column comes from the earlier runs on `4277998ed7`. | scenario | base | this PR | |---|---|---| | daemon frozen, socket left open | `connected` indefinitely; commands hang ~62s | offline after 31–35s; a command then fails in 0.8s with 502 `Host is not connected`; Online again right after resume | | 10s drop during a running turn | turn continues | Machines shows Offline at once; the thread shows no notice; the turn continues and replies `done` | | 50s drop during a running turn, follow-up sent at 40s | turn interrupted at 30s | "<host> disconnected" appears after 30s and clears on reconnect; the follow-up returns `delivery: queued`, goes out on reconnect and gets its reply; the turn finishes | | stop while offline | stays `stopping`; agent keeps running after reconnect | thread settles `idle` immediately; on reconnect the daemon stops the turn (`sleep` process gone) and the thread stays stopped | | pending approval, daemon frozen 45s | cancelled permanently at ~35–40s | stays `pending`; answering offline → 502 and still `pending`; answering after reconnect → resolved, the command ran | | terminal running a 1s ticker, 40s drop | terminal ends | tab shows "(disconnected)", then reattaches and replays: ticks 1–66 with no gaps | | turn that finishes on the host during a 45s drop | interrupted at 30s | before item 9: ended in `error` and lost the final reply; with item 9 (`376defc50f`): `idle` right after reconnect with the reply "done" shown, no rejected events | Fixes #4364: its interruption (`system/thread/interrupted reason=host-daemon-restarted cause=host-connection-lost` after a heartbeat-ack drop) is main's 30s disconnect timer, removed by item 2; a turn that ends during such a drop is covered by item 9. Why that host's heartbeat acknowledgements stopped is not addressed here. Fixes #4353, both of its defects: the composer disabled while the host is away (item 10; `host-reconnecting` is also gone, item 2b), and the status that stayed stale after a reconnect (`0685d228d5`, item 8). Verified live: 36s into an outage the send button was enabled ("Steer current run (Enter), ⌘ Enter to queue"), Enter queued the draft ("Waiting for Manual machine qdpe65 to be ready"), and after reconnect it was steered in and answered. Supersedes #3613, which clears the connection error after a turn completes during a disconnect. Here the error is never raised: the timer is gone (item 2) and the reconnect waits for the daemon's held events (item 9). Related: #421, #2358 (the opposite direction: daemon heartbeating while server-to-daemon commands failed, fixed with a daemon-side watchdog). > AGENT GENERATED --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 18, 2026
## Human comments ## What was wrong Creating an interaction has two entry points in `PendingInteractionLifecycle`: `registerPendingInteraction` for provider requests from the daemon, and `requestPluginInteraction` for plugin cards (`bb.ui.requestInput`, which `AskUserQuestion` uses on Codex, Pi and ACP). Each path ran its own copy of the side effects that follow creation. The parent needs-attention notice was not in either copy. It lived in the HTTP route `/internal/session/interactive-request`, so only the provider path sent it. A child's plugin question therefore never reached its parent in `auto` or `stuck` mode (#7457). #3397 was the same split: the plugin copy was missing `interaction.pending`. ## What changed - **One creation method:** `PendingInteractionLifecycle.createInteraction` is now the only caller of `createPendingInteraction`. In one transaction it inserts the row, after the provider's lookup for an existing row. It then calls `announceCreatedInteraction`, which appends the timeline event, sends `interactions-changed`, emits `interaction.pending`, and requests the parent notice. Both `registerPendingInteraction` and `requestPluginInteraction` go through it, so a new creation path can't store an interaction without those effects. A retried provider registration (`outcome: "existing"`) returns before the announcement, so the parent is still notified once. - **Plugin waiter order:** the plugin path now registers its waiter after the announcement rather than before. Nothing can answer the card in between: plugin event handlers run on `setImmediate`, the hub notification goes over the WebSocket, and the parent notice is deferred. The two `signal.aborted` checks between the insert and the announcement are gone; nothing asynchronous happens there, so they could never be true. On setup failure the row is still interrupted ("Plugin interaction setup failed") and the error rethrown. - The parent notice and the blocker summary builder moved from `internal/interactive-requests.ts` to `services/interactions/pending-interaction-parent-notice.ts`. The code is unchanged, except that it reuses the thread row the lifecycle already loaded. The route now only registers the interaction. - No wire, protocol, schema, CLI or SDK changes. Third-party plugins see no API change. Plugins that call `bb.ui.requestInput` on a child thread now cause a parent notice. **Patches this deletes or supersedes** - The route-only notice call (`requestChildThreadNeedsAttentionNotification` in `interactive-requests.ts`). - The duplicate post-creation blocks in `registerPendingInteraction` and `requestPluginInteraction`, which is the per-path emit #3398 had to patch. - #7458 (closed), which added a second notice call to `requestPluginInteraction` and left two call sites. This PR leaves one and keeps #7458's notice wording. **Issues and fixes from this root cause (separate per-path producers of creation side effects)** | Item | What happened | Prevented by this change? | |---|---|---| | #3397 / #3398 | Plugin cards never emitted `interaction.pending`; #3398 added the emit to the plugin copy | Yes. The emit is in the shared step, and the guard fails if a path skips it | | #7457 (this) | Plugin cards never notified the parent | Yes | | #7458 (closed) | Per-call-site patch for #7457 | Superseded; its wording is kept | **Remaining follow-up: #7457 point 6.** When someone answers the child's question, the parent is not told that a decision was made. Resolution, expiry and dismissal notices are tracked in #3614 and are out of scope here. Not in this class, and not changed here: turn-end notices (#3956/#4356, #6820/#6821), and parents never learning that a child was unblocked (#3614). ## Decisions for review - **Plugin cards in child threads now notify the parent.** This is the #7457 ask. It also covers any third-party plugin that calls `bb.ui.requestInput` on a child thread. The same filters apply as for provider requests: `auto` and `stuck` notify, `off` and fork children do not. - **Wording.** Plugin cards don't hold the child's turn, so their notice reads `Pending plugin request: <title>` followed by `Interaction: <id>` (the wording from #7458), for example `Pending plugin request: Which color?` / `Interaction: pint_…`. The ID lets the parent answer with `bb thread interactions answer`. Provider requests keep `Blocked on <kind>:`, because they do block the turn. ## How you verified - **Guard (contract table):** `apps/server/test/services/interaction-parent-notifications.test.ts` covers 4 creation paths and 4 child kinds, 16 cases. The paths are a provider command approval, a provider user question and a provider plugin-defined request, all sent over the real HTTP route with a retried registration, plus a plugin card. The child kinds are `auto`, `stuck`, `off` and a fork child. Each case holds parent delivery and asserts that exactly one `interaction.pending` was emitted and that the parent has exactly the expected number (0 or 1) of `child-needs-attention` notices. - On main: 2 of 16 fail, the plugin card in `auto` and `stuck` (`expected [] to have a length of 1 but got +0`). That is #7457. - On main with the plugin path's `emitPluginInteractionPending` removed (the pre-#3398 shape): all 4 plugin-card cases fail (`expected [] to deeply equal [ 'pint_…' ]`). - With this change: 16 of 16 pass. - **Live reproduction on a `pnpm start:worktree` instance:** a Codex parent and a Codex child (`--parent-thread`, `auto`), where the child calls `AskUserQuestion`. - main: the card stays `pending`, and the parent gets only `child-completed`. No `child-needs-attention` arrives. - This branch: the parent gets one `child-needs-attention` in the same second the card is created, then `child-completed`. With a `stuck` child, the parent gets only the notice: `@thread:… needs help.` / `Pending plugin request: Which color?` / `Interaction: pint_…`. - **Single-caller check:** the `interaction creation ownership` test scans every `apps/*/src`, `packages/*/src` and `plugins/*/src` file outside tests. It fails if `createPendingInteraction` is called anywhere except the lifecycle; the function's own definition is excluded. Adding a stray call in `internal/interactive-requests.ts` made it fail and name that file. The `packages/db/scripts/query-costs` seed scripts are dev tools that write fixture rows, so the check doesn't scan them. - **Moved tests:** the route tests for `stuck`/`off` filtering and fork-child filtering are now covered for every path by the contract table, so they were removed. The route's message-content and retry test stays. - `pnpm exec turbo run test --filter=@bb/server -- test/services/interaction-parent-notifications.test.ts test/services/pending-interaction-blocker-summary.test.ts test/internal/internal-interactive-requests.test.ts test/services/pending-interactions.test.ts test/threads/system-notice-dispatch.test.ts test/services/plugins/plugin-thread-events.test.ts test/threads/thread-send-dispatch.test.ts test/internal/internal-tool-call-regressions.test.ts test/public/public-thread-interactions.test.ts test/services/plugins/plugin-background.test.ts`: 10 files, 218 tests pass. - `pnpm exec turbo run typecheck --filter=@bb/server` passes. `oxfmt` is clean on the changed files. Fixes #7457 > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Root cause
Several child failure paths close work without a provider completion event, so the parent can remain unaware. The existing child notice also reported only
interrupted; the recordedsystem/thread/interruptedreason and cause were lost before the notice reached its parent. Parent delivery could fail while its host was offline.Change
How you verified
pnpm exec turbo run typecheck lint --filter=@bb/server --filter=@bb/domainand app, server, and domain typechecks passed.pnpm start:worktreereviewer app is running at exact PR head625acfa1d2. A fresh parent thread received a real child-completed notice whose event hassystemMessageSubject.outcomes[0]naming the child and status. A fresh manual Stop QA parent at this exact head remained silent after its active child loggedmanual-stopand an interrupted completion. The source CLI, parent event log, and rendered browser transcript agree.Fixes #3956