Repository navigation
Resume threads a restart cut off (resumeThreadsAfterRestart experiment) - #6955
Merged
ymichael merged 4 commits intoNov 4, 2026
Merged
Conversation
When a machine's daemon comes back as a new instance (bb quit, crashed, updated, or the machine restarted), the server still interrupts the turns it was running with host-daemon-restarted. With the new continueThreadsAfterRestarts experiment (default off), it then queues a retry of each cut turn through retryFailedTurn with reason "bb restarted", scheduled 5 seconds out. The retry sends "Please continue." when the provider accepted the cut turn's input and the original input otherwise. Which threads resume: only active, unarchived threads cut by a new daemon instance. Manual stops (stopping threads finalize as stopped), threads with a pending question or approval, and archived or deleted threads stay as before. A turn is not resumed again once its retry chain reaches attempt 4, so a turn that keeps crashing bb resumes at most three times in a row. A resuming thread's interruption reads "Thread interrupted because bb restarted" with "bb will continue the thread in a few seconds.", and its parent is not told about the interruption; it hears when the child finishes. If queueing the resume fails, the parent gets the usual interrupted notice. Retries go first: a new retry row takes the front of the thread's queue, and automatic claims skip rows behind a live retry (not Not sent, not exhausted) until it sends or is dropped. A message sent before the resume goes out still supersedes it, per #6727. No daemon wire change and no plugin SDK change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-up. Retries going first is needed for resume: a message steered (the default send) while the daemon is down waits as host-offline, and the reconnect's host-connected wake sends it before the resume, which then drops the resume. Queued (thread-busy) rows already wait on an error thread, so they were never the problem. The earlier version refused automatic claims behind a live retry. That stranded exactly those host-offline rows: the reconnect wake is their only wake, so they stayed host-offline after the resume finished. Now the hold is a core wait in the dispatch checkpoint: a drained, non-retry row on a thread with a live retry is re-queued as thread-busy and sends when the retry's turn ends. Inline sends and Send now are not held, so they still overtake a pending retry. Both halves are behind continueThreadsAfterRestarts: retry rows are moved to the front of the queue only with it on, and the hold only applies with it on. With it off, retry order and holding are exactly as on main, and the two #6842 tests are back to main's version. The live-retry check is SQL built on #6727's notSupersededQueuedThreadMessage instead of a JSON parse. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Settings label: Resume interrupted threads after a restart. The interruption detail now reads: bb will resume the thread shortly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/implement-thread-resume-after-restart-thr_wdpu83w37w
branch
from
November 4, 2026 04:02
8634df7 to
c1767ac
Compare
ymichael
deleted the
bb/implement-thread-resume-after-restart-thr_wdpu83w37w
branch
November 4, 2026 04:11
This was referenced Nov 4, 2026
Merged
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
…AfterRestart) (#7007) ## Human comments ## What was wrong With `resumeThreadsAfterRestart` on (#6955), an update restart already resumes the threads it cuts. The source, npm and desktop updates stop the server and its local daemon, the daemon comes back as a new instance, and `handleHostSessionOpened` queues a "bb restarted" resume for each cut turn. Nothing was missing in that path. But the confirmation still said "N threads are running. Updating restarts bb and interrupts them." in three places: the Update now dialog (`runningThreadsWarning`), the CLI prompt and non-interactive error in `bb updates app apply`, and the server's `threads_running` error (`runningThreadsError`). So users were warned about losing work that bb now resumes. Follow-up to #6203 and #6955 in #6127. ## What changed - `runningThreadsError(count, threadsResume)` (server), `runningThreadsWarning(count, threadsResume)` (app) and the CLI warning take whether restarts resume threads. With the experiment on they read "N threads are running. Updating restarts bb, and they resume after the update." (singular: "1 thread is running. Updating restarts bb, and it resumes after the update."). - The launcher and desktop update services get a `threadsResumeAfterRestart` callback, which reads the experiment, for the `threads_running` message. Settings → Updates reads it from the system config's experiments. The CLI reads it from `system.config`, which it already fetched for `updateWhenIdle`. - Without a terminal, the CLI hint now ends "or --yes to update now" instead of "or --yes to interrupt them" when threads resume. The `--yes` help is now "Update without asking about running threads". - Docs: `docs/configuration.md` (`resumeThreadsAfterRestart`) and `bb guide machines`. - With the experiment off, every message is unchanged. No API shape, daemon wire or plugin SDK change. **What users see differently:** with "Resume interrupted threads after a restart" on, the Update now dialog, `bb updates app apply` and the API's 409 say running threads resume after the update instead of being interrupted. And they do resume (verified live below). ## How you verified Tests: - `apps/server/test/system/app-update.test.ts`: the `threads_running` message is checked with the experiment off ("interrupts them") and on ("it resumes after the update"). - `apps/app/.../app-update-presentation.test.ts`: both wordings, singular and plural. `UpdatesSettingsSection.test.tsx`: with the experiment on, the Update now dialog shows the resume wording. - `apps/cli/src/__tests__/command-output/updates.test.ts`: non-interactive `apply` with two running threads and the experiment on prints the resume wording and the "--yes to update now" hint. - `pnpm exec turbo run lint typecheck` for server, app, cli, templates and integration-tests passes, and so do the targeted test files above. Live: a real source-mode install (`pnpm start` from a clone of a local bare origin), with a marker commit pushed to the origin. A real Codex agent thread was running a 100 s foreground shell loop. Both experiments were on. - `bb updates app apply` without a terminal printed: `Error: 1 thread is running. Updating restarts bb, and it resumes after the update. Re-run with --when-idle to update once they finish, or --yes to update now.` - `POST /system/app-update/apply` returned: `{"code":"threads_running","message":"1 thread is running. Updating restarts bb, and it resumes after the update.","details":{"runningThreadCount":1}}` - With the experiment turned off, the CLI went back to "...interrupts it. ... or --yes to interrupt them." - In Settings → Updates, Update when idle ▾ → Update now opened "Update bb now? 1 thread is running. Updating restarts bb, and it resumes after the update." I clicked Update and restart. bb came back on the marker commit about 10 s later. The thread showed "Thread interrupted because bb restarted / bb will resume the thread shortly", resumed ("I'll check the running command and wait for it to finish."), and finished with A-FINISHED. Refs #6127 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 4, 2026
## Human comments ## What was wrong With `updateWhenIdle` on, bb restarts once no thread is running, but nothing stopped a new send from starting a turn in the gap between that decision and the process exiting. The launcher's restart decision ([app-update.ts](https://github.com/get-bb/bb/blob/b77a9c9c47/apps/server/src/services/system/app-update.ts#L162-L184)) counts running threads once and answers `restart`. The launcher then waits 1.5 s and shuts bb down, and the desktop path waits 1.5 s and installs. A message sent in that window starts a turn, and the restart cuts it straight away. The same applies to Update now. This is one of the follow-ups to #6203 and #6955 in #6127. ## What changed Behind `updateWhenIdle` (on for early adopters): - **Send hold.** `apps/server/src/services/system/app-update-send-hold.ts` arms a hold flag in `app_settings` (`appUpdateSendHold`). The launcher service arms it in `decideRestart` before it counts running threads. The desktop service arms it once the download finishes, also before counting. The flag is in the database, so a crash or restart can't leave it set in a later process. - **Dispatch checkpoint.** `dispatch-attempt.ts` queues every dispatch attempt as a new `app-update` wait while the flag is set. That covers sends, Send now, retries, new threads' first messages and child notices. The turn doesn't start. - **Release.** The flag clears in these cases: - The launcher decides `defer` or `cancel`. - The launcher rejects the `restart` request, or returns to idle afterwards. - The desktop defers, refuses, or fails to download or install. - The server boots, which covers every real restart, including an update that fails after the server stopped, where the old version comes back. Clearing the flag sends a new `app-update-released` queue wake. Like `host-connected`, it re-attempts each held row in order, and the normal checkpoint routes it. - **Ordering.** At boot the release runs before the startup sweep and before daemons reconnect. A held row on a thread the restart cut waits as `thread-busy` or `host-offline`. On reconnect, #6955 queues the resume at the front, and the held rows go out after the resumed turn, in order. - **Wording.** - Queue row: "Sending after bb restarts to update" with the Download icon. - Send now is disabled on held rows; the server refuses it with "bb is restarting to update". - `bb thread queue list`: "sending after bb restarts to update". - Domain: `app-update` added to `queuedMessageWaitingOnSchema`. - Docs: `docs/configuration.md` (`updateWhenIdle`) and `bb guide machines`. - No daemon wire change, so `HOST_DAEMON_PROTOCOL_VERSION` stays the same. No plugin SDK surface file changed. **What users see differently:** with the experiment on, a message sent in the second or two between "Restarting" and bb going down no longer starts a turn that gets cut. It shows in the queue as "Sending after bb restarts to update", and goes out once bb is back, after the thread's resume. If the update doesn't happen, it goes out at once. ## How you verified Tests (`apps/server`): - `test/threads/restart-resume.test.ts` → "holding sends while bb restarts to update" (real server harness): - A held send stays queued with no turn; release sends it. - Experiment off: the send isn't held. - A hold followed by a server boot and daemon restart: an idle thread's held message sends on reconnect. A cut thread runs resume, "First follow-up", "Second follow-up", in that order. The first and third fail with the checkpoint disabled (checked). - `test/system/app-update.test.ts`: the launcher service holds before it counts threads. It keeps the hold through `restart`, and releases it when the launcher returns to idle, on `cancel`, on `defer`, and when the `restart` request is rejected. - `test/system/desktop-app-update.test.ts`: hold on install; hold then release on a refuse failure or a defer. - `pnpm exec turbo run lint typecheck` for server, app, cli, db, domain, templates and integration-tests passes. Targeted tests for `app-update`, `desktop-app-update`, `restart-resume`, `public-system-app-update` and the app's `queued-message-wait` pass. Live: a real source-mode install (`pnpm start` from a clone of a local bare origin), with marker commits pushed to the origin and real Codex agent threads. A script polled `/system/app-update` and posted `/threads/:id/send` as soon as the activity read `restarting`. 1. **Update when idle, nothing running:** the send returned `{"delivery":"queued","waitingOn":{"kind":"app-update"}}` and the log showed "Holding new sends until bb restarts to update". bb came back on marker 1 about 10 s later, and the thread answered the held message. 2. **Update now (`--yes`) with a thread running a 100 s shell loop and `resumeThreadsAfterRestart` on:** sends to the running thread and an idle thread were both held. After the restart: - The running thread read "Thread interrupted because bb restarted / bb will resume the thread shortly". It resumed and answered A-FINISHED. - Only then did it run the held message. Its queue showed it as "waiting for the current turn to finish" during the resume. - The idle thread's held message was requested at 20:34:08, as soon as bb was back. 3. **Failed update:** I dirtied the checkout right after the restart decision, so the fast-forward failed ("Update to source checkout a51ccad183 failed: The working tree has uncommitted changes"). bb came back on the old commit and sent the held message. Refs #6127 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 4, 2026
…the agent what was cut (#7004) ## Human comments ## What was wrong #6955 resumes only threads that were mid-turn when the daemon came back as a new instance: `planRestartResumes` selects `status = "active"` threads ([restart-resume.ts#L37](https://github.com/get-bb/bb/blob/64c2f7099e1a678070dd24d730aa1120b2fb18e1/apps/server/src/services/threads/restart-resume.ts#L37)). An idle thread whose agent started a long background command (Claude Code `run_in_background`) and ended its turn to wait for it is not resumed. On reconnect the server only marks that background task `stopped` ([session-owner-side-effects.ts#L135](https://github.com/get-bb/bb/blob/64c2f7099e1a678070dd24d730aa1120b2fb18e1/apps/server/src/internal/session-owner-side-effects.ts#L135)). The process is gone, so the provider never sends the completion that would wake the agent. The thread stays idle indefinitely. That is the migration example in #6127. Mid-turn threads were resumed with a bare "Please continue." ([turn-retry.ts#L98](https://github.com/get-bb/bb/blob/64c2f7099e1a678070dd24d730aa1120b2fb18e1/apps/server/src/services/threads/turn-retry.ts#L98)), which didn't say which command or background job the restart cut off. Claude Code also records the cut tool call as rejected by the user. Reproduced live on main (`pnpm start:worktree`, experiment on, real Claude Code thread): the agent started `./migrate.sh` as a background command and went idle. I killed the daemon with `kill -9 <literal pid>`, and the daemon came back as a new process. 4 s later the server settled the task as stopped, with the migration stuck at batch 15/600. 3.5 minutes later the thread was still idle: no new events, no queued rows. ## What changed All of it is behind `resumeThreadsAfterRestart` and uses #6955's retry row, front-of-queue hold, and attempt cap. Nothing new is scheduled or parked. - **Wake idle threads** (`restart-resume.ts`): before interrupting and settling, `planRestartResumes` reads the host's open background tasks (`listOpenBackgroundTaskItemRowsForHost`; tasks with `skipTranscript` are left out). It plans a resume for every live (unarchived, undeleted) `idle` thread that has one, alongside the cut `active` turns. The resume is a retry row of the thread's latest turn with reason "bb restarted" (`retryTurnAfterRestart` in `turn-retry.ts`, which shares `dispatchRetry` with `retryFailedTurn`). Loop protection is the same retry-chain counter, so a thread that keeps losing its job to restarts is woken at most three times in a row. Idle threads without stopped background work are untouched. - **Name what was cut:** the agent-only continuation that replaced "Please continue." comes from a new `systemMessageRestartResume` template. It names the unfinished foreground command from the cut turn (`getUnfinishedCommandItemData`) and every background job the restart stopped, as `` `command` (description) ``. The command comes from the task's parent tool call (`listCommandItemDataByItemIds`). The message says once that the restart, not the user, cut the work off, and asks the agent to check before rerunning anything. The forms: | Case | Message after `[bb system]` | |---|---| | Idle, one job | bb restarted and may have stopped this background work: JOB. The user didn't stop it. Check whether it's still running and how far it got, then restart it only if that is safe. | | Idle, several jobs | bb restarted and may have stopped this background work:<br>- JOB<br>- JOB<br><br>The user didn't stop them. Check whether each is still running and how far it got, then restart each only if that is safe. | | Cut turn, running a command | bb restarted while you were running `CMD`. The restart cut it off, not the user, even if your history says the user rejected it. Check what it finished, then continue the task, rerunning it only if that is safe. | | Cut turn, no command | bb restarted while you were working. The restart cut off your turn, not the user, even if your history says the user rejected it. Check whether your last step finished, then continue the task without repeating work. | | Cut turn with jobs | Either cut-turn form, then: It also stopped this background work: JOB. Check how far it got, and restart it only if that is safe. (With several jobs: one per line, "Check how far each got, and restart only what is safe to restart.") | Several jobs are listed one per line in the order they started, up to ten, then "- and N more". To keep that order, `listOpenBackgroundTaskItemRowsForHost` now sorts by event sequence instead of item id. Its other caller, settling dangling tasks, doesn't depend on order. When the provider never accepted the cut turn's input, the original input is still re-sent as before. The Retry button and provider-retry still send "Please continue.". - **Resume title:** a retry row whose reason is the restart reason (`RESTART_RESUME_RETRY_REASON`, `@bb/domain`) is titled "Resume after bb restarted" instead of "Retry failed turn from …". Its wait line reads "resuming at … · attempt N". This applies in the app's queue card and collapsed queue list (`queued-message-wait.ts`) and in `bb thread queue list` (`organization.ts`). Retry-button and provider-retry rows keep their wording. - **Not on for early adopters:** the experiment stays off by default for everyone, including early adopters. It has to be turned on in Settings → Experiments. - **Docs:** `docs/configuration.md`, `bb guide thread-lifecycle`, `bb guide customization`, and the Settings → Experiments description. No daemon wire change, so no `HOST_DAEMON_PROTOCOL_VERSION` bump. No CLI, SDK, or plugin API change. ### What users see - **Idle thread waiting on a background command:** a few seconds after bb comes back, the queue briefly shows "Resume after bb restarted · resuming at … · attempt N". The agent then picks up on its own: it checks the job, restarts it if that is safe, and goes back to waiting. Before this change the thread sat idle and the job was dead. - **Restart resume rows** for mid-turn threads now carry the same "Resume after bb restarted" title. In #6955 they read "Retry failed turn from …". - **Mid-turn thread:** the agent's next reply reflects that it was told what was cut. For example: "The build only reached step 13 of 300 and nothing is still running…". The message itself is agent-only, as before. - All of this applies only with the experiment on. ## How you verified New tests in `apps/server/test/threads/restart-resume.test.ts`, on the real server harness with the daemon reopened as a new instance: | Test | Against main's source (test file only changed) | |---|---| | Idle thread with a stopped background command is woken with a message naming `./migrate.sh` (description); idle thread without background work and an archived one are not | fails: no resume row | | Experiment off: that idle thread stays idle | passes (no-change check) | | Cut turn's message names its foreground command and the stopped background job, with the "not the user" wording | fails: "Please continue." | App (`queued-message-wait.test.ts`) and CLI (`thread-organization.test.ts`) tests cover the resume title, and check that other retry rows keep theirs. The four existing restart tests now expect the new continuation instead of "Please continue.". - `pnpm exec turbo run test --filter=@bb/server -- test/threads/restart-resume.test.ts`: 14/14 pass, including a new test for twelve stopped jobs (ten bullets plus "and 2 more"). With `turn-failed-retry` and the background-task tests, 57/57 pass. `@bb/db` events and query-plan tests: 150/150. - `turbo run test --filter=@bb/templates`: 47 pass. - `turbo run typecheck` (server, app, cli, db, templates) and `lint` pass. - `turbo run test` on `@bb/app` (queued-message-wait, QueuedMessagesList: 86) and `@bb/cli` (thread-organization: 18) passes. - Full suites are left to CI. Live, `pnpm start:worktree` on this branch, real Claude Code threads, daemon killed with `kill -9` on literal PIDs: - **AFTER, idle:** the agent started `./migrate.sh` in the background and went idle. After the kill, the daemon came back and the resume went out 7 s later (attempt 2) with the message above. The agent read the task output and `ps`, found it stopped at batch 14 with nothing running, saw that the script resumes from `progress.txt`, and restarted it in the background (from batch 15). It then went idle waiting again. - **Second restart on the same thread:** the next daemon kill stopped that restarted job too. The thread was woken again (attempt 3) and resumed from batch 53. - **AFTER, mid-turn:** the agent started `./watch-logs.sh` in the background and then ran `./build.sh` in the foreground. After the kill, the error row read "Thread interrupted because bb restarted · bb will resume the thread shortly." The resume named `` `./build.sh` `` and `` `./watch-logs.sh` (Start log watcher in background) ``. The agent checked both, said "The build only reached step 13 of 300 and nothing is still running. Both scripts are safe to rerun…", and restarted both. It then finished: "The last line of `./build.sh` was: BUILD-DONE … The new build finished all 300 steps. `./watch-logs.sh` is running in the background again." - **Full server + daemon restart** (stop and relaunch `pnpm start:worktree` with the title change): both idle threads, each waiting on a background job, were woken. `bb thread queue list` showed both rows as "Resume after bb restarted · scheduled … in 5s". The app's queue card read "Resume after bb restarted · resuming at 8:48 PM · attempt 4". Re-verified after rebasing onto `4f973b851a` (#7012), `pnpm start:worktree` on `ef0d75fcf9`, fresh Claude Code threads, four `kill -9`s on literal daemon PIDs: | Check | Result | |---|---| | Idle thread waiting on `./migrate.sh` in the background | Woken each time (attempts 2, 3, 4). The agent found the job stopped (batches 260, 439, 479) and restarted it from `progress.txt`. | | Mid-turn `./build.sh` plus background `./watch-logs.sh` | The resume named both. The agent restarted both each time. | | Idle thread with no background work | No new events and no queue rows after any kill. | | Fourth restart in a row | Server logged "Not resuming a thread that restarts keep cutting off" (attempt 5) for both threads. The mid-turn thread ended in error with "Please retry the thread to continue." | | `bb thread retry` on that thread (Retry path) | Sent "Please continue.". The build finished with BUILD-DONE. | | App queue row, same live row, branch vs main bundle | "Resume after bb restarted · resuming at 10:37 AM · attempt 3" vs "Retry failed turn from 10:37 AM · bb restarted · retrying at 10:37 AM · attempt 3" | | `bb thread queue list`, branch vs main CLI | "Resume after bb restarted" vs the raw agent-only text "[bb system] bb restarted, or the machin…" | | A user's scheduled message | Same title and wait line in both builds | | Fresh idle thread on `ef0d75fcf9` | Woken; resumed the migration from batch 35 | Re-verified the shorter wording on `df6e457c26` with live Claude Code threads and a `kill -9` on the literal daemon PID: | Thread | Message received | What the agent did | |---|---|---| | Idle, waiting on `./migrate.sh` and `./watch-logs.sh` | Both jobs as bullets, in start order | Checked `progress.txt` (batch 5) and both scripts, then restarted both: "The restart stopped both scripts, and I've started them again." | | Mid-turn `./build.sh` with background `./watch-logs.sh` | "bb restarted while you were running `./build.sh`. … It also stopped this background work: `./watch-logs.sh` (…)" | Ran `cat build-progress.txt; tail -2 watch.log; pgrep -fl 'watch-logs\|build.sh'`, then restarted both | Refs #6127 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED --------- 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]>
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
When bb restarts (an update, quit, crash, or machine restart) while threads are running, the daemon comes back as a new instance and the server interrupts every turn it was running with
host-daemon-restarted(session-owner-side-effects.ts#L113-L127). That reason maps torun.failed(thread-lifecycle.ts#L400-L403), so the thread ends inerrorwith "Please retry the thread to continue." (thread-lifecycle.ts#L454-L456). Nothing ever retries it, so every running thread needs a manual Retry after each update. This is the first half of #6127 (resume after restart). Update-when-idle is the other half.What changed
Everything is behind a new experiment,
resumeThreadsAfterRestart(Settings → Experiments → "Resume interrupted threads after a restart") (default off, also off for early adopters).Resume = the existing retry row (
apps/server/src/services/threads/restart-resume.ts, wired intohandleHostSessionOpened). Nothing is recorded at shutdown: thehost-daemon-restartedinterruption on reconnect is the signal. After it, the server queues one retry per cut turn throughretryFailedTurnwith reason "bb restarted", scheduled 5 s out. It is the same row as the Retry button and provider-retry. It sends the agent-only "Please continue." if the provider accepted the cut turn's input, otherwise the original input.Which threads resume: only active, unarchived threads cut because the daemon came back as a new instance. Not resumed:
Loop protection: a turn is not resumed once its retry chain would pass attempt 4 (
retry_attempt), so a turn that keeps crashing bb resumes at most three times in a row and then stays in error.Wording: a resuming thread's interruption reads "Thread interrupted because bb restarted", with the detail "bb will resume the thread shortly."
Child threads: a resuming child doesn't send its parent an "interrupted" notice; the parent hears when the child finishes. If queueing the resume fails, the parent gets the usual interrupted notice.
Retries go first (experiment only):
moveQueuedThreadMessageToFrontInTransaction,queue-waits.ts);hasLiveQueuedRetry, SQL on Make queued retries safe: drop or hold them once overtaken #6727'snotSupersededQueuedThreadMessage), the dispatch checkpoint re-queues any other row the queue drains asthread-busy(dispatch-attempt.ts), so it goes out after the retry's turn ends;This is needed for messages steered while the daemon is down: they wait as
host-offline, and without the hold the reconnect sends them before the resume, which then drops the resume.Docs:
docs/configuration.md,bb guide thread-lifecycle,bb guide customization, Settings → Experiments.No daemon wire change, so no
HOST_DAEMON_PROTOCOL_VERSIONbump. Plugin SDK surface unchanged (check-plugin-sdk-version.mjs).What users see
error, with the red error icon in the sidebar and a red "Thread interrupted because bb restarted · error" timeline row. The queue shows "Retry failed turn from 1:00 PM · bb restarted · retrying at 1:00 PM · attempt 2". The retry is scheduled 5 s out, and the periodic queue sweep that sends every scheduled retry picks it up on its next pass. After that the agent carries on in the same thread; "Please continue." is agent-only and not shown.bb thread waitfollows the pending resume like any retry (live: started while the resume was pending, exited 0 at idle).--send-atmessage coming due, a row a plugin releases, ahost-offlinerow on reconnect, a child-finished notice. For a provider-retry row scheduled hours out for a subscription window, those rows now wait those hours instead of going out and overtaking it. With the experiment off, ordering and holding are unchanged from main.How you verified
The new tests are in
apps/server/test/threads/restart-resume.test.ts. They run on the real server harness and open the daemon session through/internal/session/openas a new instance. Run against main's source (with only the experiment key added), every one fails except the experiment-off ordering check, which is there to show nothing changes:queue-if-active) during the restart sends after the resume, in orderauto) during the restart sends after the resume, in orderI also checked that the steered test fails with an earlier version that held rows at claim time: the reconnect wake is the only one for
host-offlinerows, so they stayed stuck. That is why the hold lives in the dispatch checkpoint.Commands:
pnpm exec turbo run typecheck lint --filter='...[origin/main]'(155 tasks) passes.turbo run testfor@bb/db(651),@bb/domain,@bb/templates(47) passes.@bb/serverpasses in full on the first commit. On the final code, timing-sensitive suites (install-machine-scriptand similar) timed out on a host at load average ~100. They pass on rerun, exceptinstall-machine-script, which fails the same way on the base commit's source.Live, with
pnpm start:worktreeand real Claude Code threads running a 3-minute foreground shell loop, restarted withkillon literal PIDs:kill -9: queued "bb restarted" attempt 2, resumed ("The loop was cut off before it printed LOOP-DONE, so I'm running it again."), finished.bb thread waitfollowed it to idle.activein the DB after shutdown (nothing recorded), then it was cut on reconnect, resumed and finished.thread-busy. It ran in order: resume, FINISHED, then "STEERED-FOLLOW-UP".Refs #6127
🤖 Generated with Claude Code