Skip to content

Sync open questions and background tasks when a daemon reconnects - #6870

Merged
ymichael merged 1 commit into
mainfrom
bb/reconnect-sync-for-questions-and-background-task-thr_rjeha5i4v9
Nov 2, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/reconnect-sync-for-questions-and-background-task-thr_rjeha5i4v9

Conversation

@ymichael

@ymichael ymichael commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

When a host daemon reconnects, session open reports only which threads are active (hostDaemonSessionOpenRequestSchema, activeThreads). 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). 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). The daemon's InteractiveRequestRegistry keeps waiting, and onSessionOpened 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):
  • 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

AGENT GENERATED

A reconnecting daemon reported only its active threads, so the server
and daemon could disagree about open work with nothing to reconcile it:
a question the server interrupted during a drop kept the provider
waiting forever (#6251), and a background task whose owner process died
stayed "Running" (#6123).

Session open now carries openThreadWork: each thread's open background
item ids and the provider questions the daemon still waits on, including
registrations in flight. The server settles 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 rest resolved, skipping threads
whose buffered events are still replaying. The response's
endedInteractiveRequests, and a live interactive-requests.end message,
end a provider's wait on a question the server already closed.

An answer whose delivery hit host_unavailable stays resolving and is
re-sent when the daemon's socket opens; a stale reply to a redelivery
completes the answer instead of interrupting it; bulk interrupts no
longer discard resolving provider answers; and a question registered
for a turn that already ended is rejected.

Bumps HOST_DAEMON_PROTOCOL_VERSION to 259.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit bb01f85 into main Nov 2, 2026
50 checks passed
@ymichael
ymichael deleted the bb/reconnect-sync-for-questions-and-background-task-thr_rjeha5i4v9 branch November 2, 2026 23:41
ymichael added a commit to alexandre-vl/bb that referenced this pull request Nov 4, 2026
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 added a commit that referenced this pull request Nov 4, 2026
…at owns them stops (#6124)

## 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`:
- The settle paths read stored items through
`convertLegacyStoredThreadEvent`, like every other reader of stored
events, so tasks stored before #5650 settle too. `packages/db` now
returns each open-task row's event type for that upgrade.
- Each settle logs `Settled background tasks left open on the host` with
its reason: `host-daemon-restarted`, `host-connection-lost`,
`host-removed` or `host-daemon-no-longer-runs-task` (#6870's reconnect
reconcile). The line is written only when something settled.
- `Session opened` logs 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:
- 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`: #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](https://claude.com/claude-code)

---------

Co-authored-by: Michael Yong <[email protected]>
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.

Provider stays blocked on a question the server interrupted after a same-instance daemon reconnect

1 participant