orca icon indicating copy to clipboard operation
orca copied to clipboard

Agent status over WSL: guest-resident hook relay + WSL-side hook installers (STA-1515)

Open brennanb2025 opened this issue 4 months ago • 12 comments

Summary

Agent hooks have never worked from inside WSL, for any agent — so worktree-card rows, status transitions, prompt/last-message previews, and completion notifications are all dead for WSL worktrees (class gap behind #6907/#7565; only OMP had scoped stopgaps). Two independent gaps, both fixed here:

Transport (Gap A). Under WSL2's default NAT networking, 127.0.0.1 inside the guest is the guest's own loopback, so every hook POST to Orca's Windows listener dies ECONNREFUSED — silently, because hook clients are fail-open. This PR runs a small hooks-only relay inside the distro (src/relay/wsl-agent-hook-relay.ts), listening on WSL loopback on the very port the clients were already given (that port only exists Windows-side, so it's free in the guest), authenticating with the host-issued token, and forwarding parsed envelopes over its own wsl.exe stdio into the existing agentHookServer.ingestRemote trust boundary — the exact shape of the SSH relay (src/relay/agent-hook-server.ts + framed JSON-RPC + SshChannelMultiplexer). Zero per-client transport changes; the Windows listener stays loopback-only.

Installation (Gap B). Hook configs/scripts were only ever written to the Windows home; agents inside WSL read the WSL-side $HOME and saw none of it. The unchanged SSH remote installers (installRemoteManagedAgentHooks, all 14 managed agents) now also run against a WSL guest, via an SFTP-shaped adapter whose primitives are home-scoped fs RPCs served by the relay over the already-open stdio channel — no per-file wsl.exe spawns, no \\wsl.localhost metadata quirks.

Lifecycle. A per-distro manager is ensured from buildPtyHostEnv on every WSL PTY spawn — which also covers post-restart daemon reattach re-spawns, when the new instance has a new port+token. The guest bundle installs by streaming base64 over wsl.exe stdin (works with interop/automount disabled), reinstalls on a stale-version exit (42), backs off with a long cooldown when the distro has no node ≥ 18 (43), retries WSL's intermittent "Catastrophic failure (E_UNEXPECTED)" a bounded number of times, and the relay exits when its stdin closes so a freed Windows-side port can never be forwarded into a dead guest listener. On EADDRINUSE (e.g. mirrored networking, where the Windows listener shares loopback) the relay falls back to an ephemeral port and clients re-coordinate through the relay-written guest endpoint file, which ORCA_AGENT_HOOK_ENDPOINT points at once the guest home is known (/u vs /p WSLENV translation now follows the value's shape).

Design doc with full context, alternatives considered, and validation facts: docs/agent-status-over-wsl.md (updated in this PR with the port-fallback, lifecycle, and reliability-contract decisions plus an implementation map).

Screenshots

No visual change (transport/installation plumbing; the UI surfaces are the existing hook-driven rows and notifications).

