fix(opencode): a running background shell keeps its session until it reports#18920

closed14
main
GitHub fork: fix/18880-opencode-background-shells
openedOct 13, 2026bySScottN-PV
View on GitHubTwo-way sync enabledPR last imported 18d ago

A background shell can outlive its initiating OpenCode turn. T3 previously treated that thread as idle and could unload it before the shell reported its result.

The OpenCode 2 adapter now keeps ownership while a known shell runs and while its result is queued. The follow-up execution takes ownership before inbox delivery. Successful stream recovery reads each known shell at its launch directory and reads its session inbox, preserving running jobs across worktree moves and releasing results already delivered during a gap. Deleted locations and sessions release only their own pending work. Exhausted recovery still clears ownership. Shell ownership stays separate from the existing subagent recovery predicate, so reconnect does not falsely interrupt foreground subagents. Stop interrupts the turn; it does not kill OpenCode's background shell. Rollback remains blocked while that background work is pending.

Thanks @ScottN-PV for the original fix in #18920. Contributor commits are preserved; main was merged and maintainer commits added on top.

Scope and approval

Closes #18880. The maintainer triage confirmed that background shells were missing from pending work. This is a focused OpenCode 2 adapter fix. No wire contract, UI, other provider, or idle timeout policy changes.

Verification

  • Replaced eight shell tests with four lifecycle cases and one foreground-subagent reconnect regression in the existing adapter suite. Recovery uses the existing HTTP replay harness for native shell/inbox reads. Exact main production reversal fails the original lifecycle regression; move and foreground-subagent reconnect cases were red before their respective fixes; restored head passes all 106 adapter tests. Three existing manager tests also pass: runtime retention, shared-thread retention, and the existing pin cap. Scoped provider/server typechecks and targeted lint/format checks pass.
  • Three independent full-PR review rounds on Codex GPT-6-Sol and Claude Opus 5.5. Earlier rounds found launch-directory recovery, deleted-resource handling, and foreground-subagent interruption defects; all were fixed. Both final reviews found no confirmed defects.
  • Current-head CI: build/typecheck, lint, all eight server shards, package tests, and web tests passed. A cancelled native-fingerprint run is superseded by a successful run. CodeRabbit's current-head review was requested twice but rate-limited; its older approval does not certify this head. Human follow-up is needed to obtain that review when capacity is available. No unresolved review threads.
  • Linux web with actual OpenCode 2.0.29, an isolated local model endpoint, and a real background shell held on a FIFO: its initiating run completed, forced SSE disconnect recovered through native shell/inbox reads while the job remained alive, and releasing the FIFO delivered its result and completed the automatic follow-up. The observed event order was result enqueue, execution start, inbox delivery. Both app runs persisted as completed. Sanitized before/after test results and native event trace.

This is backend behavior; the regression proof is the failing/passing tests. The images show two states of the live fixed flow, not a visual base/head comparison.

Held shell after stream recovery:

After release, the automatic follow-up reports the result:

Recording of result delivery.

Limits

The live run did not wait 30 minutes for eviction; adapter pending-work assertions and existing manager TestClock tests verify that contract. The existing four-hour pin cap remains for idle runtimes. In an actively used thread, a long-lived shell can block rollback until the job exits; Stop does not release that shell, and the client can show the existing still-working error without a running turn. This product behavior remains for human review. Recovery reconciles known jobs and queued results; it does not discover a launch wholly missed during a stream gap or reconstruct a wholly missed follow-up execution. The pre-existing nested held-follow-up limitation remains. Results deliberately queued without a wake stay pending until delivery/cancellation or the cap.

Not verified: real provider accounts, macOS, Windows, iOS, Android, Electron desktop, or remote/tunnel transport. No merge performed.

Models and harnesses: Codex GPT-6.1-Sol (implementation), GPT-6-Astra (tests), GPT-6-Sol and Claude Opus 5.5 (independent reviews), through T3 Code.

Fixes pingdotgg/t3code#18880

Checks

22 successful · 12 skipped
All checks passed
11a2068
Synced from GitHub

Approvability

Verdict: Approved at 3db8565

Macroscope's review found this PR approvable — This is a focused OpenCode adapter bug fix that keeps sessions alive for background shell results without changing schemas, defaults, or deployment behavior. The production logic is narrowly scoped and accompanied by comprehensive tests for delivery, cancellation, ordering, follow-ups, subagents, and reconnect cleanup.

