Repository navigation
Reconcile completed turns after host reconnect - #3613
Closed
davidondrej wants to merge 2 commits into
Closed
davidondrej wants to merge 2 commits into
davidondrej wants to merge 2 commits into
Conversation
davidondrej
marked this pull request as ready for review
September 14, 2026 09:16
This was referenced Sep 25, 2026
Collaborator
|
This is an automated message. We have closed this pull request because it has been open for more than two weeks. |
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]>
Collaborator
|
Thanks for digging into this, and for the thorough repro. This is fixed by #4271, which takes a different approach: instead of clearing the connection error after the fact, bb no longer raises it. A disconnect no longer interrupts running turns on a timer. The reconnect decides what happens to the work. |
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.
Human comments
What was wrong
BB marked threads as failed when their cloud host disconnected. The agents kept working, but BB refused to clear the error when their completed output arrived.
Reproduced on BB 0.43.1 and
mainat9e1641114.What changed
No new dependencies, database schema, API, or protocol changes. This handles incoming events; it does not repair old error badges automatically.
How you verified
idle, and retries of completed work were rejected. Agent execution was simulated; live threads were untouched.