Testing

  • [x] pnpm lint (oxlint clean on touched dirs; max-lines ratchet OK — new manager split at the DI seam rather than suppressed)
  • [x] pnpm typecheck
  • [x] pnpm test (targeted: 21 new tests + adjacent suites agent-hook-server, agent-hook-integration, remote-hook-service-installers, installer-utils-remote, wsl-orca-env, ipc/pty — 293 tests green)
  • [x] pnpm build:relay (new out/relay/wsl/wsl-agent-hook-relay.js bundle + content-hash .version)
  • [x] New oracles: preferred-port bind + fixed token + EADDRINUSE fallback; fs-bridge/adapter errno mapping (ENOENT→2) and home scoping; a full run of the unchanged remote installers against an in-memory guest (this test caught a real bug: the installers' top-down mkdir-p probes ancestors of home, so the bridge allows ancestor readdir probes); manager fault injection (dedupe, stale-42 reinstall, no-node-43 cooldown, bounded catastrophic retry, exit→cooldown re-ensure gating, off-platform inertness).

Live Windows+WSL validation is the remaining step — acceptance criteria are in the design doc (Codex or Claude in a WSL worktree → live hook-driven row + completion notification on a NAT machine, hooks installed WSL-side automatically, status resumes after an Orca restart with a surviving PTY).

AI Review Report

Reviewed against the design doc's reliability contract (invariant class agent-session.hook-transport): fail-open hook clients paired with breadcrumbed (never silent) relay failures; bounded retries everywhere (no spawn loops); relay lifetime strictly tied to host stdin so no lingering guest listeners; ingest re-validates paneKey/tabId and re-normalizes payloads at the same trust boundary as SSH. Cross-platform: ensure path is gated on win32 and fires only from WSL PTY spawns (macOS/Linux inert — verified by test); guest scripts are POSIX sh with no bashisms; no argv quoting crosses the wsl.exe boundary (script bodies travel over stdin heredocs with quoted delimiters); WSLENV translation flags follow value shape. The multi-instance case (several concurrent Orca instances) is safe because each instance's relay binds its own distinct port and publishes to a port-keyed endpoint dir.

Security Audit

  • The relay's HTTP receiver binds 127.0.0.1 only inside the guest and requires the host-issued bearer token (403 otherwise) — same posture as the SSH relay; the Windows listener's loopback-only bind is untouched.
  • The fs bridge is home-scoped: mutations resolve under the guest $HOME or are refused (EACCES); the only exception is read-only readdir existence probes on ancestors of home, required by the installers' top-down mkdir-p. The channel it serves is the host-owned stdio of a process Orca itself spawned — equivalent trust to the SSH flow's SFTP channel, with strictly narrower capability.
  • Hook coordinates cross into the guest via WSLENV process env (same mechanism already shipped for WSL PTYs); the token is never placed on a command line.
  • Guest install writes with umask 077, version marker written last so partial installs self-heal as stale.
  • No new IPC surface; no dependency changes.

Notes

  • If a distro has no node ≥ 18, hooks stay degraded there (breadcrumbed, 10-min re-probe cooldown) — same runtime requirement as SSH remotes. Claude Code itself requires node, so the acceptance-path agents are unaffected.
  • The OMP curl.exe interop stopgap (PRs #7642/#7641) is left in place as a fallback; once this is live-validated it stops firing naturally (the guest loopback POST now succeeds) and can be retired in a follow-up.
  • Windows-rig validation to follow on this branch; results will be posted here.

How to verify (Windows 11 + WSL2, default NAT)

Setup. Check out this branch, pnpm install, pnpm build:relay (must produce out/relay/wsl/wsl-agent-hook-relay.js + .version), launch a dev instance. Confirm the machine is default NAT (wsl.exe wslinfo --networking-mode → nat) and the distro has node ≥ 18 on PATH or under ~/.nvm (wsl.exe -- sh -c 'command -v node && node --version').

  1. Relay provisioning. Open a terminal in a WSL worktree. Within ~15s the guest should have ~/.orca-wsl/hook-relay/{wsl-agent-hook-relay.js,launch.sh,.version} and ~/.orca-wsl/agent-hooks/port-<hookport>/endpoint.env with port/token matching the Windows listener, and WSL-side hooks installed: ~/.claude/settings.json referencing ~/.orca/agent-hooks/claude-hook.sh, ~/.codex/hooks.json, etc. Failures are breadcrumbed as [agent-hooks]-prefixed main-process console warns — capture those if anything is missing.
  2. Acceptance path. Launch Claude Code (and separately Codex — explicitly NOT omp) inside the WSL worktree and send a prompt. The worktree-card row must be live hook-driven: status transitions (working → waiting/done), prompt preview, and a completion notification. Codex is the strongest signal — it was fully dark in WSL before this (#6907).
  3. Restart resilience. With the WSL agent still running, quit and relaunch Orca, reattach, send another prompt. Status events must resume without relaunching the agent (fresh relay; new endpoint.env under the NEW port's dir).
  4. Posture checks. netstat -ano | findstr <hookport> on Windows must show the listener bound to 127.0.0.1 only. A plain non-WSL PowerShell terminal's agent status must be unaffected. OMP in WSL should still work — its curl.exe fallback should no longer fire, since the in-guest loopback POST now succeeds.
  5. Multi-instance (optional). A second dev instance gets its own hook port → its own relay per distro; no cross-talk between instances.

Gotchas. wsl.exe under concurrent spawn load can intermittently throw "Catastrophic failure (E_UNEXPECTED)" — the manager retries twice; wsl --terminate <distro> clears a wedged WSL. If exercising hook POSTs synthetically, use real uuid:uuid-shaped paneKeys (ingest silently drops others) and unset ORCA_AGENT_HOOK_ENDPOINT first so events don't route to a real running app.

Linear: STA-1515

Made with Orca 🐋

brennanb2025 avatar Jul 09 '26 07:07 brennanb2025

Review Change Stack

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds a WSL guest relay for agent-status delivery, with shared relay contracts, guest and host relay processes, filesystem bridging for hook installation, relay lifecycle management, PTY endpoint routing, Codex WSL runtime-home support, a WSL relay bundle build step, and tests plus documentation covering the new flow and related installer behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.83% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main WSL agent-hook relay and installer work.
Description check ✅ Passed The description includes all required sections and covers summary, testing, review, security, and notes with relevant detail.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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[bot] avatar Jul 09 '26 07:07 coderabbitai[bot]

Windows + WSL2 (NAT) validation — mechanisms proven, GUI acceptance still open

Validated on Windows 11 + WSL2 Ubuntu, default NAT (wslinfo --networking-mode → nat), guest node v22.22.1 — the exact rig this PR targets.

✅ Build & static

  • pnpm build:relay → produces out/relay/wsl/wsl-agent-hook-relay.js + .version (0.1.0+a016c874930b)
  • pnpm typecheck → exit 0 · oxlint on touched dirs → clean · CI verify → green

✅ Live mechanism validation — driven against the real relay bundle running inside WSL (not mocks)

Gap A transport (7/7): READY sentinel · binds 127.0.0.1:<inherited-port> inside the guest · publishes ~/.orca-wsl/agent-hooks/port-<port>/endpoint.env with matching port+token · token-authed POST → 204 · forwards the agent.hook envelope over stdio (framed JSON-RPC) · unauthenticated POST → 403 · exits when stdin closes (no lingering guest listener).

EADDRINUSE fallback (4/4) — mirrored-networking / collision path: comes up when the port is occupied · stderr breadcrumb port <p> occupied; bound <ephemeral> · rewrites endpoint.env to the fallback port · serves POSTs on the published fallback port.

Gap B fs-bridge / installer channel (6/6) over the real framed stdio: wslfs.home → /root · write/read round-trip inside home · mutation outside home → EACCES · missing file → ENOENT · read-only readdir probe on ancestors of home allowed (the top-down mkdir-p exception) · non-ancestor readdir → EACCES.

⚠️ Minor: manager test not Windows-host-portable (not a product bug, not a CI blocker)

src/main/agent-hooks/wsl-hook-relay-manager.test.ts fails 4/11 when run on a Windows host: the fixture builds the fake guest home from mkdtempSync(join(tmpdir(), …)) → a C:\… path, but the bridge correctly uses posix.resolve() (it runs inside the Linux guest), so posix.resolve('C:\…') becomes relative and mkdir throws EINVAL. CI runs on ubuntu-latest where tmpdir() is /tmp/…, so it's green there and the production path is fine (proven against a real /root guest home above). Optional cleanup: hardcode a POSIX guest-home string (or use an in-memory fs) in the fixture so the suite is runnable on a Windows dev box. The wsl-agent-hook-relay and wsl-orca-env suites pass on Windows.

⏳ Still open — full GUI acceptance

Transport + installer mechanisms are proven end-to-end, but the app-level acceptance (dev Orca → WSL worktree → Claude/Codex → live hook-driven card row + completion notification, restart-resilience, netstat loopback-only posture) is still the remaining step, as the PR notes. Running that next.

OrcaWin avatar Jul 09 '26 18:07 OrcaWin

Manual QA: agent status over WSL (STA-1515)

Tested live on Windows 11 against a real WSL2 Ubuntu distro (NAT networking), using the dev build of this branch. Summary: Step 1 and Step 4 pass. Step 2 fails for both agents, for two distinct, confirmed root causes. Step 3 is inconclusive due to a pre-existing, PR-unrelated tab-restore issue in the shared test environment (details below), but the parts of it that could be verified independent of that confound passed.

Step 1 — Guest-side hook relay + config setup: PASS

Confirmed in a prior pass of this same session: the WSL-side installer places ~/.orca/agent-hooks/{claude,codex}-hook.sh, wires ~/.claude/settings.json hooks, and starts /root/.orca-wsl/hook-relay/wsl-agent-hook-relay.js, which forwards to a Windows-side listener bound to 127.0.0.1.

Step 2 — Live agent run in WSL: FAIL (both agents), two separate confirmed bugs

(a) Claude Code in WSL: hooks fire and reach the relay, but status never renders. Ran a real claude CLI session inside the WSL worktree, sent a real prompt. Confirmed via WSL-side curl tracing that the hook script fires and posts to the relay with HTTP 204 (success) on every lifecycle event (session_start, user_prompt_submit, pre/post_tool_use, stop). Despite that, agentStatusByPaneKey in the renderer store never gets an entry for that pane, and the sidebar/worktree row never shows working/done for that session.

To isolate whether this was a general regression or WSL-specific, I ran a control test: same worktree, same claude CLI, forced to run as a genuine Windows-host (non-WSL) PowerShell terminal via the project's localWindowsRuntimePreference. That session worked flawlessly end-to-end — agentStatusByPaneKey progressed working → done with full metadata (toolName, toolInput, lastAssistantMessage, providerSession/transcriptPath), and the sidebar visibly reflected it. This confirms the general (non-remote) agent-hook → store pipeline is intact and unaffected by this PR; the break is isolated to the WSL-relay ingestion path (ingestRemote / the WSL relay manager wiring) specifically — the hook event apparently never gets attributed to a pane/tab once it arrives over the relay, even though the transport itself succeeds.

(b) Codex in WSL: hooks likely never fire at all, because they're installed to the wrong CODEX_HOME. Root cause found by static code reading (not just inference from a flaky repro):

CodexHookService.installRemote() in src/main/codex/hook-service.ts (lines ~965-1059) hardcodes the install paths relative to the plain, unredirected remote home:

const remoteConfigPath = `${remoteHome.replace(/\/$/, '')}/.codex/hooks.json`
const remoteTomlPath = `${remoteHome.replace(/\/$/, '')}/.codex/config.toml`
const remoteScriptPath = `${remoteHome.replace(/\/$/, '')}/.orca/agent-hooks/codex-hook.sh`

This function is shared by both the pre-existing SSH-remote install path and this PR's new WSL install path — confirmed via src/main/agent-hooks/remote-managed-hook-installers.ts (['codex', (sftp, remoteHome) => codexHookService.installRemote(sftp, remoteHome)]) and src/main/agent-hooks/wsl-hook-relay-deps.ts, which imports installRemoteManagedAgentHooks from that same shared module.

But real Orca-spawned WSL Codex sessions do not use ~/.codex — Orca deliberately redirects CODEX_HOME for WSL Codex sessions to a managed, mirrored home at ~/.local/share/orca/codex-runtime-home/home (confirmed via src/main/codex-accounts/runtime-home-service.ts, src/main/codex/wsl-codex-session-bridge.ts, and the WSL-specific CODEX_HOME rewriting in src/main/daemon/pty-subprocess.ts ~lines 676-725 and src/main/pty/codex-home-wsl-env.ts). I verified this redirection is live: a real WSL terminal's CODEX_HOME (via /proc/<pid>/environ) pointed at the managed runtime home, not ~/.codex.

Net effect: installRemote writes hooks.json/config.toml to ~/.codex/..., but the Codex CLI actually spawned by Orca in WSL reads its config from ~/.local/share/orca/codex-runtime-home/home/.... The hooks are never read by the process that's actually running, so Codex hook events never fire in WSL at all. This fully explains why "Codex shows nothing in WSL" persists after this PR — the relay/UI plumbing this PR adds is fine, but the hook installer for Codex writes to a location Codex-in-WSL never reads.

Step 3 — Restart/reattach check: partially verified, with a caveat

  • Confirmed: the WSL agent process and its daemon-hosted PTY are not relaunched merely because the Orca UI process restarts. I killed only the main Electron process (both via forceful taskkill /F and via a graceful taskkill/WM_CLOSE), leaving Orca's daemon (daemon-entry.js) and its WSL wsl.exe children running. The originally-running claude process (same PID) stayed alive, uninterrupted, across two full app relaunches.
  • Confirmed: the WSL-side relay bootstrap is resilient across restarts — opening a new WSL terminal in the relaunched app automatically spawned a fresh wsl-agent-hook-relay.js process and a fresh loopback-only forwarded port, with no manual reinstall needed.
  • Not conclusively verified: whether the original pre-restart session's live status specifically resumes in the UI after reattach. In this test environment, Orca's tab/session restore-across-relaunch (a real, pre-existing, implemented feature — see src/renderer/src/store/slices/tabs-hydration.ts, src/shared/workspace-session-schema.ts, src/main/persistence.ts) did not restore the prior tabs on relaunch. I confirmed via git diff main...HEAD --stat that this PR does not touch any of that tab-persistence machinery, and I believe this non-restore is an artifact of this test environment running three concurrent dev Orca instances (this worktree plus two unrelated ones) against the same shared orca-dev user-data directory, not a defect in this PR. Separately, even if tabs had restored, Step 2 already shows the WSL Claude status pipeline doesn't populate live regardless of restart, so this specific check is somewhat moot until 2(a) is fixed.

Step 4 — Sanity checks: PASS

  • Port binding: confirmed both WSL-side (ss -ltnp → 127.0.0.1:<port>) and Windows-side (netstat -ano → TCP 127.0.0.1:<port> ... LISTENING) that the relay's forwarded port is loopback-only. Re-verified after restart with a newly-assigned port — same result.
  • Non-WSL control unaffected: a plain Windows-host (non-WSL) PowerShell terminal running Claude Code in the same worktree tracked status correctly end-to-end (see Step 2(a) control test above) — this PR does not regress the existing local agent-status pipeline.

Recommendation

Do not merge as "Codex in WSL now works" — it still won't, because of 2(b). The Claude-in-WSL relay→store gap (2(a)) also needs to be root-caused before this closes out STA-1515's stated goal, since the WSL relay transport succeeding (HTTP 204) was previously assumed to be sufficient evidence of end-to-end correctness but isn't. Both are concrete, file-level findings above, not vague repro flakiness.


Screenshots captured as evidence during this pass (WSL Claude "working" state, WSL Codex exec output, Windows-host control-test "done" state with full sidebar) were not attached here — no compliant attachment mechanism was available in the test environment, and per repo policy PR evidence images must not be committed to the repository.

OrcaWin avatar Jul 09 '26 19:07 OrcaWin

Live GUI acceptance — did NOT pass (two concrete root causes)

Following up on the mechanism validation above with the full app-level acceptance run on Windows 11 + WSL2 (NAT). The transport/installer mechanisms proven in isolation do not yet add up to a working end-to-end path.

  • Step 1 — guest provisioning: PASS. Relay bundle + endpoint.env + WSL-side hook configs all written on opening a WSL worktree.

  • Step 2 — live agent run: FAIL (two distinct causes):

    • Claude Code: hooks fire and reach the relay (HTTP 204), but agentStatusByPaneKey never populates and the sidebar row never updates. A control test (same worktree forced to Windows-host instead of WSL) showed the general hook→store pipeline is intact — isolating the break to the host-side WSL-relay ingestion path (i.e. downstream of the relay forwarding the envelope over stdio, which was separately confirmed working). This is a directional conclusion, not a pinned line — worth confirming before acting.
    • Codex: CodexHookService.installRemote() (src/main/codex/hook-service.ts ~965–1059) hardcodes install paths to ${remoteHome}/.codex/..., but Orca redirects WSL Codex's CODEX_HOME to ~/.local/share/orca/codex-runtime-home/home (src/main/codex-accounts/runtime-home-service.ts, src/main/codex/wsl-codex-session-bridge.ts). Hooks are written where the real Codex process never reads them, so Codex stays dark in WSL even with this PR. High-confidence, most actionable finding.
  • Step 3 — restart resilience: partial. Daemon + live WSL claude PTY survive an Orca restart and the relay reconnects on a new terminal; live UI status resumption couldn't be conclusively confirmed because tab-restore-across-relaunch (pre-existing, untouched by this PR) didn't restore tabs in the shared test env — likely an environment artifact, not a PR defect.

  • Step 4 — posture: PASS. Listener bound 127.0.0.1 only (WSL- and Windows-side, re-checked after restart); non-WSL terminal status unaffected.

Net: the PR's stated acceptance (Codex or Claude in a WSL worktree → live hook-driven row + completion notification) is not met as-is — Codex is broken by a wrong-home install, and Claude's status doesn't reach the store over WSL. Instrumentation was cleaned up and the tree left clean. Screenshots were captured but couldn't be attached (no compliant attach mechanism in this environment).

OrcaWin avatar Jul 09 '26 20:07 OrcaWin

Both validation findings addressed — ready for a re-run (commit 9245852d5)

Thanks for the precise root-causing — both findings were real, and both are now fixed.

2(b) Codex wrong-home install — fixed exactly as diagnosed

CodexHookService.installRemote() now accepts an explicit CODEX_HOME dir (flat layout), and the WSL relay manager passes the managed runtime home (~/.local/share/orca/codex-runtime-home/home, derived from the same shared segment list getWslRuntimeHomePath uses, so the two can't drift). Two subtleties handled:

  • Seed race: the runtime home's config.toml is seeded only-if-absent by the launch path — if the relay created it first (trust entries only), the user's real config would never be seeded. The trust write is therefore deferred while config.toml doesn't exist, and the manager re-runs the byte-equality-idempotent installers on later WSL PTY spawns (30s throttle) to upsert trust once the seed lands. Known consequence: the very first WSL Codex session after a cold relay may still miss hooks; the next one has them.
  • SSH remotes are unchanged (~/.codex, immediate trust write).

2(a) Claude status never reaching the store — hardened + made diagnosable

I could not reproduce a drop in the host chain itself: a new live integration test (wsl-hook-relay-live.integration.test.ts) runs the real esbuild bundle as a real child process over real stdio pipes, through the real manager, into a real AgentHookServer.ingestRemote with the exact Claude POST shape — working and done both land, with connectionId wsl:<distro>. So the break on the rig was in the one thing that test can't cover: the live link's lifetime.

And there was a real blackhole bug there matching your observed signature exactly: if the multiplexer died (protocol error / keepalive timeout) while the guest process stayed alive, the manager stayed running, hook POSTs kept returning 204 (clients are fail-open), and every forwarded envelope silently vanished — indistinguishable from "transport works but store never populates". Fixed:

  • wsl-hook-relay-link.ts: exactly-once link-death handling from either signal (mux dispose or child exit) — breadcrumbed ([agent-hooks] WSL hook relay (<distro>): relay link ... scheduling restart), child killed, and self-restart after a short cooldown (a live agent session produces no new PTY spawns, so waiting for the next ensure would leave status dead for good).
  • ORCA_WSL_HOOK_RELAY_DEBUG=1 now logs every received envelope pre-ingest (WSL relay envelope (<distro>): pane=<paneKey> state=<state>).

Also fixed: the Windows-host test portability you flagged

The fs-backed suites now skip on a Windows dev host with a comment pointing at rig coverage (the bridge is POSIX-by-design), and the manager suite uses a fixed POSIX guest home so it runs everywhere.

Requested re-run

Same acceptance flow as before, plus:

  1. Launch the dev instance with ORCA_WSL_HOOK_RELAY_DEBUG=1 and watch the main-process console.
  2. Claude in a WSL worktree: if the row still doesn't populate, the console now tells us exactly where it died — either WSL relay envelope ... pane=... state=... lines appear (envelopes reach the manager → any drop is inside ingestRemote's validations; paste the pane values) or they don't (link-level issue; the relay link ... scheduling restart breadcrumb + restart behavior is the evidence to capture).
  3. Codex in a WSL worktree: expect hooks at ~/.local/share/orca/codex-runtime-home/home/hooks.json guest-side. Launch Codex once (lets the launch path seed config.toml), then open one more WSL terminal (or wait 30s and spawn one) so the reinstall pass writes the trust entries, then run a second Codex session — that one should report status end-to-end. Confirm ~/.codex/hooks.json is NOT created.
  4. Restart-resilience re-check as before — the relay-restart breadcrumbs should now make its behavior legible even if tab-restore misbehaves in the shared env.

Full context recorded in docs/agent-status-over-wsl.md (§ 2026-07-09 Windows-rig validation follow-ups). Typecheck/lint clean; 1030 tests green across agent-hooks + relay, including the new live chain test.

brennanb2025 avatar Jul 09 '26 20:07 brennanb2025

Manual QA re-run — agent status over WSL (commit 9245852d5)

Environment: Windows 11 + WSL2 (Ubuntu, nat networking), Node ≥18 in guest. Dev instance launched from this worktree with ORCA_WSL_HOOK_RELAY_DEBUG=1. Both Claude Code and Codex CLIs authenticated in the guest against internal dev proxies for this test session.

Step 1 — Setup: PASS

  • wsl.exe wslinfo --networking-mode → nat
  • wsl.exe -l -v → Ubuntu (Running)
  • Node ≥ 18 confirmed in guest

Step 2 — Claude in a WSL worktree: transport FIXED, render-side status still does not surface

  • Launched claude in a WSL-runtime terminal tab in this worktree, confirmed the trust prompt, sent a prompt ("reply with exactly: pong").
  • Main-process debug trace (the fix under test) fired correctly and only once per state — no link-death/restart breadcrumbs occurred, i.e. the host↔guest mux link stayed healthy the whole session:
    [agent-hooks] WSL relay envelope (Ubuntu): pane=0f934536-fa57-490f-9a69-c8cec69f1c4e:c1915058-1292-485b-bc70-eba368de27bf state=working
    [agent-hooks] WSL relay envelope (Ubuntu): pane=0f934536-fa57-490f-9a69-c8cec69f1c4e:c1915058-1292-485b-bc70-eba368de27bf state=done
    
  • Main process did accept and persist the event (ingestRemote succeeded), confirmed via the durable last-status.json cache:
    "0f934536-fa57-490f-9a69-c8cec69f1c4e:c1915058-1292-485b-bc70-eba368de27bf": {
      "connectionId": "wsl:Ubuntu",
      "payload": {"state":"done","agentType":"claude","lastAssistantMessage":"pong", ...}
    }
    
  • However, the sidebar worktree-card status row never showed a live transition, no prompt preview propagated to the row, and no completion notification fired. Verified via the renderer store: agentStatusByPaneKey stayed {} and agentStatusEpoch stayed 0 for the entire session — store.setAgentStatus was never called for this pane.
  • Root cause identified in src/renderer/src/hooks/useIpcEvents.ts (~lines 2987‑2999, function applyAgentStatus). The ownership gate compares the incoming envelope's connectionId against the owning repo's repoConnectionId:
    const canAcceptPendingRemoteOwnership =
      data.connectionId !== undefined && data.connectionId !== null &&
      !repoConnectionResolved && data.worktreeId !== undefined && data.worktreeId === owningWorktreeId
    if (data.connectionId !== undefined && data.connectionId !== repoConnectionId && !canAcceptPendingRemoteOwnership) {
      return 'dropped'
    }
    
    For this worktree, repo.connectionId is null (confirmed live via window.__store) since it's a purely local, non‑SSH repo, and repoConnectionResolved is true (repo is hydrated). The WSL relay stamps events with connectionId: "wsl:Ubuntu" (also confirmed in the persisted cache above). "wsl:Ubuntu" !== null and canAcceptPendingRemoteOwnership is false (short-circuited by !repoConnectionResolved being false) ⇒ every WSL-relayed status update for a local (non-SSH) repo is unconditionally dropped by this renderer-side gate, before store.setAgentStatus or the completion-notification observer ever run. This gate was written for the SSH relay design (docs/design/agent-status-over-ssh.md §5), which never anticipated a local repo receiving a non-null synthetic connectionId from a same-machine WSL relay.
  • Verdict: FAIL on the user-visible acceptance criterion ("worktree-card status row updates live, shows prompt preview, produces completion notification"), for a different reason than the previous run (that one failed at the transport layer; this one fails at the renderer ownership gate, one layer further along). The link-death/self-restart fix itself is verified working.

Step 3 — Codex in a WSL worktree: hook-install fix PASS, same render-side gate applies

  • Cold-launched Codex once in a new WSL terminal (seeds config.toml); by the time of this test the reinstall/trust-write pass had already completed (trust entries for hooks were present in the runtime-home config.toml on the very first session — faster than the two-session dance the protocol anticipated, in this run).
  • Sent a prompt in that same session ("reply with exactly: pong") — Codex replied correctly.
  • Guest-side file check, exactly as required:
    • ~/.local/share/orca/codex-runtime-home/home/hooks.json — exists
    • ~/.codex/hooks.json — does NOT exist (confirmed via ls -la ~/.codex/)
    • This confirms the CODEX_HOME redirect fix is working: hooks are installed only to the managed runtime home Codex actually reads.
  • Main-process trace and persisted cache show the same pattern as Claude:
    [agent-hooks] WSL relay envelope (Ubuntu): pane=cff575e9-...:29632e20-... state=working
    [agent-hooks] WSL relay envelope (Ubuntu): pane=cff575e9-...:29632e20-... state=done
    
    last-status.json entry: agentType: "codex", state: "done", lastAssistantMessage: "pong", transcriptPath correctly pointing at ~/.local/share/orca/codex-runtime-home/home/sessions/....
  • Renderer agentStatusByPaneKey again stayed {} for this pane — same root cause as Step 2 (the connectionId ownership gate is agent-agnostic; it drops any wsl:*-stamped event against a local repo). No sidebar row update, no notification.
  • Verdict: Codex-specific hook-install fix PASS. Live status surfacing FAIL, same root cause as Step 2 (not agent-specific).

Step 4 — Restart resilience: partially verified, environment limitation encountered

  • With the WSL agents from steps 2/3 still running, force-quit the dev Orca main process and relaunched it (same ORCA_DEV_USER_DATA_PATH, ORCA_WSL_HOOK_RELAY_DEBUG=1) to simulate an app restart.
  • (Operational note: the original CDP debug port had a lingering Windows TCP bind that blocked immediate reuse — relaunched on a fresh port; unrelated to the PR.)
  • After relaunch, the app came up cleanly, but the sidebar did not auto-restore the worktree/tabs for this shared dev profile — window.api.worktrees.list(repoId) returned [] even though git worktree list on disk is correct and the tree is clean. This matches the task's own caveat ("capture relay-restart breadcrumbs even if tab-restore misbehaves in this shared env") — this looks like a pre-existing worktree-discovery quirk unrelated to the agent-hooks relay code (the project's repo id is registered against the worktree path itself rather than the parent bare repo), not a regression from this PR.
  • Given the tab/worktree state didn't restore, I could not re-drive a live prompt through the restored UI to capture a fresh relay-restart breadcrumb in this pass. This is an explicit gap — not exercised, flagged rather than silently skipped.
  • Confirmed unrelated to hook-relay correctness: the new instance's agent-hook HTTP listener came back up fine (see Step 5).

Step 5 — Sanity: PASS

  • netstat -ano | findstr 60265 (the new instance's agent-hook HTTP port, from its endpoint.cmd) → bound to 127.0.0.1 only, no 0.0.0.0 exposure.
  • A plain non-WSL PowerShell terminal tab ("Terminal 1") was open throughout steps 2–3 and never showed any status change — consistent with the relay only attaching to WSL-labeled panes; unaffected by design.

Side finding (out of scope for this PR, not acted on — no product code modified)

Repeated main-process error throughout the session for this WSL-runtime worktree:

Error occurred in handler for 'git:upstreamStatus': Error: fatal: not a git repository:
/mnt/c/Users/neil/orca/workspaces/orca/7903/C:/Users/neil/orca/orca/.git/worktrees/7903

This looks like a WSL /mnt/c/... path being concatenated with a Windows C:/... path when computing git upstream status for a WSL-runtime worktree. The same malformed-path pattern also showed up as a Codex project-trust key in the runtime-home config.toml ([projects."/mnt/c/.../7903/C:/Users/neil/orca/orca"]). Likely unrelated to the hook-relay fix itself, but worth a look since it touches the same WSL-runtime-worktree code path.

Summary

Step Result
1. Setup PASS
2. Claude WSL — transport (link-death fix) PASS
2. Claude WSL — live UI status/notification FAIL (renderer connectionId ownership gate drops all WSL-relayed events for local repos)
3. Codex WSL — hook install path (CODEX_HOME fix) PASS
3. Codex WSL — live UI status/notification FAIL (same root cause as above)
4. Restart resilience Not fully exercised — dev-profile tab/worktree restore quirk in this shared environment prevented re-driving a live prompt after restart
5. Sanity (listener binding, non-WSL terminal unaffected) PASS

The two fixes described in the commit message (link-death self-restart, Codex CODEX_HOME redirect) are both verified working at the layer they target. But the end-to-end acceptance bar ("sidebar row updates live, notification fires") still fails for both agents, one layer further downstream, at the renderer's SSH-era connectionId ownership check in useIpcEvents.ts. Recommend gating this PR until that check is updated to recognize wsl:* connection ids as belonging to their local repo (or the WSL relay stops stamping a synthetic connectionId for local repos).


Cleanup: no product code was modified (worktree git status stays clean); all temp instrumentation/screenshots/scratch files were removed; the dev Orca instance and its daemon were shut down at the end of this run. Screenshots taken during this run are not attached here per instructions (text evidence only).

OrcaWin avatar Jul 09 '26 21:07 OrcaWin

Round-2 finding fixed: renderer ownership gate now treats wsl:* as local (commit 4556f2f1a)

Great pinpointing — the trace + last-status.json evidence made this a one-line diagnosis. Exactly as you found: envelopes reached ingestRemote and the durable cache, and the SSH-era gate in useIpcEvents.applyAgentStatus dropped them because "wsl:Ubuntu" !== null.

Fix: wsl:* connection ids are transport provenance, not ownership. The gate now normalizes them to local before the comparison, via a shared-contract predicate (isWslHookRelayConnectionId) that the relay link also uses when stamping — so the two sides can't drift. Deliberately kept the provenance stamp rather than stamping null: it's what made this drop diagnosable at all (your last-status.json check), and the normalized gate still rejects WSL-stamped events against SSH-owned repos (covered by a new test alongside the accept-for-local-repo case; the existing "rejects ssh-1 against a local repo" case still passes).

Renderer suite: 72/72 including the two new gate tests; agent-hooks + relay suites still green; typecheck/lint clean. Doc updated (§ 2026-07-09 follow-ups, item 2).

Requested final re-run (should be the last one)

Same flow — this was the last layer between the relay and the UI:

  1. Claude in a WSL worktree → the sidebar worktree-card row should now transition live (working → done), with prompt preview and a completion notification.
  2. Codex in a WSL worktree → same (your run showed trust entries landed on the first session already, so no two-session dance needed).
  3. If time permits: the restart-resilience pass that the shared-profile tab-restore quirk blocked last time — even just "new WSL terminal after relaunch → fresh relay → send a prompt in a resumed agent → row updates" would close the remaining acceptance gap.

Side finding acknowledged (not addressed here)

The malformed /mnt/c/...<worktree>/C:/Users/... git upstream-status path (also appearing as a Codex project-trust key) is a real WSL-runtime-worktree path-join bug in a different subsystem — agreed it's out of scope for this PR; I'll make sure it gets tracked separately rather than lost.

brennanb2025 avatar Jul 09 '26 21:07 brennanb2025

Pre-rig adversarial review round: 4 independent lenses, all confirmed findings fixed (commit 28537ec9d)

Before requesting another validation round, four independent adversarial reviewers (lifecycle/state-machine, environment-matrix + guest scripts, contracts/consumers, hostile-scenarios + perf) swept the full branch diff. Every confirmed finding is fixed; the next rig run should not rediscover any of these.

The headline (found independently by all four): restart re-coordination was structurally broken

The guest endpoint dir was keyed by the ephemeral Windows hook port — a new port every app launch — so a daemon-surviving agent kept sourcing the dead port-P1/endpoint.env after an Orca restart while the new instance wrote port-P2/. That silently failed the PR's own restart-resume acceptance criterion and regressed the shipped OMP recovery (whose old /p-translated Windows endpoint file WAS restart-stable). Fix: the dir is now keyed by a restart-stable instance key (hash of the Windows endpoint file path — userData + namespace — crossed via ORCA_WSL_HOOK_INSTANCE), so the restarted instance's relay rewrites the same file, which is exactly the re-coordination mechanism the design counts on. This also bounds guest endpoint-dir accumulation to one per instance instead of one per app run.

Lifecycle & recovery

  • Restart chain no longer dies after one failed attempt — every failure arms the restart timer, not just post-connect deaths.
  • Recovery can't resurrect a stopped distro — wsl -d boots a stopped distro, so a user running wsl --shutdown to reclaim vmmem would have had their VM silently rebooted every ~10s, forever. The timer now probes wsl --list --running (which boots nothing) and drops the state when the distro is stopped; the next WSL terminal re-ensures.
  • Crash loops escalate — failure counters reset only after 2 minutes of stable uptime, so a connect-then-die loop backs off to the 10-minute cap instead of a steady 10s spawn cycle.
  • The one unbounded await is gone — the guest install spawn has a 30s timeout + kill; a wedged wsl.exe could previously pin the state machine at 'starting' forever, silently disabling hooks for the distro until app restart.
  • Timer policy extracted to wsl-hook-relay-recovery.ts with direct tests (running → re-ensure, stopped → drop, replaced/disposed → no-op, cancellation).

Guest scripts & multi-instance

  • Version-namespaced install dir — concurrent instances with different bundles (dev + prod on one machine) previously fought a reinstall war over one shared dir, burning escalating cooldowns; each version now owns its dir, tmp files are PID-suffixed.
  • Node resolution probes each candidate — an apt node 12 on PATH no longer masks an nvm node 20 into a false "no node ≥ 18" 10-minute cooldown (last-match-wins + lexical nvm glob both fixed by first-passing-version-wins).
  • WSL_UTF8=1 + NUL-stripped stderr — wsl.exe's UTF-16LE output would have defeated the "Catastrophic failure" transient-retry matcher and mangled every breadcrumb.
  • Spawn command now escaped per the repo's wsl.exe precedent and derived from the shared contract constants.

Smaller confirmed items

Ordered post-sentinel chunk handoff (a rare frame-decoder desync race during relay restarts), the EADDRINUSE-fallback breadcrumb now reaches host logs via the home handshake, a bad wslfs.home reply fails the connect instead of yielding a permanently hookless "running" relay, missing-bundle warn-once (was: one warn per WSL terminal spawn), distro map keys case-normalized (two casings could run two relays), disposeAll wired to app will-quit, and a one-shot 60s reinstall timer so a single-spawn Codex session can't strand its deferred trust entries.

Cleared by review (traced, not assumed)

Persistence round-trip of wsl:* ids through snapshot replay; the full renderer gate case-walk (incl. SSH repos rejecting WSL-stamped events); no other connectionId reader anywhere (renderer/main/mobile/web); guest transcriptPaths fail soft in the vault; codex trust upsert idempotency (probed live, converges by run 2); SSH installers byte-identical; non-WSL platforms proven no-op; endpoint file format compatible with the shipped OMP parser in both directions; healthy-path per-PTY-spawn cost is a map lookup (no subprocess, no per-event spawns).

Accepted gaps (documented in the design doc)

Guest relay per-pane cache count grows for the relay's lifetime (bounded bytes/entry; replay absorbed by main-side suppression); old version dirs accrete across upgrades (~200KB each); OMP curl.exe bridge coexists until validated, then retires; an outdated running daemon /p-translates the guest endpoint path until it restarts (hook scripts fall back to env coords, which same-port binding keeps correct).

Evidence: typecheck/lint clean, 1337 tests green across agent-hooks + relay + pty + renderer suites, including the live host-chain integration test re-run against the rebuilt bundle. Ready for the final rig round — same steps as before; the restart-resilience step (step 3) is now the most valuable one to complete, since the endpoint-identity fix specifically targets it.

brennanb2025 avatar Jul 09 '26 22:07 brennanb2025

Manual QA re-run (round 3) — live GUI acceptance, Windows 11 + WSL2

Tested at HEAD 28537ec9d on branch brennanb2025/sta-1515-wsl-agent-hooks, in a dedicated worktree (C:\Users\neil\orca\workspaces\orca\7903), dev instance launched via config/scripts/run-electron-vite-dev.mjs with ORCA_WSL_HOOK_RELAY_DEBUG=1, CDP-driven verification (playwright-core against the dev instance's remote-debugging port), WSL distro Ubuntu.

Environment caveat (same as prior rounds): no Claude/Codex CLI credentials exist anywhere on this machine (checked guest ~/.claude.json/~/.claude/, Windows-side ~/.claude.json, Windows Credential Manager, ANTHROPIC_API_KEY/CLAUDE_CODE_OAUTH_TOKEN/CODEX_LB_API_KEY env vars, Orca's own claudeManagedAccounts/codexManagedAccounts settings — all empty). Both CLIs fail their actual model calls ("Not logged in" / "Missing environment variable: CODEX_LB_API_KEY"). This does not block validation of the WSL hook-relay pipeline under test — the hook lifecycle (SessionStart/UserPromptSubmit/Stop) fires regardless of API auth outcome, and that lifecycle is exactly what the relay forwards. Genuine "task actually completed successfully" content is out of scope for this environment; state-transition plumbing is fully exercised.

Step 1 — Guest provisioning: PASS

Fresh WSL terminal opened in the worktree. Guest side provisioned:

  • ~/.orca-wsl/hook-relay/0.1.0+03242936dbd3/{launch.sh,wsl-agent-hook-relay.js,.version}
  • ~/.orca-wsl/agent-hooks/instance-5fe16dc04c67/endpoint.env — instance-keyed, not port-keyed, from the very first launch:
    ORCA_AGENT_HOOK_PORT=61521
    ORCA_AGENT_HOOK_TOKEN=4f9ad517-3ccb-448f-95ca-4d4ea1b7600d
    ORCA_AGENT_HOOK_ENV=remote
    ORCA_AGENT_HOOK_VERSION=1
    
    (An old port-55341/ directory from a prior round's pre-fix build is still present alongside it, untouched — historical evidence of the old scheme, not new output of this build.)

Step 2 — Claude in WSL worktree: PASS (with the auth caveat above)

Across 3 prompt cycles (including one post-restart, see Step 4), real working → done transitions were captured both in the console and in the renderer store.

Console breadcrumb (verbatim):

[agent-hooks] WSL relay envelope (Ubuntu): pane=8b078431-2ce2-41b1-9aae-bc0554cf64a9:ffec1839-02e5-4818-8bb4-33540b2dc691 state=working
[agent-hooks] WSL relay envelope (Ubuntu): pane=8b078431-2ce2-41b1-9aae-bc0554cf64a9:ffec1839-02e5-4818-8bb4-33540b2dc691 state=done

Renderer store (window.__store.getState().agentStatusByPaneKey[...]) after a cycle:

{
  "state": "done",
  "prompt": "second test done please",
  "agentType": "claude",
  "paneKey": "8b078431-2ce2-41b1-9aae-bc0554cf64a9:ffec1839-02e5-4818-8bb4-33540b2dc691",
  "worktreeId": "531ce0b8-ae63-4e46-af4e-975c97db28d1::C:\\Users\\neil\\orca\\workspaces\\repro-repo\\qa-wsl-claude-1783639604637",
  "providerSession": { "key": "session_id", "id": "9bf43650-...", "transcriptPath": "/root/.claude/projects/.../9bf43650-....jsonl" }
}

Row in the terminal transcript visibly transitioned "Cooked for 0s" → "Worked for 0s" labels live in the UI (screenshots captured locally, not attached per instructions). A real native Windows toast fired ("Electron — qa-wsl-claude-... — Claude finished") once notifications.suppressWhenFocused was temporarily flipped to false to work around focus-suppression during CDP automation (reverted after capture — settings-only change, no code/file modified).

Step 3 — Codex in WSL worktree: PARTIAL PASS

Guest-side file facts confirmed:

  • ~/.local/share/orca/codex-runtime-home/home/hooks.json exists, with correct hook config (SessionStart/UserPromptSubmit/PreToolUse/PermissionRequest/PostToolUse/Stop → /root/.orca/agent-hooks/codex-hook.sh).
  • ~/.codex/hooks.json does not exist (confirmed via ls, No such file or directory).

Relay correctly forwarded a distinct Codex-originated envelope into the store: agentType: "codex", correct paneKey/worktreeId/transcriptPath, state: "working", live sidebar row update. No done/Stop event was observed for Codex in this run — Codex's CLI never emitted a Stop hook in this particular pre-flight-auth-error path (unlike Claude, which does complete its hook lifecycle even on auth failure). This reads as a Codex CLI behavior difference in this specific failure mode, not a relay bug — the relay faithfully forwarded whatever Codex actually emitted.

Step 4 — Restart resilience: PASS (this is the one that matters)

This is the step both prior rounds could not complete. This run completed it end-to-end:

  1. Pre-restart baseline: guest relay process alive (old PID), Claude (PID 9263) and Codex (PID 51990/52029) alive, instance-5fe16dc04c67/endpoint.env present with port 61521.
  2. Windows-side app quit: identified the exact process tree for this dev instance via Get-CimInstance Win32_Process | Where CommandLine -match '7903' and terminated only the main/gpu/utility/renderer/parcel-watcher processes — explicitly leaving the terminal-host daemon (daemon-entry.js, named pipe orca-terminal-host-v18-ddc624c25b56) running. Verified PID 7460 (an unrelated "nautilus" worktree's Orca instance) was never touched.
  3. Daemon survived the main-process kill (confirmed via Get-CimInstance immediately after), keeping the WSL-hosted PTYs (Claude/Codex processes) alive uninterrupted across the restart — same PIDs before and after.
  4. Relaunch: run-electron-vite-dev.mjs with the same ORCA_WSL_HOOK_RELAY_DEBUG=1. (First relaunch attempt hit a stale-socket bind failure on the original CDP port from the force-kill; relaunched cleanly on a fresh debug port — a test-harness artifact, not a product issue.)
  5. Renderer state restored: tabs and prior agentStatusByPaneKey entries (including the pre-restart Claude done and Codex working states) were present immediately after relaunch — no tab-restore quirk hit this run.
  6. Resumed live status flow: sent a fresh prompt ("post-restart resume check please") to the still-running Claude process. Got a new working → done cycle, captured in console:
    [agent-hooks] WSL relay envelope (Ubuntu): pane=8b078431-2ce2-41b1-9aae-bc0554cf64a9:ffec1839-02e5-4818-8bb4-33540b2dc691 state=working
    [agent-hooks] WSL relay envelope (Ubuntu): pane=8b078431-2ce2-41b1-9aae-bc0554cf64a9:ffec1839-02e5-4818-8bb4-33540b2dc691 state=done
    
    and in the store, with correct stateHistory showing both the pre-restart and post-restart cycles for the same paneKey.
  7. Critical check — instance keying survives restart: guest-side, the relay process itself restarted (new PID, since it's tied to the Windows-side host connection and dies with it — expected), but it wrote to the same instance-keyed directory as before the restart:
    ~/.orca-wsl/agent-hooks/instance-5fe16dc04c67/endpoint.env
    ORCA_AGENT_HOOK_PORT=53088          # new ephemeral port (expected — new listener)
    ORCA_AGENT_HOOK_TOKEN=13e7552e-...  # new token (expected — new session)
    ORCA_AGENT_HOOK_ENV=remote
    ORCA_AGENT_HOOK_VERSION=1
    
    No new port-XXXXX-style directory was created. This is exactly the restart-resume behavior the ORCA_WSL_HOOK_INSTANCE fix targets: the guest endpoint directory is keyed by a stable identity across the Windows-side restart, not re-minted per launch.

Not observed this run: a "relay link ... scheduling restart" log line — this build's full app-quit path goes through the normal provisioning path on next launch rather than an in-process retry-after-link-death path, so that particular log line's absence is expected here, not a gap.

Step 5 — Sanity: PASS / PARTIAL

  • netstat -ano | findstr on the (new, post-restart) relay port: listener is 127.0.0.1 only, owned by the current dev instance's main process PID — no 0.0.0.0 exposure.
    TCP    127.0.0.1:53088        0.0.0.0:0              LISTENING       14368
    
  • Non-WSL terminal regression check: I was not able to get a live non-WSL (PowerShell) terminal through the UI in this session — every worktree in this profile had WSL as its last-used/sticky terminal type, and the composer's "New Terminal" entry followed that per-worktree stickiness rather than the global "Default Shell: PowerShell" setting. In lieu of a live repro, I verified by code inspection that the fix is correctly scoped: isWslHookRelayConnectionId (src/shared/wsl-hook-relay-contract.ts) only matches strings with the wsl: prefix, and in useIpcEvents.ts's applyAgentStatus the normalization (isWslHookRelayConnectionId(data.connectionId) ? null : data.connectionId) is a no-op for any non-wsl: connectionId — local and SSH-owned panes take the exact same path as before this change. Flagging this as the one item not directly observed live; the code-level scoping gives high confidence but it's not the same as a screen-verified regression check.

What was NOT verified

  • Genuine successful agent task completion (real API content) — blocked by missing credentials in this environment, unrelated to the PR.
  • Live UI reproduction of the non-WSL-terminal regression check (Step 5b) — verified by code inspection instead, see above.
  • Codex done/Stop transition and completion notification — Codex didn't emit a Stop hook in the pre-flight-auth-error path exercised here.

Cleanup

Dev instance and daemon fully shut down (verified no 7903-tagged processes remain; unrelated "nautilus" instance, PID 7460, confirmed untouched throughout). WSL guest test processes (Claude/Codex) stopped. All QA instrumentation (tmp-qa/ — screenshots, CDP helper script) removed from the worktree; git status is clean.

Bottom line: the two fixes under test in this build — the renderer ownership-gate normalization for wsl:* connection ids, and the restart-stable instance keying for the guest endpoint directory — both hold up under live GUI testing, including the restart-resilience scenario that blocked the previous two rounds.

OrcaWin avatar Jul 10 '26 00:07 OrcaWin

Round-3 re-run (commit 28537ec9d) — acceptance essentially PASSES; one Codex leg unproven

Third validation pass. The two prior rounds' fixes plus the renderer-gate fix and the restart-hardening all hold up live.

Results

  • Step 1 — provisioning: PASS. Guest dir is instance-keyed (instance-5fe16dc04c67) from first launch, not ephemeral-port-keyed.
  • Step 2 — Claude in WSL: PASS. Real working→done transitions in both the console trace and the renderer store across 3 cycles, plus a native completion toast. The round-2 renderer connectionId-gate fix holds — this is the full feature working live.
  • Step 4 — restart resilience: PASS (the step both prior rounds couldn't complete). Daemon survived the Windows main-process kill across two restarts, WSL PTYs stayed alive with unchanged PIDs, a post-restart prompt produced a fresh working→done, and — critically — the guest endpoint dir reused the same instance key after restart instead of minting a new ephemeral-port dir. The ORCA_WSL_HOOK_INSTANCE fix works as designed.
  • Step 5 — posture: PASS. Listener 127.0.0.1-only. The non-WSL-terminal-unaffected check couldn't be reproduced live (this profile defaulted every worktree to WSL), so it was verified by code inspection: isWslHookRelayConnectionId matches only wsl:-prefixed ids — a no-op for local/SSH panes.

Two soft spots (noting for completeness — neither is a relay defect)

  • Codex — PARTIAL. File facts correct (~/.local/share/orca/codex-runtime-home/home/hooks.json present, ~/.codex/hooks.json absent) and the relay forwarded working, but no done/Stop was observed — the Codex CLI didn't emit a Stop event in this run's auth-error path. So Codex's completion leg isn't proven live, though everything that did fire behaved correctly. Worth a final confirmation on a rig with real Codex credentials.
  • Credentials caveat: no real Claude/Codex credentials exist on this machine, so agents ran auth-limited. The hook relay fires regardless of auth outcome (Claude still produced the full working→done + toast), but a genuine successful task completion wasn't exercisable here.

Bottom line

Transport, install, renderer attribution, and restart resilience are all validated live — the PR's core acceptance criteria are met for Claude, including the restart-resume path that was structurally broken before the hardening round. The single remaining unproven item is Codex's done/completion-notification leg, blocked by the CLI's auth-error path rather than anything in this PR.

Cleanup: no product code modified, git tree clean, dev instance + daemon shut down, temp files removed.

OrcaWin avatar Jul 10 '26 00:07 OrcaWin

Status: acceptance validated — ready for review/merge

With the round-3 pass above, every layer of this PR has now been proven live on the target rig (Windows 11 + WSL2 NAT):

Criterion Status
Guest relay provisioning + WSL-side hook installs ✅ live, instance-keyed from first launch
Claude in a WSL worktree → live working→done row + completion toast ✅ live, 3 cycles
Restart resume over a daemon-surviving PTY (the criterion broken pre-hardening) ✅ live, same instance key reused across two restarts
Loopback-only listener posture ✅ live, re-checked post-restart
Codex hook install into the redirected runtime home ✅ live (file facts + working forwarded)
Codex done/completion leg ⚠️ unproven live — the rig has no real Codex credentials and the CLI's auth-error path emits no Stop event; not a defect in this PR's code paths

The Codex residual is agent-behavioral, not relay/installer behavior — everything that fired behaved correctly, and Claude exercises the identical envelope → ingest → renderer path end-to-end. Suggested follow-up: one authed Codex prompt in a WSL worktree on any machine with real credentials, either pre-merge or as a post-merge check.

Doc status updated in d7e6b711d. Full history: 3 validation rounds + 1 four-lens adversarial review round, all findings fixed on this branch; 1337 tests green.

brennanb2025 avatar Jul 10 '26 00:07 brennanb2025

Round-4 adversarial review — architecture confirmed, confirmed findings fixed (commit 4a47d9c82)

A second adversarial sweep over the full branch, five independent lenses this time: guest relay + fs bridge, host lifecycle state machine, app integration + renderer gate, design-vs-alternatives, and a web fact-check of every WSL platform claim the design leans on. Verdict on "is this the right fix": yes — the guest-resident relay over host-owned stdio is the established shape for this problem, and the zero-per-client-change chokepoint (all 14 hook clients work unmodified, plus every future one) is what the interop-bridge alternative can't match. All 12 platform claims checked out except two nuances, both now acted on (below).

Confirmed findings → fixed

  • dropState identity race (the one real bug). The recovery timer re-checked state identity only before the async wsl --list --running probe; an ensure() landing during the probe could get its fresh state deleted by key — orphaning a live relay child outside the manager's map (unkillable by disposeAll, duplicate relay on the next ensure). Fixed with a post-probe identity re-check (wsl-hook-relay-recovery.ts) plus an identity-guarded delete (wsl-hook-relay-manager.ts). The new regression tests were verified to fail with the fixes reverted.
  • Distro-running probe failed OPEN. Any probe error (including its 10s timeout) reported "running", so recovery could wsl -d — and thereby boot — a distro the user shut down, in exactly the wedged-wsl.exe mode where the probe errors. Now fails closed: drop the state; the next WSL PTY spawn re-ensures.
  • Spawn form hardened to --exec. Fact-check result: wsl.exe -- <cmd> routes through the distro's default login shell (only --exec runs "without using the default Linux shell" per Microsoft's docs), so a fish/nushell chsh could mangle the relay launch. Both relay spawns now use --exec sh -c/-s — argv passes verbatim, the $-escape shim is dropped, matching the existing Codex WSL login spawn form. ⚠️ This is the one behavior change on the rig-validated path — worth a spot-check on the next rig pass (relay provisioning + one working→done cycle is enough).
  • Post-sentinel handoff. Trailing bytes after READY flushed synchronously inside the mux constructor — before the notification handler was registered — so an envelope from a fast-POSTing surviving agent could dispatch to zero handlers (masked today by the replay request). The flush now rides a microtask: after the caller's synchronous wiring, still ahead of any subsequent stdout IO event.
  • Relay process posture. The guest relay now mirrors the SSH relay's uncaughtException (log + exit → manager respawns) / unhandledRejection (log + survive) handlers.
  • Replay cache recency cap. The WSL relay has no per-pane teardown signal (PTYs live host-side), so the per-pane replay cache grew for the relay's lifetime — the previously "accepted gap" is now closed with a 256-pane recency cap (delete-then-set keeps Map order = last-update recency; eviction goes through clearPaneState so the meta map stays in lockstep). Backstop for the SSH relay too.
  • Smaller: launch script derives the stale-exit code from the shared contract constant (was a hardcoded 42 twin), the one-shot reinstall timer refuses to arm after dispose, and the fs-bridge scope comment now states its lexical (symlink-following) bound honestly.

Strategic change: the OMP curl.exe bridge is NOT retired

The fact-check killed the "node is commonly present" assumption: a fresh WSL Ubuntu ships no node, Codex CLI is a native binary that brings none, and Claude Code's native installer no longer implies a system node. A distro running only Codex would hit the no-node cooldown and stay dark — the exact #6907 shape this PR exists to fix. The interop bridge is the one delivery path with no guest runtime requirement, so it stays as the documented no-node fallback (extending it to the shared shell-script builders is the tracked follow-up if no-node distros show up); the relay remains primary (resident, no per-event spawn, interop-independent). Design doc updated (§ round-4).

Cleared by this round (checked, not assumed)

Renderer gate case-walk (wsl:* accepted for local repos, still rejected against SSH-owned repos; connectionId never reaches the store; id prefix spaces provably disjoint), SSH installer path byte-identical, Codex deferred-trust idempotence (byte-equality writes, no mtime churn; runtime-home sync never touches hooks.json), WSLENV flag-by-value-shape logic, EADDRINUSE fallback race-safety, bundle version-hash determinism, fs-bridge unreachable from agent CLIs (stdio-only, never HTTP).

Known low-severity residuals, documented not fixed: native-chat transcript resolution can't follow guest paths (/root/...jsonl) from the Windows host — falls back cleanly to the id-glob, feature-absent not broken; default-distro resolution caches its first answer for the app run.

Evidence

  • New oracles: sentinel unit suite (chunk splits, 64 KiB overflow kill, timeout, microtask handoff ordering), fs-bridge scoping suite (traversal/sibling-prefix/ancestor-probe/errno mapping), fixed-token 403/204 pair, EADDRINUSE endpoint-file rewrite assertion (the re-coordination contract itself), cache-cap recency eviction, and the two race regressions.
  • pnpm typecheck clean; oxlint clean on touched dirs; max-lines ratchet OK; pnpm build:relay → new bundle 0.1.0+10299eb2a697; 1139 tests green across agent-hooks + relay + pty + renderer suites, including the live host-chain integration test against the rebuilt bundle.

Remaining before close-out (unchanged + one addition)

  1. Authed Codex done/Stop leg on a credentialed rig (standing residual from round 3), ideally on a fresh distro to also confirm the deferred trust entries land after Codex seeds config.toml.
  2. Quick rig spot-check of the --exec spawn form (provisioning + one status cycle).

brennanb2025 avatar Jul 10 '26 01:07 brennanb2025

Independent live verification (round 4) — works as designed; Codex done-leg env-blocked, not a defect

Re-verified the acceptance on Windows 11 + WSL2 (Ubuntu, NAT) against a fresh dev build of this branch (relay bundle 0.1.0+03242936dbd3), driving a live WSL terminal via CDP and reading the renderer store + main-process breadcrumbs directly. WSL was wedged at the start (unrelated glab auth status hangs — not a relay spawn loop); wsl --terminate Ubuntu cleared it.

✅ Proven live this session

Layer Evidence
Guest provisioning ~/.orca-wsl/agent-hooks/instance-5fe16dc04c67/endpoint.env written on this launch, reusing the same restart-stable instance key (no new port-* dir)
Transport Guest relay bound 127.0.0.1:63187 in-guest; hook POSTs forwarded over stdio → host manager ([agent-hooks] WSL relay envelope (Ubuntu): … state=working/done)
Claude end-to-end Interactive claude in a WSL terminal → agentStatusByPaneKey reached done with correct prompt, agentType:claude, WSL transcriptPath (/root/.claude/projects/…), stateHistory:[working], and it persisted. The wsl:* renderer-gate fix accepts WSL-stamped events against a local (non-SSH) repo.
Codex CODEX_HOME fix Codex read + fired hooks from ~/.local/share/orca/codex-runtime-home/home/hooks.json (hook: SessionStart / hook: UserPromptSubmit in its own output); ~/.codex/hooks.json absent; working forwarded through the relay
Loopback posture Windows listener 127.0.0.1:63187 only (netstat); guest relay loopback-only (ss)
Relay lifetime On host death, the guest relay process and port 63187 disappeared — no orphaned guest listener
Tests All 7 PR-touched suites green. The only failures in a broad run are in untouched files (installer-utils cmd.exe-caret, managed-hook-timeout Droid) — pre-existing/environmental, PR touches neither their source nor test

⚠️ Codex done/completion leg — blocked by environment, not by this PR

Codex fired its working hooks correctly but exited before any Stop:

hook: SessionStart / SessionStart Completed
hook: UserPromptSubmit / UserPromptSubmit Completed
ERROR: Missing environment variable: `CODEX_LB_API_KEY`.

Two independent blockers on this rig: (1) the dev profile has empty managed accounts, so Orca injects no CODEX_LB_API_KEY; (2) even with the key, the model backend (openclaw:2455 / :31416) is unreachable from the WSL guest under NAT — MagicDNS resolves it to the Tailscale IP but TCP fails (the guest doesn't share the host's Tailscale interface). Either alone prevents a Stop hook. Claude's identical relay→ingest→renderer→done path is fully demonstrated, so the Codex leg would surface done given real creds + a reachable backend — consistent with the "needs a credentialed rig" residual, now with both root causes pinned.

Minor, expected (not defects): claude -p / codex exec clear pane status on process exit (interactive agents persist, which is what real users run); the completion toast doesn't fire while the pane is focused (focus-suppression, same as prior rounds).

Net: transport, guest provisioning, restart-stable instance keying, Codex runtime-home install, the renderer wsl:* gate, and loopback/lifetime posture all hold up live. The one remaining acceptance item is blocked by this machine's environment, not the PR.

Cleanup: dev instance + daemon shut down, WSL un-wedged, git tree clean, all host/guest scratch removed. Screenshots not attached per repo policy (text evidence only).

OrcaWin avatar Jul 10 '26 03:07 OrcaWin

Correction + re-run pinned to 4a47d9c82 (round-4 fixes now validated on-rig)

Good catch on the version — my previous comment validated bundle 0.1.0+03242936dbd3, which is the round-3 bundle. My checkout was at 28537ec9d, two commits behind the branch HEAD; the round-4 guest-relay source changes move the hash. I re-ran pinned to remote HEAD 4a47d9c82 with an explicit pnpm build:relay first.

Pinned re-run — Windows 11 + WSL2 (Ubuntu, NAT)

  • git fetch → fast-forward to 4a47d9c82; no package.json/lockfile changes in the delta, so no reinstall.
  • pnpm build:relay → out/relay/wsl/.version == 0.1.0+10299eb2a697 (the expected round-4 hash). ✅
  • Launched a fresh dev instance on this build, opened a WSL terminal.

Guest picked up the new bundle via the stale-exit reinstall (old 0.1.0+03242936dbd3 dir left in place; new dir installed and launched):

/usr/bin/node /root/.orca-wsl/hook-relay/0.1.0+10299eb2a697/wsl-agent-hook-relay.js

--exec spawn form confirmed live (the specific round-4 change) — captured from the host process table:

wsl.exe -d Ubuntu --exec sh -c "exec sh \"$HOME/.orca-wsl/hook-relay/0.1.0+10299eb2a697/launch.sh\""

--exec (not bare --), $HOME passed verbatim/unescaped — the $-escape shim is gone, matching the diff. The guest install spawn also moved to --exec sh -s.

Claude working→done on the new bundle — one full cycle, fresh prompt to distinguish from restored state:

[agent-hooks] WSL relay envelope (Ubuntu): pane=e9b2d910-…:598120af-… state=working
[agent-hooks] WSL relay envelope (Ubuntu): pane=e9b2d910-…:598120af-… state=done

Renderer store: state=done, prompt="reply with exactly: pong (round4 rerun)", stateHistory=[working], persisted.

Loopback posture (new port 55507): guest LISTEN 127.0.0.1:55507 only; Windows TCP 127.0.0.1:55507 … LISTENING only.

What this covers vs. doesn't

  • ✅ Covered: the --exec spawn-form change, provisioning/stale-exit reinstall to the new version, and a Claude working→done cycle end-to-end on the round-4 bundle.
  • ⚠️ Not directly exercised (defensive, in the running bundle by version): guest uncaughtException/unhandledRejection posture and the 256-pane replay-cache eviction — would need fault injection / 256+ panes to drive, out of scope for a spot-check.
  • The Codex done-leg residual is unchanged (env-blocked: no dev-profile CODEX_LB_API_KEY + backend unreachable from the guest under NAT).

Everything in my prior comment about Claude, posture, lifetime, and the Codex install/root-causes still holds — it just now stands on 4a47d9c82 / 0.1.0+10299eb2a697 rather than the round-3 bundle. Dev instance + daemon shut down, git tree clean, scratch removed.

OrcaWin avatar Jul 10 '26 04:07 OrcaWin