You can add or adjust custom eligibility rules. Learn more.

Synced from GitHub

Review in Change Stack →

No actionable comments were generated in the recent review.

Walkthrough

The OpenCode 2 adapter now tracks background shell jobs and queued completion reports as pending work. It updates this tracking when shell events arrive, including during replay, and clears it when stream recovery fails or background-work reconciliation runs.

Changes: OpenCode background shell tracking

Layer / File(s)Summary
Track shell events and pending work
packages/provider-opencode/src/server/v2/adapter.ts, apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
Thread state tracks running shells, completions received before launch results, and queued shell reports. Shell events update these sets, and running or queued work counts as pending. Tests cover multiple jobs, follow-ups, cancellation, replay, and subagent-started shells.
Clear shell tracking during stream recovery
packages/provider-opencode/src/server/v2/adapter.ts, apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
Stream failure and background-work reconciliation clear shell tracking. A test verifies that pending shell work clears when the event stream cannot reconnect.

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

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: juliusmarminge

Merge Risk: Minimal · up to 4bc0b

The reviewed shell-tracking changes have no identified merge-blocking issue. Normal checks remain appropriate before merging.

Security architecture risk: Low · up to 4bc0b

Background jobs now keep their sessions available until results are delivered or cancelled. No added execution privileges or newly exposed endpoint were identified. Unverified event-delivery assumptions leave some uncertainty around stale pending work and recovery.

Retained concerns No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — Retention can be affected across the sessions hosted by one adapter runtime. Thread-specific completion checks aggregate only the selected native session and its registered descendants, rather than unrelated sibling threads.

Trust Boundaries and Controls

  • observed — The existing client supplies Basic authentication to the provider connection and decodes incoming events against the provider schema. New shell accounting resolves the event's session ID against tracked state. These controls establish the local processing boundary but do not prove the provider's duplicate-delivery or metadata guarantees.

Resilience and Maintainability Implications

  • inferred — Duplicate launch delivery after an early completion could recreate a running-shell entry after its completion is delivered or cancelled. The early-end marker is consumed once, and no launch-event deduplication appears in the tracker. Provider behavior establishing that this sequence can occur was unavailable, so this is an unresolved retention invariant rather than a verified vulnerability.

Hardening Proposals

  • proposed — Establish the provider's ordering and duplicate-delivery contract. If duplicate launch events are permitted, make early-completion handling idempotent so replay cannot retain a session for an already completed shell.
Pre-merge checks: 4

