fix(server): Claude model changes no longer kill running background agents #14726
main fromrefs/pull/14726/head·merged by juliusmarminge View on GitHubReported from a downstream V2 fork.
Problem#
Claude starts background agents (Agent with run_in_background) and background shells inside its CLI process, and those keep running after the root turn ends. If the user then switches to a model or option that changes the query identity (compileClaudeModelSelection(...).queryIdentity) or the query policy and sends a message, openQuery in ClaudeAdapterV2.ts closed the live process and opened a new one. Nothing checked for running background work first, so the process and its agents were killed and their results were lost. hasPendingBackgroundWork only kept the session from being released while idle.
Reproduction#
The new adapter test refuses a model change that would kill a running background subagent launches a background subagent, which stays running after the root result. It then starts a user turn on another model. On current V2 that turn opens a second process and closes the first one, and the test fails. With this change the turn is refused and the first process stays open.
Fix#
- Before
openQueryreplaces the live process of the same native thread, it checks whether that process still runs background work: the thread's background-task roster (shells and monitors), or a session subagent that is stillrunningand whose completion isn't already buffered. If it does, the turn start fails withClaudeBackgroundWorkBlocksQueryReplacementError: "Claude is still running background agents or commands, and this model or setting change would end them. Wait for them to finish, or press Stop, then send the message again." - Subagents that were already running when the live process opened don't count. Their process was closed (Stop, rollback, fork, or an allowed replacement) and will never report their end. Otherwise a stopped subagent would block every later change. A later
task_startedre-registers a resumed subagent, so it counts again. ProviderFailurepasses that text through to the failed-turn item, so the user sees why the send failed instead of the generic "could not start this turn".- Stop still allows the change. A settled Stop (#14636) closes the live query, so the next turn finds no process to protect. A turn started while that Stop is still waiting for the CLI to exit sees the query marked
stoppingand replaces it, as before. The new test covers Stop, and the existing Stop-race test still passes. - A live process that belongs to another native thread is still replaced without a check. Claude reports
supportsMultipleProviderThreadsPerSession: false, soproviderSessionIdFor(Orchestrator.ts) allocates one provider session per app thread, and two native threads only meet on one session when that app thread has already moved off the old one (rollback to thread start, a resume fallback that binds a fresh native session, a provider handoff back to Claude). Refusing there would block a thread for work it has abandoned, and the error text would be wrong. The existing sibling-replacement test still covers that path. - Continuation (wake) turns keep the live process regardless of selection. They prompt nothing and only drain output that process already produced, and replacing it would drop exactly that output.
Not losing the user's message#
The refusal goes through the same failed-start path as any other startTurn failure (RunExecutionService.startRootRun): the user's message stays in the thread on a failed run with a visible error, and queued messages for the same provider are held (provider_error, not validation_error) until the user resumes. The thread keeps the new selection, so resending after the agents finish (or after Stop) goes through.
Alternatives considered and not taken: defer the switch until the background work drains (queue the run behind the work, or run the turn on the old process and apply the selection later). Either one silently runs or delays the message on a model the user didn't pick, and needs new queue or orchestrator machinery. Applying the model in-process with setModel only covers the model, not effort, thinking, fast mode or policy changes.
Verification#
- New test
refuses a model change that would kill a running background subagentfails on current V2: with the guard removed, a second process opens. It passes with the fix. Its last step (Stop, switch, then switch back) fails if subagents from earlier processes are counted. - Updated two existing tests that replaced the process while a background shell was still on the roster.
resets Waiting roster and wake eligibility when the CLI process is replacednow empties the roster first, which the CLI does before the notification, so it still checks the reset. The old same-thread open-failure test is nowkeeps the process and its roster when a model change meets a running background shell. Failed opens with nothing running are still covered byclears buffered wake and continuation state when same-native-thread replacement open fails. - Inside
unshare -U --map-current-user -p -f --mount-proc:ClaudeAdapterV2.test.tsandProviderFailure.test.ts(138 passed). Claude cases ofClaudeReplayFixtures,OrchestratorReplayFixturesandOrchestratorReplayRecoveryintegration tests (36 passed). vp exec tsc --noEmit -p .in apps/server: exit 0.vp run knip:check: exit 0.vp linton the touched files: only the pre-existing unusedlayerwarning inClaudeAdapterV2.ts.- Not run: no live Claude run, no repo-wide suites.
Follow-up (not in this PR)#
Rollback to thread start and native fork close the source query through closeLiveQueryForNativeThread without this check, so they can still end running background agents. They are explicit history operations, and the user may expect that, so this PR leaves them alone.
Model: Claude Opus 5.5 (Claude Code)
🤖 Generated with Claude Code
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
juliusmarminge added labelsmacroscope-review
- apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 6682Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -6642,3 +6653,16 @@66426653 }),66436654 );664466556656+ // Work the live process still runs. A subagent whose completion is6657+ // already buffered is done: the buffer outlives the process.6658+ const liveProcessRunsBackgroundWork = Effect.fnUntraced(function* (nativeThreadId: string) {6659+ if (6660+ rosterForNativeThread(6661+ yield* Ref.get(pendingBackgroundTasksByNativeThread),6662+ nativeThreadId,6663+ ).size > 06664+ ) {6665+ return true;6666+ }6667+ const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];6668+ for (const [taskId, subagent] of yield* Ref.get(sessionSubagentsByTaskId)) {
🟡 Medium
Adapters/ClaudeAdapterV2.ts:6668After
interruptTurn(..., { requestRuntimeRestart: true })orcloseLiveQueryForNativeThreadkills the CLI, a later query can still be rejected indefinitely as having live background work.liveProcessRunsBackgroundWorkcounts everysessionSubagentsByTaskIdentry withtask.status === "running", but that session-wide registry is not cleared or terminalized when the process owning the agent is closed, so stale agents block model or policy replacement until a notification that can never arrive. Clear those entries when their native-thread process is stopped, or associate the check with the current process.🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 6668: After `interruptTurn(..., { requestRuntimeRestart: true })` or `closeLiveQueryForNativeThread` kills the CLI, a later query can still be rejected indefinitely as having live background work. `liveProcessRunsBackgroundWork` counts every `sessionSubagentsByTaskId` entry with `task.status === "running"`, but that session-wide registry is not cleared or terminalized when the process owning the agent is closed, so stale agents block model or policy replacement until a notification that can never arrive. Clear those entries when their native-thread process is stopped, or associate the check with the current process.Real, fixed in 5e1eb69cdd. The live query now records the subagents that were already running when its process opened, and the guard only counts subagents the current process started. A later task_started replaces the registry entry, so a resumed subagent counts again. The new test now Stops, switches the model, then switches back on the replacement process. Without this change the switch-back is refused.
Approvability#
Verdict: Approved at
69463d6Macroscope's review found this PR approvable — This is a focused Claude orchestration bug fix that prevents model or setting changes from terminating active background work, while allowing intentional Stop-driven replacement. The behavior is localized and covered by regression tests, with no schema, deployment, security, billing, default, or static-analysis changes.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
Navigate logical layers of code changes, visualize relationships, and explore their blast radius.
🧰 Additional context used
📚 Code guidelines (1)
docs/internals/effect-services.md — configuredNo actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Repository: pingdotgg/t3code/.coderabbit.yaml
Review profile: CHILL
Plan: Team
Run ID:
5da54cb4-4470-4dc2-bad1-c354b96117ee📥 Commits
Reviewing files that changed from the base of the PR and between e9298af6f5200fc7e63e0ad7213fe44a4151f36c and 69463d6d52a4fe8c43c13d1595b665598bd906f2.
📒 Files selected for processing (3)
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.tsapps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsapps/server/src/orchestration-v2/ProviderFailure.ts
Included review availability: This review used your included allowance. 6 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 10 reviews per hour.
📝 Walkthrough
Walkthrough#
The Claude adapter now tracks background work when deciding whether to replace a query for the same native thread. It blocks replacement while qualifying work remains active and reports a dedicated error. Tests cover the replacement guard and background-task roster behavior.
Changes#
Claude query replacement
Layer / File(s) Summary Track background work and guard replacement
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts,apps/server/src/orchestration-v2/ProviderFailure.tsThe adapter tracks running subagents and pending background tasks. It blocks replacement while background work remains active and maps the dedicated error to its message. Verify replacement and background-work behavior
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.tsTests cover model changes during running subagents, background-task roster updates, and pending work after a failed replacement open. Priority: ➖ Normal
Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Bug fix
Merge Risk: ⚪ Minimal · up to
69463Changing the model or an option while background work is running is now refused with a clear error, and Stop still allows the change. No merge-blocking risk was identified in the supplied changes.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
Check name Status Explanation Resolution Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold. ✅ Passed checks (4 passed)
Check name Status Explanation Title check ✅ Passed The title clearly and concisely describes the primary fix: preventing Claude model changes from terminating running background agents. Description check ✅ Passed The description is detailed and covers the problem, reproduction, fix, alternatives, user-message behavior, follow-up scope, and focused verification results. It does not include the template's explic… Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request. Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request. - Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
- Commit to this branch
- Create a new PR
🧪 Generate unit tests (beta)
- Commit to this branch
- Create a new PR
- Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Autopilot is currently an internal CodeRabbit preview.
Comment `@coderabbitai help` to get the list of available commands.juliusmarminge merged thisb4d3d51
juliusmarminge closed this
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
e9298af· PR result:69463d6· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.