Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): settle Claude background agents when their process exits #19464

MergedExotic209093(GitHub profile, opens in a new tab)merged 7 commits intomain fromrefs/pull/19464/headmerged by juliusmarminge View on GitHub

A plain Claude background agent can remain Running after its parent turn completes and the CLI process exits without a final task notification. Fixes #19440.

Use the exiting query's own last turn for cleanup, and apply the existing process-owned settlement path to plain background agents as well as workflows. Unexpected exit fails their tasks and open tool calls; Stop cancels the tasks. Buffered terminal outcomes retain precedence, and existing process/run ownership guards protect replacement work.

Based on @Exotic209093's fix in #19464, with their commits preserved and current main merged. The takeover retains the two minimal executable corrections after independently tracing their ownership and buffering behavior, simplifies comments, combines exit/Stop regression coverage, and simplifies the durable restart fixture.

Verification on 5c86d1c202, headless Linux:

  • Three PR-specific adapter cases before → two exit/Stop cases in one table in the existing file. Both fail against main because no terminal subagent update arrives, hitting the existing test deadline; both pass with the fix. No new test file.
  • 287 adapter tests and six recovery/restart integration cases pass (293 total). Existing coverage exercises buffered outcomes, replacement processes and stale cleanup. The restart fixture still verifies legacy orphan recovery under both continuation settings: cancelled task, no automatic continuation, cancellation note exactly once on the next user turn.
  • Server typecheck, targeted lint, formatting and git diff --check pass. Existing Effect suggestions and one unused-layer warning remain.
  • An unchanged foreground-subagent steering test intermittently timed out during intermediate full runs. Isolated rechecks and the final full 293-test run passed without code or timeout changes.

CI exposed another recovery fixture that used CLI exit to create a running orphan. Its setup now snapshots unfinished work before teardown; all original recovery, child-thread, conversation and full-transcript assertions are preserved. No test cases were added.

This is adapter and persisted replay evidence. A live Claude CLI exit, browser/client flow, macOS, Windows, Electron desktop, iOS and Android were not exercised. Screenshots do not demonstrate this server lifecycle change. No live T3 data was used.

