Skip to content
Source
Sign inSign up
pingdotgg/t3code

[orchestrator-v2] fix(orchestrator): Restore Claude session continuity for resume, wake, and idle release #3860

Mergedmwolson(GitHub profile, opens in a new tab)merged 3 commits intot3code/codex-turn-mapping fromrefs/pull/3860/headmerged by juliusmarminge View on GitHub

Summary

Mirrors the shape of the Grok v2 PR (#3578): one shared provider-continuation plumbing commit (identical to the one carried by #3578) plus one Claude specialty commit.

Four related failure modes around Claude provider session lifetime and background work are fixed:

  • Idle-released sessions failed to reopen (Session ID ... is already in use); the adapter now resumes the persisted native session instead of recreating it.
  • Background tasks (run_in_background Bash) vanished when they settled; the CLI's post-settle wake turn is now ingested as a first-class continuation run, and idle release stays pinned while background work is pending.
  • Background subagents (Agent tool with run_in_background) lost their completion when it arrived after the root turn settled, and resuming a completed subagent via SendMessage was invisible: the row kept its stale first result forever. Both lifecycles now project correctly across turns and runs.
  • Releasing an idle session could deadlock silently on the SDK's suspended message read, orphaning the CLI child; the release path now unblocks the pending read and persists released events even if a finalizer wedges.

Branch shape

  • Base: t3code/codex-turn-mapping
  • Commit 1: feat(orchestrator): Add shared provider continuation and background item plumbing (C0, the same commit object carried by #3578; not a standalone PR). Besides the continuation queue/worker/idle pin, it now carries a shared RunExecutionService fix: run event ingestion stays open after root settlement until background-capable turn items (background commands, monitors, subagent rows) terminalize, so their trailing turn_item.updated(completed) is no longer dropped and the thread's item spinner completes instead of sticking on running.
  • Commit 2: fix(orchestrator): Restore Claude session continuity for resume, wake, and idle release (this PR's reviewable delta)

Problem and Fix

Problem and Why it HappenedFix
After ProviderSessionManager idle-releases a provider session (30 min default), the adapter's in-memory openedNativeThreads set is lost. The next turn's openQuery opens the native thread with {sessionId} (create semantics, --session-id) instead of {resume}, and the Claude CLI fails fast because the session id already exists on disk.In openQuery, treat a persisted provider turn as proof the native session exists: providerTurnOrdinal > 1 forces {resume} alongside the existing in-memory and rollback signals.
When a background task settles, the Claude CLI re-invokes itself and streams a whole new turn (task notification, assistant response, result) over the still-open SDK query. ClaudeAdapterV2.handleSdkMessage early-returned when activeTurn was null, so every message of the wake turn was dropped.Null-activeTurn wake evidence now buffers per native thread. A pending-task notification or result offers one continuation request (deduped per wake) to a new ProviderContinuationRequests queue; the ProviderContinuationService worker dispatches an internal message.dispatch (createdBy: "agent", creationSource: "provider", queue_after_active) so the wake flows through the normal run pipeline. The continuation turn sends no prompt to the CLI and drains the buffered wake messages into itself.
A background subagent's task_notification arriving after settle hit the same null-activeTurn drop, and even when replayed, the continuation turn's fresh per-turn maps could not find the subagent row created by the earlier turn.Subagent notifications for known running subagents count as wake evidence, and a session-scoped subagent registry (sessionSubagentsByTaskId) lets a wake-replay turn hydrate and terminalize a subagent created by an earlier, settled turn.
SendMessage to a completed subagent resumes it: the CLI re-emits task_started with the same task id but the SendMessage call's tool_use_id, then a second task_notification carries the new answer. Subagent status was monotone, so the re-open was ignored; the SendMessage tool_result (a delivery ACK) could also terminalize the re-opened row with ACK JSON as its "result".task_started for a known task id is an authoritative CLI lifecycle event and may re-open a terminal row (stale result and progress cleared); a late task_progress still cannot. Only a tool_result whose id is absent from toolCalls may terminalize a subagent, which excludes SendMessage ACKs (Agent launches never enter toolCalls; they project as subagent rows). Post-settle resume frames pre-open the session registry entry so idle stays pinned and the eventual notification counts as wake evidence.
Even after the re-open projected correctly at the adapter boundary, the events could vanish: RunExecutionService.routeProviderEvent only persists parent-thread subagent events whose runId matches the currently executing run, and a run's ingestion fiber only lingers past settle while it has active child subagents. A subagent that completed in-turn and was resumed later emitted events attributed to the launch run, whose fiber was already gone; they were silently dropped and the row froze on the stale result.A reopen re-attributes the subagent's runId to the run whose turn processes the resume. The continuation run's event filter then accepts the events, and its child-lifecycle tracking keeps its ingestion fiber alive until the resumed task completes. Parenting (parentNodeId/rootNodeId) stays with the launch run's root node.
The 30 minute idle release killed the CLI child (and any pending background task) before the wake could arrive.The adapter exposes an optional hasPendingBackgroundWork runtime capability; releaseIfStillIdle defers the idle_timeout release while it reports true, re-arming the timer, with cumulative deferral capped by maxIdlePinMs (default 4h).
Session scope finalizers run LIFO, so the message-pump fiber is interrupted before the closeSession finalizer. Interruption calls return() on the SDK's raw sdkMessages generator, which queues behind the in-flight idle read forever; the scope close never completes and query.close is never reached, orphaning the CLI child and leaving the projection stuck on "ready".claudeQueryMessages hands the stream an iterable whose [Symbol.asyncIterator]() returns the Query itself. The SDK's Query.return() runs cleanup() first, closing the transport and terminating the CLI child, so interruption completes and the remaining finalizers run.
The replay testkit typechecked only against claude-agent-sdk 0.3.170; 0.3.205 requires requestId on canUseTool options and allows a null PermissionResult.Raise the @anthropic-ai/claude-agent-sdk floor to ^0.3.205 (lockfile resolves 0.3.205), derive requestId from toolUseID for replayed permission requests, and fail the replay if canUseTool returns null. The native-stack patch file also gains its diff --git header so current aube can parse it.

Defensive Fixes

Problem and Why it HappenedFix
Any wedged session-scope finalizer parks releaseEntry forever with no released events and no log line.releaseEntry forks the scope close and joins with a 30s timeout. On timeout it logs provider-session-scope-close-timeout, attaches a detached observer for late completion or failure, and persists the released events regardless.
hasPendingBackgroundWork yields to the adapter between the idle check and the release, so a release could race a session that turned busy during the check.releaseEntry takes onlyIfIdleGeneration and revalidates busyCount/idleGeneration inside its atomic entry removal.
A live-stream fiber and a continuation drain can update the same subagent registry entry concurrently, so a resume re-open could clobber a newer terminal result installed between its lookup and its write.The session registry update is a CAS: a re-open only replaces the exact terminal generation its lookup resolved; otherwise the newer entry wins.

Validation

  • vp check: pass
  • pnpm install --frozen-lockfile: pass after the SDK bump to 0.3.205
  • vp run typecheck: pass (full monorepo)
  • vp test .../ClaudeAdapterV2.test.ts: 24/24, including background wake turns (buffer + single deduped continuation request; drain into a continuation turn with no CLI prompt; racing user turn leaving the buffer for the queued continuation; null-summary notification clearing the pending-task registry; spurious continuation settling immediately) and the subagent lifecycle (post-settle completion via the session registry; in-turn SendMessage resume with re-open, ACK guard, and run re-attribution; post-settle resume whose frames race past settle; late task_progress unable to re-open a terminal row)
  • vp test .../ProviderSessionManager.test.ts: 18/18 (idle release deferred while background work is pending, pinned session released once maxIdlePinMs expires, turn starting during the pending-work check never losing the session)
  • ClaudeReplayFixtures.integration.test.ts and OrchestratorReplayFixtures.integration.test.ts (claude fixtures): pass
  • Live scenario packs against a headless serve of this branch: claude-smoke (in-turn background bash, background subagent, monitor) and claude-continuation (post-settle bash wake, post-settle subagent completion, SendMessage resume of a completed subagent), all passing, covering both resume shapes (in-turn nudge with lingering launch-run ingestion, and CLI autonomous-turn nudge requiring the run re-attribution)
  • Manual AppImage verification of all six scenarios, including thread-data audits of run, subagent, and message projections in sqlite
  • Independently reviewed pre-fix by grok (composer-2.5) and codex (gpt-5.5); all Medium findings addressed. The subagent resume and re-attribution deltas were reviewed by grok-4.5 across four rounds; final verdict approve, no High or Medium findings

Known limitations

  • Background tasks do not survive a server restart: the CLI child dies with the server and the wake is lost (out of scope).
  • Wake traffic arriving while a normal turn is active ingests into that active turn, exactly as today; this PR only changes the previously-dropped null-activeTurn path.
  • If the pin cap expires with a task still running, the session releases as today and that wake is lost (same outcome as before, minus up to 4 hours).
  • A continuation dropped by the worker (archived thread, transient dispatch failure) is logged but not retried; the wake buffer then sits until a later turn drains it or the pin cap releases the session.
  • The 30s scope-close timeout is a diagnosable backstop, not a substitute for cleanup; provider-session-scope-close-timeout is the operational signal.
  • After a resume re-attributes a subagent to the resuming run, the UI's optional attempt-metadata link for that row can resolve to none (its runId moves while its parent node stays with the launch run). The timeline entry itself still renders.

Note

Restore Claude session continuity across idle release, resume, and wake turns

  • Adds session resume logic in ClaudeAdapterV2 so that after an idle release or process restart, the SDK query reopens with resume instead of a new sessionId when a prior provider turn exists.
  • Introduces a ProviderContinuationRequests queue and ProviderContinuationService worker that drains background wake-turn events and dispatches internal message.dispatch commands to re-engage the session.
  • Buffers SDK messages that arrive outside an active turn; continuation runs attach to that buffered output instead of sending a new user prompt, settling immediately when the buffer is empty.
  • Adds hasPendingBackgroundWork to the session runtime interface so ProviderSessionManager defers idle release while background tasks or subagent work is still in flight, bounded by a configurable maxIdlePinMs cap (default 4 hours).
  • Fixes terminalStatusFromResult so SDK results with is_error: true resolve to failed instead of completed, and adds two new replay fixtures (claude_idle_resume, claude_result_is_error) to cover these scenarios end-to-end.
Macroscope summarized 05b5fb2.

Note

High Risk Changes core orchestration paths (session idle/release, continuation runs, Claude SDK streaming, subagent attribution) where regressions can drop wake output, strand sessions, or mis-report run status; scope is large but heavily tested.

Overview Claude orchestration v2 gains end-to-end handling for sessions that idle out, background CLI work, and post-settle SDK traffic, plus shared plumbing so those wake turns become real runs.

A new ProviderContinuationRequests queue and ProviderContinuationService worker let the Claude adapter offer one continuation per wake; the worker dispatches an internal agent/provider message.dispatch (queue_after_active) so buffered SDK messages are ingested without re-prompting the CLI. ClaudeAdapterV2 buffers messages when no turn is active, drains them on continuation turns, resumes native sessions when providerTurnOrdinal > 1 (fixing post-idle sessionId vs resume), tracks background tasks and a session-scoped subagent registry (re-open on task_started, SendMessage ACK guards, run re-attribution on resume), treats result with is_error as failed turns, and exposes hasPendingBackgroundWork so ProviderSessionManager can defer idle release (capped by maxIdlePinMs, default 4h) and time-box wedged scope closes (30s) while still persisting released events. claudeQueryMessages iterates the SDK Query object so interruption runs cleanup and avoids stream deadlocks.

RunExecutionService keeps ingesting after a completed root terminal until background-capable turn items (commands, dynamic tools, subagent rows) finish, so late turn_item.updated events are not dropped.

@anthropic-ai/claude-agent-sdk is bumped to ^0.3.205; replay testkit adapts requestId / null permission handling. New replay fixtures cover idle resume and is_error results; fixture inputs can advance_clock past session idle timeout.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 05b5fb20a4fae14866a4a402228ff2ec7320b032. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro

      Run ID: 70c22255-c94b-4858-baa8-5df55643f46c

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. @@ -0,0 +22,21 @@
      22+ Effect.gen(function* () {
      23+ const ids = yield* IdAllocatorV2;
      24+ const requests = yield* ProviderContinuationRequests;
      25+ const threads = yield* ThreadManagementService;
      26+
      27+ const dispatchContinuation = Effect.fn("ProviderContinuationService.dispatchContinuation")(
      28+ function* (request: ProviderContinuationRequest) {
      29+ const projection = yield* threads.getThreadProjection(request.threadId);
      30+ if (projection.thread.archivedAt !== null) {
      31+ yield* Effect.logInfo("orchestration-v2.provider-continuation.thread-archived", {
      32+ threadId: request.threadId,
      33+ providerThreadId: request.providerThreadId,
      34+ });
      35+ return;
      36+ }
      37+ const messageId = yield* ids.allocate.message({
      38+ threadId: request.threadId,
      39+ ordinal: projection.messages.length + 1,
      40+ });
      41+ const commandId = CommandId.make(`provider-continuation:${messageId}`);
      42+ yield* threads.dispatch({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderContinuationService.ts:42

      When a provider continuation request is dispatched, the worker sends a message.dispatch using only request.threadId and ignores request.providerThreadId. The orchestrator resolves the target provider thread from the thread's current activeProviderThreadId, so if the active provider thread changed between when the wake was queued and when it is drained, the continuation run starts against the wrong provider thread. The buffered Claude wake messages pinned to the original native thread are never consumed by that run, so the background-task wake is silently lost until some later turn happens to target the original thread. Consider including request.providerThreadId (or the original native thread identifier) in the dispatch so the continuation is routed to the correct provider thread regardless of any subsequent thread switch.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProviderContinuationService.ts around line 42:
      
      When a provider continuation request is dispatched, the worker sends a `message.dispatch` using only `request.threadId` and ignores `request.providerThreadId`. The orchestrator resolves the target provider thread from the thread's *current* `activeProviderThreadId`, so if the active provider thread changed between when the wake was queued and when it is drained, the continuation run starts against the wrong provider thread. The buffered Claude wake messages pinned to the original native thread are never consumed by that run, so the background-task wake is silently lost until some later turn happens to target the original thread. Consider including `request.providerThreadId` (or the original native thread identifier) in the dispatch so the continuation is routed to the correct provider thread regardless of any subsequent thread switch.
      @@ -3643,2 +3861,2 @@
      36433861 const idAllocator = yield* IdAllocatorV2;
      36443862 const queryRunner = yield* ClaudeAgentSdkQueryRunner;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/ClaudeAdapterV2.ts:3862

      makeDefaultClaudeAdapterV2 yields ProviderContinuationRequests and passes it into the adapter, but the exported layer omits ProviderContinuationRequests from its requirement type. Since ProviderContinuationRequests is a Context.Reference, composing ClaudeAdapterV2.layer with ProviderContinuationRequests.layer resolves the default { offer: () => Effect.void } inside the adapter, silently dropping every continuation request. Claude background-task wake turns are never enqueued, breaking session continuity. Add ProviderContinuationRequests to the Layer.Layer requirement type so callers must supply (or inherit) the live queue.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 3862:
      
      `makeDefaultClaudeAdapterV2` yields `ProviderContinuationRequests` and passes it into the adapter, but the exported `layer` omits `ProviderContinuationRequests` from its requirement type. Since `ProviderContinuationRequests` is a `Context.Reference`, composing `ClaudeAdapterV2.layer` with `ProviderContinuationRequests.layer` resolves the default `{ offer: () => Effect.void }` inside the adapter, silently dropping every continuation request. Claude background-task wake turns are never enqueued, breaking session continuity. Add `ProviderContinuationRequests` to the `Layer.Layer` requirement type so callers must supply (or inherit) the live queue.
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      2 blocking correctness issues found. This PR introduces significant new infrastructure for Claude session continuity including background task wake handling, continuation request services, and complex session state management. Two unresolved review comments identify potential correctness issues with provider thread routing and layer composition that warrant human attention.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    5. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c489f02704f5529dd75973d331bbeb3b17439e2c. Configure [here](https://www.cursor.com/dashboard/bugbot).
    6. Pushed 05b5fb20a4 onto this branch (coordinated with Julius): the Claude-specific fixes from #3677, rebased onto this PR's architecture so there's a single Claude-continuity PR.

      • is_error on result messages: terminalStatusFromResult treated every subtype: "success" as completed, so 401/529 API failures projected as successful runs (4 real occurrences in the session audit). Now failed, with the API error text + api_error_<status> code on the failure. Fixture claude_result_is_error replays the real 401 chunks.
      • Resume hardening on top of your providerTurnOrdinal signal: the openedNativeThreads insert now happens only after queryRunner.open succeeds — previously a failed create pre-inserted the id, leaving the runtime believing a never-created session exists. Also claude_idle_resume: a replay fixture that drives the real 30-min idle reaper via a new advance_clock fixture step and asserts the reopen uses resume — a regression test for exactly the "Session ID … is already in use" bug this PR fixes.

      vp run --filter t3 typecheck clean, contract + integration replay suites and ClaudeAdapterV2.test.ts all green (97 tests) on top of your commits. Note: C0 (ea57e97d58) was fast-forwarded onto t3code/codex-turn-mapping per plan, so this PR and #3578 now show only their specialty commits. #3677 is being rebased to keep only the fixes not covered here (error-cause chains, cursor detail, native-log failure frames, reconcile visibility, codex log routing, ACP delta coalescing, opencode file_search) with its wakeup implementation dropped in favor of this PR's continuation design.

      🤖 Generated with Claude Code

    7. juliusmarminge merged this798c458

    8. juliusmarminge closed this

Sign in to join this conversation.