Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): Claude model changes no longer kill running background agents #14726

Mergedjuliusmarmingemerged 3 commits intomain fromrefs/pull/14726/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Reported 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 openQuery replaces 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 still running and whose completion isn't already buffered. If it does, the turn start fails with ClaudeBackgroundWorkBlocksQueryReplacementError: "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_started re-registers a resumed subagent, so it counts again.
  • ProviderFailure passes 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 stopping and 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, so providerSessionIdFor (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 subagent fails 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 replaced now 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 now keeps the process and its roster when a model change meets a running background shell. Failed opens with nothing running are still covered by clears buffered wake and continuation state when same-native-thread replacement open fails.
  • Inside unshare -U --map-current-user -p -f --mount-proc: ClaudeAdapterV2.test.ts and ProviderFailure.test.ts (138 passed). Claude cases of ClaudeReplayFixtures, OrchestratorReplayFixtures and OrchestratorReplayRecovery integration tests (36 passed).
  • vp exec tsc --noEmit -p . in apps/server: exit 0. vp run knip:check: exit 0. vp lint on the touched files: only the pre-existing unused layer warning in ClaudeAdapterV2.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


Devin Review
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    2. juliusmarminge added labelsmacroscope-review

    3. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire4.9 KiB4.9 KiB0 B (0.0%)6.8 KiB✅
      CodexThread snapshot wire3.7 KiB3.7 KiB0 B (0.0%)4.9 KiB✅
      CodexLive turn WebSocket wire1.2 KiB1.2 KiB0 B (0.0%)2.0 KiB✅
      CodexLive turn WebSocket decoded20.4 KiB20.4 KiB0 B (0.0%)29.3 KiB✅
      CodexLive turn messages220 (0.0%)8✅
      ClaudeTotal thread wire4.9 KiB4.9 KiB0 B (0.0%)6.8 KiB✅
      ClaudeThread snapshot wire3.7 KiB3.7 KiB0 B (0.0%)4.9 KiB✅
      ClaudeLive turn WebSocket wire1.2 KiB1.2 KiB0 B (0.0%)2.0 KiB✅
      ClaudeLive turn WebSocket decoded20.8 KiB20.8 KiB0 B (0.0%)29.3 KiB✅
      ClaudeLive turn messages220 (0.0%)8✅

      Baseline: e9298af · PR result: 69463d6 · Source CI: success

      Scenario 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.

      • Codex decoded thread snapshot: 106.1 KiB
      • Claude decoded thread snapshot: 106.4 KiB

      Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.

    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Approved at 69463d6

      Macroscope'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).
    5. Review in Change Stack →

      Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

      🧰 Additional context used
      📚 Code guidelines (1)
      docs/internals/effect-services.md — configured

      No 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.ts
      • apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
      • apps/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.ts
      The 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.ts
      Tests 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 69463

      Changing 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 nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring 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 nameStatusExplanation
      Title check✅ PassedThe title clearly and concisely describes the primary fix: preventing Claude model changes from terminating running background agents.
      Description check✅ PassedThe 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✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck 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.
    6. juliusmarminge merged thisb4d3d51

    7. juliusmarminge closed this

Sign in to join this conversation.