Model and harness: implementation with Codex gpt-6.1-sol; separate tests with Codex gpt-6-astra; independent reviews with Claude claude-opus-5-5 and Codex gpt-6-sol, through T3 Code.

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

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

      Approvability

      Verdict: Approved at 5c86d1c

      Macroscope's review found this PR approvable — This is a localized Claude server bug fix that settles orphaned background agents and open calls on process exit or Stop while guarding replacement-process ownership. The accompanying changes are test-only coverage and restart-fixture setup, with no schema, deployment, default, or static-analysis changes.

      Notes:

      • No code objects were reviewed. Approvability was decided on eligibility alone.
      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration
      • Configuration used: Path: .coderabbit.config.ts
      • Review profile: CHILL
      • Plan: Advanced
      • Run ID: 7f16b528-7e2c-485e-94cb-5caa7200a436
      📥 Commits

      Reviewing files that changed from the base of the PR and between 6529453ec4f386720469b875d616678d87fafdd0 and 3c390d74c37744fb92ecaaebd01732d8621c072a.

      📒 Files selected for processing: 1
      • apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts

      Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

      📝 Walkthrough

      Query-exit cleanup now uses the closing query’s recorded last turn and handles its running background subagents. Tests cover cleanup after CLI exit and Stop, plus restart recovery from a snapshot taken while a background subagent is running.

      Changes: Background subagent exit cleanup

      Layer / File(s)Summary
      Query-exit cleanup
      apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
      Cleanup uses the closing query’s recorded last turn. It handles running background subagents without requiring a workflow, while retaining process and run ownership checks.
      Exit cleanup tests
      apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
      Tests verify that CLI exit fails a running subagent, Stop cancels a running subagent, and pending background work clears.
      Background subagent restart recovery
      apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts
      The test snapshots SQLite state while the provider query remains open and the background subagent is running. Recovery and post-restart replay use the snapshot database.

      Priority: ➖ Normal

      Estimated code review effort: 3 (Moderate) | ~20 minutes

      Change: Bug fix · Severity of issue fixed: Medium

      Suggested reviewers: juliusmarminge

      Merge Risk: ⚪ Minimal · up to 3c390

      No identified issue currently blocks merging the background-subagent cleanup change after normal checks.

      Security architecture risk: 🔵 Low · up to 3c390

      The change improves background-task cleanup and retains ownership checks intended to protect replacement work. No introduced security issue was established. Recovery testing covers a deliberately constructed legacy state, but does not establish every repeated-restart or real-process failure transition.

      Retained concerns No architecture-level concerns identified.

      Security review details

      Security Blast Radius

      • inferred — The demonstrated impact concerns provider-session task lifecycle, associated child tool calls and provider-facing recovery context. The inspected changes do not establish a new cross-service, credential or tool-authority path.

      Trust Boundaries and Controls

      • observed — Cleanup retains query ownership checks, excludes captured tasks from earlier processes, and rechecks running status and run identity atomically before committing a terminal registry update. These controls constrain stale cleanup from settling replacement work.

      Resilience and Maintainability Implications

      • observed — Stop marks the closing query as stopping and includes a timeout fallback that retires ownership before cleanup. Ordinary subagent cleanup now shares the existing cancellation and failure-containment path, including ending open child tool calls.
      Pre-merge checks: Passed 4
      Check nameStatusExplanation
      Linked Issues checkPassedThe change satisfies #19440. finalizeActiveTurnAfterQueryExit now uses the closing query's lastTurn and processes every running background subagent owned by that process, including plain agents. T…
      Out of Scope Changes checkPassedThe changes stay within #19440. The source change fixes Claude process-exit cleanup. The adapter tests verify the required lifecycle behavior. The restart fixture creates the legacy orphaned state and…
      Title checkPassedThe title is concise, specific, and accurately describes the main server-side fix for Claude background agents after process exit.
      Description checkPassedThe description covers the problem, implementation, scope, verification results, limitations, and agent details. It links the relevant issue and related pull request. It does not include an explicit m…
      Full details: Linked Issues check

      Explanation

      The change satisfies #19440. finalizeActiveTurnAfterQueryExit now uses the closing query's lastTurn and processes every running background subagent owned by that process, including plain agents. The change retains the process and run ownership guards. Buffered outcomes remain applied before finalization. Tests cover idle-exit failure, Stop cancellation, workflow failure, pending-work cleanup, and buffered outcomes.

      Full details: Out of Scope Changes check

      Explanation

      The changes stay within #19440. The source change fixes Claude process-exit cleanup. The adapter tests verify the required lifecycle behavior. The restart fixture creates the legacy orphaned state and verifies recovery behavior. These changes support the linked issue and do not introduce an unrelated product change.

      Full details: Description check

      Explanation

      The description covers the problem, implementation, scope, verification results, limitations, and agent details. It links the relevant issue and related pull request. It does not include an explicit maintainer approval comment as requested by the Scope and approval section, but the description is otherwise substantially complete.

      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
      Comment `@coderabbitai help` to get the list of available commands.
    4. I hit exactly this bug today. A main thread had launched several background Claude subagents, and one of them was running cargo test while the parent turn was idle. The machine ran out of memory, and the kernel killed ld inside the agent's systemd scope. Because of OOMPolicy=stop, systemd then stopped the whole scope, including the Claude CLI. The subagent's transcript ends with Exit code 137, but its card in T3 kept showing "Running" for hours and no error appeared.

      I traced it to the same subagent.task.workflow === undefined filter in finalizeActiveTurnAfterQueryExit and applied the same change locally. With it, the idle-exit test settles the subagent as failed, and without it the test fails with expected 'running' to equal 'failed'. Thanks for the fix. I'd love to see this merged.

    5. juliusmarminge assignedjuliusmarminge

    6. Taking over this one as maintainer for batch claude-06. I will merge current main, reduce the tests to the essential lifecycle regressions, rebuild the cleanup against current ownership handling, and verify buffered outcomes and stale-process isolation before pushing here. Your commits and author credit will be preserved.

    7. juliusmarminge added labelsmacroscope-review

    8. juliusmarminge merged thisa3d73c9

    9. juliusmarminge closed this

Sign in to join this conversation.