Skip to content

Settle background tasks when the bridge, Claude Code or the daemon that owns them stops - #6124

Merged
ymichael merged 3 commits into
get-bb:mainfrom
alexandre-vl:fix/settle-orphaned-background-tasks
Nov 4, 2026
Merged

ymichael merged 3 commits into
get-bb:mainfrom
alexandre-vl:fix/settle-orphaned-background-tasks

Conversation

@alexandre-vl

@alexandre-vl alexandre-vl commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • When a bridge process exited, the runtime dropped its threads' open work without a word.
  • Runtime shutdown cleared that state before it killed the provider processes.
  • When the Claude SDK stream ended, the bridge left the translator's tasks open.

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 activeBackgroundCommandCount at 1, for as long as the daemon stayed down. It also skipped any task stored before #5650, logging Skipping dangling background task with unparsable item payload, because those items have no foreground field. See #6123.

What changed

Whoever owns a task's state now settles the tasks it drops:

  • packages/agent-runtime:
    • RuntimeBackgroundWorkState keeps each open task's latest item instead of only its id.
    • When a bridge process exits, the runtime emits item/backgroundTask/completed (interrupted / stopped, thread scope) for every task still open on that bridge's threads.
    • The runtime does the same on shutdown, after the provider processes stop. The daemon flushes its event sink after runtimeManager.shutdownAll() and before the connection closes, so a graceful daemon shutdown (including a machine suspension) delivers these settlements.
    • It skips threads whose events are suppressed (rewind staging) and tasks the provider already settled.
  • 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:
  • 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:

  • the server-side settle at machine suspension and its machine.shutdown-ack tracking, since a suspension shuts the daemon down gracefully and the runtime now settles first;
  • the shared stoppedBackgroundTaskItem in @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_VERSION is unchanged. Two cases are still not covered:

  • A daemon that is SIGKILLed or loses power relies on the server's settle for a new daemon instance.
  • When Claude Code dies, the shell command it started (for example sleep) keeps running. bb now shows the task as stopped, but it doesn't kill that process.

How you verified

Live, on pnpm start:worktree with real Claude Code threads, I ran each case on main first and then on this branch:

Case main this branch
SIGKILL the provider bridge (literal PID) task stays open, activeBackgroundCommandCount 1, still open after another turn all three of the bridge's threads settled in the same second
SIGKILL the Claude Code CLI (SDK stream ends) task stays open, count 1 settled in the same second
Daemon SIGTERM while its launcher is SIGSTOPped, so it stays down like a suspended machine still "Running" after 70 s; settles only when a new daemon instance connects settled in the same second the session closed; no duplicate after the daemon came back
Task stored before #5650 (foreground removed from the row), then the daemon restarted Skipping dangling background task with unparsable item payload settled with foreground: false

Tests:

  • 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" in runtime.process-lifecycle.test.ts. There are also unit tests for settleThread and settleAll.
  • 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 lint on the touched packages passes.
  • Targeted turbo run test passes:
    • agent-runtime: 44 tests (both runtime files);
    • provider-claude-code: 107 (bridge tests);
    • apps/server: 22 (background-task-reconciliation.test.ts);
    • integration: 3 (background-task-shutdown.test.ts, reconnect-open-work.test.ts).

Fixes #6123

AGENT GENERATED

🤖 Generated with Claude Code

alexandre-vl added a commit to alexandre-vl/bb that referenced this pull request Oct 22, 2026
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]>
alexandre-vl and others added 2 commits November 3, 2026 20:36
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
ymichael force-pushed the fix/settle-orphaned-background-tasks branch from 68bba55 to 5a41856 Compare November 4, 2026 18:45
@ymichael ymichael changed the title Settle background tasks when the process that owns them stops Settle background tasks when the bridge, Claude Code or the daemon that owns them stops Nov 4, 2026
…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
ymichael merged commit 5c5d3e5 into get-bb:main Nov 4, 2026
50 checks passed
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]>
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.

An idle thread's background command stays "Running" after its machine is suspended: nothing settles a task whose owner process stops

2 participants