Skip to content

fix(opencode): attribute shared-server sessions to their panes - #21577

Merged
nwparker merged 6 commits into
stablyai:mainfrom
werlang:fix/opencode-shared-server-pane-attribution
Sep 21, 2026
Merged

nwparker merged 6 commits into
stablyai:mainfrom
werlang:fix/opencode-shared-server-pane-attribution

Conversation

@werlang

@werlang werlang commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

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:

the hook server rewrites paneKey/tabId/worktreeId/launchToken on inbound opencode posts
before disposition, using a session→pane registry (opencodeSessionPaneBySessionId) fed by a
main-process binder.

How the registry gets filled (a 60-second loop plus a debounced kick whenever an OpenCode
SessionStart arrives):

the binder reads new sessions from OpenCode's local SQLite store (session_v2, falling back
to the v1 session table), snapshots local panes from the PTY registry (pane key, worktree
root, shell pid), and sweeps the host process table (ps on macOS/Linux, PowerShell CIM on
Windows) for live OpenCode client processes; a session binds to its pane when the pane's
worktree contains the session's directory and exactly one pane has a live client that brackets
the creation, or when the client's command line names the session outright
(--session <id> / -s <id> / --session=<id>). Child sessions inherit their root's owner.
Ambiguous cases (same directory, indistinguishable clients) are deliberately left unbound
rather than guessed.

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:

  • Per-pane servers would make each process's environment truthful again, but N OpenCode
    processes instead of one wastes the memory the shared server saves, so this direction was
    rejected by design.
  • Heuristic-only attribution (timing correlation with no registry) would misattribute
    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

  • Automated tests added/updated: 48 tests across 6 files covering the registry
    (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 ps and Windows CIM shapes), and the live loop
    (SQLite read incl. v1 fallback, SessionStart kick, teardown unbind).
  • Decision core validated against live data on macOS: real store (39 sessions), real host
    process table (715 rows), the real client correctly attributed over a same-directory decoy,
    and a frozen-stamp SessionBusy reattributed to the right pane.
  • Manual end-to-end on a running app: not completed locally (headless dev-environment pane
    spawns die before a shell appears — unrelated to this change); CI and a packaged-build check
    are the intended validation path.
  • Not platform-specific: correlation is directory/containment-based and works for macOS paths
    including the /tmp → /private/tmp aliasing (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

  • Not applicable — no skills, skill installers, or skill registries are touched.

Notes

Known residual limitations, deliberately accepted:

  • Ambiguous same-directory panes (no distinguishing client evidence) stay unbound and keep the
    stamped attribution — same-directory sessions are indistinguishable by design of OpenCode 2.
  • After an Orca restart the registry re-populates within ~60 seconds; during that window posts
    behave as before.
  • Sessions beyond the first 500 rows on a very large store converge over successive rounds
    (the watermark query marches forward); the unbound-retry map keeps recently seen sessions
    sticky for 10 minutes in the meantime.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

orca-agent and others added 4 commits September 18, 2026 22:06
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.
Copilot AI lite review requested due to automatic review settings September 19, 2026 03:36

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 High severity · 2 Medium severity

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)
Comment on lines +51 to +62
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
@coderabbitai

coderabbitai Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 3338c164-bc33-405b-9934-c1ca74019ac2

📥 Commits

Reviewing files that changed from the base of the PR and between b7b8e5d and 2d329fb.

📒 Files selected for processing (8)
  • src/main/agent-hooks/server-opencode-binder.test.ts
  • src/main/agent-hooks/server/server-opencode-binder.ts
  • src/main/opencode/opencode-client-sweep.test.ts
  • src/main/opencode/opencode-client-sweep.ts
  • src/main/opencode/opencode-session-binder.test.ts
  • src/main/opencode/opencode-session-binder.ts
  • src/shared/agent-hook-listener-opencode-reattribution.test.ts
  • src/shared/agent-hook-listener/opencode-session-registry.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/shared/agent-hook-listener/opencode-session-registry.ts
  • src/main/opencode/opencode-client-sweep.test.ts
  • src/main/agent-hooks/server-opencode-binder.test.ts
  • src/shared/agent-hook-listener-opencode-reattribution.test.ts
  • src/main/opencode/opencode-client-sweep.ts
  • src/main/opencode/opencode-session-binder.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

The 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 SessionStart hooks control binder activity. Tests cover these behaviors.

Priority: ➖ Normal

