Repository navigation
Settle background tasks when the bridge, Claude Code or the daemon that owns them stops - #6124
Merged
ymichael merged 3 commits intoNov 4, 2026
Conversation
alexandre-vl
added a commit
to alexandre-vl/bb
that referenced
this pull request
Oct 22, 2026
2 tasks done
ymichael
added a commit
that referenced
this pull request
Nov 2, 2026
) ## Human comments ## What was wrong When a host daemon reconnects, session open reports only which threads are active ([`hostDaemonSessionOpenRequestSchema`](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/packages/host-daemon-contract/src/session.ts#L38-L40), [`activeThreads`](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/packages/host-daemon-contract/src/session.ts#L168-L169)). Nothing compares the daemon's open work with the server's. Background tasks are settled only when a *new* daemon instance opens a session ([session-owner-side-effects.ts#L108-L122](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/apps/server/src/internal/session-owner-side-effects.ts#L108-L122)). If the same instance reconnects after a task's provider process died, the task stays "Running" (#6123). Nothing ends a provider's wait on a question the server closed. A failed live `interactive.resolve`, for example `host_unavailable` when the socket drops mid-delivery, interrupts the interaction ([pending-interactions.ts#L829-L837](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/apps/server/src/services/interactions/pending-interactions.ts#L829-L837)). The daemon's [`InteractiveRequestRegistry`](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/apps/host-daemon/src/interactive-request-registry.ts#L106-L210) keeps waiting, and [`onSessionOpened`](https://github.com/get-bb/bb/blob/c2365296a4503675fc721752a55f794db5e89b61/apps/host-daemon/src/app.ts#L910-L946) never looks at open waits. The turn stays active, and later messages are accepted as steers that never run (#6251). This ports the question and background-task sync out of #6552. It leaves out #6552's input ledger, turn-start deadline and every stop-related change. ## What changed - **Wire, `HOST_DAEMON_PROTOCOL_VERSION` 258 → 259:** - Session open sends `openThreadWork`: per thread, the open background item ids and the provider questions the daemon still waits on, including registrations in flight. - The session-open response returns `endedInteractiveRequests`. - New server→daemon message `interactive-requests.end`. - **Server, `open-work-reconciliation.ts` (runs on every session open):** - settles background tasks the daemon no longer runs; - interrupts pending questions it no longer waits on; - re-sends saved answers it still waits on, and marks the other in-flight answers resolved; - returns the questions it waits on that the server already closed. - Threads whose buffered events are still replaying are skipped, except that answers are still re-sent for them. - **Server, `PendingInteractionLifecycle`:** - An answer whose delivery fails with `host_unavailable` stays `resolving` and is re-sent when the daemon's socket opens. - A `stale_interactive_request` reply to a re-sent answer marks it resolved instead of interrupting it. - Bulk thread interrupts no longer discard `resolving` provider answers. - Interrupting a provider question sends `interactive-requests.end` to the connected daemon. Inside a transaction the send waits until after commit. - A question registered for a turn that already ended is rejected. - **Daemon:** - reports open work from the runtime (`listOpenBackgroundWork`) and the registry (`listOpenRequests`); - ends waits named by `endedInteractiveRequests` or `interactive-requests.end`; - an ended registration still in flight no longer raises an unhandled rejection. **Visible behaviour changes:** - After a reconnect, a question the server closed no longer leaves the thread stuck `active`. The provider's turn ends, and the next message starts a new turn. - An answer sent while the connection drops is delivered once the daemon is back, instead of the question turning "interrupted". - A background task whose provider process died is shown as stopped once the same daemon reconnects, instead of "Running" forever. **#6123 is only partly fixed.** Tasks settle when the daemon comes back as the same instance (a restarted daemon already settled them on main). Settling tasks when the machine goes away, at shutdown or suspension, is left to #6124. So is settling rows stored without the `foreground` field (written before #5650), which the reconnect settle still skips. ## How you verified New tests; each fails on main and passes here: - `tests/integration/fake/recovery/reconnect-open-work.test.ts` (real server, daemon and scripted-echo bridge): - **#6251 shape:** while the daemon's socket is down, the server interrupts a pending `ask_user` question, and the same instance reconnects. The provider's wait ends and a later message runs. On main the thread stays `active`. - **#6123 shape:** the bridge that owns a `bg_task` is `SIGKILL`ed while the daemon stays up, then the same instance reconnects. The task settles as interrupted/stopped. On main it stays open. - `apps/server/test/services/pending-interactions.test.ts`: - keeps, interrupts or ends questions according to the report; - an answer cut off by a socket drop is re-sent and resolves; - a saved answer is re-sent while buffered events replay, and again when a slow socket opens; - a stale reply to a re-sent answer resolves it; - a lost ack resolves the answer; - a question for an ended turn is rejected. - `apps/server/test/internal/background-task-reconciliation.test.ts`: the same instance settles a task it no longer runs, and keeps one it still reports or whose events are still buffered. - Daemon: `interactive-request-registry.test.ts`, `server-connection.test.ts` and `app.test.ts` (the reconnect reports the open question, and the server ends it). Graceful shutdown and machine suspension followed by the daemon's return already settle tasks on main (checked with an integration probe), so I added no test for them. Commands: - `pnpm exec turbo run typecheck lint --filter='...[origin/main]'` - `pnpm exec turbo run test --filter=@bb/server --filter=@bb/host-daemon --filter=@bb/host-daemon-contract --filter=@bb/db --filter=@bb/agent-runtime --filter=@bb/integration-tests` Fixes #6251 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED Co-authored-by: Claude Opus 5.5 <[email protected]>
The runtime settles the open background tasks of a bridge whose process exits, and of every thread when it shuts down, so a graceful daemon shutdown (a machine suspension) delivers them before the session closes. The Claude Code bridge settles its tasks when the SDK stream ends, and the server settles a host's open tasks once a machine suspension has shut its daemon down. Every server-side settle logs its reason.
Resolve the conflicts with get-bb#6870, get-bb#6923 and get-bb#6955: keep main's session-open flow, pass a reason to its settle call, report the runtime's open work from the new map, and name the reason for get-bb#6870's reconcile settle. Drop the server-side settle at machine suspension and its shutdown-ack tracking: a suspension shuts the daemon down gracefully, and the runtime now settles its open tasks before the daemon closes its session. Keep the stopped-item helper out of @bb/domain, and skip settlements for rewind staging threads, whose events the runtime already suppresses. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
fix/settle-orphaned-background-tasks
branch
from
November 4, 2026 18:45
68bba55 to
5a41856
Compare
…connects The reconnect open-work test asserted that a task stayed open after its bridge was killed until the same daemon reconnected. The runtime now settles it when the bridge exits, so the test checks that settlement and that the reconnect reconcile adds no second completion. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 5, 2026
…topped (#7134) ## Human comments ## What was wrong Two PRs merged on Nov 4 conflict: - #7004 (restart resume) finds the background work a restart stopped by listing tasks that are **still open** when the new daemon instance connects. - #6124, merged 51 minutes later, settles every open background task as `stopped` during a graceful daemon shutdown and flushes those events before the connection closes. The server also settles open tasks when it loses the daemon connection. So after a graceful restart, such as an update, no task is left open. Idle threads waiting on background commands are never nudged. On Nov 5 an update at 18:07:09 UTC stopped four idle threads' commands (CI watchers and a dev server). The runtime recorded each as `item/backgroundTask/completed` with `taskStatus: "stopped"` at 18:07:13, before the old session closed. The new daemon instance connected at 18:07:31, `planRestartResumes` found no open tasks, and no resume was queued. Turns cut mid-flight still resumed, because that path doesn't depend on open tasks. ## What changed - `packages/domain`: the background-task item gains an optional `ownerStopped: true`. It means bb settled the task because the process running it went away, not because the task, the agent or the user ended it. - `packages/agent-runtime`: the runtime's own settlements set the marker when they force a running task to `stopped`. These are the settlements on bridge exit and runtime shutdown (#6124). A task already in a settled status keeps its status and gets no marker. - `apps/server` (`background-task-reconciliation.ts`): - Host-level settles mark the tasks they force-stop. These are `host-daemon-restarted`, `host-connection-lost`, `host-removed` and `host-daemon-no-longer-runs-task`. - The settle for a thread the user stopped does not mark them. - `packages/db`: `listOwnerStoppedBackgroundTaskRowsForHost` returns marked completions on a host's live active or idle threads since a given time. It is index-driven: thread status, then `events_background_task_thread_type_item_sequence_idx`. On a production DB it takes about 11 ms. - `apps/server` (`restart-resume.ts`, `session-owner-side-effects.ts`): `planRestartResumes` combines two sources: - tasks still open; - tasks marked `ownerStopped` since the replaced daemon session opened and after the thread's last turn request. Each stop nudges the thread once, and the agent and the user stopping a task still never trigger a resume. The wording sent to the agent is unchanged. - Wire: the marker is a new field in daemon-to-server events, so `HOST_DAEMON_PROTOCOL_VERSION` goes from 262 to 263. The plugin SDK goes to 0.6.126 because the domain item schema ships in its bundled types. ## How you verified - New tests in `apps/server/test/threads/restart-resume.test.ts`: - An idle thread whose background command was settled with `ownerStopped` before the daemon reconnected is woken with the command named, and is not woken again after a second restart. This fails on main, where no open task remains and no resume is queued. - An idle thread whose command was stopped without the marker (by the agent or the user) is left alone. - Assertions added: - host settles mark `ownerStopped` (`background-task-reconciliation.test.ts`); - an idle-release thread stop does not mark it (`public-thread-stop-runtime.test.ts`); - runtime settlements on bridge exit and shutdown carry it (`agent-runtime` tests updated). - `turbo run test`: `@bb/agent-runtime` 309 passed. The `@bb/server` restart-resume, reconciliation and thread-stop suites have 66 passed. - `turbo run typecheck lint --filter='...[origin/main]'`: 155 tasks pass. - Not yet checked live, by restarting a daemon while a thread's background command runs. > 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.
Human comments
What was wrong
Only the process that owns a background task settles it. The provider CLI owns it and reports through the bridge, the runtime and the daemon. When that owner stopped, nothing settled the task:
The only fallback was the server's settle for a new daemon instance. It runs once the daemon comes back, so a task stayed "Running", with
activeBackgroundCommandCountat 1, for as long as the daemon stayed down. It also skipped any task stored before #5650, loggingSkipping dangling background task with unparsable item payload, because those items have noforegroundfield. See #6123.What changed
Whoever owns a task's state now settles the tasks it drops:
packages/agent-runtime:RuntimeBackgroundWorkStatekeeps each open task's latest item instead of only its id.item/backgroundTask/completed(interrupted/stopped, thread scope) for every task still open on that bridge's threads.runtimeManager.shutdownAll()and before the connection closes, so a graceful daemon shutdown (including a machine suspension) delivers these settlements.plugins/provider-claude-code: when the SDK stream ends (the CLI exited or was killed), the bridge settles the translator's open tasks. The existing error path still settles the turn.apps/server:convertLegacyStoredThreadEvent, like every other reader of stored events, so tasks stored before Show foreground Claude Code commands and subagents as foreground work #5650 settle too.packages/dbnow returns each open-task row's event type for that upgrade.Settled background tasks left open on the hostwith its reason:host-daemon-restarted,host-connection-lost,host-removedorhost-daemon-no-longer-runs-task(Sync open questions and background tasks when a daemon reconnects #6870's reconnect reconcile). The line is written only when something settled.Session openedlogs both instance ids, so the log shows whether the new-instance settle ran.docs/provider-bridge-protocol.md: rule 5 now says what the runtime settles on a bridge's behalf.This was rebased onto main after #6870, #6923 and #6955, and keeps main's session-open flow and reconnect reconcile. Compared with the earlier revision, it drops:
machine.shutdown-acktracking, since a suspension shuts the daemon down gracefully and the runtime now settles first;stoppedBackgroundTaskItemin@bb/domain, which is now local to the runtime.No wire change: the daemon emits an existing event type that the server already accepts, so
HOST_DAEMON_PROTOCOL_VERSIONis unchanged. Two cases are still not covered:sleep) keeps running. bb now shows the task as stopped, but it doesn't kill that process.How you verified
Live, on
pnpm start:worktreewith real Claude Code threads, I ran each case on main first and then on this branch:activeBackgroundCommandCount1, still open after another turnforegroundremoved from the row), then the daemon restartedSkipping dangling background task with unparsable item payloadforeground: falseTests:
packages/agent-runtime: "settles an idle thread's open background task when its provider process dies", "settles open background tasks when the runtime shuts down" and "does not settle a background task its provider already settled" inruntime.process-lifecycle.test.ts. There are also unit tests forsettleThreadandsettleAll.plugins/provider-claude-code: "settles a background command when the Claude SDK stream ends under it".apps/server: "settles a task stored before items carried the foreground flag".tests/integration/fake/recovery/reconnect-open-work.test.ts: Sync open questions and background tasks when a daemon reconnects #6870's test asserted that a task stayed open after its bridge was SIGKILLed until the same daemon reconnected, which is the gap this PR closes. It now asserts the task settles when the bridge dies and that the reconnect reconcile adds no second completion.tests/integration/fake/recovery/background-task-shutdown.test.ts: "records an idle thread's open background task as stopped when the daemon shuts down" (real server, real daemon, scripted-echo bridge).Commands:
turbo run typecheck linton the touched packages passes.turbo run testpasses:background-task-reconciliation.test.ts);background-task-shutdown.test.ts,reconnect-open-work.test.ts).Fixes #6123
🤖 Generated with Claude Code