Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(orchestration-v2): attribute reused subagents to the run driving them (2/4) #4662

Closedshivamhwp(GitHub profile, opens in a new tab)wants to merge 8 commits intosubagent-obs/01-contracts fromsubagent-obs/03-reuseopened View on GitHub

Second of four stacked PRs (renumbered in the 5→4 consolidation; content unchanged). Stacked on #4779 — review that first; this diff is against it.

A subagent row keeps the run id it was spawned under. Routing admits a row by run or by parent thread, and the parent thread is excluded by construction — so a later run re-activating that subagent could only see its updates while the spawning run's ingestion fiber happened to still be alive. The Claude adapter already re-attributed on reopen for exactly this reason; this brings the same treatment to routing and to Codex.

The bug that made this invisible

The rebind was hooked to item/started. Codex's reuse frames — resumeAgent, sendInput — only ever arrive on item/completed, and registerSubagentThreads ignores them because they aren't spawnAgent. So the rebind never fired, and I could not reproduce the fix working.

Moving the hook is what makes it observable. subagent_continue now asserts the subagent is attributed to the run that drove it:

subagent.runId
beforeordinal:1 (spawning run)
afterordinal:2 (run that drove the reuse)

Routing

Identity becomes a third ownership test, seeded from the projection at turn start. Two constraints shape it:

  • The child thread is adopted only while the agent is live. A settled row is also re-emitted by trailing traffic — a token-usage frame, a collab state sweep — and adopting on those would hand a later run an interrupted agent's thread, readmitting exactly the stale events that post-interrupt recovery exists to exclude.
  • A subagent's row and its timeline item are emitted together, so both route by identity. Matching only the row advanced the agent while its item stayed frozen on the spawning run.

That is also why the reactivation predicate is separate from canRouteRelatedSubagent rather than a widening of it: an interrupted agent must not have its child thread pre-owned, but its identity is still resumable — the user stopped it, they didn't lose it.

Rehydration

Seeds turn ordinals alongside the registry (restarting at 1 would re-derive childRootNodeId for a different native turn) and parks non-terminal leftovers at idle, since a new session can never terminalize an activation it didn't drive and would otherwise keep the session pinned open.

Rehydration is covered directly. CodexAdapterV2.test.ts clears the process-local registry, seeds the next turn from projection-known subagents, and verifies that the same identity is reused with activation ordinal/count and lifetime usage advanced correctly. The recorded subagent_reuse_after_idle fixture is registered in the orchestrator replay suite; the replay hang observed while drafting no longer reproduces (full suite passes it in ~2s).

Testing

Typecheck clean across server, contracts, client-runtime, web. Server 1,684 passing.

Reviewed by an independent agent pass, which found the item/started / item/completed bug above plus the child-thread adoption hole, the row/item routing asymmetry, and both rehydration gaps. All fixed here.

Note

Attribute reused subagents to the run that reactivates them in orchestration-v2

  • Adds subagent identity tracking to ProviderEventRoutingState so events from reused subagents are routed to the reactivating run rather than the original spawning run.
  • Introduces canReactivateSubagent alongside existing canRouteRelatedSubagent to distinguish subagents eligible for rehydration from those eligible for live routing; interrupted agents' child threads are not adopted until reactivation is observed.
  • ProviderTurnStartService now rehydrates persisted child thread projections for reactivatable subagents before opening the provider session, passing relatedSubagentIds and existingSubagents to RunExecutionService.startRootRun.
  • CodexAdapterV2 seeds its process-local registry from existingSubagents on session open and rebinds registered subagents to the current turn context on collab tool call interactions, without emitting events during seeding.
  • cascadeTerminalizeRunOwnedSubagents now terminalizes all open activations and non-terminal turn items regardless of runId, and clears currentActivationId on subagent rows.
  • Adds a new subagent_reuse_after_idle replay fixture and integration test scenario to validate end-to-end subagent reuse across an idle/reap window.
Macroscope summarized e151f62.

Note

High Risk Touches core orchestration routing, Codex adapter lifecycle, and run finalization for subagents; incorrect identity or child-thread adoption could mis-attribute events or leave runs stuck open.

Overview Later runs that re-activate an existing Codex subagent now keep updates on the run that is actually driving the agent, instead of losing them when the spawning run’s ingestion has already finished.

Codex adapter seeds the process-local subagent registry from existingSubagents at root-turn start (after session reap or restart), rebinds reused agents to the current run via rebindSubagentToContext on collabAgentToolCall / interacted events (including on item/completed, where Codex’s resumeAgent / sendInput frames arrive), and ignores trailing token/status noise for settled identities when no activation is in flight.

Turn start & routing rehydrates child projections for reactivatable subagents (including interrupted), passes relatedSubagentIds and existingSubagents into execution, and admits provider events by subagent identity as well as run/thread—adopting the child thread only while the agent is live so stale interrupted-child traffic does not leak into the next attempt.

Tests & fixtures add subagent_reuse_after_idle / interrupt replay scenarios, adapter rehydration tests, and stronger assertions on subagent_continue run attribution and cascade terminalization of open activations.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit b0398e1ae362af183db28d9dfa164fcfff41978a. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Review-fix verification (2026-08-01)

  • b0398e1ae gates settled Codex token/state noise on a live activation while retaining historical activation-only usage updates.
  • The idle-identity regression transcript and 50 focused Codex adapter tests pass; reuse and activation attribution remain covered by the registered replay fixture.
  • Chrome confirmed a settled Codex child stays a single Agents-panel row and remains absent from the top-level sidebar.