Severity of issue fixed: Medium

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 70.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 50 functions across 15 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description follows the required template. It explains the user impact, implementation, rationale, linked issue, testing, limitations, platform considerations, and checklist status.
Title check ✅ Passed The title clearly and concisely describes the main change: attributing shared-server OpenCode sessions to their owning panes.
Linked Issues check ✅ Passed The PR implements #21359. It records OpenCode session-to-pane bindings and correlates sessions with SQLite data, pane snapshots, and host processes. It rewrites bound status metadata with the bound pa…
Out of Scope Changes check ✅ Passed The changed production code, lifecycle integration, shared listener state, correlation logic, process inspection, and automated tests support the #21359 attribution fix. The supplied scope contains no…
  • Fix all pre-merge checks with AI

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 4e3efbd8-0f3b-4059-9d00-aa6dedff3014

📥 Commits

Reviewing files that changed from the base of the PR and between 0817476 and 7fe47a7.

📒 Files selected for processing (17)
  • .gitignore
  • docs/reference/opencode-tool-readout-followup.md
  • src/main/agent-hooks/server-opencode-binder.test.ts
  • src/main/agent-hooks/server/server-ingest-normalization.ts
  • src/main/agent-hooks/server/server-lifecycle.ts
  • src/main/agent-hooks/server/server-opencode-binder.ts
  • src/main/opencode/opencode-client-sweep.test.ts
  • src/main/opencode/opencode-client-sweep.ts
  • src/main/opencode/opencode-session-binder.test.ts
  • src/main/opencode/opencode-session-binder.ts
  • src/shared/agent-hook-listener-opencode-reattribution.test.ts
  • src/shared/agent-hook-listener-opencode-session-correlation.test.ts
  • src/shared/agent-hook-listener-opencode-session-registry.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-listener/listener-state.ts
  • src/shared/agent-hook-listener/opencode-session-correlation.ts
  • src/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.

Comment thread src/shared/agent-hook-listener.ts Outdated
} = 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.ts

Repository: 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.ts

Repository: 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 320

Repository: 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 260

