Skip to content

Resume threads whose background commands a restart stopped, and tell the agent what was cut - #7004

Merged
ymichael merged 4 commits into
mainfrom
bb/resume-after-restart-wake-threads-waiting-on-kil-thr_fhftu3jeaa
Nov 4, 2026
Merged

ymichael merged 4 commits into
mainfrom
bb/resume-after-restart-wake-threads-waiting-on-kil-thr_fhftu3jeaa

Conversation

@ymichael

@ymichael ymichael commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

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). 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). 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), 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:
    - JOB
    - JOB

    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 Resume threads a restart cut off (resumeThreadsAfterRestart experiment) #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 -9s 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

AGENT GENERATED

@ymichael
ymichael force-pushed the bb/resume-after-restart-wake-threads-waiting-on-kil-thr_fhftu3jeaa branch 2 times, most recently from cee7974 to ef0d75f Compare November 4, 2026 18:40
ymichael and others added 3 commits November 4, 2026 11:33
…was cut

With resumeThreadsAfterRestart on, the restart resume now also wakes idle
threads whose background work (such as a background command the agent is
waiting on) the restart stopped, through the same retry row and attempt cap.
The resume message names the command a cut turn was running and any
background work the restart stopped, and says the restart, not the user,
interrupted or rejected it. The experiment is now on for early adopters.

Refs #6127

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The queue card, the collapsed queue list and bb thread queue list title a
retry row with the restart reason as a resume instead of "Retry failed
turn", since an idle thread woken after a restart has no failed turn. Retry
button and provider-retry rows keep their wording.

Refs #6127

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…per line

The message now opens with "bb restarted", says once that the restart, not
the user, cut the work off, and says "only if that is safe" once. Several
stopped background jobs are listed one per line in the order they started,
up to ten, followed by "and N more", and the wording follows how many there
are.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/resume-after-restart-wake-threads-waiting-on-kil-thr_fhftu3jeaa branch from df6e457 to 3cbe01f Compare November 4, 2026 19:34
The experiment stays off unless it is turned on in Settings → Experiments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 783a606 into main Nov 4, 2026
95 of 96 checks passed
@ymichael
ymichael deleted the bb/resume-after-restart-wake-threads-waiting-on-kil-thr_fhftu3jeaa branch November 4, 2026 19:57
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.

1 participant