Settled Codex child

    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 Plus

      Run ID: 8c30b74b-f26f-4a50-85c4-3515e634a341

      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
      • Commit unit tests in branch `subagent-obs/03-reuse`

      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:trusted

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

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/cde25982f91a4a46bf4c707b135ecd44a738e00c/apps/server/src/orchestration-v2/RunExecutionService.ts#L775

      A reused subagent's turn_item.updated event passes the new ownsSubagent route check but trackChildLifecycle only considers belongsToRootRun = event.turnItem.runId === input.run.id for the subagent-item branch, so the item is never inserted into openRunOwnedSubagents.turnItems. When the reactivating run is interrupted or fails, the cascade terminalizes the subagent row and activation but leaves this timeline item non-terminal, so it stays visibly stuck in the projection. Extend the root-ownership test in trackChildLifecycle to include routing.ownedSubagentIds.has(event.turnItem.subagentId) (matching the routing logic).

      No longer relevant as of 32cbb3d41525d1b13c6d5ec98cb6315637b25951

    4. Effect service conventions: one issue found. Known tagged failures should be recovered with Effect.catchTags rather than catchIf + a schema predicate.

      Posted via Macroscope — Effect Service Conventions
    5. @@ -387,3 +389,18 @@
      387389 },
      388390 ],
      389391 },
      392+ {
      393+ name: "subagent_reuse_after_idle",
      394+ buildInput: subagentReuseAfterIdleInput,
      395+ providers: [
      396+ {
      397+ driver: ProviderDriverKind.make("codex"),
      398+ transcriptFile: new URL(
      399+ "./subagent_reuse_after_idle/codex_transcript.ndjson",
      400+ import.meta.url,
      401+ ),
      402+ modelSelection: CODEX_MODEL_SELECTION,
      403+ assertOutput: assertSubagentReuseAfterIdleOutput,
      404+ },
      405+ ],
      406+ },

      Hanging fixture registered in suite

      High Severity

      subagent_reuse_after_idle is registered in ORCHESTRATOR_REPLAY_FIXTURES even though this PR calls out a known replay hang and says the fixture should stay unregistered while that path is investigated. That pulls the hanging scenario into the orchestrator replay suite and risks stuck CI.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d453837b42768190e8fbd6a0fe66edb9bf5af0a9. Configure [here](https://www.cursor.com/dashboard/bugbot).

      The PR description was stale, not the registration: the hang no longer reproduces. Verified locally on this branch — subagent_reuse_after_idle passes the orchestrator replay suite standalone (~2.6s) and in the full run (68 passed; the only failures are the pre-existing queued_turn/* ones inherited from the base branch). Updated the description to match.

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

      Approvability

      Verdict: Needs human review

      This PR introduces significant orchestration behavior changes for subagent reuse attribution across runs, including new state management and event routing logic. Combined with an unresolved high-severity comment about a potentially hanging test fixture, human review is warranted.

      No code changes detected at e151f62. Prior analysis still applies.

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

      There are 2 total unresolved issues (including 1 from previous review).

      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 1dec2aa03588792e645979dff9dd19c9fc1e5546. Configure [here](https://www.cursor.com/dashboard/bugbot).
    8. shivamhwp(GitHub profile, opens in a new tab) changed the title

    9. shivamhwp(GitHub profile, opens in a new tab)commented

      This is covered by 30af905dfc: RunExecutionService now uses isRunOwnedSubagentTurnItem so both delegated-task ownership paths receive the same runId filtering, with focused coverage in RunExecutionService.test.ts.

      — Codex on behalf of shivamhwp

    10. @@ -447,0 +474,21 @@
      474+ },
      475+ {
      476+ type: "turn",
      477+ label: "reuse-interrupted-subagent",
      478+ prompt: SUBAGENT_REUSE_AFTER_INTERRUPT_RESUME_PROMPT,
      479+ },
      480+ ],
      481+ },
      482+ ],
      483+ },
      484+ {
      485+ name: "subagent_reuse_after_idle",
      486+ fileName: "subagent_reuse_after_idle.ndjson",
      487+ description:
      488+ "A root turn spawns a native Codex subagent, then a later root turn re-activates it. Replay advances past the session idle timeout between turns so the adapter registry is empty on reuse.",
      489+ runs: [
      490+ {
      491+ name: "reuse-after-idle",
      492+ description:
      493+ "Second root turn messages the same subagent after the session would have been reaped.",
      494+ steps: [
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium scripts/record-codex-app-server-replay-fixture.ts:494

      The new subagent_reuse_after_idle scenario runs both turns as ordinary sequential steps in a single runReplaySession. Unlike provider_thread_resume, there is no runtime_exit/restart/thread/resume between the two turns, so the app-server session never exits and the adapter registry is never cleared. The recording therefore captures normal continuation behavior instead of idle-reuse behavior, silently overwriting the regression fixture with a recording that does not exercise the intended idle-reuse path. This scenario needs recorder control flow analogous to provider_thread_resume (or an explicit restart step) between the two turns.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/scripts/record-codex-app-server-replay-fixture.ts around line 494:
      
      The new `subagent_reuse_after_idle` scenario runs both turns as ordinary sequential steps in a single `runReplaySession`. Unlike `provider_thread_resume`, there is no `runtime_exit`/restart/`thread/resume` between the two turns, so the app-server session never exits and the adapter registry is never cleared. The recording therefore captures normal continuation behavior instead of idle-reuse behavior, silently overwriting the regression fixture with a recording that does not exercise the intended idle-reuse path. This scenario needs recorder control flow analogous to `provider_thread_resume` (or an explicit restart step) between the two turns.
    11. Converged into #4664, which now carries the full series against the orchestrator-v2 base — the commit history there preserves this PR's slice, and this PR's review record (findings and fix replies) remains the reference for it.

Sign in to join this conversation.