Repository navigation
fix(opencode): attribute shared-server sessions to their panes - #21577
Conversation
The v2 shared server stamps every hook post with its own frozen pane, so all panes' status lands on the starter pane (stablyai#21359). - shared: session->pane registry plus ingest-time envelope rewrite; bound sessions resolve to their real pane, tab and live launch token before disposition, unbound sessions keep the stamped identity. - main: binder poll (SQLite session store, PTY-registry pane snapshots, argv-aware client sweep) with directory-containment plus client-lifetime correlation; 60s loop plus debounced SessionStart kick, wired into the hook server lifecycle.
Live verification against the dev instance found two binder gaps: remint rows for one pane counted as an ambiguous tie, and /tmp vs /private/tmp spellings never met on macOS.
- applyBinderOwnerships now overwrites per-pane worktree, matching the round's newest-wins pane dedupe; a remint's live row wins over a stale row (pinned by test). - remove the unused OPENCODE_CLIENT_PRE_CREATE_WINDOW_MS export and the nowMs residue from clientCouldCreate. - give the per-pane launch-token cache its own named cap constant.
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Unresolved attribution, pagination, lifecycle, and platform-compatibility issues block approval.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Open (3)
What changed in this PR
Adds session-to-pane attribution for shared OpenCode servers, using SQLite session discovery and process correlation to rewrite inbound events for the correct pane.
Changes:
- Adds session registry and ingest-time reattribution.
- Adds correlation, process sweeping, binder lifecycle, and teardown.
- Adds tests and reference documentation.
Unresolved findings include one critical watermark-pagination issue and six moderate issues covering shutdown races, Windows process parsing, Mimo detection, process-table integration, path normalization, and worktree fallback.
| File | Description |
|---|---|
src/shared/agent-hook-listener/opencode-session-registry.ts |
Stores bindings and rewrites envelopes. |
src/shared/agent-hook-listener/opencode-session-correlation.ts |
Correlates sessions with panes and clients. |
src/shared/agent-hook-listener/listener-state.ts |
Adds registry and token state. |
src/shared/agent-hook-listener.ts |
Applies attribution during normalization. |
src/shared/agent-hook-listener-opencode-session-registry.test.ts |
Tests registry behavior. |
src/shared/agent-hook-listener-opencode-session-correlation.test.ts |
Tests correlation logic. |
src/shared/agent-hook-listener-opencode-reattribution.test.ts |
Tests ingest rewriting. |
src/main/opencode/opencode-session-binder.ts |
Reads sessions and applies ownership. |
src/main/opencode/opencode-session-binder.test.ts |
Tests binder rounds. |
src/main/opencode/opencode-client-sweep.ts |
Enumerates OpenCode processes. |
src/main/opencode/opencode-client-sweep.test.ts |
Tests process parsing. |
src/main/agent-hooks/server/server-opencode-binder.ts |
Runs periodic attribution rounds. |
src/main/agent-hooks/server/server-lifecycle.ts |
Starts and stops the binder. |
src/main/agent-hooks/server/server-ingest-normalization.ts |
Kicks binding on session start. |
src/main/agent-hooks/server-opencode-binder.test.ts |
Tests live binder integration. |
docs/reference/opencode-tool-readout-followup.md |
Documents future tool-readout work. |
.gitignore |
Includes the reference document. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| const parent = columnExists(db, table, 'parent_id') ? 'parent_id' : 'NULL' | ||
| const rows: unknown[] = db | ||
| .prepare( | ||
| `SELECT id, directory, time_created, ${parent} AS parent_id FROM ${table} WHERE time_created > ? ORDER BY time_created ASC LIMIT 500` |
| // Why ticks: ConvertTo-Json datetime shapes vary by PowerShell version; | ||
| // ticks are unambiguous and parse with one division. | ||
| const startedAtMs = Number.parseInt(ticksText ?? '', 10) / 10_000 - 62_135_596_800_000 | ||
| const argv = (commandLine ?? '').split(/\s+/).filter((part) => part.length > 0) |
| function normalizeDir(directory: string): string { | ||
| let out = directory.trim().replace(/\\/g, '/') | ||
| // Why: macOS resolves /tmp to /private/tmp (and opencode records whichever | ||
| // spelling the process saw). Strip the well-known prefix so both spellings | ||
| // meet; no legitimate cross-platform path depends on it. | ||
| if (out === '/private' || out.startsWith('/private/')) { | ||
| out = out.slice('/private'.length) || '/' | ||
| } | ||
| while (out.endsWith('/') && out.length > 1) { | ||
| out = out.slice(0, -1) | ||
| } | ||
| return out |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (8)
🚧 Files skipped from review as they are similar to previous changes (6)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughThe changes correlate OpenCode sessions with panes using database sessions, pane snapshots, process ancestry, command-line arguments, directory matching, and parent-session inheritance. They add session bindings and launch-token state, shared-server envelope reattribution, and pane lifecycle cleanup. The binder uses composite cursors, immediate polling, generation guards, and cross-platform process discovery. Server lifecycle methods and Priority: ➖ Normal Severity of issue fixed: Medium 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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: 5
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 4e3efbd8-0f3b-4059-9d00-aa6dedff3014
📒 Files selected for processing (17)
.gitignoredocs/reference/opencode-tool-readout-followup.mdsrc/main/agent-hooks/server-opencode-binder.test.tssrc/main/agent-hooks/server/server-ingest-normalization.tssrc/main/agent-hooks/server/server-lifecycle.tssrc/main/agent-hooks/server/server-opencode-binder.tssrc/main/opencode/opencode-client-sweep.test.tssrc/main/opencode/opencode-client-sweep.tssrc/main/opencode/opencode-session-binder.test.tssrc/main/opencode/opencode-session-binder.tssrc/shared/agent-hook-listener-opencode-reattribution.test.tssrc/shared/agent-hook-listener-opencode-session-correlation.test.tssrc/shared/agent-hook-listener-opencode-session-registry.test.tssrc/shared/agent-hook-listener.tssrc/shared/agent-hook-listener/listener-state.tssrc/shared/agent-hook-listener/opencode-session-correlation.tssrc/shared/agent-hook-listener/opencode-session-registry.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| } = envelope | ||
| // Why: a rewritten shared-server post needs the bound pane's live token, so | ||
| // remember every pane's latest one regardless of source. | ||
| trackOpenCodePaneLaunchToken(state, stampedPaneKey, stampedLaunchToken) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '35,100p' src/shared/agent-hook-listener.ts
sed -n '105,180p' src/shared/agent-hook-listener/opencode-session-registry.ts
sed -n '40,75p' src/shared/agent-hook-listener-opencode-reattribution.test.tsRepository: stablyai/orca
Length of output: 6601
🏁 Script executed:
set -e
printf '%s\n' '--- hook listener imports and normalization flow ---'
sed -n '1,125p' src/shared/agent-hook-listener.ts
printf '%s\n' '--- token symbols and resolver usages ---'
rg -n -C 4 'trackOpenCodePaneLaunchToken|lookupOpenCodePaneLaunchToken|resolveOpenCodeSharedServerEnvelope|lastLaunchTokenByPaneKey|launchToken' src/shared/agent-hook-listener.ts src/shared/agent-hook-listener src/shared/agent-hook-listener-opencode-reattribution.test.ts
printf '%s\n' '--- reattribution tests ---'
cat -n src/shared/agent-hook-listener-opencode-reattribution.test.tsRepository: stablyai/orca
Length of output: 30150
🏁 Script executed:
set -e
printf '%s\n' '--- launch-token consumers ---'
rg -n -C 6 'lastLaunchTokenByPaneKey|lookupOpenCodePaneLaunchToken|launchToken.*hash|hash.*launchToken|launch token|launchToken' src | head -n 260
printf '%s\n' '--- related fence and status code ---'
rg -n -C 8 'fence|launch' src/shared/agent-hook-listener src/shared | head -n 320Repository: stablyai/orca
Length of output: 48933
🏁 Script executed:
set -e
rg -n -C 8 'getAgentStatusLaunchConfigForPaneKey|launchConfigForPaneKey|launchTokenHash|launchToken.*===' src/main src/shared src/renderer | head -n 260Repository: stablyai/orca
Length of output: 25880
Resolve the shared-server envelope before recording its launch token.
The current order records the stamped token before resolution. For a same-pane binding, the resolver returns the stamped envelope unchanged, so a stale shared-server token can overwrite the pane’s live token. Moving the tracking call alone is not sufficient if the bound resolver still falls back to that stamped token; tracking then becomes self-reinforcing.
Use the stored pane token for every bound session, including same-pane bindings. Do not record the stamped fallback as live when no stored token exists.
Proposed fix
- trackOpenCodePaneLaunchToken(state, stampedPaneKey, stampedLaunchToken)
if (source === 'claude') {
state.claudeUnconfirmedRestoredStatusPaneKeys.delete(stampedPaneKey)
}
...
- const { paneKey, tabId, worktreeId, launchToken } = resolveOpenCodeSharedServerEnvelope({
+ const resolved = resolveOpenCodeSharedServerEnvelope({
state,
source,
stamped: {
paneKey: stampedPaneKey,
tabId: stampedTabId,
worktreeId: stampedWorktreeId,
launchToken: stampedLaunchToken
},
sessionId: providerSession?.id
})
+ const { paneKey, tabId, worktreeId, launchToken } = resolved
+ trackOpenCodePaneLaunchToken(state, paneKey, launchToken)- if (!binding || binding.paneKey === stamped.paneKey) {
+ if (!binding) {
return stamped
}
...
- launchToken: lookupOpenCodePaneLaunchToken(state, binding.paneKey) ?? stamped.launchToken
+ launchToken: lookupOpenCodePaneLaunchToken(state, binding.paneKey)Add a regression test where a bound same-pane session already has a live token and a shared-server post carries a stale token. The result and stored token must remain the live token.
There was a problem hiding this comment.
Important
Three changes before merge: the Windows client sweep bypasses the mandated native process-table reader, normalizeDir cannot match Windows paths that differ only in case, and the unbound-retry cap permanently abandons sessions once the map is full. Details inline.
Reviewed changes
- Session→pane registry (
opencode-session-registry.ts) — new in-memorysessionId → panemap plus a per-pane launch-token cache, wired into pane teardown, pane move, and clear-all. - Ingest reattribution (
agent-hook-listener.ts) — foropencode/mimo-code, a bound session'spaneKey/tabId/worktreeId/launchTokenreplace the frozen shared-server stamp before disposition and fences. - Binder loop (
server-opencode-binder.ts,opencode-session-binder.ts) — 60s poll plus a debouncedSessionStartkick; reads new rows fromopencode.db(session_v2, v1sessionfallback), snapshots local panes, sweeps live clients, correlates, and applies bindings. - Client sweep (
opencode-client-sweep.ts) — argv-aware host process enumeration (pson macOS/Linux, CIM on Windows). - Pure correlation (
opencode-session-correlation.ts) — argv hits, directory containment, client-lifetime bracketing, child inheritance, explicit ambiguity. - Tests — 48 tests across 6 files; all pass locally, and
tsc -p config/tsconfig.node.jsonandoxlintare clean on the changed sources.
ℹ️ Nitpicks
unbindOpenCodeSessionsOfPane(opencode-session-registry.ts:80) andmoveOpenCodeSessionBindings(:100) test a${paneKey}\0prefix, but pane keys aretabId:uuid(makePaneKey) andbindOpenCodeSessionrejects anythingparsePaneKeycannot parse — so those branches are unreachable. The exact-match arm already covers every binding; the\0idiom is copied from the hierarchical pane-scoped helpers.startOpenCodeBinderLooponly installs a 60s interval and never runs a round immediately, so after launch or restart existing sessions stay on the frozen stamp for up to a minute. A single round at start would close that window.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…lifecycle - composite (time_created, id) store cursor advanced past handled rows only, so same-millisecond pagination and full unbound maps no longer drop sessions silently. - Windows sweep reads the native process table instead of forking powershell.exe; quote-aware argv parsing on both platforms. - directory keys via normalizeRuntimePathForComparison (Windows case-fold, POSIX backslash literals) plus narrow macOS /tmp|/var|/etc aliases and lexical dot-segment resolution. - bound sessions always take the stored pane token (never the frozen stamp); token tracking runs after resolution. - binder generation guard discards post-stop rounds; first round runs immediately at loop start. - unbind/move use exact pane-key match; pane launch-token cache gets its own cap constant. - move the tool-readout note out of this PR for its own branch.
|
Review round addressed (pushed as Copilot
CodeRabbit
Pullfrog
Pre-merge checks
|
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 Major · Do not let an obsolete round clear the new round's running flag. · server-opencode-binder.ts:204
src/main/agent-hooks/server/server-opencode-binder.ts:204
🩺 Stability & Availability | 🟠 Major | ⚡ Quick winDo not let an obsolete round clear the new round's running flag.
If the server stops and restarts before the old sweep resolves, the restart can begin a new round. The old round then reaches
finallyand setsopenCodeBinderRunningtofalsewhile the new round is still active.A timer or kick can then start another round. The overlapping rounds can apply ownership snapshots out of order and overwrite the current pane attribution with an older snapshot.
Capture the generation before the
try. Clear the flag only when that generation is still current.Proposed fix
this.openCodeBinderRunning = true + const generation = this.openCodeBinderGeneration try { const deps = this.openCodeBinderDeps const nowMs = deps.now() const fresh = deps.listSessions(deps.dbPath(), this.openCodeBinderWatermark) // ... - const generation = this.openCodeBinderGeneration const processes = await deps.sweep() if (generation !== this.openCodeBinderGeneration) { return 0 } // ... } finally { - this.openCodeBinderRunning = false + if (generation === this.openCodeBinderGeneration) { + this.openCodeBinderRunning = false + } }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 1554d520-aeee-4403-a315-0afd6f6707b3
📒 Files selected for processing (11)
src/main/agent-hooks/server-opencode-binder.test.tssrc/main/agent-hooks/server/server-opencode-binder.tssrc/main/opencode/opencode-client-sweep.test.tssrc/main/opencode/opencode-client-sweep.tssrc/main/opencode/opencode-session-binder.test.tssrc/main/opencode/opencode-session-binder.tssrc/shared/agent-hook-listener-opencode-reattribution.test.tssrc/shared/agent-hook-listener-opencode-session-correlation.test.tssrc/shared/agent-hook-listener.tssrc/shared/agent-hook-listener/opencode-session-correlation.tssrc/shared/agent-hook-listener/opencode-session-registry.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/main/opencode/opencode-session-binder.test.ts
- src/shared/agent-hook-listener/opencode-session-correlation.ts
- src/shared/agent-hook-listener-opencode-session-correlation.test.ts
- src/main/opencode/opencode-client-sweep.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Re-reviewed the delta since the prior pullfrog review (7fe47a7 → b7b8e5d), which resolves all three prior findings and two nitpicks, and also addresses the earlier Copilot findings.
- Composite store cursor (
opencode-session-binder.ts,server-opencode-binder.ts) — the millisecond watermark became a(time_created, id)cursor;advanceBinderCursoradvances only past rows the round actually handled and freezes before the first unhandled row, so a session the unbound cap skipped is re-listed rather than silently dropped. - Native Windows process table (
opencode-client-sweep.ts) — the win32 branch now reads throughreadWindowsProcessTable()and maps rows vianativeWindowsRowToIdentity; the barepowershell.exewhole-tableGet-CimInstancefork is gone. - Shared path normalization (
opencode-session-correlation.ts) —normalizeDirnow delegates tonormalizeRuntimePathForComparison(NFC + Windows-only case/backslash folding) with a narrow/tmp|/var|/etcmacOS alias fold and lexical./..resolution, so distinct/private/repoand/reporoots no longer merge while Windows case differences do. - Launch-token integrity (
agent-hook-listener.ts,opencode-session-registry.ts) — tracking moved after reattribution and a bound post now takes the stored pane token or nothing, so the shared server's stale frozen stamp can no longer overwrite a pane's live token. - Loop lifecycle (
server-opencode-binder.ts) — a generation counter discards a round in flight acrossstop(), andstartOpenCodeBinderLoopruns one round immediately instead of leaving existing sessions on the frozen stamp for a full interval. - Quoted argv splitting (
opencode-client-sweep.ts) —splitCommandLineArgvpreserves a quoted executable path asargv[0]for bothpsand Windows command lines. - Scope reduction — the unrelated
opencode-tool-readout-followup.mdreference doc and its.gitignoreentry were removed.
Verified locally: the 62 tests across the six touched suites pass, and oxlint is clean on the changed sources.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…, round lifecycle - POSIX sweep reads comm= alongside args= and classifies on the kernel executable name, so unquoted install paths with spaces no longer split argv[0] and reject the client; Windows rows carry the native table name. Degrades to argv[0] when comm is unavailable. - bound sessions take only the binding's worktree (never the stamped pane's), so a worktree-less binding cannot file a row under the wrong worktree. - the binder generation is captured before the round body and the running flag clears only for the current generation, so an obsolete post-stop round cannot admit an overlapping round.
|
Second review round addressed (pushed as New CodeRabbit findings
Confirmations
Gates on the new tip: |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Re-reviewed the delta since the prior pullfrog review (b7b8e5d → 2d329fb), which closes the round-lifecycle race CodeRabbit flagged and hardens client classification.
- Kernel-reported executable classification (
opencode-client-sweep.ts,opencode-session-binder.ts) —ProcessIdentityRowgains anexecutablefield, read from a secondps -eo pid=,comm=sweep on POSIX (degrading toargv[0]when that sweep fails) and from the native Windowsname. An install path with an unquoted space can no longer splitargv[0]and veto an otherwise-matching client. - Binder generation captured before the sweep (
server-opencode-binder.ts) — an obsolete round that resumes afterstop()no longer clears the running flag a restarted round holds, so two rounds can't apply ownership snapshots out of order. The new regression test drives that exact race and fails (sweepCalls3 vs 2) with the guard removed. - Stamped worktree dropped when the binding has none (
opencode-session-registry.ts) — a reattributed post takes the bound pane's worktree or nothing, never the server-starter's, so a worktree-less bound pane can't be filed under the wrong worktree. - Tests — comm-line parser, executable-preferring classification, comm-sweep join and failure degradation, and the round-lifecycle race; 72 tests across the six suites pass locally.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Validated against current OpenCode source (packages/opencode/src/session/session.ts): session records expose projectID/directory but no terminal/pane identity, while shared-server hooks inherit the starter process environment. This is therefore an Orca-side attribution bug, not an upstream OpenCode fix. The current PR head 2d329fb has the attribution implementation and targeted checks passing; it remains the appropriate fix vehicle for #21359. |



ELI5
When you run OpenCode in more than one terminal pane at the same time, each pane's status dot
(the little spinner / colored dot next to the pane) stopped being truthful: the pane that
happened to start OpenCode's background process would spin for everyone's work, while the
other panes stayed gray forever — even while they were working.
This PR makes Orca re-learn which pane owns which OpenCode session, so each pane's dot moves
when that pane's session is working, and goes idle when it settles.
What Changed
Before: an OpenCode pane reported its status by stamping every status message with the pane's
identity, taken from environment variables frozen when the pane's process started. That was
correct when every pane ran its own OpenCode process. With OpenCode 2.x, one shared background
server serves every pane, and a server process has exactly one environment — so every status
report from every pane arrived stamped with whichever pane started the server. One dot moved;
the rest stayed dark, by design.
After: Orca keeps a small in-memory map from an OpenCode session id to the pane that owns it.
When a status post arrives, Orca looks the session up in that map and, if known, replaces the
stamped pane/tab/worktree and the (usually empty) launch token with the bound pane's real
values before anything downstream acts on them. Sessions Orca couldn't attribute keep the old
stamped behavior — the fix is a no-op wherever it has no evidence.
The mechanism, in one line:
How the registry gets filled (a 60-second loop plus a debounced kick whenever an OpenCode
SessionStartarrives):Why
The pane a session belongs to is unknowable from inside the plugin — the shared server's
environment is frozen and the OpenCode session object carries no pane info, so no plugin-side
fix can work. The alternatives:
processes instead of one wastes the memory the shared server saves, so this direction was
rejected by design.
exactly during overlapping same-directory turns — the case users care about most.
A session→pane registry filled from client-side evidence is the only approach that is
deterministic in the common cases while keeping one shared server: the command line when it
names a session, directory-containment plus client-lifetime bracketing otherwise, explicit
ambiguity when panes race, and today's behavior when nothing is known.
Note on ordering: on OpenCode 2.x the status plugin must also load (the loader/event-shape
breakage fixed in #21322). That PR is the foundation; this PR fixes the attribution of the
posts that arrive. Together they make v2 panes light up correctly; #21359's reporting predates
#21322's merge, so the two should land in that order.
Linked Issue
Fixes #21359
Visual Proof
N/A — no UI surfaces changed; the fix corrects which existing dot lights up for which pane. An
E2E capture is planned against a packaged release after this and #21322 land (headless pane
spawns currently die in the dev environment used for authoring, so end-to-end proof is deferred
to CI / a packaged build).
Testing
(bind/lookup/evict/move/unbind, token tracking), the ingest-time rewrite (reattribution,
token substitution so the pane's fence passes, no-op for unbound/other sources), pure
correlation (argv, single-pane-directory, client-evidence tie-breaks, child inheritance,
explicit-ambiguity), the binder round (pane dedupe newest-wins, watermark advancement), the
argv-aware process sweep parser (macOS
psand Windows CIM shapes), and the live loop(SQLite read incl. v1 fallback, SessionStart kick, teardown unbind).
process table (715 rows), the real client correctly attributed over a same-directory decoy,
and a frozen-stamp
SessionBusyreattributed to the right pane.spawns die before a shell appears — unrelated to this change); CI and a packaged-build check
are the intended validation path.
including the
/tmp→/private/tmpaliasing (pinned by test); Windows uses the CIM sweep;WSL/SSH panes stay unbound by design (their sessions stay gray rather than guessed).
AI Disclosure
Authored with OpenCode (GLM-5.3-Flash agent) under human direction; all findings reviewed and
confirmed by the human author.
Review
Self-reviewed for correctness (fail-open everywhere; unbound sessions keep stamped behavior),
security (no new inputs trusted beyond the existing authenticated hook envelope; process sweep
is read-only
ps/CIM), and performance (steady state is one bounded SQLite read per minute;the process sweep only runs while unbound work exists and is coalesced).
Agent skill upstream boundary
Notes
Known residual limitations, deliberately accepted:
stamped attribution — same-directory sessions are indistinguishable by design of OpenCode 2.
behave as before.
(the watermark query marches forward); the unbound-retry map keeps recently seen sessions
sticky for 10 minutes in the meantime.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)