Repository: 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-memory sessionId → pane map plus a per-pane launch-token cache, wired into pane teardown, pane move, and clear-all.
  • Ingest reattribution (agent-hook-listener.ts) — for opencode/mimo-code, a bound session's paneKey/tabId/worktreeId/launchToken replace the frozen shared-server stamp before disposition and fences.
  • Binder loop (server-opencode-binder.ts, opencode-session-binder.ts) — 60s poll plus a debounced SessionStart kick; reads new rows from opencode.db (session_v2, v1 session fallback), snapshots local panes, sweeps live clients, correlates, and applies bindings.
  • Client sweep (opencode-client-sweep.ts) — argv-aware host process enumeration (ps on 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.json and oxlint are clean on the changed sources.

ℹ️ Nitpicks

  • unbindOpenCodeSessionsOfPane (opencode-session-registry.ts:80) and moveOpenCodeSessionBindings (:100) test a ${paneKey}\0 prefix, but pane keys are tabId:uuid (makePaneKey) and bindOpenCodeSession rejects anything parsePaneKey cannot parse — so those branches are unreachable. The exact-match arm already covers every binding; the \0 idiom is copied from the hierarchical pane-scoped helpers.
  • startOpenCodeBinderLoop only 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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.
@werlang

werlang commented Sep 19, 2026

Copy link
Copy Markdown
Contributor Author

Review round addressed (pushed as b7b8e5d429). All changes are inside this PR's files; no surrounding code touched.

Copilot

  • Watermark pagination (high): the store cursor is now composite (time_created, id) — WHERE time_created > ? OR (time_created = ? AND id > ?) ORDER BY time_created ASC, id ASC — and the loop advances it past handled rows only, so same-millisecond page boundaries and a full unbound-retry map can no longer drop sessions silently (pinned by cursor-advance tests).
  • Windows quoted paths (medium): argv parsing is now quote-aware on both platforms (splitCommandLineArgv), so "C:\Program Files\...\opencode.exe" classifies correctly.
  • Path normalization (medium): directory keys go through normalizeRuntimePathForComparison (Windows case/NFC folding, POSIX backslash literals preserved) plus a narrow macOS /tmp|/var|/etc → /private alias step and lexical dot-segment resolution, each pinned by tests.

CodeRabbit

  • Token order (major): resolution now runs before token tracking; a bound session always takes the stored pane token (possibly absent — never the frozen stamp), including same-pane bindings, so a stale shared-server stamp can no longer overwrite the live token. Regression test added.
  • Quoted paths (major): same fix as above.
  • Dot segments (minor): resolved lexically before containment, with a regression test.
  • Stop-during-await (minor): generation counter discards post-stop round continuations (no watermark resurrection, no late applies); tested.

Pullfrog

  • Native Windows table (important): the win32 path now reads only through readWindowsProcessTable(); the powershell.exe fork and CIM parser are gone. argv[0] classification still works off the native command field via the quote-aware parser.
  • Case/NFC + /private merge (important): covered by the shared-helper normalization above; the old blanket /private strip is replaced by the narrow alias map.
  • Unbound cap vs watermark (important): the watermark advances past handled rows only (new advanceBinderCursor helper, tested); untracked rows stay re-listable.
  • Nitpicks: unreachable \0 prefix arms removed (pane keys are validated tabId:uuid); the loop now runs one round immediately at start instead of waiting out the first 60s interval.

Pre-merge checks

  • Out-of-scope note moved out: docs/reference/opencode-tool-readout-followup.md and its .gitignore exception are removed from this branch and will go up as a separate PR.
  • Docstring coverage: documented every previously-undocumented function/type in the new modules.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟠 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 win

Do 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 finally and sets openCodeBinderRunning to false while 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7fe47a7 and b7b8e5d.

📒 Files selected for processing (11)
  • src/main/agent-hooks/server-opencode-binder.test.ts
  • src/main/agent-hooks/server/server-opencode-binder.ts
  • src/main/opencode/opencode-client-sweep.test.ts
  • src/main/opencode/opencode-client-sweep.ts
  • src/main/opencode/opencode-session-binder.test.ts
  • src/main/opencode/opencode-session-binder.ts
  • src/shared/agent-hook-listener-opencode-reattribution.test.ts
  • src/shared/agent-hook-listener-opencode-session-correlation.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-listener/opencode-session-correlation.ts
  • src/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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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; advanceBinderCursor advances 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 through readWindowsProcessTable() and maps rows via nativeWindowsRowToIdentity; the bare powershell.exe whole-table Get-CimInstance fork is gone.
  • Shared path normalization (opencode-session-correlation.ts) — normalizeDir now delegates to normalizeRuntimePathForComparison (NFC + Windows-only case/backslash folding) with a narrow /tmp|/var|/etc macOS alias fold and lexical ./.. resolution, so distinct /private/repo and /repo roots 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 across stop(), and startOpenCodeBinderLoop runs one round immediately instead of leaving existing sessions on the frozen stamp for a full interval.
  • Quoted argv splitting (opencode-client-sweep.ts) — splitCommandLineArgv preserves a quoted executable path as argv[0] for both ps and Windows command lines.
  • Scope reduction — the unrelated opencode-tool-readout-followup.md reference doc and its .gitignore entry were removed.

Verified locally: the 62 tests across the six touched suites pass, and oxlint is clean on the changed sources.

Pullfrog  | View workflow run | Using 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.
@werlang

werlang commented Sep 19, 2026

Copy link
Copy Markdown
Contributor Author

Second review round addressed (pushed as 2d329fb0c1). All changes stay inside this PR's files.

New CodeRabbit findings

  • POSIX executable boundary (major): the sweep now runs ps -eo pid=,comm= alongside args= and classifies on the kernel-reported executable (isOpenCodeClientProcess), so an unquoted /opt/Open Code/opencode no longer splits argv[0] and rejects the client. --session parsing still reads args=, whose values never contain spaces; a failed comm= sweep degrades to argv[0] matching. Replied inline.
  • Frozen worktree on worktree-less bindings (major): bound sessions take binding.worktreeId with no stamped fallback — absent is honest, wrong is not. Regression test added. Replied inline.
  • Obsolete round clearing the new round's flag (major, outside-diff note): the generation is now captured before the round body and the finally clears openCodeBinderRunning only for the current generation. New test pins it deterministically (third round refused while the new round is parked) and was verified to fail without the guard.

Confirmations

  • Pullfrog's three Addressed in b7b8e5d notes and the No new issues found re-review: acknowledged, no action needed.

Gates on the new tip: typecheck:node clean, 72/72 targeted tests green (including 3 new regression tests, one mutation-verified), full src/main/opencode suite green, oxfmt/oxlint clean, changed-code quality gate passed.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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) — ProcessIdentityRow gains an executable field, read from a second ps -eo pid=,comm= sweep on POSIX (degrading to argv[0] when that sweep fails) and from the native Windows name. An install path with an unquoted space can no longer split argv[0] and veto an otherwise-matching client.
  • Binder generation captured before the sweep (server-opencode-binder.ts) — an obsolete round that resumes after stop() 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 (sweepCalls 3 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 646fa36 into stablyai:main Sep 21, 2026
1 check passed
@nwparker

Copy link
Copy Markdown
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: opencode v2 shared background server freezes pane identity — every pane's status lands on whichever pane started the server

3 participants