Skip to content

Re-send a stop once the daemon's socket opens after a slow reconnect - #6923

Merged
ymichael merged 1 commit into
mainfrom
bb/retry-stop-command-on-daemon-reconnect-thr_i4iwvmff3f
Nov 3, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/retry-stop-command-on-daemon-reconnect-thr_i4iwvmff3f

Conversation

@ymichael

@ymichael ymichael commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

When a daemon reconnects, reconcileDaemonReportedThreads re-sends a stop for any thread the daemon still runs but the user stopped while it was away. That call waits only 5 s for the daemon's socket (waitForReconnectingDaemon in apps/server/src/services/hosts/online-rpc.ts), then fails with host_unavailable. settleThreadStopCommandResult settles the thread to idle on that failure, and nothing re-sends the stop once the socket opens. The stopped turn keeps running on the machine behind an idle thread. This is item 1 of the investigation of #6552's stop fixes against main.

What changed

  • settleThreadStopCommandResult (apps/server/src/services/threads/thread-lifecycle.ts) now records an interrupt stop that failed with host_unavailable while the host's latest session is still open. It saves the thread, host and the time the stop was sent. Any other outcome for that thread clears the record. Both the reconnect stop and the Stop button settle here, so both are covered.
  • handleDaemonSocketOpened calls the new resendStopsAwaitingDaemon, next to the existing redeliverAnswersAwaitingDaemon. It re-sends that host's recorded stops through dispatchThreadStopCommand, behind the same in-flight guard.
  • A re-sent stop can't interrupt a newer run. It is skipped unless the thread is still idle or errored, and skipped if a client/turn/requested event was recorded since the original stop went out (new hasStoredTurnRequestEventSince in @bb/db). That window starts when the stop was sent, not when it failed, so a run started during the 5 s wait is also protected.
  • Stops that fail while no session is open aren't recorded. The next session open already re-stops those threads from the daemon's list of active threads.
  • Server only. No daemon wire change and no HOST_DAEMON_PROTOCOL_VERSION bump.

How you verified

Two regression tests were added to apps/server/test/internal/background-task-reconciliation.test.ts, next to the existing reconnect-stop tests:

Test Before fix After fix
Re-sends a reconnect stop that missed the daemon once its socket opens fails (no stop sent) passes
Does not re-send a missed stop once a newer run was requested passes (main never re-sends) passes; fails if the newer-run check is removed
  • pnpm exec turbo run typecheck lint --filter='...[origin/main]' passes.
  • pnpm exec turbo run test --filter=@bb/server: everything passes except some tests in test/app/install-machine-script.test.ts. Those tests spawn install processes, and a different set of them failed on each run. This change doesn't touch them.

AGENT GENERATED

🤖 Generated with Claude Code

When a daemon reconnects, the server re-sends a stop for any thread the
daemon still runs but the user stopped while it was away. That call
waits only 5 s for the daemon's socket. If the socket opens later, the
stop fails with host_unavailable, the thread settles to idle, and
nothing retries it, so the stopped turn keeps running behind an idle
thread.

A stop that fails with host_unavailable while the host's session is
still open is now remembered and re-sent when the socket opens, like
answers that missed the daemon. The re-send is skipped if the thread is
no longer idle or errored, or if a run was requested after the original
stop went out, so it cannot interrupt newer work.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 7130d96 into main Nov 3, 2026
33 checks passed
@ymichael
ymichael deleted the bb/retry-stop-command-on-daemon-reconnect-thr_i4iwvmff3f branch November 3, 2026 20: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.

1 participant