Check nameStatusExplanation
Linked Issues checkThe pull request satisfies the coding requirements in [#18880]. The OpenCode 2 adapter tracks running background shell IDs and shell-end items queued for delivery. owesWork counts this state, and de…
Out of Scope Changes checkThe pull request changes only the OpenCode 2 adapter and its focused test file. The adapter changes implement the background-shell session retention required by [#18880]. The tests verify required ret…
Title checkThe title is concise, specific, and accurately describes the primary fix: retaining the session while a background shell runs until it reports.
Description checkThe description explains the problem and change, identifies the linked issue and maintainer approval, and gives detailed verification results and limitations. It does not use explicit Problem or Chang…
Full details: Linked Issues check

Explanation

The pull request satisfies the coding requirements in [#18880]. The OpenCode 2 adapter tracks running background shell IDs and shell-end items queued for delivery. owesWork counts this state, and delivery or cancellation clears queued shell work. Reconciliation and failure cleanup clear the shell state. The tests cover running shells, queued ends, follow-up handling, cancellation, out-of-order events, and reconnect reconciliation.

Full details: Out of Scope Changes check

Explanation

The pull request changes only the OpenCode 2 adapter and its focused test file. The adapter changes implement the background-shell session retention required by [#18880]. The tests verify required retention and cleanup behavior. No unrelated product or UI changes are shown.

Full details: Description check

Explanation

The description explains the problem and change, identifies the linked issue and maintainer approval, and gives detailed verification results and limitations. It does not use explicit Problem or Change headings, but it includes the required information and follows the Scope and approval and Verification sections.

Finishing Touches

🧪 Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
ℹ️ Recent review info

⚙️ Run configuration

  • Configuration used: Path: .coderabbit.config.ts
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 502ea418-1565-411f-a396-a34aa38afedf
📥 Commits

Reviewing files that changed from the base of the PR and between 3db856571f2d2432848882a8d089fe8fae041257 and 4bc0b21e3a7e40f9e1d591fc76e35d7fb2ef4217.

📒 Files selected for processing: 2

  • apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
  • packages/provider-opencode/src/server/v2/adapter.ts

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

Added 1 commit

  • fix(opencode): a running background shell keeps its session until it reports4bc0b21

Taking over this one. I will trim the replay tests, preserve pending shell jobs across stream recovery, and verify shell completion ordering against a live OpenCode runtime before pushing back here.

Added 9 commits

  • Merge remote-tracking branch 'refs/remotes/op17-main/main' into fix/18880-opencode-background-shells778904b
  • test(opencode): consolidate background shell lifecycle coverage3b7040f
  • fix(opencode): reconcile background shells after stream recovery9e55537
  • test(opencode): cover shell recovery after worktree moves6dae0eb
  • test(opencode): cover missing shell recovery resources1dddf60
  • fix(opencode): retain shell locations through recoverya674ab5
  • Merge remote-tracking branch 'refs/remotes/op17-main/main' into fix/18880-opencode-background-shells78ddae0
  • test(opencode): cover foreground subagent reconnect with a background shellfeb8431
  • fix(opencode): preserve foreground subagents during shell recovery7183807
Synced from GitHub
⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Synced from GitHub
⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Added 4 commits

  • Merge remote-tracking branch 'origin/main' into l69-18920f5261b4
  • Merge remote-tracking branch 'origin/main' into l69-18920b29e5a4
  • fix(opencode): track background shells recovered from reconnect history04929fe
  • Merge remote-tracking branch 'origin/main' into l69-1892011a2068
Synced from GitHub

Related visibility gap, in case it fits here or in a small follow-up: this PR makes the adapter know about running background shells (state.shells), but the UI still never shows them as running.

derivePendingBackgroundWork builds the running-task list from providerThread.pendingBackgroundTasks and nonterminal turn items. For OpenCode, syncRoster fills pendingBackgroundTasks from background subagents only, and the shell's command_execution item is marked completed when the launch acknowledgement arrives. So on 0.1.6 a backgrounded shell shows nothing between the turn ending and "Background activity updated". With this PR, the thread can be held by an invisible shell, which matches the "still-working error without a running turn" noted under Limits.

Publishing the entries of state.shells as pendingBackgroundTasks (kind: "command"), as the Claude adapter does with its roster, would cover it.

Synced from GitHub

Tested 11a20681be against its merge base 44f977f4e8 in a VM (OpenCode 2.2.5, Cursor models through cursor-opencode-provider), with DEFAULT_IDLE_TIMEOUT_MS patched to 2 minutes in both builds and another thread kept busy so the runtime stayed up.

With sleep 200 started through OpenCode's shell tool with background: true, the PR kept the thread loaded in 2 of 2 runs, T3 showed the wake turn, its t3_project_list call worked, and the thread was released about 2 minutes later. On the base the thread was unloaded at 2 minutes in 2 of 2 and the wake turn's T3 tool call was refused. An idle thread next to it was still unloaded at 2 minutes in all 8 runs.

It doesn't cover the case from #31307: there the shell ran in the provider's own runner (the launch is a completed shell call and the result comes back as a synthetic source: "shell" note with a numeric shellID), so state.shells never sees it and both builds unloaded the thread. That path is provider-specific, so it's no reason to hold this PR.

Synced from GitHub

unsync's point shows in my VM runs above: on 11a20681be OpenCode reported the shell job as running, but T3 marked its item completed in the same event batch, pendingBackgroundTasks stayed [], and the run settled about 200 s before the shell ended. On main (6577c6b) syncRoster still lists only background subagent calls (adapter.ts#L1259-L1269). That matters beyond the banner: restart recovery reads the roster to tell the agent what was cancelled (ProviderRuntimeRecoveryService.ts#L679-L687), so a shell missing from it is lost without a note.

A subagent's own shell has the same gap. Once the subagent ends its turn, settleCall drops its call (L1427), so neither the root's roster nor stopBackground reaches that session. Since this PR already counts children's state.shells in hasBackground through sessionsOf, publishing those shells on the root roster as kind: "command" would cover both cases.

For Stop, the pinned @opencode/client 2.0.28 has client.shell.remove (DELETE /api/shell/:id), so stopBackground could terminate each tracked shell.

Note

🤖 Claude Opus 5.5 responding on behalf of Theo

Closing. This PR has been open for more than 3 weeks, and main has moved a long way since then. If the change still matters, open a fresh PR from current main.