Repository navigation
fix(opencode2): resolve subagent session lineage so child work stops taking over the pane - #22444
Conversation
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- OpenCode 2 session lineage shim —
getOpenCode2SetupSource()(src/main/opencode2/status-plugin-setup-source.ts:8) now re-envelopesctx.session.get's flat record as{ data: record }before the shared lineage walk consumes it. Without this,lookupSessionList(status-plugin-session-lineage-source.ts:100) discarded every lookup,resolveRootSessionIDreturnednull, and child attention was keyed to the child session id. Thetypeof result.id === "string"guard leaves an already-enveloped result (and the OpenCode 1server()path) untouched. - opencode2 added to the double-Escape interrupt set — new shared
requiresDoubleEscapeInterrupt()(src/shared/agent-interrupt-intent.ts:55) replaces the duplicated list in the server gate (server-status-inference.ts:49) and the renderer gate (agent-interrupt-inference.ts:47), addingopencode2so a single Escape (OC2's Subagents-dock dismiss) no longer infers an interrupt. - Tests — new
hook-plugin-opencode2-session-lineage.test.tsruns the generated plugin against both variants and pins root attribution plus child-idle retirement; the two interrupt suites addopencode2cases; the v1 plugin sha256 is re-pinned.
Verification
I ran the touched suites: the four changed test files pass (100 tests), and the full src/main/opencode + src/main/opencode2 dirs pass (18 files). I also confirmed the new tests are real regression guards rather than theatre — reverting the shim reproduces 7 failures in the lineage suite, and removing opencode2 from the set reproduces 3 failures across the interrupt suites. The generated plugin uses client solely for ancestry lookup, so the re-envelope has no other consumer.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 📝 WalkthroughWalkthroughThe changes adapt OpenCode 2 session lookup results for lineage resolution and add tests and reproduction captures for session-lineage behavior. They also add a shared double-Escape guard for OpenCode, OpenCode 2, and Copilot, then use it in renderer and server inference checks. Server-inferred interrupt and answered-question payloads no longer include Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to Inferred status updates can lose main-agent state, and the lineage tests may miss regressions. Preserve that state and make the assertions wait for the relevant events before merging. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 391b15bd-d6b2-41a8-b801-a1e7639d63b6
📒 Files selected for processing (11)
docs/bug-reproductions/opencode2-session-lineage/README.mddocs/bug-reproductions/opencode2-session-lineage/hook-posts-after.jsonldocs/bug-reproductions/opencode2-session-lineage/hook-posts-before.jsonlsrc/main/agent-hooks/server-interrupt-inference-guards.test.tssrc/main/agent-hooks/server/server-status-inference.tssrc/main/opencode/hook-plugin-opencode2-session-lineage.test.tssrc/main/opencode/hook-service.test.tssrc/main/opencode2/status-plugin-setup-source.tssrc/renderer/src/components/terminal-pane/agent-interrupt-inference.test.tssrc/renderer/src/components/terminal-pane/agent-interrupt-inference.tssrc/shared/agent-interrupt-intent.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| } | ||
| } | ||
| }) | ||
| return { posts, lookups, cleanup } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '65,225p' src/main/opencode/hook-plugin-opencode2-session-lineage.test.ts
rg -n 'subscribe|session.get|handleLifecycleEvent' src/main/opencode2/status-plugin-setup-source.ts src/main/opencode/hook-service.ts src/main/opencode/status-plugin-session-lineage-source.tsRepository: stablyai/orca
Length of output: 7030
🏁 Script executed:
set -e
printf '%s\n' '--- setup source ---'
cat -n src/main/opencode2/status-plugin-setup-source.ts
printf '%s\n' '--- generated/source event wiring ---'
sed -n '1,180p' src/main/opencode/status-plugin-session-lineage-source.ts
printf '%s\n' '--- test setup and assertions ---'
sed -n '1,150p' src/main/opencode/hook-plugin-opencode2-session-lineage.test.ts
printf '%s\n' '--- setup callers and generated plugin source builders ---'
rg -n -C 4 'getOpenCode2PluginSource|getOpenCodePluginSource|status-plugin-setup|event\.subscribe|for await|session\.execution\.started|form\.created|setup\s*:' src/main/opencode src/main/opencode2Repository: stablyai/orca
Length of output: 42553
🏁 Script executed:
set -e
printf '%s\n' '--- factory setup and shared handler ---'
sed -n '1,120p' src/main/opencode/status-plugin-factory-source.ts
sed -n '220,305p' src/main/opencode/status-plugin-factory-source.ts
rg -n -C 8 'async function OrcaOpenCodeStatusPlugin|function OrcaOpenCodeStatusPlugin|hook_event_name|SessionBusy|AskUserQuestion|fetch\\(' src/main/opencode src/main/opencode2
printf '%s\n' '--- completion and fixture synchronization search ---'
rg -n -C 3 'consum|completion|done|eventsConsumed|event.*promise|runSetupBridge' src/main/opencode/hook-plugin-opencode2-session-lineage.test.ts src/main/opencodeRepository: stablyai/orca
Length of output: 10471
🏁 Script executed:
set -e
printf '%s\n' '--- plugin source selections ---'
rg -n -C 10 'function getOpenCodePluginSource|function getOpenCode2PluginSource|getStatusPluginFactorySource\\(' src/main/opencode/hook-service.ts
printf '%s\n' '--- lifecycle handler and post queue ---'
sed -n '120,245p' src/main/opencode/status-plugin-factory-source.ts
printf '%s\n' '--- synchronization symbols in target test ---'
rg -n -C 4 'runSetupBridge|event\\.subscribe|vi\\.waitFor|cleanup|Promise' src/main/opencode/hook-plugin-opencode2-session-lineage.test.tsRepository: stablyai/orca
Length of output: 342
🏁 Script executed:
set -e
printf '%s\n' '--- plugin source selections ---'
grep -n -F -C 10 'getOpenCodePluginSource' src/main/opencode/hook-service.ts
grep -n -F -C 10 'getOpenCode2PluginSource' src/main/opencode/hook-service.ts
printf '%s\n' '--- lifecycle handler and post queue ---'
sed -n '120,245p' src/main/opencode/status-plugin-factory-source.ts
printf '%s\n' '--- synchronization symbols in target test ---'
grep -n -F -C 4 'runSetupBridge' src/main/opencode/hook-plugin-opencode2-session-lineage.test.ts
grep -n -F -C 4 'vi.waitFor' src/main/opencode/hook-plugin-opencode2-session-lineage.test.tsRepository: stablyai/orca
Length of output: 15033
Await the fixture event stream before lineage assertions.
setupOpenCode2Status starts consuming events asynchronously and returns before the subscription finishes. The first test can observe the root SessionBusy before the child event. The cache test can assert after the first child event, before the repeated events run. Await a fixture completion promise before these assertions. Do not use cleanup as the barrier because it aborts the subscription.
Suggested synchronization fix
@@
async function runSetupBridge(
events: { type: string; data: Record<string, unknown> }[]
): Promise<{
posts: Post[]
lookups: string[]
+ eventsConsumed: Promise<void>
cleanup?: () => Promise<void>
}> {
const posts: Post[] = []
const lookups: string[] = []
+ let resolveEventsConsumed!: () => void
+ const eventsConsumed = new Promise<void>((resolve) => {
+ resolveEventsConsumed = resolve
+ })
@@
subscribe: async function* () {
for (const event of events) {
yield event
}
+ resolveEventsConsumed()
}
}
})
- return { posts, lookups, cleanup }
+ return { posts, lookups, eventsConsumed, cleanup }
@@
- const { posts, lookups, cleanup } = await runSetupBridge([
+ const { posts, lookups, eventsConsumed, cleanup } = await runSetupBridge([
@@
- await vi.waitFor(() => {
- expect(posts.filter((post) => post.hook_event_name === 'SessionBusy').length).toBeGreaterThan(
- 0
- )
- })
+ await eventsConsumed
@@
- const { posts, lookups, cleanup } = await runSetupBridge([
+ const { posts, lookups, eventsConsumed, cleanup } = await runSetupBridge([
@@
- await vi.waitFor(() => {
- expect(posts.length).toBeGreaterThan(0)
- })
+ await eventsConsumedabaa5e0 to
0525d55
Compare
0525d55 to
473b668
Compare
473b668 to
d11f6ce
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 8ded1f2a-a883-4fa9-95a2-af7c21a2489f
📒 Files selected for processing (3)
src/main/agent-hooks/server/server-status-inference.tssrc/main/opencode/hook-service.test.tssrc/main/opencode2/status-plugin-setup-source.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| payload.mainAgent?.state === 'done' | ||
| ? payload.mainAgent | ||
| : { state: 'done', outcome: 'cancellation', stateStartedAt: Date.now() } | ||
| ...(payload.subagents ? { subagents: payload.subagents } : {}) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the mainAgent contract and its consumers.
rg -n -C 5 '\bmainAgent\b|applyNormalizedStatus' srcRepository: stablyai/orca
Length of output: 42718
🏁 Script executed:
set -euo pipefail
printf '%s\n' '--- inference methods ---'
sed -n '70,190p' src/main/agent-hooks/server/server-status-inference.ts
printf '%s\n' '--- status update consumer ---'
sed -n '1,190p' src/main/agent-hooks/server/server-status-update.ts
printf '%s\n' '--- type declarations ---'
sed -n '1,120p' src/main/agent-hooks/server/server-types.ts
printf '%s\n' '--- direct mainAgent-related implementation references ---'
rg -n -C 4 'withHeldChildWaitMainAgent|continueMainAgentStatus|mainAgentStatusEqual|mainAgent\.state|payload\.mainAgent|restored\.mainAgent' src/main src/shared src/renderer/src/components/native-chat -g '*.ts' -g '*.tsx'Repository: stablyai/orca
Length of output: 42113
🏁 Script executed:
set -euo pipefail
sed -n '85,180p' src/main/agent-hooks/server/server-status-inference.ts
rg -n -C 6 'withHeldChildWaitMainAgent|continueMainAgentStatus|mainAgentStatusEqual|mainAgent\.state|payload\.mainAgent|restored\.mainAgent' src/main src/shared src/renderer/src/components/native-chat -g '*.ts' -g '*.tsx'Repository: stablyai/orca
Length of output: 42296
Preserve mainAgent in both inferred payloads.
applyNormalizedStatus does not restore this field from the previous row. The child-wait helper also requires next.payload.mainAgent. Without it, the fold treats the row as having no settled main-agent fact, and restart or provider restoration cannot recover that state.
Suggested fix
interrupted: true,
+ mainAgent:
+ payload.mainAgent?.state === 'done'
+ ? payload.mainAgent
+ : { state: 'done', outcome: 'cancellation', stateStartedAt: Date.now() },
// Why: idle children are display state; dropping them on an inferred interrupt blanks rows a later hook would restore.
...(payload.subagents ? { subagents: payload.subagents } : {})
@@
prompt: payload.prompt,
agentType: payload.agentType,
+ mainAgent: restored.mainAgent,
...(restored.state === 'done' && restored.interrupted ? { interrupted: true } : {}),There was a problem hiding this comment.
Caution
This re-based head reverts #22452's mainAgent handling in src/main/agent-hooks/server/server-status-inference.ts, and two existing tests fail as a result. Restore the two mainAgent lines from 8352752e54 before this is mergeable.
Reviewed changes
What changed since the prior pullfrog review (abaa5e0 → d11f6ce):
- Re-based onto
8352752e54(#22544) — one new commitd11f6cenow sits on currentmain(f2ac9f29b). The OpenCode 2 lineage shim, the shared double-Escape helper, and the lineage/interrupt test changes are unchanged from the previous review. mainAgentaccidentally dropped — the rebase reverted#22452's payload fields in bothinferInterruptandinferQuestionAnswered, so an inferred interrupt no longer records the cancelled main-agent turn.- Cosmetic — the shim in
status-plugin-setup-source.tscollapsed to a one-liner (behavior identical) and the OpenCode 1 plugin digest was repinned.
Verified this run: pnpm test src/main/agent-hooks/server-interrupt-inference-validation.test.ts fails the two mainAgent cases; the other four PR-touched test files pass (101 tests).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…taking over the pane
OpenCode 2's plugin adapter unwraps a single-property `{ data }` success schema,
so `ctx.session.get` resolves to the bare session record. The shared lineage
lookup only accepts `result?.data?.id === sessionID`, and OpenCode 2 has no
`session.list` fallback, so `resolveRootSessionID` returned null for every
session and `childState` was permanently null.
With unknown lineage `canFailOpen` is true for attention events, so a subagent's
`permission.asked`/`question.asked` fell through and pinned an un-evictable
blocker keyed to the child's own session id — publishing a subagent as if it
were a root. Observed in hook posts: SessionBusy for a child session id whose
`session_v2` row carries a parent.
Envelope the result in the OC2 client shim so the shared lineage module works
unchanged; OpenCode 1 already receives enveloped results and is untouched.
Also adds `opencode2` to the double-Escape interrupt list, extracted into one
shared helper so the server inference and renderer gate cannot drift. A single
Escape was inferring an interrupt, and Escape is how the Subagents dock closes.
7 of 11 new lineage tests fail without the shim.
d11f6ce to
2f3d174
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
What changed since the prior pullfrog review (d11f6ce → 2f3d174):
- Restored
#22452'smainAgenthandling —inferInterruptandinferQuestionAnsweredinsrc/main/agent-hooks/server/server-status-inference.tsagain publish the main agent's own state on an inferred interrupt and on an inferred resolved question, undoing the rebase regression the previous review flagged. - Nothing else changed — the range-diff against the prior head shows the OpenCode 2 lineage shim, the shared double-Escape predicate, the tests, and the plugin digests are all unchanged; the branch was re-based, so its merge-base with
mainis now8352752e54.
Verification: pnpm test src/main/agent-hooks/server-interrupt-inference-validation.test.ts passes 8/8, and the four PR-touched suites pass 101/101. Both inline threads from the prior review are addressed and resolved.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…taking over the pane (stablyai#22444) OpenCode 2's plugin adapter unwraps a single-property `{ data }` success schema, so `ctx.session.get` resolves to the bare session record. The shared lineage lookup only accepts `result?.data?.id === sessionID`, and OpenCode 2 has no `session.list` fallback, so `resolveRootSessionID` returned null for every session and `childState` was permanently null. With unknown lineage `canFailOpen` is true for attention events, so a subagent's `permission.asked`/`question.asked` fell through and pinned an un-evictable blocker keyed to the child's own session id — publishing a subagent as if it were a root. Observed in hook posts: SessionBusy for a child session id whose `session_v2` row carries a parent. Envelope the result in the OC2 client shim so the shared lineage module works unchanged; OpenCode 1 already receives enveloped results and is untouched. Also adds `opencode2` to the double-Escape interrupt list, extracted into one shared helper so the server inference and renderer gate cannot drift. A single Escape was inferring an interrupt, and Escape is how the Subagents dock closes. 7 of 11 new lineage tests fail without the shim. (cherry picked from commit b0ae7d1)

ELI5
When an OpenCode agent delegates work to a subagent, and that subagent asks a question, Orca is supposed to keep the question attached to the subagent and just show the pane as busy. Instead Orca treated the subagent as if it were your main session, so the pane lit up with "needs your input" — while the agent you were talking to correctly told you it had no question. Nothing could clear it except switching Orca tabs.
The reason is small: Orca asks OpenCode "who is this session's parent?", and for OpenCode 2 it was never able to read the answer.
What Changed
src/main/opencode2/status-plugin-setup-source.tsbuilds the session client that Orca's shared lineage code uses. OpenCode 2'sctx.session.getreturns the session record directly, butlookupSessionListonly accepts a result whenresult?.data?.id === sessionID. Thesession.listfallback doesn't exist on OpenCode 2 either, so there was no second chance:ctx.session.get({ sessionID }, { signal })→ the record directly, keys["id","projectID","agent","model","cost","tokens","time","location"]ctx.session.get({ path: { id } }, { signal })→ throwsMissing key at ["sessionID"]ctx.session.list→undefinedSo
resolveRootSessionIDreturnednullfor every OpenCode 2 session andchildStatewas permanentlynull.The shim now envelopes the direct result:
Keyed on
typeof result.id === "string"rather than "has no.data", so an already-enveloped result passes straight through — an envelope has no top-levelid. The wrapper keeps arity 2 solookupSessionListstill tries the[{sessionID}, {signal}]call shape first. The shared lineage module is untouched.Also in this PR:
opencode2was missing from the double-Escape list, so a single Escape on an opencode2 pane inferred an interrupt — and Escape is exactly how you dismiss OpenCode 2's Subagents dock. The same list was duplicated in the renderer gate (requiresDoubleEscapeForAgent), so fixing only the server would have silently removed double-Escape interrupts for opencode2. Both call sites now share onerequiresDoubleEscapeInterruptinsrc/shared/agent-interrupt-intent.ts, next to the existingisNavigationEscapeIntent.Why
Investigating #22371. With
childState === null,canFailOpenis true for attention events, so a subagent'spermission.asked/question.askedfell through to the attention branch instatus-plugin-lifecycle-source.ts:81-102and pinned an un-evictable blocker keyed to the child's own session id. The entire "child work rolls up to the pane but stays non-authoritative" design was bypassed for OpenCode 2.It also could not un-stick itself.
clearQuestionForToolPartis already dead for OpenCode 2 (it never emitsmessage.part.updated, and its formmetadata.toolcarriesid, notcallID), so only an exact idle for that child session could retire the blocker.Why the shim rather than the lineage module: OpenCode 1 drives the same module through
server()with the raw SDK client, and that client already returns enveloped results. Normalising at the one place the shapes differ keeps a single lineage implementation instead of forking a parallel OpenCode 2 path.Why no relay or remote-wire change: the reporter confirmed this reproduces on a local machine as well as a Remote Orca Server workspace, so the cause is common to both hosts. Fixing the plugin's own client shim covers local, SSH, and remote at once with no protocol change and nothing to capability-negotiate.
Linked Issue
Refs #22371 — but see Visual Proof: this is no longer claimed as the fix for that report.
Visual Proof
Attempted, and it does not support a user-visible claim. Reporting that rather than dropping it.
I drove both builds in the real app: OpenCode 2 in a scratch dir, a subagent delegated a task and called its
questiontool, captured at the moment the question was outstanding.17ffbf3b318)abaa5e0f382)waitingwaitingses_f2ff3c848…(parent set)ses_f2ffd258a…(no parent)done, indicator clearsdone, indicator clearsThe only measurable difference is the session id row — which is precisely the lineage rollup this PR fixes. The screenshots are identical to the eye, so I am not presenting them as a before/after.
This corrects the causal story I originally wrote for #22371. A subagent's question surfacing on the pane is correct behaviour —
handleLifecycleEventdeliberately "show[s] the blocker on the root turn while retaining its real child owner". So this fix does not, and should not, stop the indicator from appearing. What it changes is that the blocker is now attributed to the root session instead of the child's, which is what lets the normal retirement paths (an exact idle for that session, or a reply) clear it.So the honest scope is narrower than the PR originally implied: this fixes incorrect session attribution, which is a real bug with observable evidence in the hook posts. It is not demonstrated to fix the stuck-indicator symptom in #22371. I have not reproduced that symptom in either build.
Testing
Platforms: macOS, against the shipped
opencode v2.0.12.New
src/main/opencode/hook-plugin-opencode2-session-lineage.test.ts— 11 tests, run against both plugin variants. It pins the actual user-visible regression, not just the helper: a child session'squestion.askedmust not mint a root-level blocker, and a child-raised blocker must retire when that child goes idle. Also pins one lineage lookup per child across four events, so positive caching still holds.Verified the tests fail without the shim — 7 failures, e.g.
expected [ 'ses_root', 'ses_root', 'ses_child' ] to not include 'ses_child'. The three newopencode2Escape cases likewise fail without the list entry.pnpm test src/main/opencode src/main/opencode2— 18 files, 222 passedsrc/main/agent-hooks,src/shared, renderer terminal-pane) — 904 files, 10171 passedpnpm tc— 0;pnpm run check:code-quality:changed— 0 new findingsThe plugin byte digest in
hook-service.test.tsis re-pinned, expected for any change to emitted plugin source. The mimo-code digest is byte-identical, confirming OpenCode 1's path is untouched.Not verified: that the reporter's exact frame is gone on their machine. This is
Refs, notFixes, until they confirm.AI Disclosure
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
docs/reference/remote-wire-compatibility.mdnothing here alters RPC params, stream opcodes, or published content — the fix is inside the plugin that runs on the execution host, which keeps owning agent status.childStatestaysnulland behaviour degrades to the current fail-open. The fix can only improve on it.awaitand a type check per lineage lookup, and lookups are already cached per child.Two adjacent defects found, deliberately not fixed here
"orca-opencode-status"and both are written into~/.config/opencode/plugins/. OpenCode 2 keeps only one; when it keeps the v1 file, itsORCA_OPENCODE_AGENTgate returns no hooks and the pane reports nothing, silently. This blocked the harness until the v1 file was moved aside. Already addressed by open PR fix(opencode): fail-open plugin setup and distinct opencode2 plugin id #22158.agent-status-patch.tsis gated only on ownership and on the host snapshot carrying no status for the surface — nothing inspects the entry's state. Oncedispose()callsreleaseRendererOwnedAgentStatusPane(), a real unresolvedwaitingrow is dropped on exactly the same path as a stale one. This is what made the reporter's tab-switch "workaround" work, and it means a real question can vanish from the sidebar just because you looked at another tab. Filing separately.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm testpass locally