Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(server): OpenCode 2 native steering, fork and rollback #14468

Mergedjuliusmarmingemerged 7 commits intot3code/codex-turn-mapping fromrefs/pull/14468/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

OpenCode 2 sessions steered by interrupt-and-restart and couldn't fork or roll back. Layer 7 of the OpenCode 2 stack adds native steering, fork, and rollback through OpenCode's staged revert.

Restacked on layer 6 (#14474). Layer 6 treats any execution OpenCode starts on its own as a subagent's follow-up. So revert.clear's empty execution is now swallowed before that check, or it would have offered a spurious continuation turn (an adapter test fails without this). Continuation turns get their own turn id (<session>:wake:<attempt>), and fork and rollback skip them. Rollback is refused while background work is pending.

Review fixes. Each has an adapter test that fails without its fix.

  • A rollback after a Stop that timed out asks the server whether that run is still going, and refuses while it is.
  • A stranded steer whose inbox cancel failed is cancelled again before the next prompt.
  • The snapshot a rollback returns lists only the provider turns it kept.
  • T3's prompt and steer ids now include the OpenCode session id. OpenCode answers a message id reused in another session with a 409, and two T3 databases on one external server can repeat thread ids and run ordinals.
  • A fork whose target thread runs in another worktree is moved there when it is made, since its first turn starts without a resume.
  • Starting a turn and rolling back share a per-session gate, so a turn sent during a rollback waits for the cut.
  • A fork of a session with a running turn is refused, as on 1.x, under the same gate.
  • A rollback of a session this runtime hasn't loaded yet asks the server whether it runs, and its snapshot keeps the recorded turns up to the target.
  • Fork and rollback share one busy check: a running turn, a follow-up OpenCode runs on its own, or a run on the server this runtime doesn't own. Revert stage and commit are bounded, so a hung server can't block later turns.

What changed

All of it is in OpenCode2AdapterV2.ts. Orchestration and the UI are unchanged.

  • Steering (supportsActiveSteering: true). A message steered into a running turn goes out as session.prompt{delivery: "steer"}. OpenCode reads it at the running execution's next step boundary, so the steer joins that turn: one provider turn, one terminal.
    • The prompt id is derived from T3's message id, so a retried steer effect lands on the same inbox item. OpenCode answers a repeated id with the item it already has (checked live on 2.0.18).
    • If the execution ends before reading the steer, OpenCode wakes the session into another execution for it. The turn stays open until that one ends.
    • A Stop leaves undelivered steers in OpenCode's inbox, where the next prompt would deliver them first. The next turn cancels them with session.inbox.cancel.
  • Queue. Queueing stays app-owned, as it is for every provider in V2. Queued, cancelled, edited and reordered runs never reach an adapter; a queued run calls startTurn after the previous turn's terminal. So OpenCode's delivery: "queue" is not used, a cancelled queued message never reaches OpenCode, and inbox.update has no V2 counterpart: it changes the delivery mode, while V2's edit changes the text.
  • Turn boundaries. Prompts now go out under T3-chosen ids (msg_t3_turn_<attempt>). Each provider turn's nativeTurnRef is therefore the user message it prompted with, which is where fork and rollback cut.
  • Fork (canForkThread, canForkFromTurn). session.fork{before} cuts at the next turn's prompt, provided it is still in the session. The fork gets the target thread's rules. canForkFromSubagentThread stays false while subagents are denied (layer 6).
  • Rollback (canRollbackThread, providerCanRollbackConversation, providerRollbackReturnsSnapshot):
    • Rollback is revert.stage{files: false} followed by revert.commit. T3's own checkpoint stays authoritative for files, and a "rewind without files" must not touch them.
    • If the stage or commit fails or is interrupted, the adapter clears the stage, because OpenCode commits a staged revert on the next prompt. It also skips the spurious empty execution that clear runs.
    • If the clear fails too, it is retried before the next prompt.
    • Turns recorded before this layer have no message id, so a cut behind one of them is refused with a clear error.

Verification

  • Replay fixtures from the spike recordings, run through the whole orchestrator:
    • opencode2_inbox (from inbox.ndjson): a steer into a running shell turn plus two queued messages, one of them cancelled.
    • opencode2_revert (from revert.ndjson): two write turns, then a rollback to the first.
    • The fork scenario in OpenCode2OrchestratorV2.integration.test.ts (from fork.ndjson): a real thread.fork from the first of two turns.
    • All three fail against layer 5's adapter.
  • OpenCode2OrchestratorV2.integration.test.ts also gains an orchestrator test showing a cancelled queued message is never prompted.
  • An adapter test covers a failed commit whose clear also fails. A real server can't fail on demand, so this one is not a replay. It checks that the stage is cleared before the next prompt.
  • Live runs on 2.0.18 through the real driver (OPENCODE2_MODEL=openrouter/deepseek/deepseek-v4-flash); the whole live file passes (4 tests). The new live test:
    • steers a running shell turn, and the steer lands in that run with one attempt;
    • queues two messages, which run as their own turns;
    • forks from the first turn; the fork doesn't know the later turns;
    • rolls back the source to the first turn: reverted.txt goes back from BETA to ALPHA, and OpenCode's session is left with the first user message plus the new one.
  • Tests run inside unshare -U -p:
    • vp test run on OpenCode2AdapterV2.test.ts, OpenCodeAdapterV2.test.ts, OpenCode2OrchestratorV2.integration.test.ts, OrchestratorReplayFixtures.integration.test.ts and processGroup.test.ts: 194 passed.
    • After the review fixes and the restack onto V2 5eae8ff36b: OpenCode2AdapterV2.test.ts plus OpenCode2OrchestratorV2.integration.test.ts give 71 passed, and OrchestratorReplayFixtures.integration.test.ts gives 111 passed.
  • Checks:
    • tsc --noEmit -p apps/server exits 0;
    • vp lint on touched files: one pre-existing warning in shared.ts;
    • vp run knip:check is clean.
  • Not run: repo-wide checks.

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. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR adds substantial OpenCode runtime capabilities for steering, forking, rollback, and nested background execution, with complex state and history-concurrency behavior. An unresolved Medium-severity replay concern also affects the new continuation path.

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

      Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ℹ️ No successful main baseline artifact is available yet. This run establishes the initial measurement.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire—4.9 KiB—6.8 KiB✅
      CodexThread snapshot wire—3.7 KiB—4.9 KiB✅
      CodexLive turn WebSocket wire—1.2 KiB—2.0 KiB✅
      CodexLive turn WebSocket decoded—20.4 KiB—29.3 KiB✅
      CodexLive turn messages—2—8✅
      ClaudeTotal thread wire—4.9 KiB—6.8 KiB✅
      ClaudeThread snapshot wire—3.7 KiB—4.9 KiB✅
      ClaudeLive turn WebSocket wire—1.2 KiB—2.0 KiB✅
      ClaudeLive turn WebSocket decoded—20.7 KiB—29.3 KiB✅
      ClaudeLive turn messages—1—8✅

      Baseline: unavailable · PR result: 0637907 · 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

      🟠 High

      https://github.com/pingdotgg/t3code/blob/ac13b6828db3922569cb3b1ac2c498cf04dca585/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts#L1806

      When an unsupported form belongs to a subagent and form.cancel fails, abandonRequest finishes the parent thread instead of the child session that owns the form. The child remains blocked on the unanswered form, so its execution runs indefinitely. Pass the form session's ThreadState to abandonRequest.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts around line 1806:
      
      When an unsupported form belongs to a subagent and `form.cancel` fails, `abandonRequest` finishes the parent thread instead of the child session that owns the form. The child remains blocked on the unanswered form, so its execution runs indefinitely. Pass the form session's `ThreadState` to `abandonRequest`.
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/OpenCode2AdapterV2.ts:154

      Child sessions can execute shell and edit operations without the parent thread's required approval or deny policy. supportsSubagents: true exposes children, but attachChild only records them and startChildTurn starts them without calling writeRules, which applies runtime-policy rules only to root sessions; disable this capability until child sessions receive the same rules.

          supportsSubagents: false,
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts around line 154:
      
      Child sessions can execute shell and edit operations without the parent thread's required approval or deny policy. `supportsSubagents: true` exposes children, but `attachChild` only records them and `startChildTurn` starts them without calling `writeRules`, which applies runtime-policy rules only to root sessions; disable this capability until child sessions receive the same rules.
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/OpenCode2AdapterV2.ts:2715

      A failed or timed-out session.interrupt still causes settleCall(call, "interrupted"), so the background child is removed from tracking even though it continues running. This makes hasPendingBackgroundWork return false and allows unload while the subagent can still perform work and report later; only settle the call after a confirmed interrupt, or retain it as pending when interruption fails.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts around line 2715:
      
      A failed or timed-out `session.interrupt` still causes `settleCall(call, "interrupted")`, so the background child is removed from tracking even though it continues running. This makes `hasPendingBackgroundWork` return false and allows unload while the subagent can still perform work and report later; only settle the call after a confirmed interrupt, or retain it as pending when interruption fails.
    5. juliusmarminge added labelsmacroscope-review

    6. Real, and introduced in layer 6. Fixed at the top of layer 6, c330e41, and carried into this layer by the rebase.

      onFormCreated now resolves the asking session with threads.get(form.sessionID) ?? state, the same as the permission path. Fixing that turned up a second instance of the bug: a declined unsupported form on a subagent also failed the parent's turn and set the parent's unsettled flag. Now:

      • a cancel that fails abandons the subagent's own session;
      • a cancel that succeeds ends only the subagent's turn. The parent reads the failed subagent call and goes on.

      See OpenCode2AdapterV2.ts around L1739 on layer 6.

      Tests, both failing before the fix:

      • "stops the subagent whose form T3 cannot show or decline"
      • "ends only the subagent's turn when it declines the subagent's form"
    7. Mostly not real, but it found one real gap. That gap is fixed in layer 6, c330e41, and subagents stay enabled.

      Why the flagged path is safe. A new child session inherits its parent's rules from OpenCode itself. In the 2.0.18 binary:

      • Session.create publishes permissions: C.permissions ?? X?.permissions, where X is the parentID session.
      • The subagent tool creates the child with a.create({parentID, title, agent, model}) and passes no permissions.
      • Permission.evaluate reads [...agentRules, ...session.permissions] from the child session.
      • Layer 5's live probe on 2.0.18 confirmed it ("child sessions inherit the parent's session rules", in #14407).

      The parent's rules are T3's for the thread's mode: ensureThread creates them and writeRules runs on every startTurn. So a new subagent runs under the thread's mode. Layer 6 also writes "allow this session" grants to the child with rootOf(state).policy.

      The gap. Inheritance happens only when the session is created, so two cases kept stale rules:

      1. A background subagent still running when the thread's mode changes between turns.
      2. A subagent the model resumes by sessionID, whose session OpenCode made under an earlier mode.

      Fix.

      • startTurn now writes the thread's rules to every running subagent's session too (around L2692).
      • attachChild writes them to a resumed child, meaning one with no session.created announcement. It also records the inherited rules and keeps an earlier session's grants (around L1156).

      Tests, all failing before the fix:

      • "gives a background subagent the rules of a mode changed while it runs"
      • "gives a resumed subagent the rules of the thread's current mode"
    8. Real, and introduced in layer 6. Fixed at the top of layer 6, c330e41.

      stopBackground now settles a background call only once the interrupt for its child is confirmed. SessionNotFoundError counts as confirmed, since that session is gone. When the interrupt fails or times out:

      • the failure is logged;
      • the call stays running and listed, so hasPendingBackgroundWork and hasPendingBackgroundWorkForThread stay true, and the session is neither idle-released nor unloaded under it;
      • a later Stop reaches it again.

      The child keeps its stop marker. Its eventual report still ends the follow-up rather than opening a continuation, because the user asked to stop it. See around L2475.

      Test: "keeps tracking a background subagent whose Stop did not reach it". It failed before the fix.

    9. The stack was restacked after layer 5 merged, so the fix is now ffa1bc8 on layer 6. The patch is unchanged.

    10. The stack was restacked after layer 5 merged, so the fix is now ffa1bc8 on layer 6. The patch is unchanged.

    11. The stack was restacked after layer 5 merged, so the fix is now ffa1bc8 on layer 6. The patch is unchanged.

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

      🟡 Medium Adapters/OpenCode2AdapterV2.ts:1469

      Finishing the root turn interrupts and removes a still-running nested background subagent, so its eventual report is no longer tracked or delivered and the root is released early. At line 1469, settleCall recursively settles every child of the foreground call; preserve nested background calls when settling a foreground parent.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts around line 1469:
      
      Finishing the root turn interrupts and removes a still-running nested background subagent, so its eventual report is no longer tracked or delivered and the root is released early. At line 1469, `settleCall` recursively settles every child of the foreground call; preserve nested background calls when settling a foreground parent.
    13. Fixed in 050105d. Confirmed against OpenCode 2.0.18 live (experimental.subagent_depth 2): a foreground subagent that starts a background subagent returns while that one still runs. OpenCode then reports it to that subagent's session and wakes it to answer.

      • settleCall no longer settles a nested background call when its foreground parent ends, unless the parent failed. finishTurn already applied that rule to top-level calls.
      • runningCalls, hasBackground and stopBackground now walk every subagent session under the thread, via sessionsOf, instead of only running calls. They also count a subagent session that OpenCode is running to answer such a report. A user Stop interrupts that turn too.
      • Test: the opencode2_nested_background fixture replays the live recording through the orchestrator. At 042d553d94 it fails (the grandchild is interrupted instead of completed). With the fix the run completes only after the grandchild reports. Two adapter tests cover Stop before and during the middle session's follow-up turn; both fail at 042d553d94.
    14. juliusmarminge merged this40920d9

    15. juliusmarminge closed this

Sign in to join this conversation.