Skip to content

refactor(ipc): split preflight and SSH registry out of the ipcMain modules - #15927

Merged
nwparker merged 22 commits into
mainfrom
nwparker/preflight-ipc-split
Aug 23, 2026
Merged

nwparker merged 22 commits into
mainfrom
nwparker/preflight-ipc-split

Conversation

@nwparker

@nwparker nwparker commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 48 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​163 $\color{#cf222e}{\Huge{\mathbf{−}}}$​9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​154
Prod 44 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1635 $\color{#cf222e}{\Huge{\mathbf{−}}}$​661 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​974

Stacked on #15919 → #15918 → #15916. Review those first.

ELI5

src/main/ipc/preflight.ts did two unrelated jobs in one file: 285 lines of "which agent CLIs are installed on this machine?" and 35 lines of "register those as Electron IPC handlers."

The Orca runtime needs the first job — it calls agent detection during normal operation. But because both lived in one file, importing the detection logic dragged ipcMain (and therefore all of Electron) into the runtime's module graph.

This splits them. Detection moves to src/main/preflight/agent-detection.ts. The IPC file keeps only the handler registration. Nothing behaves differently; the runtime just no longer needs Electron to ask "is Claude Code installed?"

Why this PR exists at all

Round-2 adversarial review overturned the parent design's phasing. I had scheduled the IPC split as "phase 3", independent of building the Node backend. That was wrong: the runtime doesn't merely import ../ipc/*, it calls into it during normal operation — agent detection (orca-runtime.ts:573), watcher coordination, SSH state.

So a Node backend built on the old plan would start, pair, answer host.platform, and then hang ten seconds and fail to open a terminal. The split is a prerequisite, not cleanup. This is the first one.

What changed

src/main/preflight/agent-detection.ts new — the detection logic, named for what it contains (per AGENTS.md, not preflight-utils).
src/main/ipc/preflight.ts 321 → 56 lines. Handler registration only. Re-exports the domain module, so existing importers are untouched.
orca-runtime.ts, rpc/methods/preflight.ts Import the domain module directly — this is what removes ipcMain from the graph.
config/runtime-electron-baseline.txt 36 → 35

The gate did its job

I ran the ratchet from #15919 after the split and it refused to pass:

[runtime-electron-ratchet] 1 module(s) no longer import electron — nice.
Refresh the baseline so the gate keeps its new, tighter floor:
  - src/main/ipc/preflight.ts

That is the designed behaviour: a baseline that doesn't tighten is a gate quietly losing its floor. This PR is also the first real exercise of #15919 against an actual improvement rather than a synthetic regression.

Proof of no regressions

Check Result
Every suite touching preflight (incl. orca-runtime.test.ts) 2 files / 1,187 tests pass
pnpm typecheck (node + web + cli) clean
oxlint (full repo) clean
Ratchet 35 entries, stable

Three test files mocked '../ipc/preflight'; those mocks were repointed at the domain module. No assertion changed — the mocks return the same shapes.

Why behaviour cannot differ: the moved functions are byte-identical; only their file changed. ipc/preflight.ts re-exports everything it previously exported, so any importer not yet repointed still resolves the same symbols.

User-facing trade-offs

None. No UI, wire format, on-disk format, or CLI change.

Review loops

Round Reviewer Outcome
1–2 Grok 4.6 + GPT-5.6-Sol (adversarial, design) Both independently proved the IPC split is a phase-1 prerequisite. This PR is the direct consequence.
3 In progress Convergence check on the revised design.

Verdict: ready to merge, after #15919. Smallest possible instance of the extraction pattern — one file, mechanical, with the number moving to prove it worked.

Follow-ups

ssh.ts (1,805 lines), filesystem-watcher.ts (1,961), pty.ts (8,031) are the remaining depth-1 modules. Those are materially harder: ipcMain.handle there carries event.sender identity, which has no RPC equivalent — see the "ControlChannel withdrawn" box in the design doc.

@nwparker nwparker changed the title refactor(preflight): split agent detection out of the ipcMain registration refactor(ipc): split preflight and SSH registry out of the ipcMain modules Aug 22, 2026
@nwparker

Copy link
Copy Markdown
Contributor Author

Second extraction added: the SSH target registry

This PR now contains two IPC extractions. The second is much bigger than the first.

The runtime needed five thin accessors from src/main/ipc/ssh.ts — connectRegisteredSshTarget, getRegisteredSshState, listRegisteredSshTargets, listRegisteredRemovedSshTargetLabels, getActiveMultiplexer. Every one is a one-line read over module-level state. Importing them dragged in ipcMain, powerMonitor and a BrowserWindow accessor — and transitively ipc/pty.ts, all 8,031 lines of it, which the runtime never imports directly and only ever reached through ipc/ssh.

src/main/ssh/ssh-target-registry.ts now owns that state. registerSshHandlers populates it; the runtime reads it. ipc/ssh.ts re-exports all five so non-test importers are untouched.

The number

baseline
session start 50
after the two port PRs 36
after the preflight split 35
after the SSH split 27

Eight modules dropped in one change: ipc/pty.ts, ipc/ssh.ts, ipc/ssh-browse.ts, ipc/ssh-passphrase.ts, ssh/ssh-relay-deploy.ts, ssh/ssh-remote-cli-host-passthrough.ts, agent-hooks/wsl-hook-relay-launch.ts, persistence/loading-store/user-data-path.ts.

What's left, and why it matters

Of the remaining 27, 15 are the browser cluster (13 × browser/* plus orca-runtime-browser.ts and ipc/browser-tab-registration-wait.ts) — which variant B drops by design. Two more are speech/*. Five are require('electron').app inside a try/catch that already returns null on failure (parcel-watcher-entry-path, session-scanner-service-entry-path, port-scan-command-client, computer/sidecar-client) — they are already Node-safe at runtime and only fail the static text check, so getAppEnvironment().getAppPath() removes them for free.

That leaves roughly seven real couplings for a variant-B orcad: ipc/filesystem-watcher, ipc/plugins, ipc/plugin-marketplaces, jira/authenticated-request + network/proxy-settings (the HttpClient port), and orca-runtime.ts itself.

Behaviour preserved deliberately

connectRegisteredSshTarget still throws ssh_handlers_not_registered when no handler layer has registered. A headless host must fail loudly rather than report a target as unreachable — reporting absence would read as exited, which docs/reference/ssh-execution-boundary.md forbids without positive host evidence.

Verification

9 files / 59 tests across ssh, automations and trust-preset suites; orca-runtime.test.ts 1,183 pass; pnpm typecheck clean; oxlint clean. Full-suite run in progress.

@nwparker

Copy link
Copy Markdown
Contributor Author

The acceptance gate now exists — and it fails when it should

Added config/scripts/runtime-serve-terminal-smoke.mjs (pnpm smoke:serve-terminal).

Both adversarial reviewers independently made the same point: "the server started" proves almost nothing. Terminal creation dispatches into OrcaRuntimeService, and without an installed headless PTY controller that path falls through to a renderer reply that never arrives and times out after ten seconds. A boot probe, a port bind and a host.platform call all pass against a server whose terminals are dead — which is exactly why the design doc's original boot proof was retracted.

This boots the built out/main/index.js --serve, parses its orca_server_ready payload, pairs a real client over the advertised endpoint, lists worktrees, creates a terminal, runs a command through the PTY, asserts the output returns, and asserts clean shutdown.

[serve-terminal-smoke] ready: ws://127.0.0.1:6800
[serve-terminal-smoke] paired client sees 200 worktree(s)
[serve-terminal-smoke] created term_ad0b5554-…
[serve-terminal-smoke] terminal round trip OK
[serve-terminal-smoke] PASS

Verified in both directions. Made to fail by having the command produce no output:

FAIL: terminal produced no output containing ORCA_SMOKE_f8632e08… within 8000ms
— the server started and answered RPC, but its PTY path is dead

That message describes the exact failure the design predicts for a backend with no headless PTY controller. A smoke that cannot fail is worthless, so this was checked rather than assumed.

It drives nothing but the public pairing + RPC surface, so a future Node-only backend must pass it unchanged. The gate exists before the thing it gates.

Also in this PR now

  • orca-runtime.ts reads app paths and the packaged flag through the port (19 sites), and its dead require('electron') in getOrchestrationDb is gone — the precise dynamic-require pattern plain-node-entry-guard.ts exists to catch, sitting in the runtime's own constructor path. Its Electron surface is now three sites: one Notification, one BrowserWindow.fromId, one ipcMain renderer round-trip.
  • getActiveMultiplexer throws when its resolver was never installed. Previously a process that never loaded the SSH layer got undefined from every call — and undefined already means "not connected", so a wiring error and a disconnected target were indistinguishable. That is the unverifiable-reported-as-exited conflation ssh-execution-boundary.md exists to prevent.

@nwparker

Copy link
Copy Markdown
Contributor Author

Round-3 review: two reviewers split, and the dissent was right

Grok returned SETTLED; a second Grok pass returned NOT-SETTLED on one item. The dissent found a real spec gap that both the design and I had missed, and it is now corrected in the doc.

The gap: the design specified PtyHost as the three thunks the options bag already carries — getLocalProvider, getSshProvider, canRecoverPersistentLocalPtys. None of them is the spawn path. terminal.create's background branch calls this.ptyController?.spawn and throws runtime_unavailable without it (orca-runtime.ts:28051). ptyController is set by exactly one production call — runtime?.setPtyController({…}) at src/main/ipc/pty.ts:4538, inside registerPtyHandlers.

So an implementer building the documented port faithfully would get a backend that binds, pairs, answers RPC, and fails every terminal.create. The design would have walked into the exact false-green its own acceptance test exists to catch. Verified against the code before accepting.

The port is now specified as "install a RuntimePtyController", and the real phase-1 work is named: extract that controller from the ~5,500-line registerPtyHandlers closure so it can be built without a window. Today the headless path fakes one (pty.ts:7992-8021, a BrowserWindow with isDestroyed: () => true) — the same stub-window pattern the design rejects elsewhere.

Doc rot both reviewers flagged, now cleared

ControlChannel was withdrawn as a port in round 2 but survived in the live architecture diagram, the §02 API table, an §03 paragraph saying it "is still the right idea", the §08 injection list and the §13 remaining-ports list. An implementer following those would have built the withdrawn thing. All now corrected or marked superseded; the four remaining mentions are withdrawal context only.

Also fixed: phase-1 "done when" is now the terminal round-trip rather than a port bind; NetFetch → HttpClient and no longer claims parity; PowerEvents no longer says "degrades, silent"; stale PR/baseline counts.

Readiness 01 (SSH/network): clean

No P0/P1/P2. Independently verified: the registry split preserves ssh_handlers_not_registered exactly and no caller converts it to target absence; reconnect, ownership, lease, generation-fencing and the live/unverifiable/exited vocabulary are untouched; all 12 guarded plain-Node/worker entries and all 6 relay entries were bundled and confirmed not to reach either throwing host port.

One reviewer raised the resolver ordering hazard I'd flagged — confirmed not reachable: src/main/index.ts:301 statically imports ipc/ssh.ts, installing the resolver before any operation-scoped caller runs. The guard I added stands as defence for future entries.

OSS claims corrected

A second pass against local clones refuted several §09 delivery claims: Zed tries a host-side download first and only falls back to client upload; Coder injects a bootstrap script that downloads the binary, not the binary; DevPod is hybrid via preferDownload; cmux is Go. Current waveterm also carries a machine-readable NoWshCode beside the string — it reached the same conclusion this design did, independently.

@nwparker

Copy link
Copy Markdown
Contributor Author

The fake window is gone

Closing the round-3 blocker's first half. Both reviewers independently named this: registerHeadlessPtyRuntime passed registerPtyHandlers a stub cast to BrowserWindow:

const headlessWindow = {
  isDestroyed: () => true,
  webContents: { send: () => {}, on: () => {}, removeListener: () => {} }
} as unknown as BrowserWindow

A window-shaped object that lied about being a window, purely to satisfy the type — the same "looks fine, silently returns a lie" pattern this design rejects elsewhere, and the thing keeping electron on a path that needs none.

registerPtyHandlers now takes BrowserWindow | null. An absent renderer is semantically identical to a destroyed one — all 42 call sites already guarded on isDestroyed() and skipped — so src/main/ipc/pty-renderer-surface.ts states that in three functions: isRendererGone, sendToRenderer, rendererWebContents. The compound isDestroyed() || webContents.isDestroyed() guards collapse into one predicate.

isPtyWriteEventFromMainWindow becomes null-tolerant and fails closed: with no renderer no sender can legitimately match, so every write is rejected. Those handlers cannot fire headless today, but failing closed is the right answer if that ever changes.

Why this matters

This is the precondition for installing a PTY controller without Electron — which is what a Node-only backend needs and what terminal.create actually calls. It does not finish that job (lifting controller construction out of the registerPtyHandlers closure remains), but it removes the stub that made the job look impossible.

The gate earned its keep

This changes the headless PTY path itself — precisely the code the acceptance smoke exists to protect. Rebuilt and re-ran it:

[serve-terminal-smoke] paired client sees 200 worktree(s)
[serve-terminal-smoke] created term_0b0b3711-…
[serve-terminal-smoke] terminal round trip OK  →  PASS

The built server still boots, pairs, and opens a working terminal with no window object anywhere in the path. That is the check that matters most here, and it is exactly why the gate was written before the thing it gates.

Verified: 129 files / 2,473 tests across ipc/pty, providers and orca-runtime; typecheck and oxlint clean; ratchet unchanged at 25.

@nwparker

Copy link
Copy Markdown
Contributor Author

CI note: shard tests node 24 4/16 failed once on orca-runtime.test.ts > does not keep retrying when every pending row was already pointed (expected 1 to be +0), then passed on rerun.

Classified as flake — but this one needed more than "it's a flake", because that file is touched by this PR, so I checked rather than assumed:

  • Passes 3/3 isolated, 2/2 whole-file, and in a full local suite run (57,146 passed / 0 failed).
  • My diff to that file is exactly three things: retarget vi.mock('../ipc/ssh') → ../ssh/ssh-target-registry, retarget vi.mock('../ipc/preflight') → ../preflight/agent-detection, and install a fake AppEnvironment in the existing reset. None touches timers or the message-repoint scheduler the failing assertion counts.
  • The assertion is a retry-scheduling counter, which is the shape of test that fails under runner contention.
  • CI rerun is green.

Flagging rather than burying it, since "rerun until green" is how real regressions ship.

@nwparker

Copy link
Copy Markdown
Contributor Author

Round-3 blocker closed: the PTY module loads without Electron

verdict3's stated blocker was "the doc never says how orcad installs setPtyController without Electron." It does now, because the code does.

registerPtyHandlers owns the RuntimePtyController that terminal.create actually spawns through — the thing a Node backend needs and cannot get from the provider thunks the design originally specified. The module was otherwise host-agnostic already. The only thing pinning 8,031 lines to Electron was a static ipcMain/powerMonitor import, used purely to register renderer handlers no headless host will ever receive.

src/main/ipc/pty-host-bindings.ts makes those surfaces settable. The desktop installs the real objects before its handlers run; a headless host installs none.

The proof

$ npx esbuild src/main/ipc/pty.ts --bundle --platform=node --format=cjs …
$ grep -c 'require("electron")' bundle.js
0

A Node entry can now call registerPtyHandlers(null, runtime, …) and get a working PTY controller.

One deliberate difference from the other ports

AppEnvironment and SecretStore throw when uninstalled — a missing data path or secret store is a wiring error that must fail loudly. setPtyHostBindings defaults to no-ops instead: a host with no renderer legitimately has nothing to register against, so not registering handlers nobody can call is correct, not a hidden downgrade. Same reasoning, opposite answer, because the situations differ.

A trap oxlint caught

I first left the electron import as inline type specifiers. no-import-type-side-effects flagged that this still leaves a side-effect import at runtime — precisely the "type-only is not enough if esbuild still emits require('electron')" case a reviewer warned about. Converted to a top-level import type; the zero above is measured after that fix.

Verification

128 files / 1,290 tests across ipc/pty and providers; typecheck and oxlint clean; ratchet unchanged at 25.

The acceptance gate passed after every step of this change — which matters more than usual here, because this changes how every PTY handler registers. Boot → pair → terminal.create → sentinel → close, green each time.

@greptile-apps

greptile-apps Bot commented Aug 22, 2026

Copy link
Copy Markdown

Too many files changed for review (118 files, 100 file limit).

Bypass the limit by tagging @greptile-apps to review.

@nwparker
nwparker force-pushed the nwparker/preflight-ipc-split branch from f7c20ff to ac6519f Compare August 22, 2026 17:18
@nwparker
nwparker force-pushed the nwparker/runtime-electron-ratchet branch from 0c3b4c0 to 3bf6460 Compare August 22, 2026 22:33
@nwparker
nwparker force-pushed the nwparker/preflight-ipc-split branch from ac6519f to 3839cdc Compare August 22, 2026 22:33
@nwparker
nwparker force-pushed the nwparker/runtime-electron-ratchet branch from 3bf6460 to 17ab89b Compare August 22, 2026 23:11
@nwparker
nwparker force-pushed the nwparker/preflight-ipc-split branch from 3839cdc to 8c41411 Compare August 22, 2026 23:11
@nwparker
nwparker force-pushed the nwparker/runtime-electron-ratchet branch from 17ab89b to 4c1133a Compare August 22, 2026 23:27
@nwparker
nwparker force-pushed the nwparker/preflight-ipc-split branch from 8c41411 to 178a90a Compare August 22, 2026 23:27
@nwparker

Copy link
Copy Markdown
Contributor Author

@greptile-apps review

This PR exceeded the 100-file limit (118 files) so the automated pass declined it, leaving the largest change in this stack with no automated review. Tagging to request one.

Most of the file count is mechanical: the SSH target registry extraction moves five thin accessors and updates their importers. The parts worth actual scrutiny are src/main/ssh/ssh-target-registry.ts (new module owning state that registerSshHandlers populates and the runtime reads), src/main/ipc/pty-host-bindings.ts, and src/main/ipc/pty-renderer-surface.ts (which replaced a fake BrowserWindow stub whose isDestroyed() returned true with an honest BrowserWindow | null).

@nwparker
nwparker force-pushed the nwparker/runtime-electron-ratchet branch from 4c1133a to bd69e21 Compare August 23, 2026 01:15
@nwparker
nwparker force-pushed the nwparker/preflight-ipc-split branch from 412da10 to 59c5e79 Compare August 23, 2026 01:16
@nwparker
nwparker force-pushed the nwparker/runtime-electron-ratchet branch from bd69e21 to fda832f Compare August 23, 2026 04:13
…ation

First of the IPC extractions the revised design requires. `src/main/ipc/preflight.ts`
mixed 285 lines of agent/tool detection with 35 lines of `ipcMain.handle`
registration, and the runtime calls that detection during normal operation
(`orca-runtime.ts:573`, plus the preflight RPC methods). So the runtime dragged
`ipcMain` into its graph to reach pure logic.

Detection moves to `src/main/preflight/agent-detection.ts` — named for what it
contains, per AGENTS.md. `ipc/preflight.ts` keeps only the handler registration and
re-exports the domain module so existing importers are unaffected. The runtime and
its RPC methods now import the domain module directly.

Ratchet baseline 36 → 35: `src/main/ipc/preflight.ts` is no longer reachable from
the runtime. The gate detected the improvement and refused to pass until the
baseline tightened, which is the behaviour it was built for.

Verified: 2 files / 1,187 tests pass across every suite touching preflight;
`pnpm typecheck` clean; `oxlint` clean.
Second IPC extraction, and by far the biggest win: this removes **eight** modules
from the runtime's Electron graph, taking the ratchet baseline 35 → 27.

The runtime needed five thin accessors from `src/main/ipc/ssh.ts` —
`connectRegisteredSshTarget`, `getRegisteredSshState`, `listRegisteredSshTargets`,
`listRegisteredRemovedSshTargetLabels`, `getActiveMultiplexer`. Each is a one-line
read over module-level state. Importing them dragged in `ipcMain`, `powerMonitor`
and a `BrowserWindow` accessor — and, transitively, `ipc/pty.ts` (8,031 lines),
`ssh-browse`, `ssh-passphrase`, `ssh-relay-deploy`, `ssh-remote-cli-host-passthrough`,
`wsl-hook-relay-launch` and `user-data-path`.

`src/main/ssh/ssh-target-registry.ts` now holds that state plus its accessors.
`registerSshHandlers` populates it; the runtime reads it. The indirection is kept
deliberately: SSH providers register after construction and may reconnect, so
callers must resolve the current generation rather than freeze one.
`ipc/ssh.ts` re-exports all five, so non-test importers are unaffected.

`connectRegisteredSshTarget` still throws `ssh_handlers_not_registered` when no
handler layer registered — a headless host must fail loudly rather than report a
target as unreachable, which would read as `exited` (see ssh-execution-boundary.md).

Verified: 9 files / 59 tests across the ssh, automations and trust-preset suites;
orca-runtime.test.ts 1,183 pass; `pnpm typecheck` clean; `oxlint` clean.
…le modules

`parcel-watcher-entry-path.ts` and `session-scanner-service-entry-path.ts` read the
app root via `require('electron').app` inside a try/catch that already returns null
when Electron is absent. They were therefore correct under plain Node at runtime and
only failed the *static* text check — which is real, not pedantic: the comment in
`ports/port-scan-command-client.ts:19` records that the plain-node-entry-guard fails
on that literal text, try/catch or not.

`hasAppEnvironment() ? getAppEnvironment() : null` gives the identical "no app root
here" answer without the text. That restores `hasAppEnvironment`, which an earlier
commit in this stack deleted as unused — it now has the caller it was waiting for.

Ratchet baseline 27 → 25.

Verified: 74 files / 458 tests; `pnpm typecheck` clean; `oxlint` clean.
Thirty-eight suites mocked `vi.mock('./ssh')` for `getActiveMultiplexer`. That
factory went inert when production started importing the accessor from
`../ssh/ssh-target-registry`, so the real module loaded and the assertions drifted.

Adds a companion registry mock returning the same stub, plus a
`sshTargetRegistryModuleMock` builder beside the existing `sshModuleMock` so the
shared harness stays one place. No assertion changed.

Found by a full-suite run: the targeted ssh/runtime suites were green while
30 tests in ipc/worktrees and ipc/repos were not.
`orca-runtime.ts` is the last module in its own graph that imports `electron`
directly. Nineteen of its uses were `app.getPath` (12) and `app.isPackaged` (7) —
exactly what the AppEnvironment port already covers.

Also removes a dead `const { app } = require('electron')` inside
`getOrchestrationDb`. It was left unused once the path came from the port, and it
is precisely the dynamic-require pattern `plain-node-entry-guard.ts` exists to
catch, sitting in the runtime's own constructor path.

What still binds `orca-runtime.ts` to Electron is now three sites, not nineteen:
`new Notification(...)` (one), `BrowserWindow.fromId` (one), and the
`ipcMain.on('terminal:tabCreateReply')` renderer round-trip — which is the browser
tab path, and the same one that would hang a headless host for ten seconds.

Two suites drove `electronMocks.app.isPackaged` directly; they now install a fake
AppEnvironment reading the same mutable field, so their per-test toggles work
unchanged and no assertion moved.

Verified: 376 files / 4,717 tests across src/main/runtime; typecheck and oxlint clean.
"The server started" proves almost nothing. Terminal creation dispatches into
OrcaRuntimeService, and without an installed headless PTY controller that path
falls through to a renderer reply that never arrives and times out after ten
seconds. A boot probe, a port bind, and a `host.platform` call all pass against a
server whose terminals are dead — which is exactly the gap the design doc's own
boot proof was retracted for.

This boots the BUILT `out/main/index.js --serve`, parses its ready payload, pairs a
real client over the advertised endpoint, lists worktrees, creates a terminal, runs
a command through the PTY, asserts the output comes back, and asserts clean
shutdown. It drives nothing but the public pairing + RPC surface, so the same
script is the acceptance gate a future Node-only backend must pass unchanged.

The sentinel invokes `process.execPath` rather than `echo`, because the shell
differs per platform and node does not.

Verified both directions: passes against the real server, and fails with an
actionable message when the command produces no output — a smoke that cannot fail
is worthless.
`getActiveMultiplexer` resolves through a resolver that `ipc/ssh.ts` installs at
module scope. A process that never loads the SSH layer — which is the whole point
of the Node-only backend — would get `undefined` from every call.

`undefined` already means something specific here: "not connected". So a missing
resolver and a disconnected target were indistinguishable, and a host with no SSH
layer would quietly report every target as not connected. That is the
unverifiable-reported-as-exited conflation `docs/reference/ssh-execution-boundary.md`
exists to prevent — the doc is explicit that absence of contact is never evidence
of absence of the thing.

A missing resolver is a wiring error, not a connection state, so it throws, matching
what `connectRegisteredSshTarget` already does for unregistered handlers.

Verified: 432 files / 4,759 tests across ipc, ssh, preflight, automations and trust
presets; typecheck and oxlint clean.
`registerHeadlessPtyRuntime` passed `registerPtyHandlers` a stub object cast to
`BrowserWindow` whose `isDestroyed()` returned true and whose `webContents.send`
was a no-op — a window-shaped thing that lied about being a window, purely to
satisfy the type. Adversarial review named it as the same "looks fine, silently
returns a lie" pattern this codebase rejects elsewhere, and it is the shape that
keeps `electron` on a path that otherwise needs none.

`registerPtyHandlers` now takes `BrowserWindow | null`. An absent renderer is
semantically identical to a destroyed one — all 42 call sites already guarded on
`isDestroyed()` and skipped — so `src/main/ipc/pty-renderer-surface.ts` states that
directly: `isRendererGone`, `sendToRenderer`, `rendererWebContents`. The compound
`isDestroyed() || webContents.isDestroyed()` guards collapse into one predicate.

`isPtyWriteEventFromMainWindow` becomes null-tolerant and fails closed: with no
renderer no sender can legitimately match, so every write is rejected. Those
handlers cannot fire headless today, but failing closed is the right answer if that
ever changes.

This is the precondition for installing a PTY controller without Electron, which is
what a Node-only backend needs and what `terminal.create` actually calls.

Verified: 129 files / 2,473 tests across ipc/pty, providers and orca-runtime; the
built-artifact acceptance smoke still passes end-to-end (boot → pair →
terminal.create → sentinel → close), which is the check that matters most here
since this changes the headless PTY path itself; typecheck and oxlint clean.
Follows the fake-window removal. `ipc/pty.ts` had nine `app.*` reads — all
`getPath`, `getVersion` or `isPackaged` — which the AppEnvironment port already
covers. The `BrowserWindow` import was also dead after the null-window change.

What still binds this file to Electron is now `ipcMain` (75 uses, all handler
registration) and `powerMonitor` (2). That is a clean statement of the remaining
job: split logic from registration, the same shape already applied to preflight
and the SSH registry.

Test wiring: the shared `pty-ipc-suite-environment` beforeEach installs a fake
AppEnvironment that reads through the existing `vi.mock('electron')` app object
rather than freezing values — suites toggle `app.isPackaged` mid-test to exercise
dev-mode spawn paths, so the port has to observe the same mutable field. One edit
in the shared harness covers every pty suite.

Verified: 128 files / 1,290 tests across ipc/pty and providers; the built-artifact
acceptance smoke passes; typecheck and oxlint clean; ratchet unchanged at 25.
…hout Electron

This closes the round-3 blocker: "the doc never says how orcad installs
setPtyController without Electron."

`registerPtyHandlers` owns the `RuntimePtyController` that `terminal.create`
actually spawns through — the thing a Node backend needs and cannot get from the
provider thunks. The module was otherwise host-agnostic already; the only thing
pinning 8,031 lines to Electron was a static `ipcMain` / `powerMonitor` import used
purely to register renderer handlers that no headless host will ever receive.

`src/main/ipc/pty-host-bindings.ts` makes those surfaces settable, defaulting to
no-ops. Unlike AppEnvironment and SecretStore, the default does NOT throw: a host
with no renderer legitimately has nothing to register against, so not registering
handlers nobody can call is correct rather than a hidden downgrade. The desktop
installs the real objects in `attach-main-window-services` before its handlers run.

Also converts the remaining electron import to a top-level `import type`. oxlint's
`no-import-type-side-effects` caught that inline `type` specifiers still leave a
side-effect import — precisely the "type-only is not enough if esbuild still emits
require('electron')" trap a reviewer flagged.

**`src/main/ipc/pty.ts` now bundles with zero `require("electron")`.** A Node entry
can call `registerPtyHandlers(null, runtime, …)` and get a working PTY controller.

Verified: 128 files / 1,290 tests across ipc/pty and providers; the built-artifact
acceptance smoke passes end-to-end — which is the check that matters, since this
changes how every PTY handler registers; typecheck and oxlint clean.
CI runs oxlint with unused-disable reporting; the two
`@typescript-eslint/no-explicit-any` suppressions I added were never triggered by
any enabled rule, so they failed static analysis as dead directives. The `any[]`
rest args stay — they mirror electron's own IpcMain signature, and narrowing them
would reject the real object at the desktop call site.

Verified with the exact CI invocation: `oxlint --format github` reports 0 warnings,
0 errors across the repo.
…ild gate

**`src/main/runtime/orca-runtime.ts` — 41,048 lines — no longer imports electron.**
Its last three sites go through `runtime-desktop-surface.ts`: a native notification,
the authoritative-window lookup, and the one `ipcMain` channel used by the
renderer-backed tab-create fallback. All three are unreachable without a renderer —
`createTerminal` already takes the background branch when no window exists (#10333) —
so a Node host installs none and the runtime relays notifications to paired clients,
which is the better destination anyway. Ratchet 25 → 24.

Adds `src/main/orcad/orcad-entry.ts`: Node host adapters plus a `startOrcad` that
constructs the runtime, installs the PTY controller via `registerPtyHandlers(null, …)`,
and serves RPC. It sets two defaults the constructor gets wrong for a headless host —
`canRecoverPersistentLocalPtys: false` (no daemon here) and
`getDesktopWindowStatus: 'blocked'` (a Node host can never be promoted to a desktop
window, which is what `'openable'` claims).

Adds `config/scripts/build-orcad.mjs`, which **currently fails, on purpose**: 25
modules still import electron (browser and speech clusters, plugins, jira/proxy,
filesystem-watcher, and four `require('electron').app` one-liners). It names them.

Two bugs found while building it, both worth recording:
- The first bundle looked clean and was not. `electron` was bundleable, so esbuild
  rewrote the metafile `path` to the resolved file under node_modules and a check for
  `path === 'electron'` passed while the package was in the bundle — it failed at
  runtime with electron's own installer message. The check now reads `original`, and
  electron is marked external so a residual import fails loudly instead.
- `jsonc-parser`'s UMD build breaks the bundle at load; aliased to its ESM entry, the
  same fix `build-relay.mjs` already carries.

Verified: desktop unchanged — the built-artifact acceptance smoke passes, runtime/pty/
provider suites green, typecheck clean, `oxlint --format github` 0/0.
`computer/sidecar-client.ts` and `ports/port-scan-command-client.ts` read the app
root through `require('electron').app` inside a try/catch. Both were already correct
under plain Node at runtime — they return null when it throws — but the literal text
fails the plain-Node entry guard regardless, which is why port-scan carried a comment
warning it must never become reachable from a fork entry.

Reading the AppEnvironment port gives the identical "no app root here" answer without
the text, so that warning is now obsolete and the comment says so.

Ratchet 24 → 22. Every remaining entry is a real coupling: the browser cluster (15,
which variant B does not ship), speech (2), plugins (2), and jira/proxy-settings (2,
needing an HttpClient port for Chromium session partitions).

Verified: 25 files / 209 tests; acceptance smoke passes; typecheck and
`oxlint --format github` clean.
The ratchet reports 22 electron importers; the orcad build reports 23. The extra is
agent-hooks/wsl-hook-relay-launch.ts, and the cause is a gap in the gate rather than
a rounding error: the ratchet measures what orca-runtime + runtime-rpc reach, while
orcad's entry also imports ipc/pty directly to install the PTY controller.

Once orcad ships it must become a ratchet entry point, or the two numbers drift and
the gate quietly stops covering the artifact it exists for.
Drops 14 modules from the runtime's Electron graph in one change — the whole Chromium
browser cluster. Ratchet 22 → 8.

`OrcaRuntimeService` constructed `RuntimeBrowserCommands` as a field initializer, and
that construction is what pulled in `BrowserWindow`, `session`, `webContents` and the
cookie jars. Importing the class for its *type* is free; only building it costs.

So the class import becomes `import type`, and the instance comes from
`runtime-browser-commands-factory.ts`. The desktop installs the real factory at the
Electron entry. **All ~80 existing `this.browserCommands.*.bind(...)` delegations are
untouched** — a review round specifically warned that rewriting those was the
expensive, risky part, and this avoids it entirely.

With no factory installed, browser commands reject per call with `browser_unavailable`
rather than resolving to a stub that silently succeeds. The runtime already filters
browser capabilities out of `getStatus()` when no backend exists, so clients do not
offer the affordance in the first place.

Also corrects a stale comment in `pty-renderer-surface.ts` that still described the
fake window as present tense; it was deleted two commits ago.

Verified: 451 files / 5,513 tests across `src/main/browser` and `src/main/runtime` —
the entire browser automation suite; the built-artifact acceptance smoke passes;
`pnpm typecheck` and `oxlint --format github` clean.
Ratchet 8 → 5.

- `listPluginsForClients` moves to `src/main/plugins/plugin-client-list.ts`. It needed
  only three `plugins/*` helpers, none of them Electron — it was colocated with
  `ipcMain.handle` registrations, so the runtime's `plugins.list` RPC dragged all of
  Electron in to call a function that reads a lockfile. Same shape as preflight.
  Dropping it also releases `ipc/plugin-marketplaces.ts`.
- `agent-hooks/wsl-hook-relay-launch.ts` and `speech/stt-service.ts` read `getAppPath`
  and `isPackaged` through the AppEnvironment port.

The five that remain are all genuinely Chromium and need the HttpClient port or a
watcher split, not another mechanical swap: `browser/cdp-bridge` (webContents),
`ipc/filesystem-watcher` (ipcMain), `jira/authenticated-request` and
`network/proxy-settings` (net + session partitions), `speech/model-manager`
(`net.request`, which honors app proxy settings that Node https does not — replacing
it is a behaviour change, not a rename).

Verified: 219 files / 1,922 tests across plugins, speech, agent-hooks and the runtime
RPC methods; the built-artifact acceptance smoke passes; typecheck and
`oxlint --format github` clean.
Ratchet 5 → 4.

`proxy-settings.ts` needed exactly one Electron value: `session.defaultSession`, as
the fallback when a caller does not pass `options.proxySession`. Callers could already
inject a session; only the default was hard-wired. It now comes from a settable
resolver, so the module loads under plain Node.

**A resolver rather than a Session, because a Session eagerly throws.** The first
attempt installed `session.defaultSession` directly in pre-ready bootstrap and broke
startup outright — `TypeError: Session can only be received when app is ready`. The
acceptance smoke caught it before commit. Deferring to first use is always after ready.

Behaviour with no session is not a degradation: there is no Chromium proxy config to
discover, so `resolveProxy` is skipped and the environment variables become the whole
answer rather than a fallback. Applying rules to a session that does not exist is
likewise skipped; settings are still honoured because outbound requests read the env.

This reaches past Jira — a review round noted `ensureElectronProxyFromEnvironment` is
also on the Claude HTTP path via `oauth-refresh.ts` and `rate-limits/claude-fetcher.ts`.

Verified: 48 files / 526 tests across network, jira and rate-limits; the
built-artifact acceptance smoke passes; typecheck and `oxlint --format github` clean.
CI's code-quality lint (`oxlint --config config/oxlint-code-quality-native-plugins.json
--deny-warnings`) flags a module imported twice in one file. My earlier insertion added
a second `./network/proxy-settings` import beside the existing one.

Verified with CI's exact invocation: exit 0.
…of cdp-bridge

Ratchet 4 → 2.

Two unrelated couplings, both of the same shape — a small thing living inside a
Chromium-heavy file.

`BrowserError` is a seven-line error class with no dependencies, but it lived in
`browser/cdp-bridge.ts`, which imports `webContents`. The runtime catches that type on
paths with nothing to do with CDP, so one import kept a Node host from loading the
runtime at all. Moved to `browser/browser-error.ts`; cdp-bridge re-exports it.

`jira/authenticated-request.ts` fetches through `net.fetch` and reads
`session.defaultSession`. `network/http-client.ts` makes both settable. This one is a
**named port rather than a silent fallback, because the fallback is not transparent**:
Electron's net follows Chromium session/proxy state, avoids undici's stale keep-alive
sockets after a VPN path change, and sends a Chrome user agent that Jira's XSRF check
depends on. A Node host gets `globalThis.fetch`, reads proxy config from the
environment, and sends Node's user agent. That difference is documented at the port.

`session.defaultSession` is read per call, not captured at install — it throws before
the app is ready, which is the mistake the previous commit made and the acceptance
smoke caught.

Test wiring: `jira/client.test.ts` installs the port *inside* `loadClientModule`, after
its `vi.resetModules()`, since the reset gives the module a fresh singleton.

Verified: 461 files / 5,616 tests across jira, browser, network and runtime; the
built-artifact acceptance smoke passes; typecheck, `oxlint --format github` and the
code-quality lint with `--deny-warnings` all clean.
… audit

`global-fetch-call-site-audit.test.ts` guards every global-fetch use, because the
global runs on undici where an unread response body can crash the whole process
(orca#8695). The HttpClient port's Node fallback is a new such call site and was
unregistered — the guard caught it in a full-suite run.

Registered with the reasoning, and the port's doc comment now states the body-safety
contract explicitly: it hands the Response straight to its caller and never inspects
it, so the consume/cancel obligation stays exactly where it already was — with the
caller, unchanged from when they called Electron's net directly.

Two comments elsewhere mentioned the global by name and tripped the line scan as false
positives; reworded to describe the behaviour rather than name the API.

Verified: audit passes; typecheck and `oxlint --format github` clean.
@nwparker
nwparker force-pushed the nwparker/preflight-ipc-split branch from 59c5e79 to b6cfd0b Compare August 23, 2026 04:24
@nwparker
nwparker requested a review from brennanb2025 as a code owner August 23, 2026 04:24
@nwparker
nwparker changed the base branch from nwparker/runtime-electron-ratchet to main August 23, 2026 04:24
@nwparker
nwparker merged commit f975035 into main Aug 23, 2026
63 of 78 checks passed
@coderabbitai

coderabbitai Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds a Node 18 Orca runtime bundle, a server-terminal smoke test, and a Node startup entrypoint. It introduces shared application, HTTP, proxy, browser, desktop, PTY, and SSH host abstractions. Electron implementations are installed during startup. PTY registration now supports headless execution with no renderer. SSH and preflight logic move into runtime-accessible modules. Tests and mocks are updated for the new module boundaries.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the scope, rationale, testing, and trade-offs, but it omits the required linked issue and leaves required checklist sections incomplete. Add a valid Fixes #... issue reference, complete or explain the checklist items, and add N/A with a reason under Visual Proof if no visual change exists.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring check was indeterminate for this PR — some files could not be analyzed in time. Not blocking.
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.
Title check ✅ Passed The title clearly identifies the primary refactor: moving preflight and SSH registry logic out of Electron IPC modules.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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: 6

Caution

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

⚠️ Outside diff range comments (1)
src/main/jira/authenticated-request.ts (1)

61-76: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Configure proxy support for the Node fallback.

nodeHttpClient.fetch calls globalThis.fetch without a proxy dispatcher or agent. Node 24 requires NODE_USE_ENV_PROXY=1 or --use-env-proxy for environment proxy support, and this repository enables neither. Configure an EnvHttpProxyAgent or equivalent before httpClient.fetch() so Node-hosted Jira requests use HTTP_PROXY and HTTPS_PROXY.

🧹 Nitpick comments (4)
src/main/ipc/pty-host-bindings.ts (1)

3-20: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reduce the new explanatory comments. Keep only concise comments that record non-obvious constraints. Move design history to documentation if it must remain.

  • src/main/ipc/pty-host-bindings.ts#L3-L20: reduce the module and type-contract explanation to brief non-obvious constraints.
  • src/main/ipc/pty-ipc-test-surface.ts#L9-L13: reduce the factory explanation to one brief contract comment.
  • src/main/ipc/pty-renderer-surface.ts#L3-L15: reduce the headless renderer history to the null-renderer invariant.
  • src/main/ipc/pty-ipc-suite-environment.ts#L96-L104: reduce the test setup explanation to the mutable mock requirement.
  • src/main/ipc/pty.ts#L8007-L8011: reduce the fake-window history to the null-renderer requirement.
  • src/main/ipc/pty-startup-barrier-ordering.test.ts#L14-L15: remove the explanation of the renamed registration surface.
  • src/main/providers/provider-dispatch.test.ts#L86-L87: reduce the setup explanation to the required injected surface.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Source: Coding guidelines

src/main/browser/browser-error.ts (1)

1-8: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the module comment.

Keep one non-obvious sentence about the dependency boundary. Move implementation history to design documentation if it is needed.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line.”

Source: Coding guidelines

src/main/index.ts (1)

883-904: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reduce repeated inline implementation rationale.

Keep only the non-obvious contract at each site. Move detailed history and architecture explanations to focused documentation when they must remain available.

  • src/main/index.ts#L883-L904: reduce each installation comment to its required runtime contract.
  • src/main/host/electron-http-client.ts#L4-L10: reduce the adapter rationale to one concise statement.
  • src/main/network/http-client.ts#L3-L20: retain only the port behavior that callers must know.
  • src/main/network/proxy-settings.ts#L3-L17: retain only the deferred-session constraint.
  • src/main/global-fetch-call-site-audit.test.ts#L30-L33: reduce the audit-entry explanation to one line.
  • src/main/runtime/runtime-browser-commands-factory.ts#L3-L17: retain only the Node-host boundary reason.
  • src/main/runtime/runtime-browser-commands-factory.ts#L31-L35: retain only the rejecting-proxy contract.
  • src/main/runtime/runtime-desktop-surface.ts#L3-L16: retain only the headless fallback contract.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Source: Coding guidelines

src/main/preflight/agent-detection.ts (1)

1-7: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reduce extraction comments to concise, non-obvious rationale. These comments restate behavior that imports and exports already show.

  • src/main/preflight/agent-detection.ts#L1-L7: Remove the module-move narrative or reduce it to one brief reason.
  • src/main/plugins/plugin-client-list.ts#L6-L10: Remove the IPC dependency explanation or reduce it to one brief reason.
  • src/main/ipc/preflight.ts#L15-L17: Remove the import and re-export explanation or reduce it to one brief reason.

As per coding guidelines, comments must be concise, non-obvious, and brief.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9aa33c8d-8bcb-4380-8028-ef6ba447dd5d

📥 Commits

Reviewing files that changed from the base of the PR and between 15fd723 and b6cfd0b.

📒 Files selected for processing (92)
  • config/runtime-electron-baseline.txt
  • config/scripts/build-orcad.mjs
  • config/scripts/runtime-serve-terminal-smoke.mjs
  • package.json
  • src/main/agent-hooks/wsl-hook-relay-launch.ts
  • src/main/ai-vault/session-scanner-service-entry-path.ts
  • src/main/automations/external-manager.test.ts
  • src/main/automations/external-manager.ts
  • src/main/browser/browser-error.ts
  • src/main/browser/cdp-bridge-integration.test.ts
  • src/main/browser/cdp-bridge.ts
  • src/main/computer/sidecar-client.ts
  • src/main/global-fetch-call-site-audit.test.ts
  • src/main/host/electron-browser-commands.ts
  • src/main/host/electron-http-client.ts
  • src/main/host/electron-runtime-desktop-surface.ts
  • src/main/index.ts
  • src/main/ipc/parcel-watcher-entry-path.ts
  • src/main/ipc/plugins.ts
  • src/main/ipc/preflight-remote-ssh.test.ts
  • src/main/ipc/preflight-remote-windows-terminal-capabilities.ts
  • src/main/ipc/preflight.ts
  • src/main/ipc/pty-host-bindings.ts
  • src/main/ipc/pty-ipc-suite-environment.ts
  • src/main/ipc/pty-ipc-test-surface.ts
  • src/main/ipc/pty-renderer-surface.ts
  • src/main/ipc/pty-startup-barrier-ordering.test.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/repos-execution-host-catalog.test.ts
  • src/main/ipc/repos-local-add-and-project-setup.test.ts
  • src/main/ipc/repos-local-clone-lifecycle.test.ts
  • src/main/ipc/repos-nested-import.test.ts
  • src/main/ipc/repos-nested-scan.test.ts
  • src/main/ipc/repos-remote-base-ref-queries.test.ts
  • src/main/ipc/repos-remote-git-username.test.ts
  • src/main/ipc/repos-remote.test.ts
  • src/main/ipc/ssh-worktree-create-root-registration.ts
  • src/main/ipc/ssh.ts
  • src/main/ipc/worktrees-create-metadata-persistence.test.ts
  • src/main/ipc/worktrees-delete-pty-teardown.test.ts
  • src/main/ipc/worktrees-detected-scan-cache.test.ts
  • src/main/ipc/worktrees-discovery-metadata-backfill.test.ts
  • src/main/ipc/worktrees-existing-branch-checkout.test.ts
  • src/main/ipc/worktrees-forget-local.test.ts
  • src/main/ipc/worktrees-issue-command-overrides.test.ts
  • src/main/ipc/worktrees-lineage-hydration.test.ts
  • src/main/ipc/worktrees-listing-fallback-rows.test.ts
  • src/main/ipc/worktrees-local-base-ref-resolution.test.ts
  • src/main/ipc/worktrees-local-create-flow.test.ts
  • src/main/ipc/worktrees-orphan-directory-cleanup.test.ts
  • src/main/ipc/worktrees-preserved-branch-fork-remote.test.ts
  • src/main/ipc/worktrees-removal-recovery.test.ts
  • src/main/ipc/worktrees-remove-archive-hooks.test.ts
  • src/main/ipc/worktrees-remove-host-disambiguation.test.ts
  • src/main/ipc/worktrees-remove-preflight.test.ts
  • src/main/ipc/worktrees-setup-launch-sparse-checkout.test.ts
  • src/main/ipc/worktrees-ssh-base-ref-resolution.test.ts
  • src/main/ipc/worktrees-ssh-branch-conflict-suffixing.test.ts
  • src/main/ipc/worktrees-ssh-create-base-prefetch.test.ts
  • src/main/ipc/worktrees-ssh-fork-push-target-remote.test.ts
  • src/main/ipc/worktrees-ssh-local-base-refresh.test.ts
  • src/main/ipc/worktrees-ssh-pr-head-fetch.test.ts
  • src/main/ipc/worktrees-ssh-provider-authority.test.ts
  • src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts
  • src/main/ipc/worktrees-ssh-setup-launch.test.ts
  • src/main/ipc/worktrees-test-module-mocks.ts
  • src/main/ipc/worktrees-wsl-runtime-routing.test.ts
  • src/main/jira/authenticated-request.ts
  • src/main/jira/client.test.ts
  • src/main/network/http-client.ts
  • src/main/network/proxy-settings.ts
  • src/main/orcad/orcad-entry.ts
  • src/main/plugins/plugin-client-list.ts
  • src/main/ports/port-scan-command-client.ts
  • src/main/preflight/agent-detection.ts
  • src/main/providers/provider-dispatch.test.ts
  • src/main/remote-agent-trust-presets.test.ts
  • src/main/remote-agent-trust-presets.ts
  • src/main/runtime/orca-runtime-agent-skill-share.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/client-events.ts
  • src/main/runtime/rpc/methods/plugins.ts
  • src/main/runtime/rpc/methods/preflight.test.ts
  • src/main/runtime/rpc/methods/preflight.ts
  • src/main/runtime/rpc/methods/ssh.test.ts
  • src/main/runtime/rpc/methods/ssh.ts
  • src/main/runtime/runtime-browser-commands-factory.ts
  • src/main/runtime/runtime-desktop-surface.ts
  • src/main/speech/stt-service.ts
  • src/main/ssh/ssh-target-registry.ts
  • src/shared/app-environment.ts
💤 Files with no reviewable changes (1)
  • config/runtime-electron-baseline.txt

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

Comment on lines +34 to +35
// Why a random high port: a fixed one collides with a developer's own `orca serve`.
const PORT = 6800 + Math.floor(Number(process.env.ORCA_SMOKE_PORT_OFFSET ?? '0'))

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Allocate a non-conflicting smoke-test port.

The default value is always port 6800. It is not random. A local server or concurrent CI job can make the acceptance test fail before readiness. Allocate a unique port, or bind port 0 if the serve entry supports it.

Comment on lines +48 to +53
const result = spawnSync('orca', [...args, '--pairing-code', pairingCode, '--json'], {
encoding: 'utf8',
// Why not shell:true — argument encoding is handled by spawnSync; a shell would
// re-split the pairing code, which is base64url and can contain '='.
shell: false
})

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

file="config/scripts/runtime-serve-terminal-smoke.mjs"
printf '%s\n' "== file outline =="
ast-grep outline "$file" --view compact || true
printf '%s\n' "== target file =="
cat -n "$file"
printf '%s\n' "== related symbols and cleanup/port usage =="
rg -n -C 4 'spawnSync|function orca|finally|mkdtemp|rmSync|kill|6800|PORT|offset|serve' config/scripts "$file" || true

Repository: stablyai/orca

Length of output: 50372


🏁 Script executed:

#!/bin/bash
set -eu

file="config/scripts/runtime-serve-terminal-smoke.mjs"
printf '%s\n' "== target file size =="
wc -l "$file"
printf '%s\n' "== target file lines 1-180 =="
sed -n '1,180p' "$file"
printf '%s\n' "== exact target-file references =="
rg -n -C 3 'runtime-serve-terminal-smoke|spawnSync|function orca|finally|mkdtemp|rmSync|kill|6800|port|offset' "$file"
printf '%s\n' "== tests referring to this script =="
rg -n -C 5 'runtime-serve-terminal-smoke' config/scripts .github package.json 2>/dev/null || true

Repository: stablyai/orca

Length of output: 11233


🏁 Script executed:

#!/bin/bash
set -eu

file="config/scripts/runtime-serve-terminal-smoke.mjs"
printf '%s\n' "== target file lines 180-216 =="
sed -n '180,216p' "$file"

printf '%s\n' "== timeout-related tests and conventions =="
rg -n -C 4 'timeout:\s*[A-Z0-9_]+|spawnSync\(.*timeout|ETIMEDOUT|did not exit within|OUTPUT_TIMEOUT_MS|SHUTDOWN_TIMEOUT_MS' config/scripts --glob '*.mjs' --glob '*.test.mjs' | head -n 240 || true

printf '%s\n' "== standalone spawnSync timeout behavior =="
node - <<'JS'
const { spawnSync } = require('node:child_process')
const result = spawnSync(process.execPath, ['-e', 'setTimeout(() => {}, 60000)'], {
  encoding: 'utf8',
  timeout: 50
})
console.log(JSON.stringify({
  status: result.status,
  signal: result.signal,
  errorCode: result.error?.code,
  errorMessage: result.error?.message,
  stdout: result.stdout,
  stderr: result.stderr
}))
JS

Repository: stablyai/orca

Length of output: 20284


Bound each orca CLI invocation.

spawnSync() has no timeout. A blocked call prevents main() from reaching finally, leaving the server and temporary directory until the job timeout. Add a timeout and let result.error reach the existing failure path.

Comment thread src/main/ipc/ssh.ts
Comment on lines +41 to +43
setSshActiveMultiplexerResolver(
(connectionId) => activeSessions.get(connectionId)?.getMux() ?? undefined
)

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

rg -n \
  "setSshActiveMultiplexerResolver|getActiveMultiplexer|ssh-target-registry|ipc/ssh" \
  src/main/ssh/ssh-target-registry.ts \
  src/main/ipc/ssh.ts \
  src/main/preflight/agent-detection.ts \
  src/main/runtime/rpc/methods/ssh.ts \
  src/main/ipc/ssh-worktree-create-root-registration.ts \
  src/main/remote-agent-trust-presets.ts

rg -n \
  "registerSshHandlers|from ['\"].*ipc/ssh|import\\(['\"].*ipc/ssh" \
  src/main

Repository: stablyai/orca

Length of output: 6299


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- registry ---'
sed -n '1,115p' src/main/ssh/ssh-target-registry.ts

printf '%s\n' '--- ipc bootstrap ---'
sed -n '25,60p' src/main/ipc/ssh.ts
sed -n '940,980p' src/main/ipc/ssh.ts

printf '%s\n' '--- direct consumers ---'
sed -n '1,35p' src/main/preflight/agent-detection.ts
sed -n '190,220p' src/main/preflight/agent-detection.ts
sed -n '1,35p' src/main/runtime/rpc/methods/ssh.ts
sed -n '1,55p' src/main/remote-agent-trust-presets.ts
sed -n '1,60p' src/main/ipc/ssh-worktree-create-root-registration.ts

printf '%s\n' '--- main entrypoint imports and calls ---'
sed -n '1,35p' src/main/index.ts
sed -n '290,330p' src/main/index.ts
rg -n -C 3 "agent-detection|remote-agent-trust-presets|ssh-worktree-create-root-registration|runtime/rpc/methods/ssh|registerSshHandlers|from ['\"].*(ipc/ssh|preflight|runtime/rpc)" src/main --glob '!**/*.test.*'

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- runtime-related files ---'
git ls-files src | rg '(^|/)(runtime|index|entry|host|preflight)/|runtime'

printf '%s\n' '--- SSH method registration and runtime construction ---'
rg -n -C 4 \
  "SSH_METHODS|methods/index|create.*Runtime|new OrcaRuntimeService|RpcDispatcher|register.*Rpc|dispatchRpc|runtime.*entry|entry.*runtime" \
  src/main --glob '!**/*.test.*' --glob '*.ts' --glob '*.tsx'

printf '%s\n' '--- every non-test resolver installer and registry import ---'
rg -n \
  "setSshActiveMultiplexerResolver|getActiveMultiplexer|from ['\"].*ssh-target-registry['\"]|from ['\"].*ipc/ssh['\"]" \
  src --glob '!**/*.test.*'

printf '%s\n' '--- package and build entry configuration ---'
rg -n -C 3 \
  '"(main|module|入口|entry)"|electron-vite|src/main/index|runtime' \
  package.json electron.vite.config.* vite.config.* tsconfig*.json 2>/dev/null || true

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- candidate entrypoints ---'
git ls-files | rg -v '(^|/)(node_modules|dist|build|.*\.test\.)' \
  | rg '(^|/)(runtime|entry|index)([^/]*)?(\.|/)|runtime' \
  | head -200

printf '%s\n' '--- RPC method graph ---'
sed -n '1,100p' src/main/runtime/rpc/methods/index.ts
rg -n -C 3 \
  "runtime/rpc/methods|methods/index|SSH_METHODS|createRpc|RpcDispatcher|dispatch" \
  src/main --glob '*.ts' --glob '!**/*.test.ts' \
  | head -300

printf '%s\n' '--- exact SSH resolver references ---'
rg -n \
  "setSshActiveMultiplexerResolver|getActiveMultiplexer|ssh-target-registry|ipc/ssh" \
  src/main --glob '*.ts' --glob '!**/*.test.ts' \
  | head -300

printf '%s\n' '--- package entry fields ---'
python3 - <<'PY'
import json
from pathlib import Path
p = Path("package.json")
if p.exists():
    data = json.loads(p.read_text())
    for key in ("main", "module", "bin", "scripts"):
        if key in data:
            print(f"{key}: {data[key]}")
PY

Repository: stablyai/orca

Length of output: 10599


🏁 Script executed:

#!/usr/bin/env bash
set -u

printf '%s\n' '--- exact resolver references ---'
rg -n \
  "setSshActiveMultiplexerResolver|getActiveMultiplexer|ssh-target-registry|from ['\"].*ipc/ssh['\"]" \
  src/main --glob '*.ts' --glob '!**/*.test.ts' \
  || true

printf '%s\n' '--- RPC method registration ---'
rg -n -C 3 \
  "SSH_METHODS|methods/index|register.*Rpc|RpcDispatcher|dispatchRpc" \
  src/main/runtime src/main/ipc src/main/index.ts \
  --glob '*.ts' --glob '!**/*.test.ts' \
  || true

printf '%s\n' '--- likely runtime host files ---'
for f in src/main/ipc/runtime.ts src/main/runtime/rpc/methods/index.ts src/main/runtime/rpc/dispatcher.ts src/main/runtime/orca-runtime.ts; do
  if [ -f "$f" ]; then
    printf '%s\n' "--- $f ---"
    wc -l "$f"
    sed -n '1,80p' "$f"
  fi
done

printf '%s\n' '--- package entry fields ---'
python3 - <<'PY'
import json
from pathlib import Path
p = Path("package.json")
if p.exists():
    data = json.loads(p.read_text())
    for key in ("main", "module", "bin", "scripts"):
        if key in data:
            print(f"{key}: {data[key]}")
PY

Repository: stablyai/orca

Length of output: 45691


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- runtime server construction and startup ---'
rg -n -C 5 \
  "OrcaRuntimeRpcServer|runtime-rpc|registerRuntimeHandlers|new OrcaRuntimeService|start.*Runtime|serve.*Runtime|run.*Runtime" \
  src/main config/scripts tests \
  --glob '*.ts' --glob '*.tsx' --glob '*.mjs' --glob '*.cjs' \
  --glob '!**/*.test.*' \
  | head -400 || true

printf '%s\n' '--- direct main-runtime imports outside tests ---'
rg -n \
  "from ['\"].*src/main|from ['\"].*main/|from ['\"].*\.\./main|from ['\"].*\.\./\.\./main" \
  src/cli config/scripts tests \
  --glob '*.ts' --glob '*.tsx' --glob '*.mjs' --glob '*.cjs' \
  --glob '!**/*.test.*' \
  | head -300 || true

printf '%s\n' '--- runtime RPC server file ---'
sed -n '1,35p' src/main/runtime/runtime-rpc.ts
sed -n '470,620p' src/main/runtime/runtime-rpc.ts

printf '%s\n' '--- relevant non-test script imports ---'
for f in config/scripts/run-nested-runtime-ssh-e2e.mjs \
         config/scripts/runtime-serve-terminal-smoke.mjs \
         config/scripts/smoke-managed-hook-runtime-node18.mjs; do
  if [ -f "$f" ]; then
    printf '%s\n' "--- $f ---"
    sed -n '1,100p' "$f"
  fi
done

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- serve mode and main runtime startup ---'
rg -n -C 6 -- "--serve|serveMode|OrcaRuntimeRpcServer|\.start\(\)" \
  src/main/index.ts src/main/runtime/runtime-rpc.ts src/main \
  --glob '*.ts' --glob '!**/*.test.ts' \
  | head -350 || true

printf '%s\n' '--- runtime graph audit entrypoints ---'
sed -n '25,75p' config/scripts/check-runtime-electron-ratchet.mjs
rg -n -C 5 \
  "orca-runtime\.ts|runtime-rpc\.ts|runtime-rpc|out/main/index|electron-vite" \
  config electron.vite.config.* vite.config.* package.json \
  --glob '*.mjs' --glob '*.cjs' --glob '*.json' --glob '*.ts' \
  | head -250 || true

printf '%s\n' '--- runtime RPC method call sites ---'
rg -n -C 4 \
  "new RpcDispatcher|new OrcaRuntimeRpcServer|ALL_RPC_METHODS|SSH_METHODS" \
  src/main src/cli config/scripts \
  --glob '*.ts' --glob '*.tsx' --glob '*.mjs' --glob '*.cjs' \
  --glob '!**/*.test.*' \
  | head -350 || true

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re
from collections import deque

ROOT = Path(".")
entries = [
    Path("src/main/index.ts"),
    Path("src/main/runtime/runtime-rpc.ts"),
]
pattern = re.compile(r"""(?:import|export)\s+(?:[\s\S]*?\s+from\s+)?['"](\.{1,2}/[^'"]+)['"]""")

def resolve(source, spec):
    base = (source.parent / spec).resolve()
    candidates = [base, Path(str(base) + ".ts"), Path(str(base) + ".tsx"),
                  Path(str(base) + ".js"), Path(str(base) + ".mjs"),
                  base / "index.ts", base / "index.js"]
    for candidate in candidates:
        if candidate.is_file():
            return candidate.relative_to(ROOT)
    return None

def graph(entry):
    seen, queue = set(), deque([entry])
    while queue:
        current = queue.popleft()
        if current in seen:
            continue
        seen.add(current)
        text = current.read_text(errors="ignore")
        for spec in pattern.findall(text):
            target = resolve(current, spec)
            if target and target not in seen:
                queue.append(target)
    return seen

for entry in entries:
    reachable = graph(entry)
    print(f"{entry}:")
    print(f"  reaches src/main/ipc/ssh.ts: {Path('src/main/ipc/ssh.ts') in reachable}")
    print(f"  reaches src/main/ssh/ssh-target-registry.ts: {Path('src/main/ssh/ssh-target-registry.ts') in reachable}")
    direct_callers = sorted(
        str(path) for path in reachable
        if path.suffix in {".ts", ".tsx"} and "getActiveMultiplexer(" in path.read_text(errors="ignore")
    )
    print("  reachable getActiveMultiplexer callers:")
    for path in direct_callers:
        print(f"    {path}")
PY

Repository: stablyai/orca

Length of output: 572


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re
from collections import deque

ROOT = Path.cwd().resolve()
entries = [
    ROOT / "src/main/index.ts",
    ROOT / "src/main/runtime/runtime-rpc.ts",
]
pattern = re.compile(r"""(?:import|export)\s+(?:[\s\S]*?\s+from\s+)?['"](\.{1,2}/[^'"]+)['"]""")

def resolve(source, spec):
    base = (source.parent / spec).resolve()
    candidates = [
        base, Path(str(base) + ".ts"), Path(str(base) + ".tsx"),
        Path(str(base) + ".js"), Path(str(base) + ".mjs"),
        base / "index.ts", base / "index.js",
    ]
    for candidate in candidates:
        if candidate.is_file():
            return candidate
    return None

def graph(entry):
    seen, queue = set(), deque([entry])
    while queue:
        current = queue.popleft()
        if current in seen:
            continue
        seen.add(current)
        for spec in pattern.findall(current.read_text(errors="ignore")):
            target = resolve(current, spec)
            if target and target not in seen:
                queue.append(target)
    return seen

for entry in entries:
    reachable = graph(entry)
    print(f"{entry.relative_to(ROOT)}:")
    print(f"  reaches src/main/ipc/ssh.ts: {ROOT / 'src/main/ipc/ssh.ts' in reachable}")
    print(f"  reaches src/main/ssh/ssh-target-registry.ts: {ROOT / 'src/main/ssh/ssh-target-registry.ts' in reachable}")
    callers = sorted(
        path.relative_to(ROOT) for path in reachable
        if path.suffix in {".ts", ".tsx"}
        and "getActiveMultiplexer(" in path.read_text(errors="ignore")
    )
    print("  reachable getActiveMultiplexer callers:")
    for path in callers:
        print(f"    {path}")
PY

Repository: stablyai/orca

Length of output: 1174


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re
from collections import deque

ROOT = Path.cwd().resolve()
entries = {
    "main": ROOT / "src/main/index.ts",
    "runtime-rpc": ROOT / "src/main/runtime/runtime-rpc.ts",
}
import_re = re.compile(
    r"""(?ms)^\s*import\s+(?P<clause>(?:(?!^\s*import\b).)*?)\s+from\s+['"](?P<spec>\.{1,2}/[^'"]+)['"]"""
)

def resolve(source, spec):
    base = (source.parent / spec).resolve()
    for candidate in (
        base, Path(str(base) + ".ts"), Path(str(base) + ".tsx"),
        Path(str(base) + ".js"), Path(str(base) + ".mjs"),
        base / "index.ts", base / "index.js",
    ):
        if candidate.is_file():
            return candidate
    return None

def imports(source):
    text = source.read_text(errors="ignore")
    for match in import_re.finditer(text):
        target = resolve(source, match.group("spec"))
        if target:
            yield target, match.group("clause").strip()

def shortest_path(entry, wanted):
    queue = deque([(entry, [entry])])
    seen = {entry}
    while queue:
        current, path = queue.popleft()
        for target, clause in imports(current):
            if target == wanted:
                return path + [target], clause
            if target not in seen:
                seen.add(target)
                queue.append((target, path + [target]))
    return None, None

wanted = ROOT / "src/main/ipc/ssh.ts"
for name, entry in entries.items():
    path, clause = shortest_path(entry, wanted)
    print(f"{name} -> src/main/ipc/ssh.ts:")
    if not path:
        print("  unreachable through parsed static imports")
        continue
    for item in path:
        print(f"  {item.relative_to(ROOT)}")
    print(f"  importing clause: {clause!r}")
PY

Repository: stablyai/orca

Length of output: 518


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- transitive bootstrap path ---'
sed -n '1,35p' src/main/automations/precheck-runner.ts
rg -n -C 3 \
  "automations/service|precheck-runner|getSshConnectionManager|from ['\"].*ipc/ssh['\"]" \
  src/main/automations/service.ts src/main/runtime/orca-runtime.ts

printf '%s\n' '--- runtime-only entry reachability ---'
python3 - <<'PY'
from pathlib import Path
import re
from collections import deque

ROOT = Path.cwd().resolve()
entries = [
    ROOT / "src/main/runtime/orca-runtime.ts",
    ROOT / "src/main/runtime/runtime-rpc.ts",
]
wanted = ROOT / "src/main/ipc/ssh.ts"
pattern = re.compile(
    r"""(?ms)^\s*import\s+(?P<clause>(?:(?!^\s*import\b).)*?)\s+from\s+['"](?P<spec>\.{1,2}/[^'"]+)['"]"""
)

def resolve(source, spec):
    base = (source.parent / spec).resolve()
    for candidate in (
        base, Path(str(base) + ".ts"), Path(str(base) + ".tsx"),
        Path(str(base) + ".js"), Path(str(base) + ".mjs"),
        base / "index.ts", base / "index.js",
    ):
        if candidate.is_file():
            return candidate
    return None

def imports(source):
    for match in pattern.finditer(source.read_text(errors="ignore")):
        target = resolve(source, match.group("spec"))
        if target:
            yield target, match.group("clause").strip()

for entry in entries:
    queue = deque([(entry, [entry])])
    seen = {entry}
    result = None
    while queue:
        current, path = queue.popleft()
        for target, clause in imports(current):
            if target == wanted:
                result = (path + [target], clause)
                queue.clear()
                break
            if target not in seen:
                seen.add(target)
                queue.append((target, path + [target]))
    print(f"{entry.relative_to(ROOT)}:")
    if result:
        path, clause = result
        print("  " + " -> ".join(str(p.relative_to(ROOT)) for p in path))
        print(f"  clause: {clause}")
    else:
        print("  no static path to src/main/ipc/ssh.ts")
PY

Repository: stablyai/orca

Length of output: 3091


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re
from collections import deque

ROOT = Path.cwd().resolve()
entries = [
    ROOT / "src/main/runtime/orca-runtime.ts",
    ROOT / "src/main/runtime/runtime-rpc.ts",
]
wanted = ROOT / "src/main/ipc/ssh.ts"
pattern = re.compile(
    r"""(?ms)^\s*import\s+(?P<clause>(?:(?!^\s*import\b).)*?)\s+from\s+['"](?P<spec>\.{1,2}/[^'"]+)['"]"""
)

def resolve(source, spec):
    base = (source.parent / spec).resolve()
    for candidate in (
        base, Path(str(base) + ".ts"), Path(str(base) + ".tsx"),
        Path(str(base) + ".js"), Path(str(base) + ".mjs"),
        base / "index.ts", base / "index.js",
    ):
        if candidate.is_file():
            return candidate
    return None

def imports(source):
    for match in pattern.finditer(source.read_text(errors="ignore")):
        clause = match.group("clause").strip()
        # `import type { ... }` does not evaluate the imported module at runtime.
        if clause.startswith("type "):
            continue
        target = resolve(source, match.group("spec"))
        if target:
            yield target, clause

for entry in entries:
    queue = deque([(entry, [entry])])
    seen = {entry}
    result = None
    while queue:
        current, path = queue.popleft()
        for target, clause in imports(current):
            if target == wanted:
                result = (path + [target], clause)
                queue.clear()
                break
            if target not in seen:
                seen.add(target)
                queue.append((target, path + [target]))
    print(f"{entry.relative_to(ROOT)}:")
    if result:
        path, clause = result
        print("  " + " -> ".join(str(p.relative_to(ROOT)) for p in path))
        print(f"  final clause: {clause}")
    else:
        print("  no runtime static-import path to src/main/ipc/ssh.ts")
PY

Repository: stablyai/orca

Length of output: 328


Install the SSH multiplexer resolver in the Node runtime bootstrap.

The Node runtime entry graphs do not execute src/main/ipc/ssh.ts; their type-only imports do not run the module-scope installer. A runtime RPC path that calls getActiveMultiplexer throws ssh_active_multiplexer_resolver_not_installed. Add an explicit runtime-host resolver installation before dispatch.

Comment on lines +28 to +30
const nodeHttpClient: MainHttpClient = {
fetch: (url, init) => globalThis.fetch(url, init),
proxySession: () => null

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -eu

# Inspect the declared Node runtime and all proxy transport setup.
rg -n -C 2 --glob 'package.json' --glob '.node-version' --glob '.tool-versions' \
  '"node"|engines|volta|packageManager' .

rg -n -C 3 --glob '*.{ts,tsx,js,mjs,cjs}' \
  'setGlobalDispatcher|ProxyAgent|EnvHttpProxyAgent|NODE_USE_ENV_PROXY|HTTP_PROXY|HTTPS_PROXY|applyElectronProxySettings|setMainHttpClient' \
  src config

Repository: stablyai/orca

Length of output: 23519


🏁 Script executed:

#!/usr/bin/env bash
set -eu

printf '%s\n' '--- http client ---'
sed -n '1,90p' src/main/network/http-client.ts
printf '%s\n' '--- electron http client ---'
sed -n '1,100p' src/main/host/electron-http-client.ts
printf '%s\n' '--- proxy settings ---'
sed -n '1,210p' src/main/network/proxy-settings.ts
printf '%s\n' '--- startup wiring ---'
sed -n '860,925p' src/main/index.ts
sed -n '2360,2410p' src/main/index.ts
printf '%s\n' '--- fetch/client call sites ---'
rg -n -C 3 --glob '*.{ts,tsx,js,mjs,cjs}' \
  'current\.fetch|mainHttpClient|globalThis\.fetch|electronHttpClient|setMainHttpClient|fetch\s*:' src
printf '%s\n' '--- proxy-related dependencies and scripts ---'
rg -n -C 3 --glob 'package.json' \
  'undici|proxy-agent|global-agent|setGlobalDispatcher|NODE_USE_ENV_PROXY|HTTP_PROXY|HTTPS_PROXY|proxy' .

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/usr/bin/env bash
set -u

printf '%s\n' '--- production proxy and HTTP-client references ---'
rg -n --glob '!**/*.test.*' --glob '*.{ts,tsx,js,mjs,cjs}' \
  'applyElectronProxySettings|ensureElectronProxyFromEnvironment|setMainHttpClient|getMainHttpClient|nodeHttpClient|globalThis\.fetch|electronHttpClient' src

printf '%s\n' '--- entry points and serve/runtime startup ---'
rg -n --glob '*.{ts,tsx,js,mjs,cjs,json}' \
  'orca serve|serve mode|isServeMode|process\.argv|globalThis\.fetch|HTTP_PROXY|HTTPS_PROXY|NODE_USE_ENV_PROXY|ProxyAgent|EnvHttpProxyAgent|setGlobalDispatcher' src package.json

printf '%s\n' '--- package scripts and dependency declarations ---'
sed -n '1,180p' package.json
sed -n '260,320p' package.json

printf '%s\n' '--- runtime availability ---'
node --version 2>&1 || true
node -p "typeof globalThis.fetch" 2>&1 || true

Repository: stablyai/orca

Length of output: 50370


🌐 Web query:

Node.js 24 global fetch HTTP_PROXY HTTPS_PROXY NODE_USE_ENV_PROXY EnvHttpProxyAgent default behavior

💡 Result:

In Node.js 24, global fetch and the built-in http/https modules do not automatically respect HTTP_PROXY, HTTPS_PROXY, and NO_PROXY environment variables by default [1][2]. This behavior is intentionally opt-in to avoid interfering with existing applications or libraries that may handle proxying differently [3][4]. To enable proxy support for global fetch and the built-in http/https modules, you must explicitly opt-in using one of the following methods [1][5]: 1. Environment Variable: Set the environment variable NODE_USE_ENV_PROXY=1 [1][5]. 2. CLI Flag: Start your Node.js process with the --use-env-proxy flag [1][5]. When enabled, Node.js will automatically configure the global fetch dispatcher and the default global http/https agents to respect standard proxy environment variables (HTTP_PROXY, HTTPS_PROXY, and NO_PROXY) [1][2][6]. Key Technical Details: - Precedence: If both the environment variable NODE_USE_ENV_PROXY and the --use-env-proxy CLI flag are set, the CLI flag takes precedence [6]. - Scope: This mechanism affects the global fetch (via the global Undici dispatcher) and the built-in http.Agent/https.Agent [1][6]. It does not affect fetch or http/https requests that explicitly use custom dispatchers or custom agents [1][6]. - Implementation: This functionality utilizes an internal implementation of an environment-aware proxy agent [2]. For advanced or per-request proxy control, you can also use the undici library's EnvHttpProxyAgent directly, which can be configured programmatically and assigned to specific requests via the dispatcher option [7][4].

Citations:


🏁 Script executed:

#!/usr/bin/env bash
set -u

printf '%s\n' '--- production references only ---'
rg -n -g '!*.test.*' -g '!**/__fixtures__/**' \
  'applyElectronProxySettings|ensureElectronProxyFromEnvironment|setMainHttpClient|getMainHttpClient|globalThis\.fetch|net\.fetch|ProxyAgent|EnvHttpProxyAgent|setGlobalDispatcher|NODE_USE_ENV_PROXY|use-env-proxy' \
  src package.json

printf '%s\n' '--- package scripts and dependencies ---'
node - <<'JS'
const fs = require('node:fs')
const p = JSON.parse(fs.readFileSync('package.json', 'utf8'))
console.log(JSON.stringify({
  scripts: p.scripts,
  dependencies: p.dependencies,
  devDependencies: p.devDependencies,
  engines: p.engines
}, null, 2))
JS

printf '%s\n' '--- CLI launch path ---'
sed -n '1,360p' src/cli/runtime/launch.ts
printf '%s\n' '--- CLI entry ---'
sed -n '1,130p' src/cli/index.ts

printf '%s\n' '--- Jira production request path ---'
sed -n '1,115p' src/main/jira/authenticated-request.ts

Repository: stablyai/orca

Length of output: 45248


🏁 Script executed:

#!/usr/bin/env bash
set -eu

node - <<'JS'
const { execFileSync } = require('node:child_process')

function run(env) {
  const output = execFileSync(
    process.execPath,
    ['-e', `
      const http = require('node:http')
      const agent = require('node:util').inspect(globalThis.fetch)
      console.log(JSON.stringify({
        node: process.versions.node,
        fetch: typeof globalThis.fetch,
        httpProxy: process.env.HTTP_PROXY ?? null,
        httpsProxy: process.env.HTTPS_PROXY ?? null,
        nodeUseEnvProxy: process.env.NODE_USE_ENV_PROXY ?? null,
        fetchSource: agent.slice(0, 120)
      }))
    `],
    { env: { ...process.env, ...env }, encoding: 'utf8' }
  )
  process.stdout.write(output)
}

run({ HTTP_PROXY: 'http://proxy.example:8080', HTTPS_PROXY: 'http://proxy.example:8080', NODE_USE_ENV_PROXY: '' })
run({ HTTP_PROXY: 'http://proxy.example:8080', HTTPS_PROXY: 'http://proxy.example:8080', NODE_USE_ENV_PROXY: '1' })
JS

Repository: stablyai/orca

Length of output: 663


🏁 Script executed:

#!/usr/bin/env bash
set -eu

printf '%s\n' '--- environment mapping helper ---'
sed -n '1,145p' src/shared/network-proxy.ts

printf '%s\n' '--- exact non-test call graph ---'
rg -n -g '!*.test.*' \
  'applyElectronProxySettings|ensureElectronProxyFromEnvironment|getMainHttpClient|setMainHttpClient|globalThis\.fetch|net\.fetch' \
  src/main src/cli src/relay

printf '%s\n' '--- all proxy transport mechanisms ---'
rg -n -g '!*.test.*' -g '!pnpm-lock.yaml' \
  'ProxyAgent|EnvHttpProxyAgent|setGlobalDispatcher|NODE_USE_ENV_PROXY|use-env-proxy|dispatcher:|agent:' \
  .

printf '%s\n' '--- startup entry configuration ---'
rg -n -C 4 \
  'src/main/index|main/index|electron-vite|ELECTRON_RUN_AS_NODE|--serve' \
  config package.json

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/usr/bin/env bash
set -eu

node - <<'JS'
const { execFileSync } = require('node:child_process')

const child = `
  globalThis.fetch('http://127.0.0.1:9').catch(error => {
    const values = []
    let current = error
    for (let i = 0; current && values.length < 5; i += 1) {
      values.push(String(current.message ?? current))
      current = current.cause
    }
    process.stdout.write(JSON.stringify(values))
  })
`

const baseEnv = {
  ...process.env,
  HTTP_PROXY: 'http://127.0.0.1:1',
  HTTPS_PROXY: 'http://127.0.0.1:1',
  ALL_PROXY: 'http://127.0.0.1:1',
  NO_PROXY: ''
}

for (const [label, extra] of [
  ['disabled', { NODE_USE_ENV_PROXY: '' }],
  ['enabled', { NODE_USE_ENV_PROXY: '1' }]
]) {
  const output = execFileSync(process.execPath, ['-e', child], {
    env: { ...baseEnv, ...extra },
    encoding: 'utf8'
  })
  console.log(label, output)
}
JS

Repository: stablyai/orca

Length of output: 550


🏁 Script executed:

#!/usr/bin/env bash
set -eu

node - <<'JS'
const { execFileSync } = require('node:child_process')

const child = `
  globalThis.fetch('http://127.0.0.1:8123').catch(error => {
    const values = []
    let current = error
    for (let i = 0; current && values.length < 6; i += 1) {
      values.push(String(current.message ?? current))
      current = current.cause
    }
    process.stdout.write(JSON.stringify(values))
  })
`

const baseEnv = {
  ...process.env,
  HTTP_PROXY: 'http://127.0.0.1:8124',
  HTTPS_PROXY: 'http://127.0.0.1:8124',
  ALL_PROXY: 'http://127.0.0.1:8124',
  NO_PROXY: ''
}

for (const [label, extra] of [
  ['disabled', { NODE_USE_ENV_PROXY: '' }],
  ['enabled', { NODE_USE_ENV_PROXY: '1' }]
]) {
  const output = execFileSync(process.execPath, ['-e', child], {
    env: { ...baseEnv, ...extra },
    encoding: 'utf8'
  })
  console.log(label, output)
}
JS

Repository: stablyai/orca

Length of output: 586


Route proxy settings through the Node HTTP transport. nodeHttpClient.fetch calls globalThis.fetch without a dispatcher, and Node 24 ignores proxy environment variables unless env-proxy mode is enabled. When no proxySession exists, applyElectronProxySettings can report source: 'settings' or source: 'env' without changing the Node transport.

📍 Affects 2 files
  • src/main/network/http-client.ts#L28-L30 (this comment)
  • src/main/network/proxy-settings.ts#L87-L116
  • src/main/network/proxy-settings.ts#L127-L164

})
return {
getPath: (name) => (name === 'home' ? homedir() : name === 'temp' ? tmpdir() : userData),
getAppPath: () => process.cwd(),

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 | 🏗️ Heavy lift

Resolve the application root independently of cwd.

Line 52 returns process.cwd() for getAppPath(), but this port defines that value as the install or bundle root. If a service starts orcad from another directory, sidecar and service-entry resolution builds paths below that directory instead of the deployed bundle. Derive the root from the entry bundle or executable, or require a dedicated application-root setting.

Comment on lines +67 to +78
function createNodeSecretStore(): SecretStore {
return {
isEncryptionAvailable: () => false,
encryptString: () => {
throw new Error('orcad_secret_sealing_unavailable')
},
decryptString: () => {
throw new Error('orcad_secret_sealing_unavailable')
},
describeUnavailable: () =>
'This host has no OS keyring, so credentials are stored unencrypted. Pair from a desktop to manage secrets, or install and unlock a keyring.'
}

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.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Require protected secret storage before credential persistence.

Line 69 selects the unsealed-storage path for every consumer. Lines 76-77 confirm that credentials are then stored unencrypted in the Node host data directory. A principal that can read that directory, such as a backup or mounted volume, can recover the credentials. Inject protected secret storage, or reject credential persistence when it is unavailable.

paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 23, 2026
…dules (stablyai#15927)

* refactor(preflight): split agent detection out of the ipcMain registration

First of the IPC extractions the revised design requires. `src/main/ipc/preflight.ts`
mixed 285 lines of agent/tool detection with 35 lines of `ipcMain.handle`
registration, and the runtime calls that detection during normal operation
(`orca-runtime.ts:573`, plus the preflight RPC methods). So the runtime dragged
`ipcMain` into its graph to reach pure logic.

Detection moves to `src/main/preflight/agent-detection.ts` — named for what it
contains, per AGENTS.md. `ipc/preflight.ts` keeps only the handler registration and
re-exports the domain module so existing importers are unaffected. The runtime and
its RPC methods now import the domain module directly.

Ratchet baseline 36 → 35: `src/main/ipc/preflight.ts` is no longer reachable from
the runtime. The gate detected the improvement and refused to pass until the
baseline tightened, which is the behaviour it was built for.

Verified: 2 files / 1,187 tests pass across every suite touching preflight;
`pnpm typecheck` clean; `oxlint` clean.

* refactor(ssh): split the SSH target registry out of the ipcMain module

Second IPC extraction, and by far the biggest win: this removes **eight** modules
from the runtime's Electron graph, taking the ratchet baseline 35 → 27.

The runtime needed five thin accessors from `src/main/ipc/ssh.ts` —
`connectRegisteredSshTarget`, `getRegisteredSshState`, `listRegisteredSshTargets`,
`listRegisteredRemovedSshTargetLabels`, `getActiveMultiplexer`. Each is a one-line
read over module-level state. Importing them dragged in `ipcMain`, `powerMonitor`
and a `BrowserWindow` accessor — and, transitively, `ipc/pty.ts` (8,031 lines),
`ssh-browse`, `ssh-passphrase`, `ssh-relay-deploy`, `ssh-remote-cli-host-passthrough`,
`wsl-hook-relay-launch` and `user-data-path`.

`src/main/ssh/ssh-target-registry.ts` now holds that state plus its accessors.
`registerSshHandlers` populates it; the runtime reads it. The indirection is kept
deliberately: SSH providers register after construction and may reconnect, so
callers must resolve the current generation rather than freeze one.
`ipc/ssh.ts` re-exports all five, so non-test importers are unaffected.

`connectRegisteredSshTarget` still throws `ssh_handlers_not_registered` when no
handler layer registered — a headless host must fail loudly rather than report a
target as unreachable, which would read as `exited` (see ssh-execution-boundary.md).

Verified: 9 files / 59 tests across the ssh, automations and trust-preset suites;
orca-runtime.test.ts 1,183 pass; `pnpm typecheck` clean; `oxlint` clean.

* refactor(host): resolve the app root through the port in fork-reachable modules

`parcel-watcher-entry-path.ts` and `session-scanner-service-entry-path.ts` read the
app root via `require('electron').app` inside a try/catch that already returns null
when Electron is absent. They were therefore correct under plain Node at runtime and
only failed the *static* text check — which is real, not pedantic: the comment in
`ports/port-scan-command-client.ts:19` records that the plain-node-entry-guard fails
on that literal text, try/catch or not.

`hasAppEnvironment() ? getAppEnvironment() : null` gives the identical "no app root
here" answer without the text. That restores `hasAppEnvironment`, which an earlier
commit in this stack deleted as unused — it now has the caller it was waiting for.

Ratchet baseline 27 → 25.

Verified: 74 files / 458 tests; `pnpm typecheck` clean; `oxlint` clean.

* test(ssh): mock the SSH target registry alongside the ipc/ssh mock

Thirty-eight suites mocked `vi.mock('./ssh')` for `getActiveMultiplexer`. That
factory went inert when production started importing the accessor from
`../ssh/ssh-target-registry`, so the real module loaded and the assertions drifted.

Adds a companion registry mock returning the same stub, plus a
`sshTargetRegistryModuleMock` builder beside the existing `sshModuleMock` so the
shared harness stays one place. No assertion changed.

Found by a full-suite run: the targeted ssh/runtime suites were green while
30 tests in ipc/worktrees and ipc/repos were not.

* refactor(runtime): read app paths and the packaged flag through the port

`orca-runtime.ts` is the last module in its own graph that imports `electron`
directly. Nineteen of its uses were `app.getPath` (12) and `app.isPackaged` (7) —
exactly what the AppEnvironment port already covers.

Also removes a dead `const { app } = require('electron')` inside
`getOrchestrationDb`. It was left unused once the path came from the port, and it
is precisely the dynamic-require pattern `plain-node-entry-guard.ts` exists to
catch, sitting in the runtime's own constructor path.

What still binds `orca-runtime.ts` to Electron is now three sites, not nineteen:
`new Notification(...)` (one), `BrowserWindow.fromId` (one), and the
`ipcMain.on('terminal:tabCreateReply')` renderer round-trip — which is the browser
tab path, and the same one that would hang a headless host for ten seconds.

Two suites drove `electronMocks.app.isPackaged` directly; they now install a fake
AppEnvironment reading the same mutable field, so their per-test toggles work
unchanged and no assertion moved.

Verified: 376 files / 4,717 tests across src/main/runtime; typecheck and oxlint clean.

* test(serve): add the built-artifact terminal round-trip acceptance smoke

"The server started" proves almost nothing. Terminal creation dispatches into
OrcaRuntimeService, and without an installed headless PTY controller that path
falls through to a renderer reply that never arrives and times out after ten
seconds. A boot probe, a port bind, and a `host.platform` call all pass against a
server whose terminals are dead — which is exactly the gap the design doc's own
boot proof was retracted for.

This boots the BUILT `out/main/index.js --serve`, parses its ready payload, pairs a
real client over the advertised endpoint, lists worktrees, creates a terminal, runs
a command through the PTY, asserts the output comes back, and asserts clean
shutdown. It drives nothing but the public pairing + RPC surface, so the same
script is the acceptance gate a future Node-only backend must pass unchanged.

The sentinel invokes `process.execPath` rather than `echo`, because the shell
differs per platform and node does not.

Verified both directions: passes against the real server, and fails with an
actionable message when the command produces no output — a smoke that cannot fail
is worthless.

* fix(ssh): fail loudly when the multiplexer resolver was never installed

`getActiveMultiplexer` resolves through a resolver that `ipc/ssh.ts` installs at
module scope. A process that never loads the SSH layer — which is the whole point
of the Node-only backend — would get `undefined` from every call.

`undefined` already means something specific here: "not connected". So a missing
resolver and a disconnected target were indistinguishable, and a host with no SSH
layer would quietly report every target as not connected. That is the
unverifiable-reported-as-exited conflation `docs/reference/ssh-execution-boundary.md`
exists to prevent — the doc is explicit that absence of contact is never evidence
of absence of the thing.

A missing resolver is a wiring error, not a connection state, so it throws, matching
what `connectRegisteredSshTarget` already does for unregistered handlers.

Verified: 432 files / 4,759 tests across ipc, ssh, preflight, automations and trust
presets; typecheck and oxlint clean.

* refactor(pty): stop faking a BrowserWindow for the headless PTY path

`registerHeadlessPtyRuntime` passed `registerPtyHandlers` a stub object cast to
`BrowserWindow` whose `isDestroyed()` returned true and whose `webContents.send`
was a no-op — a window-shaped thing that lied about being a window, purely to
satisfy the type. Adversarial review named it as the same "looks fine, silently
returns a lie" pattern this codebase rejects elsewhere, and it is the shape that
keeps `electron` on a path that otherwise needs none.

`registerPtyHandlers` now takes `BrowserWindow | null`. An absent renderer is
semantically identical to a destroyed one — all 42 call sites already guarded on
`isDestroyed()` and skipped — so `src/main/ipc/pty-renderer-surface.ts` states that
directly: `isRendererGone`, `sendToRenderer`, `rendererWebContents`. The compound
`isDestroyed() || webContents.isDestroyed()` guards collapse into one predicate.

`isPtyWriteEventFromMainWindow` becomes null-tolerant and fails closed: with no
renderer no sender can legitimately match, so every write is rejected. Those
handlers cannot fire headless today, but failing closed is the right answer if that
ever changes.

This is the precondition for installing a PTY controller without Electron, which is
what a Node-only backend needs and what `terminal.create` actually calls.

Verified: 129 files / 2,473 tests across ipc/pty, providers and orca-runtime; the
built-artifact acceptance smoke still passes end-to-end (boot → pair →
terminal.create → sentinel → close), which is the check that matters most here
since this changes the headless PTY path itself; typecheck and oxlint clean.

* refactor(pty): read app paths and the packaged flag through the port

Follows the fake-window removal. `ipc/pty.ts` had nine `app.*` reads — all
`getPath`, `getVersion` or `isPackaged` — which the AppEnvironment port already
covers. The `BrowserWindow` import was also dead after the null-window change.

What still binds this file to Electron is now `ipcMain` (75 uses, all handler
registration) and `powerMonitor` (2). That is a clean statement of the remaining
job: split logic from registration, the same shape already applied to preflight
and the SSH registry.

Test wiring: the shared `pty-ipc-suite-environment` beforeEach installs a fake
AppEnvironment that reads through the existing `vi.mock('electron')` app object
rather than freezing values — suites toggle `app.isPackaged` mid-test to exercise
dev-mode spawn paths, so the port has to observe the same mutable field. One edit
in the shared harness covers every pty suite.

Verified: 128 files / 1,290 tests across ipc/pty and providers; the built-artifact
acceptance smoke passes; typecheck and oxlint clean; ratchet unchanged at 25.

* refactor(pty): inject the ipcMain surface so the PTY module loads without Electron

This closes the round-3 blocker: "the doc never says how orcad installs
setPtyController without Electron."

`registerPtyHandlers` owns the `RuntimePtyController` that `terminal.create`
actually spawns through — the thing a Node backend needs and cannot get from the
provider thunks. The module was otherwise host-agnostic already; the only thing
pinning 8,031 lines to Electron was a static `ipcMain` / `powerMonitor` import used
purely to register renderer handlers that no headless host will ever receive.

`src/main/ipc/pty-host-bindings.ts` makes those surfaces settable, defaulting to
no-ops. Unlike AppEnvironment and SecretStore, the default does NOT throw: a host
with no renderer legitimately has nothing to register against, so not registering
handlers nobody can call is correct rather than a hidden downgrade. The desktop
installs the real objects in `attach-main-window-services` before its handlers run.

Also converts the remaining electron import to a top-level `import type`. oxlint's
`no-import-type-side-effects` caught that inline `type` specifiers still leave a
side-effect import — precisely the "type-only is not enough if esbuild still emits
require('electron')" trap a reviewer flagged.

**`src/main/ipc/pty.ts` now bundles with zero `require("electron")`.** A Node entry
can call `registerPtyHandlers(null, runtime, …)` and get a working PTY controller.

Verified: 128 files / 1,290 tests across ipc/pty and providers; the built-artifact
acceptance smoke passes end-to-end — which is the check that matters, since this
changes how every PTY handler registers; typecheck and oxlint clean.

* fix(pty-bindings): drop two unused eslint-disable directives

CI runs oxlint with unused-disable reporting; the two
`@typescript-eslint/no-explicit-any` suppressions I added were never triggered by
any enabled rule, so they failed static analysis as dead directives. The `any[]`
rest args stay — they mirror electron's own IpcMain signature, and narrowing them
would reject the real object at the desktop call site.

Verified with the exact CI invocation: `oxlint --format github` reports 0 warnings,
0 errors across the repo.

* fix(pty): install the host bindings per process, not per window

A real regression my own change introduced, caught by the SSH docker E2E
(`paired-startup-exec-readiness` — "recovers startup exec through a headed paired
desktop owner"). It reproduced on rerun, so it was not a flake.

`setPtyHostBindings` was called inside `attachMainWindowServices`, i.e. when a
window attaches. But `registerHeadlessPtyRuntime` (index.ts:3163) calls
`registerPtyHandlers` on the serve path *before* any window exists — so those
handlers registered against the no-op default and never reached the real `ipcMain`.
A paired desktop owner then attached to a runtime whose PTY handlers were wired to
nothing.

The bindings describe the *host*, not the *window*: an Electron main process always
has `ipcMain`, whether or not a window is open. Installing them beside
`setAppEnvironment`/`setSecretStore` at the top of bootstrap fixes both paths.

Verified: 128 files / 1,290 tests; the built-artifact acceptance smoke passes;
typecheck clean; `oxlint --format github` (the exact CI invocation) reports 0/0.

* feat(orcad): de-electron the runtime core and add the Node entry + build gate

**`src/main/runtime/orca-runtime.ts` — 41,048 lines — no longer imports electron.**
Its last three sites go through `runtime-desktop-surface.ts`: a native notification,
the authoritative-window lookup, and the one `ipcMain` channel used by the
renderer-backed tab-create fallback. All three are unreachable without a renderer —
`createTerminal` already takes the background branch when no window exists (stablyai#10333) —
so a Node host installs none and the runtime relays notifications to paired clients,
which is the better destination anyway. Ratchet 25 → 24.

Adds `src/main/orcad/orcad-entry.ts`: Node host adapters plus a `startOrcad` that
constructs the runtime, installs the PTY controller via `registerPtyHandlers(null, …)`,
and serves RPC. It sets two defaults the constructor gets wrong for a headless host —
`canRecoverPersistentLocalPtys: false` (no daemon here) and
`getDesktopWindowStatus: 'blocked'` (a Node host can never be promoted to a desktop
window, which is what `'openable'` claims).

Adds `config/scripts/build-orcad.mjs`, which **currently fails, on purpose**: 25
modules still import electron (browser and speech clusters, plugins, jira/proxy,
filesystem-watcher, and four `require('electron').app` one-liners). It names them.

Two bugs found while building it, both worth recording:
- The first bundle looked clean and was not. `electron` was bundleable, so esbuild
  rewrote the metafile `path` to the resolved file under node_modules and a check for
  `path === 'electron'` passed while the package was in the bundle — it failed at
  runtime with electron's own installer message. The check now reads `original`, and
  electron is marked external so a residual import fails loudly instead.
- `jsonc-parser`'s UMD build breaks the bundle at load; aliased to its ESM entry, the
  same fix `build-relay.mjs` already carries.

Verified: desktop unchanged — the built-artifact acceptance smoke passes, runtime/pty/
provider suites green, typecheck clean, `oxlint --format github` 0/0.

* refactor(host): drop the last two require('electron') app lookups

`computer/sidecar-client.ts` and `ports/port-scan-command-client.ts` read the app
root through `require('electron').app` inside a try/catch. Both were already correct
under plain Node at runtime — they return null when it throws — but the literal text
fails the plain-Node entry guard regardless, which is why port-scan carried a comment
warning it must never become reachable from a fork entry.

Reading the AppEnvironment port gives the identical "no app root here" answer without
the text, so that warning is now obsolete and the comment says so.

Ratchet 24 → 22. Every remaining entry is a real coupling: the browser cluster (15,
which variant B does not ship), speech (2), plugins (2), and jira/proxy-settings (2,
needing an HttpClient port for Chromium session partitions).

Verified: 25 files / 209 tests; acceptance smoke passes; typecheck and
`oxlint --format github` clean.

* docs(orcad): record that the ratchet under-counts orcad's graph

The ratchet reports 22 electron importers; the orcad build reports 23. The extra is
agent-hooks/wsl-hook-relay-launch.ts, and the cause is a gap in the gate rather than
a rounding error: the ratchet measures what orca-runtime + runtime-rpc reach, while
orcad's entry also imports ipc/pty directly to install the PTY controller.

Once orcad ships it must become a ratchet entry point, or the two numbers drift and
the gate quietly stops covering the artifact it exists for.

* refactor(runtime): inject the browser commands factory

Drops 14 modules from the runtime's Electron graph in one change — the whole Chromium
browser cluster. Ratchet 22 → 8.

`OrcaRuntimeService` constructed `RuntimeBrowserCommands` as a field initializer, and
that construction is what pulled in `BrowserWindow`, `session`, `webContents` and the
cookie jars. Importing the class for its *type* is free; only building it costs.

So the class import becomes `import type`, and the instance comes from
`runtime-browser-commands-factory.ts`. The desktop installs the real factory at the
Electron entry. **All ~80 existing `this.browserCommands.*.bind(...)` delegations are
untouched** — a review round specifically warned that rewriting those was the
expensive, risky part, and this avoids it entirely.

With no factory installed, browser commands reject per call with `browser_unavailable`
rather than resolving to a stub that silently succeeds. The runtime already filters
browser capabilities out of `getStatus()` when no backend exists, so clients do not
offer the affordance in the first place.

Also corrects a stale comment in `pty-renderer-surface.ts` that still described the
fake window as present tense; it was deleted two commits ago.

Verified: 451 files / 5,513 tests across `src/main/browser` and `src/main/runtime` —
the entire browser automation suite; the built-artifact acceptance smoke passes;
`pnpm typecheck` and `oxlint --format github` clean.

* refactor(host): extract the plugin client list and port two app lookups

Ratchet 8 → 5.

- `listPluginsForClients` moves to `src/main/plugins/plugin-client-list.ts`. It needed
  only three `plugins/*` helpers, none of them Electron — it was colocated with
  `ipcMain.handle` registrations, so the runtime's `plugins.list` RPC dragged all of
  Electron in to call a function that reads a lockfile. Same shape as preflight.
  Dropping it also releases `ipc/plugin-marketplaces.ts`.
- `agent-hooks/wsl-hook-relay-launch.ts` and `speech/stt-service.ts` read `getAppPath`
  and `isPackaged` through the AppEnvironment port.

The five that remain are all genuinely Chromium and need the HttpClient port or a
watcher split, not another mechanical swap: `browser/cdp-bridge` (webContents),
`ipc/filesystem-watcher` (ipcMain), `jira/authenticated-request` and
`network/proxy-settings` (net + session partitions), `speech/model-manager`
(`net.request`, which honors app proxy settings that Node https does not — replacing
it is a behaviour change, not a rename).

Verified: 219 files / 1,922 tests across plugins, speech, agent-hooks and the runtime
RPC methods; the built-artifact acceptance smoke passes; typecheck and
`oxlint --format github` clean.

* refactor(network): resolve the default proxy session lazily

Ratchet 5 → 4.

`proxy-settings.ts` needed exactly one Electron value: `session.defaultSession`, as
the fallback when a caller does not pass `options.proxySession`. Callers could already
inject a session; only the default was hard-wired. It now comes from a settable
resolver, so the module loads under plain Node.

**A resolver rather than a Session, because a Session eagerly throws.** The first
attempt installed `session.defaultSession` directly in pre-ready bootstrap and broke
startup outright — `TypeError: Session can only be received when app is ready`. The
acceptance smoke caught it before commit. Deferring to first use is always after ready.

Behaviour with no session is not a degradation: there is no Chromium proxy config to
discover, so `resolveProxy` is skipped and the environment variables become the whole
answer rather than a fallback. Applying rules to a session that does not exist is
likewise skipped; settings are still honoured because outbound requests read the env.

This reaches past Jira — a review round noted `ensureElectronProxyFromEnvironment` is
also on the Claude HTTP path via `oauth-refresh.ts` and `rate-limits/claude-fetcher.ts`.

Verified: 48 files / 526 tests across network, jira and rate-limits; the
built-artifact acceptance smoke passes; typecheck and `oxlint --format github` clean.

* fix(index): merge the duplicate proxy-settings import

CI's code-quality lint (`oxlint --config config/oxlint-code-quality-native-plugins.json
--deny-warnings`) flags a module imported twice in one file. My earlier insertion added
a second `./network/proxy-settings` import beside the existing one.

Verified with CI's exact invocation: exit 0.

* refactor(network): add the HttpClient port and lift BrowserError out of cdp-bridge

Ratchet 4 → 2.

Two unrelated couplings, both of the same shape — a small thing living inside a
Chromium-heavy file.

`BrowserError` is a seven-line error class with no dependencies, but it lived in
`browser/cdp-bridge.ts`, which imports `webContents`. The runtime catches that type on
paths with nothing to do with CDP, so one import kept a Node host from loading the
runtime at all. Moved to `browser/browser-error.ts`; cdp-bridge re-exports it.

`jira/authenticated-request.ts` fetches through `net.fetch` and reads
`session.defaultSession`. `network/http-client.ts` makes both settable. This one is a
**named port rather than a silent fallback, because the fallback is not transparent**:
Electron's net follows Chromium session/proxy state, avoids undici's stale keep-alive
sockets after a VPN path change, and sends a Chrome user agent that Jira's XSRF check
depends on. A Node host gets `globalThis.fetch`, reads proxy config from the
environment, and sends Node's user agent. That difference is documented at the port.

`session.defaultSession` is read per call, not captured at install — it throws before
the app is ready, which is the mistake the previous commit made and the acceptance
smoke caught.

Test wiring: `jira/client.test.ts` installs the port *inside* `loadClientModule`, after
its `vi.resetModules()`, since the reset gives the module a fresh singleton.

Verified: 461 files / 5,616 tests across jira, browser, network and runtime; the
built-artifact acceptance smoke passes; typecheck, `oxlint --format github` and the
code-quality lint with `--deny-warnings` all clean.

* fix(http-client): register the Node fetch fallback with the call-site audit

`global-fetch-call-site-audit.test.ts` guards every global-fetch use, because the
global runs on undici where an unread response body can crash the whole process
(orca#8695). The HttpClient port's Node fallback is a new such call site and was
unregistered — the guard caught it in a full-suite run.

Registered with the reasoning, and the port's doc comment now states the body-safety
contract explicitly: it hands the Response straight to its caller and never inspects
it, so the consume/cancel obligation stays exactly where it already was — with the
caller, unchanged from when they called Electron's net directly.

Two comments elsewhere mentioned the global by name and tripped the line scan as false
positives; reworded to describe the behaviour rather than name the API.

Verified: audit passes; typecheck and `oxlint --format github` clean.

* fix(app-environment): read hasAppEnvironment through the realm slot

(cherry picked from commit f975035)
CodeHourra pushed a commit to CodeHourra/orca that referenced this pull request Aug 23, 2026
…dules (stablyai#15927)

* refactor(preflight): split agent detection out of the ipcMain registration

First of the IPC extractions the revised design requires. `src/main/ipc/preflight.ts`
mixed 285 lines of agent/tool detection with 35 lines of `ipcMain.handle`
registration, and the runtime calls that detection during normal operation
(`orca-runtime.ts:573`, plus the preflight RPC methods). So the runtime dragged
`ipcMain` into its graph to reach pure logic.

Detection moves to `src/main/preflight/agent-detection.ts` — named for what it
contains, per AGENTS.md. `ipc/preflight.ts` keeps only the handler registration and
re-exports the domain module so existing importers are unaffected. The runtime and
its RPC methods now import the domain module directly.

Ratchet baseline 36 → 35: `src/main/ipc/preflight.ts` is no longer reachable from
the runtime. The gate detected the improvement and refused to pass until the
baseline tightened, which is the behaviour it was built for.

Verified: 2 files / 1,187 tests pass across every suite touching preflight;
`pnpm typecheck` clean; `oxlint` clean.

* refactor(ssh): split the SSH target registry out of the ipcMain module

Second IPC extraction, and by far the biggest win: this removes **eight** modules
from the runtime's Electron graph, taking the ratchet baseline 35 → 27.

The runtime needed five thin accessors from `src/main/ipc/ssh.ts` —
`connectRegisteredSshTarget`, `getRegisteredSshState`, `listRegisteredSshTargets`,
`listRegisteredRemovedSshTargetLabels`, `getActiveMultiplexer`. Each is a one-line
read over module-level state. Importing them dragged in `ipcMain`, `powerMonitor`
and a `BrowserWindow` accessor — and, transitively, `ipc/pty.ts` (8,031 lines),
`ssh-browse`, `ssh-passphrase`, `ssh-relay-deploy`, `ssh-remote-cli-host-passthrough`,
`wsl-hook-relay-launch` and `user-data-path`.

`src/main/ssh/ssh-target-registry.ts` now holds that state plus its accessors.
`registerSshHandlers` populates it; the runtime reads it. The indirection is kept
deliberately: SSH providers register after construction and may reconnect, so
callers must resolve the current generation rather than freeze one.
`ipc/ssh.ts` re-exports all five, so non-test importers are unaffected.

`connectRegisteredSshTarget` still throws `ssh_handlers_not_registered` when no
handler layer registered — a headless host must fail loudly rather than report a
target as unreachable, which would read as `exited` (see ssh-execution-boundary.md).

Verified: 9 files / 59 tests across the ssh, automations and trust-preset suites;
orca-runtime.test.ts 1,183 pass; `pnpm typecheck` clean; `oxlint` clean.

* refactor(host): resolve the app root through the port in fork-reachable modules

`parcel-watcher-entry-path.ts` and `session-scanner-service-entry-path.ts` read the
app root via `require('electron').app` inside a try/catch that already returns null
when Electron is absent. They were therefore correct under plain Node at runtime and
only failed the *static* text check — which is real, not pedantic: the comment in
`ports/port-scan-command-client.ts:19` records that the plain-node-entry-guard fails
on that literal text, try/catch or not.

`hasAppEnvironment() ? getAppEnvironment() : null` gives the identical "no app root
here" answer without the text. That restores `hasAppEnvironment`, which an earlier
commit in this stack deleted as unused — it now has the caller it was waiting for.

Ratchet baseline 27 → 25.

Verified: 74 files / 458 tests; `pnpm typecheck` clean; `oxlint` clean.

* test(ssh): mock the SSH target registry alongside the ipc/ssh mock

Thirty-eight suites mocked `vi.mock('./ssh')` for `getActiveMultiplexer`. That
factory went inert when production started importing the accessor from
`../ssh/ssh-target-registry`, so the real module loaded and the assertions drifted.

Adds a companion registry mock returning the same stub, plus a
`sshTargetRegistryModuleMock` builder beside the existing `sshModuleMock` so the
shared harness stays one place. No assertion changed.

Found by a full-suite run: the targeted ssh/runtime suites were green while
30 tests in ipc/worktrees and ipc/repos were not.

* refactor(runtime): read app paths and the packaged flag through the port

`orca-runtime.ts` is the last module in its own graph that imports `electron`
directly. Nineteen of its uses were `app.getPath` (12) and `app.isPackaged` (7) —
exactly what the AppEnvironment port already covers.

Also removes a dead `const { app } = require('electron')` inside
`getOrchestrationDb`. It was left unused once the path came from the port, and it
is precisely the dynamic-require pattern `plain-node-entry-guard.ts` exists to
catch, sitting in the runtime's own constructor path.

What still binds `orca-runtime.ts` to Electron is now three sites, not nineteen:
`new Notification(...)` (one), `BrowserWindow.fromId` (one), and the
`ipcMain.on('terminal:tabCreateReply')` renderer round-trip — which is the browser
tab path, and the same one that would hang a headless host for ten seconds.

Two suites drove `electronMocks.app.isPackaged` directly; they now install a fake
AppEnvironment reading the same mutable field, so their per-test toggles work
unchanged and no assertion moved.

Verified: 376 files / 4,717 tests across src/main/runtime; typecheck and oxlint clean.

* test(serve): add the built-artifact terminal round-trip acceptance smoke

"The server started" proves almost nothing. Terminal creation dispatches into
OrcaRuntimeService, and without an installed headless PTY controller that path
falls through to a renderer reply that never arrives and times out after ten
seconds. A boot probe, a port bind, and a `host.platform` call all pass against a
server whose terminals are dead — which is exactly the gap the design doc's own
boot proof was retracted for.

This boots the BUILT `out/main/index.js --serve`, parses its ready payload, pairs a
real client over the advertised endpoint, lists worktrees, creates a terminal, runs
a command through the PTY, asserts the output comes back, and asserts clean
shutdown. It drives nothing but the public pairing + RPC surface, so the same
script is the acceptance gate a future Node-only backend must pass unchanged.

The sentinel invokes `process.execPath` rather than `echo`, because the shell
differs per platform and node does not.

Verified both directions: passes against the real server, and fails with an
actionable message when the command produces no output — a smoke that cannot fail
is worthless.

* fix(ssh): fail loudly when the multiplexer resolver was never installed

`getActiveMultiplexer` resolves through a resolver that `ipc/ssh.ts` installs at
module scope. A process that never loads the SSH layer — which is the whole point
of the Node-only backend — would get `undefined` from every call.

`undefined` already means something specific here: "not connected". So a missing
resolver and a disconnected target were indistinguishable, and a host with no SSH
layer would quietly report every target as not connected. That is the
unverifiable-reported-as-exited conflation `docs/reference/ssh-execution-boundary.md`
exists to prevent — the doc is explicit that absence of contact is never evidence
of absence of the thing.

A missing resolver is a wiring error, not a connection state, so it throws, matching
what `connectRegisteredSshTarget` already does for unregistered handlers.

Verified: 432 files / 4,759 tests across ipc, ssh, preflight, automations and trust
presets; typecheck and oxlint clean.

* refactor(pty): stop faking a BrowserWindow for the headless PTY path

`registerHeadlessPtyRuntime` passed `registerPtyHandlers` a stub object cast to
`BrowserWindow` whose `isDestroyed()` returned true and whose `webContents.send`
was a no-op — a window-shaped thing that lied about being a window, purely to
satisfy the type. Adversarial review named it as the same "looks fine, silently
returns a lie" pattern this codebase rejects elsewhere, and it is the shape that
keeps `electron` on a path that otherwise needs none.

`registerPtyHandlers` now takes `BrowserWindow | null`. An absent renderer is
semantically identical to a destroyed one — all 42 call sites already guarded on
`isDestroyed()` and skipped — so `src/main/ipc/pty-renderer-surface.ts` states that
directly: `isRendererGone`, `sendToRenderer`, `rendererWebContents`. The compound
`isDestroyed() || webContents.isDestroyed()` guards collapse into one predicate.

`isPtyWriteEventFromMainWindow` becomes null-tolerant and fails closed: with no
renderer no sender can legitimately match, so every write is rejected. Those
handlers cannot fire headless today, but failing closed is the right answer if that
ever changes.

This is the precondition for installing a PTY controller without Electron, which is
what a Node-only backend needs and what `terminal.create` actually calls.

Verified: 129 files / 2,473 tests across ipc/pty, providers and orca-runtime; the
built-artifact acceptance smoke still passes end-to-end (boot → pair →
terminal.create → sentinel → close), which is the check that matters most here
since this changes the headless PTY path itself; typecheck and oxlint clean.

* refactor(pty): read app paths and the packaged flag through the port

Follows the fake-window removal. `ipc/pty.ts` had nine `app.*` reads — all
`getPath`, `getVersion` or `isPackaged` — which the AppEnvironment port already
covers. The `BrowserWindow` import was also dead after the null-window change.

What still binds this file to Electron is now `ipcMain` (75 uses, all handler
registration) and `powerMonitor` (2). That is a clean statement of the remaining
job: split logic from registration, the same shape already applied to preflight
and the SSH registry.

Test wiring: the shared `pty-ipc-suite-environment` beforeEach installs a fake
AppEnvironment that reads through the existing `vi.mock('electron')` app object
rather than freezing values — suites toggle `app.isPackaged` mid-test to exercise
dev-mode spawn paths, so the port has to observe the same mutable field. One edit
in the shared harness covers every pty suite.

Verified: 128 files / 1,290 tests across ipc/pty and providers; the built-artifact
acceptance smoke passes; typecheck and oxlint clean; ratchet unchanged at 25.

* refactor(pty): inject the ipcMain surface so the PTY module loads without Electron

This closes the round-3 blocker: "the doc never says how orcad installs
setPtyController without Electron."

`registerPtyHandlers` owns the `RuntimePtyController` that `terminal.create`
actually spawns through — the thing a Node backend needs and cannot get from the
provider thunks. The module was otherwise host-agnostic already; the only thing
pinning 8,031 lines to Electron was a static `ipcMain` / `powerMonitor` import used
purely to register renderer handlers that no headless host will ever receive.

`src/main/ipc/pty-host-bindings.ts` makes those surfaces settable, defaulting to
no-ops. Unlike AppEnvironment and SecretStore, the default does NOT throw: a host
with no renderer legitimately has nothing to register against, so not registering
handlers nobody can call is correct rather than a hidden downgrade. The desktop
installs the real objects in `attach-main-window-services` before its handlers run.

Also converts the remaining electron import to a top-level `import type`. oxlint's
`no-import-type-side-effects` caught that inline `type` specifiers still leave a
side-effect import — precisely the "type-only is not enough if esbuild still emits
require('electron')" trap a reviewer flagged.

**`src/main/ipc/pty.ts` now bundles with zero `require("electron")`.** A Node entry
can call `registerPtyHandlers(null, runtime, …)` and get a working PTY controller.

Verified: 128 files / 1,290 tests across ipc/pty and providers; the built-artifact
acceptance smoke passes end-to-end — which is the check that matters, since this
changes how every PTY handler registers; typecheck and oxlint clean.

* fix(pty-bindings): drop two unused eslint-disable directives

CI runs oxlint with unused-disable reporting; the two
`@typescript-eslint/no-explicit-any` suppressions I added were never triggered by
any enabled rule, so they failed static analysis as dead directives. The `any[]`
rest args stay — they mirror electron's own IpcMain signature, and narrowing them
would reject the real object at the desktop call site.

Verified with the exact CI invocation: `oxlint --format github` reports 0 warnings,
0 errors across the repo.

* fix(pty): install the host bindings per process, not per window

A real regression my own change introduced, caught by the SSH docker E2E
(`paired-startup-exec-readiness` — "recovers startup exec through a headed paired
desktop owner"). It reproduced on rerun, so it was not a flake.

`setPtyHostBindings` was called inside `attachMainWindowServices`, i.e. when a
window attaches. But `registerHeadlessPtyRuntime` (index.ts:3163) calls
`registerPtyHandlers` on the serve path *before* any window exists — so those
handlers registered against the no-op default and never reached the real `ipcMain`.
A paired desktop owner then attached to a runtime whose PTY handlers were wired to
nothing.

The bindings describe the *host*, not the *window*: an Electron main process always
has `ipcMain`, whether or not a window is open. Installing them beside
`setAppEnvironment`/`setSecretStore` at the top of bootstrap fixes both paths.

Verified: 128 files / 1,290 tests; the built-artifact acceptance smoke passes;
typecheck clean; `oxlint --format github` (the exact CI invocation) reports 0/0.

* feat(orcad): de-electron the runtime core and add the Node entry + build gate

**`src/main/runtime/orca-runtime.ts` — 41,048 lines — no longer imports electron.**
Its last three sites go through `runtime-desktop-surface.ts`: a native notification,
the authoritative-window lookup, and the one `ipcMain` channel used by the
renderer-backed tab-create fallback. All three are unreachable without a renderer —
`createTerminal` already takes the background branch when no window exists (stablyai#10333) —
so a Node host installs none and the runtime relays notifications to paired clients,
which is the better destination anyway. Ratchet 25 → 24.

Adds `src/main/orcad/orcad-entry.ts`: Node host adapters plus a `startOrcad` that
constructs the runtime, installs the PTY controller via `registerPtyHandlers(null, …)`,
and serves RPC. It sets two defaults the constructor gets wrong for a headless host —
`canRecoverPersistentLocalPtys: false` (no daemon here) and
`getDesktopWindowStatus: 'blocked'` (a Node host can never be promoted to a desktop
window, which is what `'openable'` claims).

Adds `config/scripts/build-orcad.mjs`, which **currently fails, on purpose**: 25
modules still import electron (browser and speech clusters, plugins, jira/proxy,
filesystem-watcher, and four `require('electron').app` one-liners). It names them.

Two bugs found while building it, both worth recording:
- The first bundle looked clean and was not. `electron` was bundleable, so esbuild
  rewrote the metafile `path` to the resolved file under node_modules and a check for
  `path === 'electron'` passed while the package was in the bundle — it failed at
  runtime with electron's own installer message. The check now reads `original`, and
  electron is marked external so a residual import fails loudly instead.
- `jsonc-parser`'s UMD build breaks the bundle at load; aliased to its ESM entry, the
  same fix `build-relay.mjs` already carries.

Verified: desktop unchanged — the built-artifact acceptance smoke passes, runtime/pty/
provider suites green, typecheck clean, `oxlint --format github` 0/0.

* refactor(host): drop the last two require('electron') app lookups

`computer/sidecar-client.ts` and `ports/port-scan-command-client.ts` read the app
root through `require('electron').app` inside a try/catch. Both were already correct
under plain Node at runtime — they return null when it throws — but the literal text
fails the plain-Node entry guard regardless, which is why port-scan carried a comment
warning it must never become reachable from a fork entry.

Reading the AppEnvironment port gives the identical "no app root here" answer without
the text, so that warning is now obsolete and the comment says so.

Ratchet 24 → 22. Every remaining entry is a real coupling: the browser cluster (15,
which variant B does not ship), speech (2), plugins (2), and jira/proxy-settings (2,
needing an HttpClient port for Chromium session partitions).

Verified: 25 files / 209 tests; acceptance smoke passes; typecheck and
`oxlint --format github` clean.

* docs(orcad): record that the ratchet under-counts orcad's graph

The ratchet reports 22 electron importers; the orcad build reports 23. The extra is
agent-hooks/wsl-hook-relay-launch.ts, and the cause is a gap in the gate rather than
a rounding error: the ratchet measures what orca-runtime + runtime-rpc reach, while
orcad's entry also imports ipc/pty directly to install the PTY controller.

Once orcad ships it must become a ratchet entry point, or the two numbers drift and
the gate quietly stops covering the artifact it exists for.

* refactor(runtime): inject the browser commands factory

Drops 14 modules from the runtime's Electron graph in one change — the whole Chromium
browser cluster. Ratchet 22 → 8.

`OrcaRuntimeService` constructed `RuntimeBrowserCommands` as a field initializer, and
that construction is what pulled in `BrowserWindow`, `session`, `webContents` and the
cookie jars. Importing the class for its *type* is free; only building it costs.

So the class import becomes `import type`, and the instance comes from
`runtime-browser-commands-factory.ts`. The desktop installs the real factory at the
Electron entry. **All ~80 existing `this.browserCommands.*.bind(...)` delegations are
untouched** — a review round specifically warned that rewriting those was the
expensive, risky part, and this avoids it entirely.

With no factory installed, browser commands reject per call with `browser_unavailable`
rather than resolving to a stub that silently succeeds. The runtime already filters
browser capabilities out of `getStatus()` when no backend exists, so clients do not
offer the affordance in the first place.

Also corrects a stale comment in `pty-renderer-surface.ts` that still described the
fake window as present tense; it was deleted two commits ago.

Verified: 451 files / 5,513 tests across `src/main/browser` and `src/main/runtime` —
the entire browser automation suite; the built-artifact acceptance smoke passes;
`pnpm typecheck` and `oxlint --format github` clean.

* refactor(host): extract the plugin client list and port two app lookups

Ratchet 8 → 5.

- `listPluginsForClients` moves to `src/main/plugins/plugin-client-list.ts`. It needed
  only three `plugins/*` helpers, none of them Electron — it was colocated with
  `ipcMain.handle` registrations, so the runtime's `plugins.list` RPC dragged all of
  Electron in to call a function that reads a lockfile. Same shape as preflight.
  Dropping it also releases `ipc/plugin-marketplaces.ts`.
- `agent-hooks/wsl-hook-relay-launch.ts` and `speech/stt-service.ts` read `getAppPath`
  and `isPackaged` through the AppEnvironment port.

The five that remain are all genuinely Chromium and need the HttpClient port or a
watcher split, not another mechanical swap: `browser/cdp-bridge` (webContents),
`ipc/filesystem-watcher` (ipcMain), `jira/authenticated-request` and
`network/proxy-settings` (net + session partitions), `speech/model-manager`
(`net.request`, which honors app proxy settings that Node https does not — replacing
it is a behaviour change, not a rename).

Verified: 219 files / 1,922 tests across plugins, speech, agent-hooks and the runtime
RPC methods; the built-artifact acceptance smoke passes; typecheck and
`oxlint --format github` clean.

* refactor(network): resolve the default proxy session lazily

Ratchet 5 → 4.

`proxy-settings.ts` needed exactly one Electron value: `session.defaultSession`, as
the fallback when a caller does not pass `options.proxySession`. Callers could already
inject a session; only the default was hard-wired. It now comes from a settable
resolver, so the module loads under plain Node.

**A resolver rather than a Session, because a Session eagerly throws.** The first
attempt installed `session.defaultSession` directly in pre-ready bootstrap and broke
startup outright — `TypeError: Session can only be received when app is ready`. The
acceptance smoke caught it before commit. Deferring to first use is always after ready.

Behaviour with no session is not a degradation: there is no Chromium proxy config to
discover, so `resolveProxy` is skipped and the environment variables become the whole
answer rather than a fallback. Applying rules to a session that does not exist is
likewise skipped; settings are still honoured because outbound requests read the env.

This reaches past Jira — a review round noted `ensureElectronProxyFromEnvironment` is
also on the Claude HTTP path via `oauth-refresh.ts` and `rate-limits/claude-fetcher.ts`.

Verified: 48 files / 526 tests across network, jira and rate-limits; the
built-artifact acceptance smoke passes; typecheck and `oxlint --format github` clean.

* fix(index): merge the duplicate proxy-settings import

CI's code-quality lint (`oxlint --config config/oxlint-code-quality-native-plugins.json
--deny-warnings`) flags a module imported twice in one file. My earlier insertion added
a second `./network/proxy-settings` import beside the existing one.

Verified with CI's exact invocation: exit 0.

* refactor(network): add the HttpClient port and lift BrowserError out of cdp-bridge

Ratchet 4 → 2.

Two unrelated couplings, both of the same shape — a small thing living inside a
Chromium-heavy file.

`BrowserError` is a seven-line error class with no dependencies, but it lived in
`browser/cdp-bridge.ts`, which imports `webContents`. The runtime catches that type on
paths with nothing to do with CDP, so one import kept a Node host from loading the
runtime at all. Moved to `browser/browser-error.ts`; cdp-bridge re-exports it.

`jira/authenticated-request.ts` fetches through `net.fetch` and reads
`session.defaultSession`. `network/http-client.ts` makes both settable. This one is a
**named port rather than a silent fallback, because the fallback is not transparent**:
Electron's net follows Chromium session/proxy state, avoids undici's stale keep-alive
sockets after a VPN path change, and sends a Chrome user agent that Jira's XSRF check
depends on. A Node host gets `globalThis.fetch`, reads proxy config from the
environment, and sends Node's user agent. That difference is documented at the port.

`session.defaultSession` is read per call, not captured at install — it throws before
the app is ready, which is the mistake the previous commit made and the acceptance
smoke caught.

Test wiring: `jira/client.test.ts` installs the port *inside* `loadClientModule`, after
its `vi.resetModules()`, since the reset gives the module a fresh singleton.

Verified: 461 files / 5,616 tests across jira, browser, network and runtime; the
built-artifact acceptance smoke passes; typecheck, `oxlint --format github` and the
code-quality lint with `--deny-warnings` all clean.

* fix(http-client): register the Node fetch fallback with the call-site audit

`global-fetch-call-site-audit.test.ts` guards every global-fetch use, because the
global runs on undici where an unread response body can crash the whole process
(orca#8695). The HttpClient port's Node fallback is a new such call site and was
unregistered — the guard caught it in a full-suite run.

Registered with the reasoning, and the port's doc comment now states the body-safety
contract explicitly: it hands the Response straight to its caller and never inspects
it, so the consume/cancel obligation stays exactly where it already was — with the
caller, unchanged from when they called Electron's net directly.

Two comments elsewhere mentioned the global by name and tripped the line scan as false
positives; reworded to describe the behaviour rather than name the API.

Verified: audit passes; typecheck and `oxlint --format github` clean.

* fix(app-environment): read hasAppEnvironment through the realm slot
Jinwoo-H added a commit that referenced this pull request Aug 24, 2026
Textual conflicts (7 files) resolved as semantic merges — both sides kept in
every case; no side was dropped.

Beyond the textual conflicts, main added four gates and one behaviour that this
branch's new code violated. Fixed in this merge:

- runtime-electron ratchet (#15968): the branch's `rpc/methods/browser-network-tunnel.ts`
  reached `ipc/ssh.ts`, dragging 20 Electron modules back into the runtime graph the
  orcad work had just emptied. The connection-manager accessor moves to
  `ssh/ssh-target-registry.ts` (the same extraction #15927 did for the other five
  accessors) and the dispatch reads it there; `wsl-browser-network-relay-launch.ts`
  reads the app root through the AppEnvironment port. Baseline back to 0 entries.

- HTML side-preview focus (STA-5001, #15716): main keeps the source editor focused
  when the reserved preview split is still empty, by steering the visible tab. This
  branch's client-owned placement reconciler decides the active group on its own and
  bypassed that, refocusing the preview. It now takes the same fallback tab.

- child_process / windowsHide / wsl.exe census gates: the WSL browser-network relay
  launcher moves onto `spawnProcess`, and the two Electron test launchers now spawn
  with `windowsHide`. The four sites that cannot migrate today are allowlisted with
  their reason (detached process-group kill, a non-all-pipes stdio shape, and a
  long-lived streaming wsl.exe child that `runWslProcess` cannot express).

- max-lines: both sides grew `package-electron-runtime-contract.test.mjs`; the union
  crossed 600. This branch's two additions move to
  `config/scripts/client-hosted-browser-package-coverage.test.mjs`.

Also ports four browser-create test files onto main's
`applyWebSessionTabsSnapshot`/`decideWebSessionTabsSnapshot` split (#15644).

Gates: typecheck 0 errors, `pnpm lint` exit 0, 6316/6369 test files green. The 12
remaining failures are pre-existing on one or both parents (5 packaging tests need a
real `pnpm install`, global-fetch audit and 4 others fail on both parents) or flaky.
nwparker added a commit that referenced this pull request Aug 25, 2026
#15927 made `registerPtyHandlers` accept `BrowserWindow | null` so the headless
path could pass null instead of faking a window. #15172 reverted that signature
while splitting the PTY monolith, but the comments describing it survived, so
three of them now document an API that does not exist.

- orcad-entry.ts: the module docstring claimed orcad installs its controller via
  `registerPtyHandlers(null, …)`. It uses `registerHeadlessPtyRuntime`, and null
  is not accepted. It also claimed desktop surfaces are "declared rather than
  faked" — true except for the renderer window, which is still faked.
- register-headless-runtime.ts: record why the fake is safe rather than leaving
  `isDestroyed: () => true` looking arbitrary. It is load-bearing: every
  renderer-liveness guard reads it and skips, so no send is attempted.

Also gives the fake a `webContents.isDestroyed`. The real guards check both, and
a missing method reads as "alive" — the same gap this PR fixes in the test fake.
No behavior change: the window-level check already short-circuits.

Verified: 45 tests across the liveness-guard, startup-barrier, management and
kill/exit suites; pnpm typecheck clean; oxlint clean.
nwparker added a commit that referenced this pull request Aug 25, 2026
…73) (#16345)

* test(pty): pin the renderer-liveness guard STA-2373 relies on (STA-5373)

STA-5373 reported that #15927 dropped the `webContents.isDestroyed()` half of
the guard #10065 added for STA-2373, and that the app therefore dies when a
daemon death fans out to every pane. The guard is present on main: #15172
restored it at both senders when it split the PTY monolith, and a per-file
count across v1.4.188..HEAD shows only relocation (pty.ts:4 ->
write-input.ts:2 + bind-listeners.ts:2). The reported 4 -> 0 was scoped to
`src/main/ipc/pty.ts`, now a 39-line barrel. No production fix is needed.

What was real is that nothing pinned the guard — it survived #15927 only
because #15172 happened to re-expand it — and the shared PTY test fake made
that invisible: its `webContents` had no `isDestroyed` at all, so both guards
passed vacuously in every suite. That is also why they are written defensively
as `typeof ... === 'function' && ...`.

- Give the fake an `isDestroyed` mock, re-stubbed to `false` each beforeEach
  rather than left `undefined`, so "alive" is stated rather than accidental.
- Cover both senders red/green: the daemon-death fan-out
  (bind-listeners.ts:37) and the per-write reporter (write-input.ts:57).
  Verified red against a window-only guard and green with the real one.

The per-write case needs a chunked write. A single-chunk write is already
fenced by `isPtyWriteEventFromMainWindow`, which rejects the event once the
WebContents is gone; only the multi-chunk path yields a macrotask mid-write,
letting the renderer die after the sender check passes. That is the sole route
to this sender with a dead WebContents, and what makes its own guard
load-bearing.

Also deletes `src/main/ipc/pty-renderer-surface.ts`: zero importers repo-wide,
and its `isRendererGone` is exactly the weakened predicate. Its comment claims
the headless path "now passes null", but register-headless-runtime.ts:26 still
fakes `{ isDestroyed: () => true }` — #15172 rolled that back too. Adopting it
would reintroduce STA-5373 for real.

Verified: 17 tests across the two pty write suites; full src/main/ipc run 3156
pass (4 pre-existing @parcel/watcher failures in filesystem-watcher-real and
worktree-base-directory-poller, unrelated and failing identically on a
pristine tree); pnpm typecheck clean; oxlint clean.

* docs(pty): correct headless-path comments the #15172 rebase left stale

#15927 made `registerPtyHandlers` accept `BrowserWindow | null` so the headless
path could pass null instead of faking a window. #15172 reverted that signature
while splitting the PTY monolith, but the comments describing it survived, so
three of them now document an API that does not exist.

- orcad-entry.ts: the module docstring claimed orcad installs its controller via
  `registerPtyHandlers(null, …)`. It uses `registerHeadlessPtyRuntime`, and null
  is not accepted. It also claimed desktop surfaces are "declared rather than
  faked" — true except for the renderer window, which is still faked.
- register-headless-runtime.ts: record why the fake is safe rather than leaving
  `isDestroyed: () => true` looking arbitrary. It is load-bearing: every
  renderer-liveness guard reads it and skips, so no send is attempted.

Also gives the fake a `webContents.isDestroyed`. The real guards check both, and
a missing method reads as "alive" — the same gap this PR fixes in the test fake.
No behavior change: the window-level check already short-circuits.

Verified: 45 tests across the liveness-guard, startup-barrier, management and
kill/exit suites; pnpm typecheck clean; oxlint clean.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 25, 2026
…73) (stablyai#16345)

* test(pty): pin the renderer-liveness guard STA-2373 relies on (STA-5373)

STA-5373 reported that stablyai#15927 dropped the `webContents.isDestroyed()` half of
the guard stablyai#10065 added for STA-2373, and that the app therefore dies when a
daemon death fans out to every pane. The guard is present on main: stablyai#15172
restored it at both senders when it split the PTY monolith, and a per-file
count across v1.4.188..HEAD shows only relocation (pty.ts:4 ->
write-input.ts:2 + bind-listeners.ts:2). The reported 4 -> 0 was scoped to
`src/main/ipc/pty.ts`, now a 39-line barrel. No production fix is needed.

What was real is that nothing pinned the guard — it survived stablyai#15927 only
because stablyai#15172 happened to re-expand it — and the shared PTY test fake made
that invisible: its `webContents` had no `isDestroyed` at all, so both guards
passed vacuously in every suite. That is also why they are written defensively
as `typeof ... === 'function' && ...`.

- Give the fake an `isDestroyed` mock, re-stubbed to `false` each beforeEach
  rather than left `undefined`, so "alive" is stated rather than accidental.
- Cover both senders red/green: the daemon-death fan-out
  (bind-listeners.ts:37) and the per-write reporter (write-input.ts:57).
  Verified red against a window-only guard and green with the real one.

The per-write case needs a chunked write. A single-chunk write is already
fenced by `isPtyWriteEventFromMainWindow`, which rejects the event once the
WebContents is gone; only the multi-chunk path yields a macrotask mid-write,
letting the renderer die after the sender check passes. That is the sole route
to this sender with a dead WebContents, and what makes its own guard
load-bearing.

Also deletes `src/main/ipc/pty-renderer-surface.ts`: zero importers repo-wide,
and its `isRendererGone` is exactly the weakened predicate. Its comment claims
the headless path "now passes null", but register-headless-runtime.ts:26 still
fakes `{ isDestroyed: () => true }` — stablyai#15172 rolled that back too. Adopting it
would reintroduce STA-5373 for real.

Verified: 17 tests across the two pty write suites; full src/main/ipc run 3156
pass (4 pre-existing @parcel/watcher failures in filesystem-watcher-real and
worktree-base-directory-poller, unrelated and failing identically on a
pristine tree); pnpm typecheck clean; oxlint clean.

* docs(pty): correct headless-path comments the stablyai#15172 rebase left stale

path could pass null instead of faking a window. stablyai#15172 reverted that signature
while splitting the PTY monolith, but the comments describing it survived, so
three of them now document an API that does not exist.

- orcad-entry.ts: the module docstring claimed orcad installs its controller via
  `registerPtyHandlers(null, …)`. It uses `registerHeadlessPtyRuntime`, and null
  is not accepted. It also claimed desktop surfaces are "declared rather than
  faked" — true except for the renderer window, which is still faked.
- register-headless-runtime.ts: record why the fake is safe rather than leaving
  `isDestroyed: () => true` looking arbitrary. It is load-bearing: every
  renderer-liveness guard reads it and skips, so no send is attempted.

Also gives the fake a `webContents.isDestroyed`. The real guards check both, and
a missing method reads as "alive" — the same gap this PR fixes in the test fake.
No behavior change: the window-level check already short-circuits.

Verified: 45 tests across the liveness-guard, startup-barrier, management and
kill/exit suites; pnpm typecheck clean; oxlint clean.

(cherry picked from commit 0bfd380)
Pierre-Mike pushed a commit to Pierre-Mike/orca that referenced this pull request Aug 26, 2026
…73) (stablyai#16345)

* test(pty): pin the renderer-liveness guard STA-2373 relies on (STA-5373)

STA-5373 reported that stablyai#15927 dropped the `webContents.isDestroyed()` half of
the guard stablyai#10065 added for STA-2373, and that the app therefore dies when a
daemon death fans out to every pane. The guard is present on main: stablyai#15172
restored it at both senders when it split the PTY monolith, and a per-file
count across v1.4.188..HEAD shows only relocation (pty.ts:4 ->
write-input.ts:2 + bind-listeners.ts:2). The reported 4 -> 0 was scoped to
`src/main/ipc/pty.ts`, now a 39-line barrel. No production fix is needed.

What was real is that nothing pinned the guard — it survived stablyai#15927 only
because stablyai#15172 happened to re-expand it — and the shared PTY test fake made
that invisible: its `webContents` had no `isDestroyed` at all, so both guards
passed vacuously in every suite. That is also why they are written defensively
as `typeof ... === 'function' && ...`.

- Give the fake an `isDestroyed` mock, re-stubbed to `false` each beforeEach
  rather than left `undefined`, so "alive" is stated rather than accidental.
- Cover both senders red/green: the daemon-death fan-out
  (bind-listeners.ts:37) and the per-write reporter (write-input.ts:57).
  Verified red against a window-only guard and green with the real one.

The per-write case needs a chunked write. A single-chunk write is already
fenced by `isPtyWriteEventFromMainWindow`, which rejects the event once the
WebContents is gone; only the multi-chunk path yields a macrotask mid-write,
letting the renderer die after the sender check passes. That is the sole route
to this sender with a dead WebContents, and what makes its own guard
load-bearing.

Also deletes `src/main/ipc/pty-renderer-surface.ts`: zero importers repo-wide,
and its `isRendererGone` is exactly the weakened predicate. Its comment claims
the headless path "now passes null", but register-headless-runtime.ts:26 still
fakes `{ isDestroyed: () => true }` — stablyai#15172 rolled that back too. Adopting it
would reintroduce STA-5373 for real.

Verified: 17 tests across the two pty write suites; full src/main/ipc run 3156
pass (4 pre-existing @parcel/watcher failures in filesystem-watcher-real and
worktree-base-directory-poller, unrelated and failing identically on a
pristine tree); pnpm typecheck clean; oxlint clean.

* docs(pty): correct headless-path comments the stablyai#15172 rebase left stale

stablyai#15927 made `registerPtyHandlers` accept `BrowserWindow | null` so the headless
path could pass null instead of faking a window. stablyai#15172 reverted that signature
while splitting the PTY monolith, but the comments describing it survived, so
three of them now document an API that does not exist.

- orcad-entry.ts: the module docstring claimed orcad installs its controller via
  `registerPtyHandlers(null, …)`. It uses `registerHeadlessPtyRuntime`, and null
  is not accepted. It also claimed desktop surfaces are "declared rather than
  faked" — true except for the renderer window, which is still faked.
- register-headless-runtime.ts: record why the fake is safe rather than leaving
  `isDestroyed: () => true` looking arbitrary. It is load-bearing: every
  renderer-liveness guard reads it and skips, so no send is attempted.

Also gives the fake a `webContents.isDestroyed`. The real guards check both, and
a missing method reads as "alive" — the same gap this PR fixes in the test fake.
No behavior change: the window-level check already short-circuits.

Verified: 45 tests across the liveness-guard, startup-barrier, management and
kill/exit suites; pnpm typecheck clean; oxlint clean.

(cherry picked from commit 0bfd380)
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
…dules (stablyai#15927)

* refactor(preflight): split agent detection out of the ipcMain registration

First of the IPC extractions the revised design requires. `src/main/ipc/preflight.ts`
mixed 285 lines of agent/tool detection with 35 lines of `ipcMain.handle`
registration, and the runtime calls that detection during normal operation
(`orca-runtime.ts:573`, plus the preflight RPC methods). So the runtime dragged
`ipcMain` into its graph to reach pure logic.

Detection moves to `src/main/preflight/agent-detection.ts` — named for what it
contains, per AGENTS.md. `ipc/preflight.ts` keeps only the handler registration and
re-exports the domain module so existing importers are unaffected. The runtime and
its RPC methods now import the domain module directly.

Ratchet baseline 36 → 35: `src/main/ipc/preflight.ts` is no longer reachable from
the runtime. The gate detected the improvement and refused to pass until the
baseline tightened, which is the behaviour it was built for.

Verified: 2 files / 1,187 tests pass across every suite touching preflight;
`pnpm typecheck` clean; `oxlint` clean.

* refactor(ssh): split the SSH target registry out of the ipcMain module

Second IPC extraction, and by far the biggest win: this removes **eight** modules
from the runtime's Electron graph, taking the ratchet baseline 35 → 27.

The runtime needed five thin accessors from `src/main/ipc/ssh.ts` —
`connectRegisteredSshTarget`, `getRegisteredSshState`, `listRegisteredSshTargets`,
`listRegisteredRemovedSshTargetLabels`, `getActiveMultiplexer`. Each is a one-line
read over module-level state. Importing them dragged in `ipcMain`, `powerMonitor`
and a `BrowserWindow` accessor — and, transitively, `ipc/pty.ts` (8,031 lines),
`ssh-browse`, `ssh-passphrase`, `ssh-relay-deploy`, `ssh-remote-cli-host-passthrough`,
`wsl-hook-relay-launch` and `user-data-path`.

`src/main/ssh/ssh-target-registry.ts` now holds that state plus its accessors.
`registerSshHandlers` populates it; the runtime reads it. The indirection is kept
deliberately: SSH providers register after construction and may reconnect, so
callers must resolve the current generation rather than freeze one.
`ipc/ssh.ts` re-exports all five, so non-test importers are unaffected.

`connectRegisteredSshTarget` still throws `ssh_handlers_not_registered` when no
handler layer registered — a headless host must fail loudly rather than report a
target as unreachable, which would read as `exited` (see ssh-execution-boundary.md).

Verified: 9 files / 59 tests across the ssh, automations and trust-preset suites;
orca-runtime.test.ts 1,183 pass; `pnpm typecheck` clean; `oxlint` clean.

* refactor(host): resolve the app root through the port in fork-reachable modules

`parcel-watcher-entry-path.ts` and `session-scanner-service-entry-path.ts` read the
app root via `require('electron').app` inside a try/catch that already returns null
when Electron is absent. They were therefore correct under plain Node at runtime and
only failed the *static* text check — which is real, not pedantic: the comment in
`ports/port-scan-command-client.ts:19` records that the plain-node-entry-guard fails
on that literal text, try/catch or not.

`hasAppEnvironment() ? getAppEnvironment() : null` gives the identical "no app root
here" answer without the text. That restores `hasAppEnvironment`, which an earlier
commit in this stack deleted as unused — it now has the caller it was waiting for.

Ratchet baseline 27 → 25.

Verified: 74 files / 458 tests; `pnpm typecheck` clean; `oxlint` clean.

* test(ssh): mock the SSH target registry alongside the ipc/ssh mock

Thirty-eight suites mocked `vi.mock('./ssh')` for `getActiveMultiplexer`. That
factory went inert when production started importing the accessor from
`../ssh/ssh-target-registry`, so the real module loaded and the assertions drifted.

Adds a companion registry mock returning the same stub, plus a
`sshTargetRegistryModuleMock` builder beside the existing `sshModuleMock` so the
shared harness stays one place. No assertion changed.

Found by a full-suite run: the targeted ssh/runtime suites were green while
30 tests in ipc/worktrees and ipc/repos were not.

* refactor(runtime): read app paths and the packaged flag through the port

`orca-runtime.ts` is the last module in its own graph that imports `electron`
directly. Nineteen of its uses were `app.getPath` (12) and `app.isPackaged` (7) —
exactly what the AppEnvironment port already covers.

Also removes a dead `const { app } = require('electron')` inside
`getOrchestrationDb`. It was left unused once the path came from the port, and it
is precisely the dynamic-require pattern `plain-node-entry-guard.ts` exists to
catch, sitting in the runtime's own constructor path.

What still binds `orca-runtime.ts` to Electron is now three sites, not nineteen:
`new Notification(...)` (one), `BrowserWindow.fromId` (one), and the
`ipcMain.on('terminal:tabCreateReply')` renderer round-trip — which is the browser
tab path, and the same one that would hang a headless host for ten seconds.

Two suites drove `electronMocks.app.isPackaged` directly; they now install a fake
AppEnvironment reading the same mutable field, so their per-test toggles work
unchanged and no assertion moved.

Verified: 376 files / 4,717 tests across src/main/runtime; typecheck and oxlint clean.

* test(serve): add the built-artifact terminal round-trip acceptance smoke

"The server started" proves almost nothing. Terminal creation dispatches into
OrcaRuntimeService, and without an installed headless PTY controller that path
falls through to a renderer reply that never arrives and times out after ten
seconds. A boot probe, a port bind, and a `host.platform` call all pass against a
server whose terminals are dead — which is exactly the gap the design doc's own
boot proof was retracted for.

This boots the BUILT `out/main/index.js --serve`, parses its ready payload, pairs a
real client over the advertised endpoint, lists worktrees, creates a terminal, runs
a command through the PTY, asserts the output comes back, and asserts clean
shutdown. It drives nothing but the public pairing + RPC surface, so the same
script is the acceptance gate a future Node-only backend must pass unchanged.

The sentinel invokes `process.execPath` rather than `echo`, because the shell
differs per platform and node does not.

Verified both directions: passes against the real server, and fails with an
actionable message when the command produces no output — a smoke that cannot fail
is worthless.

* fix(ssh): fail loudly when the multiplexer resolver was never installed

`getActiveMultiplexer` resolves through a resolver that `ipc/ssh.ts` installs at
module scope. A process that never loads the SSH layer — which is the whole point
of the Node-only backend — would get `undefined` from every call.

`undefined` already means something specific here: "not connected". So a missing
resolver and a disconnected target were indistinguishable, and a host with no SSH
layer would quietly report every target as not connected. That is the
unverifiable-reported-as-exited conflation `docs/reference/ssh-execution-boundary.md`
exists to prevent — the doc is explicit that absence of contact is never evidence
of absence of the thing.

A missing resolver is a wiring error, not a connection state, so it throws, matching
what `connectRegisteredSshTarget` already does for unregistered handlers.

Verified: 432 files / 4,759 tests across ipc, ssh, preflight, automations and trust
presets; typecheck and oxlint clean.

* refactor(pty): stop faking a BrowserWindow for the headless PTY path

`registerHeadlessPtyRuntime` passed `registerPtyHandlers` a stub object cast to
`BrowserWindow` whose `isDestroyed()` returned true and whose `webContents.send`
was a no-op — a window-shaped thing that lied about being a window, purely to
satisfy the type. Adversarial review named it as the same "looks fine, silently
returns a lie" pattern this codebase rejects elsewhere, and it is the shape that
keeps `electron` on a path that otherwise needs none.

`registerPtyHandlers` now takes `BrowserWindow | null`. An absent renderer is
semantically identical to a destroyed one — all 42 call sites already guarded on
`isDestroyed()` and skipped — so `src/main/ipc/pty-renderer-surface.ts` states that
directly: `isRendererGone`, `sendToRenderer`, `rendererWebContents`. The compound
`isDestroyed() || webContents.isDestroyed()` guards collapse into one predicate.

`isPtyWriteEventFromMainWindow` becomes null-tolerant and fails closed: with no
renderer no sender can legitimately match, so every write is rejected. Those
handlers cannot fire headless today, but failing closed is the right answer if that
ever changes.

This is the precondition for installing a PTY controller without Electron, which is
what a Node-only backend needs and what `terminal.create` actually calls.

Verified: 129 files / 2,473 tests across ipc/pty, providers and orca-runtime; the
built-artifact acceptance smoke still passes end-to-end (boot → pair →
terminal.create → sentinel → close), which is the check that matters most here
since this changes the headless PTY path itself; typecheck and oxlint clean.

* refactor(pty): read app paths and the packaged flag through the port

Follows the fake-window removal. `ipc/pty.ts` had nine `app.*` reads — all
`getPath`, `getVersion` or `isPackaged` — which the AppEnvironment port already
covers. The `BrowserWindow` import was also dead after the null-window change.

What still binds this file to Electron is now `ipcMain` (75 uses, all handler
registration) and `powerMonitor` (2). That is a clean statement of the remaining
job: split logic from registration, the same shape already applied to preflight
and the SSH registry.

Test wiring: the shared `pty-ipc-suite-environment` beforeEach installs a fake
AppEnvironment that reads through the existing `vi.mock('electron')` app object
rather than freezing values — suites toggle `app.isPackaged` mid-test to exercise
dev-mode spawn paths, so the port has to observe the same mutable field. One edit
in the shared harness covers every pty suite.

Verified: 128 files / 1,290 tests across ipc/pty and providers; the built-artifact
acceptance smoke passes; typecheck and oxlint clean; ratchet unchanged at 25.

* refactor(pty): inject the ipcMain surface so the PTY module loads without Electron

This closes the round-3 blocker: "the doc never says how orcad installs
setPtyController without Electron."

`registerPtyHandlers` owns the `RuntimePtyController` that `terminal.create`
actually spawns through — the thing a Node backend needs and cannot get from the
provider thunks. The module was otherwise host-agnostic already; the only thing
pinning 8,031 lines to Electron was a static `ipcMain` / `powerMonitor` import used
purely to register renderer handlers that no headless host will ever receive.

`src/main/ipc/pty-host-bindings.ts` makes those surfaces settable, defaulting to
no-ops. Unlike AppEnvironment and SecretStore, the default does NOT throw: a host
with no renderer legitimately has nothing to register against, so not registering
handlers nobody can call is correct rather than a hidden downgrade. The desktop
installs the real objects in `attach-main-window-services` before its handlers run.

Also converts the remaining electron import to a top-level `import type`. oxlint's
`no-import-type-side-effects` caught that inline `type` specifiers still leave a
side-effect import — precisely the "type-only is not enough if esbuild still emits
require('electron')" trap a reviewer flagged.

**`src/main/ipc/pty.ts` now bundles with zero `require("electron")`.** A Node entry
can call `registerPtyHandlers(null, runtime, …)` and get a working PTY controller.

Verified: 128 files / 1,290 tests across ipc/pty and providers; the built-artifact
acceptance smoke passes end-to-end — which is the check that matters, since this
changes how every PTY handler registers; typecheck and oxlint clean.

* fix(pty-bindings): drop two unused eslint-disable directives

CI runs oxlint with unused-disable reporting; the two
`@typescript-eslint/no-explicit-any` suppressions I added were never triggered by
any enabled rule, so they failed static analysis as dead directives. The `any[]`
rest args stay — they mirror electron's own IpcMain signature, and narrowing them
would reject the real object at the desktop call site.

Verified with the exact CI invocation: `oxlint --format github` reports 0 warnings,
0 errors across the repo.

* fix(pty): install the host bindings per process, not per window

A real regression my own change introduced, caught by the SSH docker E2E
(`paired-startup-exec-readiness` — "recovers startup exec through a headed paired
desktop owner"). It reproduced on rerun, so it was not a flake.

`setPtyHostBindings` was called inside `attachMainWindowServices`, i.e. when a
window attaches. But `registerHeadlessPtyRuntime` (index.ts:3163) calls
`registerPtyHandlers` on the serve path *before* any window exists — so those
handlers registered against the no-op default and never reached the real `ipcMain`.
A paired desktop owner then attached to a runtime whose PTY handlers were wired to
nothing.

The bindings describe the *host*, not the *window*: an Electron main process always
has `ipcMain`, whether or not a window is open. Installing them beside
`setAppEnvironment`/`setSecretStore` at the top of bootstrap fixes both paths.

Verified: 128 files / 1,290 tests; the built-artifact acceptance smoke passes;
typecheck clean; `oxlint --format github` (the exact CI invocation) reports 0/0.

* feat(orcad): de-electron the runtime core and add the Node entry + build gate

**`src/main/runtime/orca-runtime.ts` — 41,048 lines — no longer imports electron.**
Its last three sites go through `runtime-desktop-surface.ts`: a native notification,
the authoritative-window lookup, and the one `ipcMain` channel used by the
renderer-backed tab-create fallback. All three are unreachable without a renderer —
`createTerminal` already takes the background branch when no window exists (stablyai#10333) —
so a Node host installs none and the runtime relays notifications to paired clients,
which is the better destination anyway. Ratchet 25 → 24.

Adds `src/main/orcad/orcad-entry.ts`: Node host adapters plus a `startOrcad` that
constructs the runtime, installs the PTY controller via `registerPtyHandlers(null, …)`,
and serves RPC. It sets two defaults the constructor gets wrong for a headless host —
`canRecoverPersistentLocalPtys: false` (no daemon here) and
`getDesktopWindowStatus: 'blocked'` (a Node host can never be promoted to a desktop
window, which is what `'openable'` claims).

Adds `config/scripts/build-orcad.mjs`, which **currently fails, on purpose**: 25
modules still import electron (browser and speech clusters, plugins, jira/proxy,
filesystem-watcher, and four `require('electron').app` one-liners). It names them.

Two bugs found while building it, both worth recording:
- The first bundle looked clean and was not. `electron` was bundleable, so esbuild
  rewrote the metafile `path` to the resolved file under node_modules and a check for
  `path === 'electron'` passed while the package was in the bundle — it failed at
  runtime with electron's own installer message. The check now reads `original`, and
  electron is marked external so a residual import fails loudly instead.
- `jsonc-parser`'s UMD build breaks the bundle at load; aliased to its ESM entry, the
  same fix `build-relay.mjs` already carries.

Verified: desktop unchanged — the built-artifact acceptance smoke passes, runtime/pty/
provider suites green, typecheck clean, `oxlint --format github` 0/0.

* refactor(host): drop the last two require('electron') app lookups

`computer/sidecar-client.ts` and `ports/port-scan-command-client.ts` read the app
root through `require('electron').app` inside a try/catch. Both were already correct
under plain Node at runtime — they return null when it throws — but the literal text
fails the plain-Node entry guard regardless, which is why port-scan carried a comment
warning it must never become reachable from a fork entry.

Reading the AppEnvironment port gives the identical "no app root here" answer without
the text, so that warning is now obsolete and the comment says so.

Ratchet 24 → 22. Every remaining entry is a real coupling: the browser cluster (15,
which variant B does not ship), speech (2), plugins (2), and jira/proxy-settings (2,
needing an HttpClient port for Chromium session partitions).

Verified: 25 files / 209 tests; acceptance smoke passes; typecheck and
`oxlint --format github` clean.

* docs(orcad): record that the ratchet under-counts orcad's graph

The ratchet reports 22 electron importers; the orcad build reports 23. The extra is
agent-hooks/wsl-hook-relay-launch.ts, and the cause is a gap in the gate rather than
a rounding error: the ratchet measures what orca-runtime + runtime-rpc reach, while
orcad's entry also imports ipc/pty directly to install the PTY controller.

Once orcad ships it must become a ratchet entry point, or the two numbers drift and
the gate quietly stops covering the artifact it exists for.

* refactor(runtime): inject the browser commands factory

Drops 14 modules from the runtime's Electron graph in one change — the whole Chromium
browser cluster. Ratchet 22 → 8.

`OrcaRuntimeService` constructed `RuntimeBrowserCommands` as a field initializer, and
that construction is what pulled in `BrowserWindow`, `session`, `webContents` and the
cookie jars. Importing the class for its *type* is free; only building it costs.

So the class import becomes `import type`, and the instance comes from
`runtime-browser-commands-factory.ts`. The desktop installs the real factory at the
Electron entry. **All ~80 existing `this.browserCommands.*.bind(...)` delegations are
untouched** — a review round specifically warned that rewriting those was the
expensive, risky part, and this avoids it entirely.

With no factory installed, browser commands reject per call with `browser_unavailable`
rather than resolving to a stub that silently succeeds. The runtime already filters
browser capabilities out of `getStatus()` when no backend exists, so clients do not
offer the affordance in the first place.

Also corrects a stale comment in `pty-renderer-surface.ts` that still described the
fake window as present tense; it was deleted two commits ago.

Verified: 451 files / 5,513 tests across `src/main/browser` and `src/main/runtime` —
the entire browser automation suite; the built-artifact acceptance smoke passes;
`pnpm typecheck` and `oxlint --format github` clean.

* refactor(host): extract the plugin client list and port two app lookups

Ratchet 8 → 5.

- `listPluginsForClients` moves to `src/main/plugins/plugin-client-list.ts`. It needed
  only three `plugins/*` helpers, none of them Electron — it was colocated with
  `ipcMain.handle` registrations, so the runtime's `plugins.list` RPC dragged all of
  Electron in to call a function that reads a lockfile. Same shape as preflight.
  Dropping it also releases `ipc/plugin-marketplaces.ts`.
- `agent-hooks/wsl-hook-relay-launch.ts` and `speech/stt-service.ts` read `getAppPath`
  and `isPackaged` through the AppEnvironment port.

The five that remain are all genuinely Chromium and need the HttpClient port or a
watcher split, not another mechanical swap: `browser/cdp-bridge` (webContents),
`ipc/filesystem-watcher` (ipcMain), `jira/authenticated-request` and
`network/proxy-settings` (net + session partitions), `speech/model-manager`
(`net.request`, which honors app proxy settings that Node https does not — replacing
it is a behaviour change, not a rename).

Verified: 219 files / 1,922 tests across plugins, speech, agent-hooks and the runtime
RPC methods; the built-artifact acceptance smoke passes; typecheck and
`oxlint --format github` clean.

* refactor(network): resolve the default proxy session lazily

Ratchet 5 → 4.

`proxy-settings.ts` needed exactly one Electron value: `session.defaultSession`, as
the fallback when a caller does not pass `options.proxySession`. Callers could already
inject a session; only the default was hard-wired. It now comes from a settable
resolver, so the module loads under plain Node.

**A resolver rather than a Session, because a Session eagerly throws.** The first
attempt installed `session.defaultSession` directly in pre-ready bootstrap and broke
startup outright — `TypeError: Session can only be received when app is ready`. The
acceptance smoke caught it before commit. Deferring to first use is always after ready.

Behaviour with no session is not a degradation: there is no Chromium proxy config to
discover, so `resolveProxy` is skipped and the environment variables become the whole
answer rather than a fallback. Applying rules to a session that does not exist is
likewise skipped; settings are still honoured because outbound requests read the env.

This reaches past Jira — a review round noted `ensureElectronProxyFromEnvironment` is
also on the Claude HTTP path via `oauth-refresh.ts` and `rate-limits/claude-fetcher.ts`.

Verified: 48 files / 526 tests across network, jira and rate-limits; the
built-artifact acceptance smoke passes; typecheck and `oxlint --format github` clean.

* fix(index): merge the duplicate proxy-settings import

CI's code-quality lint (`oxlint --config config/oxlint-code-quality-native-plugins.json
--deny-warnings`) flags a module imported twice in one file. My earlier insertion added
a second `./network/proxy-settings` import beside the existing one.

Verified with CI's exact invocation: exit 0.

* refactor(network): add the HttpClient port and lift BrowserError out of cdp-bridge

Ratchet 4 → 2.

Two unrelated couplings, both of the same shape — a small thing living inside a
Chromium-heavy file.

`BrowserError` is a seven-line error class with no dependencies, but it lived in
`browser/cdp-bridge.ts`, which imports `webContents`. The runtime catches that type on
paths with nothing to do with CDP, so one import kept a Node host from loading the
runtime at all. Moved to `browser/browser-error.ts`; cdp-bridge re-exports it.

`jira/authenticated-request.ts` fetches through `net.fetch` and reads
`session.defaultSession`. `network/http-client.ts` makes both settable. This one is a
**named port rather than a silent fallback, because the fallback is not transparent**:
Electron's net follows Chromium session/proxy state, avoids undici's stale keep-alive
sockets after a VPN path change, and sends a Chrome user agent that Jira's XSRF check
depends on. A Node host gets `globalThis.fetch`, reads proxy config from the
environment, and sends Node's user agent. That difference is documented at the port.

`session.defaultSession` is read per call, not captured at install — it throws before
the app is ready, which is the mistake the previous commit made and the acceptance
smoke caught.

Test wiring: `jira/client.test.ts` installs the port *inside* `loadClientModule`, after
its `vi.resetModules()`, since the reset gives the module a fresh singleton.

Verified: 461 files / 5,616 tests across jira, browser, network and runtime; the
built-artifact acceptance smoke passes; typecheck, `oxlint --format github` and the
code-quality lint with `--deny-warnings` all clean.

* fix(http-client): register the Node fetch fallback with the call-site audit

`global-fetch-call-site-audit.test.ts` guards every global-fetch use, because the
global runs on undici where an unread response body can crash the whole process
(orca#8695). The HttpClient port's Node fallback is a new such call site and was
unregistered — the guard caught it in a full-suite run.

Registered with the reasoning, and the port's doc comment now states the body-safety
contract explicitly: it hands the Response straight to its caller and never inspects
it, so the consume/cancel obligation stays exactly where it already was — with the
caller, unchanged from when they called Electron's net directly.

Two comments elsewhere mentioned the global by name and tripped the line scan as false
positives; reworded to describe the behaviour rather than name the API.

Verified: audit passes; typecheck and `oxlint --format github` clean.

* fix(app-environment): read hasAppEnvironment through the realm slot
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
…73) (stablyai#16345)

* test(pty): pin the renderer-liveness guard STA-2373 relies on (STA-5373)

STA-5373 reported that stablyai#15927 dropped the `webContents.isDestroyed()` half of
the guard stablyai#10065 added for STA-2373, and that the app therefore dies when a
daemon death fans out to every pane. The guard is present on main: stablyai#15172
restored it at both senders when it split the PTY monolith, and a per-file
count across v1.4.188..HEAD shows only relocation (pty.ts:4 ->
write-input.ts:2 + bind-listeners.ts:2). The reported 4 -> 0 was scoped to
`src/main/ipc/pty.ts`, now a 39-line barrel. No production fix is needed.

What was real is that nothing pinned the guard — it survived stablyai#15927 only
because stablyai#15172 happened to re-expand it — and the shared PTY test fake made
that invisible: its `webContents` had no `isDestroyed` at all, so both guards
passed vacuously in every suite. That is also why they are written defensively
as `typeof ... === 'function' && ...`.

- Give the fake an `isDestroyed` mock, re-stubbed to `false` each beforeEach
  rather than left `undefined`, so "alive" is stated rather than accidental.
- Cover both senders red/green: the daemon-death fan-out
  (bind-listeners.ts:37) and the per-write reporter (write-input.ts:57).
  Verified red against a window-only guard and green with the real one.

The per-write case needs a chunked write. A single-chunk write is already
fenced by `isPtyWriteEventFromMainWindow`, which rejects the event once the
WebContents is gone; only the multi-chunk path yields a macrotask mid-write,
letting the renderer die after the sender check passes. That is the sole route
to this sender with a dead WebContents, and what makes its own guard
load-bearing.

Also deletes `src/main/ipc/pty-renderer-surface.ts`: zero importers repo-wide,
and its `isRendererGone` is exactly the weakened predicate. Its comment claims
the headless path "now passes null", but register-headless-runtime.ts:26 still
fakes `{ isDestroyed: () => true }` — stablyai#15172 rolled that back too. Adopting it
would reintroduce STA-5373 for real.

Verified: 17 tests across the two pty write suites; full src/main/ipc run 3156
pass (4 pre-existing @parcel/watcher failures in filesystem-watcher-real and
worktree-base-directory-poller, unrelated and failing identically on a
pristine tree); pnpm typecheck clean; oxlint clean.

* docs(pty): correct headless-path comments the stablyai#15172 rebase left stale

stablyai#15927 made `registerPtyHandlers` accept `BrowserWindow | null` so the headless
path could pass null instead of faking a window. stablyai#15172 reverted that signature
while splitting the PTY monolith, but the comments describing it survived, so
three of them now document an API that does not exist.

- orcad-entry.ts: the module docstring claimed orcad installs its controller via
  `registerPtyHandlers(null, …)`. It uses `registerHeadlessPtyRuntime`, and null
  is not accepted. It also claimed desktop surfaces are "declared rather than
  faked" — true except for the renderer window, which is still faked.
- register-headless-runtime.ts: record why the fake is safe rather than leaving
  `isDestroyed: () => true` looking arbitrary. It is load-bearing: every
  renderer-liveness guard reads it and skips, so no send is attempted.

Also gives the fake a `webContents.isDestroyed`. The real guards check both, and
a missing method reads as "alive" — the same gap this PR fixes in the test fake.
No behavior change: the window-level check already short-circuits.

Verified: 45 tests across the liveness-guard, startup-barrier, management and
kill/exit suites; pnpm typecheck clean; oxlint clean.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…dules (stablyai#15927)

* refactor(preflight): split agent detection out of the ipcMain registration

First of the IPC extractions the revised design requires. `src/main/ipc/preflight.ts`
mixed 285 lines of agent/tool detection with 35 lines of `ipcMain.handle`
registration, and the runtime calls that detection during normal operation
(`orca-runtime.ts:573`, plus the preflight RPC methods). So the runtime dragged
`ipcMain` into its graph to reach pure logic.

Detection moves to `src/main/preflight/agent-detection.ts` — named for what it
contains, per AGENTS.md. `ipc/preflight.ts` keeps only the handler registration and
re-exports the domain module so existing importers are unaffected. The runtime and
its RPC methods now import the domain module directly.

Ratchet baseline 36 → 35: `src/main/ipc/preflight.ts` is no longer reachable from
the runtime. The gate detected the improvement and refused to pass until the
baseline tightened, which is the behaviour it was built for.

Verified: 2 files / 1,187 tests pass across every suite touching preflight;
`pnpm typecheck` clean; `oxlint` clean.

* refactor(ssh): split the SSH target registry out of the ipcMain module

Second IPC extraction, and by far the biggest win: this removes **eight** modules
from the runtime's Electron graph, taking the ratchet baseline 35 → 27.

The runtime needed five thin accessors from `src/main/ipc/ssh.ts` —
`connectRegisteredSshTarget`, `getRegisteredSshState`, `listRegisteredSshTargets`,
`listRegisteredRemovedSshTargetLabels`, `getActiveMultiplexer`. Each is a one-line
read over module-level state. Importing them dragged in `ipcMain`, `powerMonitor`
and a `BrowserWindow` accessor — and, transitively, `ipc/pty.ts` (8,031 lines),
`ssh-browse`, `ssh-passphrase`, `ssh-relay-deploy`, `ssh-remote-cli-host-passthrough`,
`wsl-hook-relay-launch` and `user-data-path`.

`src/main/ssh/ssh-target-registry.ts` now holds that state plus its accessors.
`registerSshHandlers` populates it; the runtime reads it. The indirection is kept
deliberately: SSH providers register after construction and may reconnect, so
callers must resolve the current generation rather than freeze one.
`ipc/ssh.ts` re-exports all five, so non-test importers are unaffected.

`connectRegisteredSshTarget` still throws `ssh_handlers_not_registered` when no
handler layer registered — a headless host must fail loudly rather than report a
target as unreachable, which would read as `exited` (see ssh-execution-boundary.md).

Verified: 9 files / 59 tests across the ssh, automations and trust-preset suites;
orca-runtime.test.ts 1,183 pass; `pnpm typecheck` clean; `oxlint` clean.

* refactor(host): resolve the app root through the port in fork-reachable modules

`parcel-watcher-entry-path.ts` and `session-scanner-service-entry-path.ts` read the
app root via `require('electron').app` inside a try/catch that already returns null
when Electron is absent. They were therefore correct under plain Node at runtime and
only failed the *static* text check — which is real, not pedantic: the comment in
`ports/port-scan-command-client.ts:19` records that the plain-node-entry-guard fails
on that literal text, try/catch or not.

`hasAppEnvironment() ? getAppEnvironment() : null` gives the identical "no app root
here" answer without the text. That restores `hasAppEnvironment`, which an earlier
commit in this stack deleted as unused — it now has the caller it was waiting for.

Ratchet baseline 27 → 25.

Verified: 74 files / 458 tests; `pnpm typecheck` clean; `oxlint` clean.

* test(ssh): mock the SSH target registry alongside the ipc/ssh mock

Thirty-eight suites mocked `vi.mock('./ssh')` for `getActiveMultiplexer`. That
factory went inert when production started importing the accessor from
`../ssh/ssh-target-registry`, so the real module loaded and the assertions drifted.

Adds a companion registry mock returning the same stub, plus a
`sshTargetRegistryModuleMock` builder beside the existing `sshModuleMock` so the
shared harness stays one place. No assertion changed.

Found by a full-suite run: the targeted ssh/runtime suites were green while
30 tests in ipc/worktrees and ipc/repos were not.

* refactor(runtime): read app paths and the packaged flag through the port

`orca-runtime.ts` is the last module in its own graph that imports `electron`
directly. Nineteen of its uses were `app.getPath` (12) and `app.isPackaged` (7) —
exactly what the AppEnvironment port already covers.

Also removes a dead `const { app } = require('electron')` inside
`getOrchestrationDb`. It was left unused once the path came from the port, and it
is precisely the dynamic-require pattern `plain-node-entry-guard.ts` exists to
catch, sitting in the runtime's own constructor path.

What still binds `orca-runtime.ts` to Electron is now three sites, not nineteen:
`new Notification(...)` (one), `BrowserWindow.fromId` (one), and the
`ipcMain.on('terminal:tabCreateReply')` renderer round-trip — which is the browser
tab path, and the same one that would hang a headless host for ten seconds.

Two suites drove `electronMocks.app.isPackaged` directly; they now install a fake
AppEnvironment reading the same mutable field, so their per-test toggles work
unchanged and no assertion moved.

Verified: 376 files / 4,717 tests across src/main/runtime; typecheck and oxlint clean.

* test(serve): add the built-artifact terminal round-trip acceptance smoke

"The server started" proves almost nothing. Terminal creation dispatches into
OrcaRuntimeService, and without an installed headless PTY controller that path
falls through to a renderer reply that never arrives and times out after ten
seconds. A boot probe, a port bind, and a `host.platform` call all pass against a
server whose terminals are dead — which is exactly the gap the design doc's own
boot proof was retracted for.

This boots the BUILT `out/main/index.js --serve`, parses its ready payload, pairs a
real client over the advertised endpoint, lists worktrees, creates a terminal, runs
a command through the PTY, asserts the output comes back, and asserts clean
shutdown. It drives nothing but the public pairing + RPC surface, so the same
script is the acceptance gate a future Node-only backend must pass unchanged.

The sentinel invokes `process.execPath` rather than `echo`, because the shell
differs per platform and node does not.

Verified both directions: passes against the real server, and fails with an
actionable message when the command produces no output — a smoke that cannot fail
is worthless.

* fix(ssh): fail loudly when the multiplexer resolver was never installed

`getActiveMultiplexer` resolves through a resolver that `ipc/ssh.ts` installs at
module scope. A process that never loads the SSH layer — which is the whole point
of the Node-only backend — would get `undefined` from every call.

`undefined` already means something specific here: "not connected". So a missing
resolver and a disconnected target were indistinguishable, and a host with no SSH
layer would quietly report every target as not connected. That is the
unverifiable-reported-as-exited conflation `docs/reference/ssh-execution-boundary.md`
exists to prevent — the doc is explicit that absence of contact is never evidence
of absence of the thing.

A missing resolver is a wiring error, not a connection state, so it throws, matching
what `connectRegisteredSshTarget` already does for unregistered handlers.

Verified: 432 files / 4,759 tests across ipc, ssh, preflight, automations and trust
presets; typecheck and oxlint clean.

* refactor(pty): stop faking a BrowserWindow for the headless PTY path

`registerHeadlessPtyRuntime` passed `registerPtyHandlers` a stub object cast to
`BrowserWindow` whose `isDestroyed()` returned true and whose `webContents.send`
was a no-op — a window-shaped thing that lied about being a window, purely to
satisfy the type. Adversarial review named it as the same "looks fine, silently
returns a lie" pattern this codebase rejects elsewhere, and it is the shape that
keeps `electron` on a path that otherwise needs none.

`registerPtyHandlers` now takes `BrowserWindow | null`. An absent renderer is
semantically identical to a destroyed one — all 42 call sites already guarded on
`isDestroyed()` and skipped — so `src/main/ipc/pty-renderer-surface.ts` states that
directly: `isRendererGone`, `sendToRenderer`, `rendererWebContents`. The compound
`isDestroyed() || webContents.isDestroyed()` guards collapse into one predicate.

`isPtyWriteEventFromMainWindow` becomes null-tolerant and fails closed: with no
renderer no sender can legitimately match, so every write is rejected. Those
handlers cannot fire headless today, but failing closed is the right answer if that
ever changes.

This is the precondition for installing a PTY controller without Electron, which is
what a Node-only backend needs and what `terminal.create` actually calls.

Verified: 129 files / 2,473 tests across ipc/pty, providers and orca-runtime; the
built-artifact acceptance smoke still passes end-to-end (boot → pair →
terminal.create → sentinel → close), which is the check that matters most here
since this changes the headless PTY path itself; typecheck and oxlint clean.

* refactor(pty): read app paths and the packaged flag through the port

Follows the fake-window removal. `ipc/pty.ts` had nine `app.*` reads — all
`getPath`, `getVersion` or `isPackaged` — which the AppEnvironment port already
covers. The `BrowserWindow` import was also dead after the null-window change.

What still binds this file to Electron is now `ipcMain` (75 uses, all handler
registration) and `powerMonitor` (2). That is a clean statement of the remaining
job: split logic from registration, the same shape already applied to preflight
and the SSH registry.

Test wiring: the shared `pty-ipc-suite-environment` beforeEach installs a fake
AppEnvironment that reads through the existing `vi.mock('electron')` app object
rather than freezing values — suites toggle `app.isPackaged` mid-test to exercise
dev-mode spawn paths, so the port has to observe the same mutable field. One edit
in the shared harness covers every pty suite.

Verified: 128 files / 1,290 tests across ipc/pty and providers; the built-artifact
acceptance smoke passes; typecheck and oxlint clean; ratchet unchanged at 25.

* refactor(pty): inject the ipcMain surface so the PTY module loads without Electron

This closes the round-3 blocker: "the doc never says how orcad installs
setPtyController without Electron."

`registerPtyHandlers` owns the `RuntimePtyController` that `terminal.create`
actually spawns through — the thing a Node backend needs and cannot get from the
provider thunks. The module was otherwise host-agnostic already; the only thing
pinning 8,031 lines to Electron was a static `ipcMain` / `powerMonitor` import used
purely to register renderer handlers that no headless host will ever receive.

`src/main/ipc/pty-host-bindings.ts` makes those surfaces settable, defaulting to
no-ops. Unlike AppEnvironment and SecretStore, the default does NOT throw: a host
with no renderer legitimately has nothing to register against, so not registering
handlers nobody can call is correct rather than a hidden downgrade. The desktop
installs the real objects in `attach-main-window-services` before its handlers run.

Also converts the remaining electron import to a top-level `import type`. oxlint's
`no-import-type-side-effects` caught that inline `type` specifiers still leave a
side-effect import — precisely the "type-only is not enough if esbuild still emits
require('electron')" trap a reviewer flagged.

**`src/main/ipc/pty.ts` now bundles with zero `require("electron")`.** A Node entry
can call `registerPtyHandlers(null, runtime, …)` and get a working PTY controller.

Verified: 128 files / 1,290 tests across ipc/pty and providers; the built-artifact
acceptance smoke passes end-to-end — which is the check that matters, since this
changes how every PTY handler registers; typecheck and oxlint clean.

* fix(pty-bindings): drop two unused eslint-disable directives

CI runs oxlint with unused-disable reporting; the two
`@typescript-eslint/no-explicit-any` suppressions I added were never triggered by
any enabled rule, so they failed static analysis as dead directives. The `any[]`
rest args stay — they mirror electron's own IpcMain signature, and narrowing them
would reject the real object at the desktop call site.

Verified with the exact CI invocation: `oxlint --format github` reports 0 warnings,
0 errors across the repo.

* fix(pty): install the host bindings per process, not per window

A real regression my own change introduced, caught by the SSH docker E2E
(`paired-startup-exec-readiness` — "recovers startup exec through a headed paired
desktop owner"). It reproduced on rerun, so it was not a flake.

`setPtyHostBindings` was called inside `attachMainWindowServices`, i.e. when a
window attaches. But `registerHeadlessPtyRuntime` (index.ts:3163) calls
`registerPtyHandlers` on the serve path *before* any window exists — so those
handlers registered against the no-op default and never reached the real `ipcMain`.
A paired desktop owner then attached to a runtime whose PTY handlers were wired to
nothing.

The bindings describe the *host*, not the *window*: an Electron main process always
has `ipcMain`, whether or not a window is open. Installing them beside
`setAppEnvironment`/`setSecretStore` at the top of bootstrap fixes both paths.

Verified: 128 files / 1,290 tests; the built-artifact acceptance smoke passes;
typecheck clean; `oxlint --format github` (the exact CI invocation) reports 0/0.

* feat(orcad): de-electron the runtime core and add the Node entry + build gate

**`src/main/runtime/orca-runtime.ts` — 41,048 lines — no longer imports electron.**
Its last three sites go through `runtime-desktop-surface.ts`: a native notification,
the authoritative-window lookup, and the one `ipcMain` channel used by the
renderer-backed tab-create fallback. All three are unreachable without a renderer —
`createTerminal` already takes the background branch when no window exists (stablyai#10333) —
so a Node host installs none and the runtime relays notifications to paired clients,
which is the better destination anyway. Ratchet 25 → 24.

Adds `src/main/orcad/orcad-entry.ts`: Node host adapters plus a `startOrcad` that
constructs the runtime, installs the PTY controller via `registerPtyHandlers(null, …)`,
and serves RPC. It sets two defaults the constructor gets wrong for a headless host —
`canRecoverPersistentLocalPtys: false` (no daemon here) and
`getDesktopWindowStatus: 'blocked'` (a Node host can never be promoted to a desktop
window, which is what `'openable'` claims).

Adds `config/scripts/build-orcad.mjs`, which **currently fails, on purpose**: 25
modules still import electron (browser and speech clusters, plugins, jira/proxy,
filesystem-watcher, and four `require('electron').app` one-liners). It names them.

Two bugs found while building it, both worth recording:
- The first bundle looked clean and was not. `electron` was bundleable, so esbuild
  rewrote the metafile `path` to the resolved file under node_modules and a check for
  `path === 'electron'` passed while the package was in the bundle — it failed at
  runtime with electron's own installer message. The check now reads `original`, and
  electron is marked external so a residual import fails loudly instead.
- `jsonc-parser`'s UMD build breaks the bundle at load; aliased to its ESM entry, the
  same fix `build-relay.mjs` already carries.

Verified: desktop unchanged — the built-artifact acceptance smoke passes, runtime/pty/
provider suites green, typecheck clean, `oxlint --format github` 0/0.

* refactor(host): drop the last two require('electron') app lookups

`computer/sidecar-client.ts` and `ports/port-scan-command-client.ts` read the app
root through `require('electron').app` inside a try/catch. Both were already correct
under plain Node at runtime — they return null when it throws — but the literal text
fails the plain-Node entry guard regardless, which is why port-scan carried a comment
warning it must never become reachable from a fork entry.

Reading the AppEnvironment port gives the identical "no app root here" answer without
the text, so that warning is now obsolete and the comment says so.

Ratchet 24 → 22. Every remaining entry is a real coupling: the browser cluster (15,
which variant B does not ship), speech (2), plugins (2), and jira/proxy-settings (2,
needing an HttpClient port for Chromium session partitions).

Verified: 25 files / 209 tests; acceptance smoke passes; typecheck and
`oxlint --format github` clean.

* docs(orcad): record that the ratchet under-counts orcad's graph

The ratchet reports 22 electron importers; the orcad build reports 23. The extra is
agent-hooks/wsl-hook-relay-launch.ts, and the cause is a gap in the gate rather than
a rounding error: the ratchet measures what orca-runtime + runtime-rpc reach, while
orcad's entry also imports ipc/pty directly to install the PTY controller.

Once orcad ships it must become a ratchet entry point, or the two numbers drift and
the gate quietly stops covering the artifact it exists for.

* refactor(runtime): inject the browser commands factory

Drops 14 modules from the runtime's Electron graph in one change — the whole Chromium
browser cluster. Ratchet 22 → 8.

`OrcaRuntimeService` constructed `RuntimeBrowserCommands` as a field initializer, and
that construction is what pulled in `BrowserWindow`, `session`, `webContents` and the
cookie jars. Importing the class for its *type* is free; only building it costs.

So the class import becomes `import type`, and the instance comes from
`runtime-browser-commands-factory.ts`. The desktop installs the real factory at the
Electron entry. **All ~80 existing `this.browserCommands.*.bind(...)` delegations are
untouched** — a review round specifically warned that rewriting those was the
expensive, risky part, and this avoids it entirely.

With no factory installed, browser commands reject per call with `browser_unavailable`
rather than resolving to a stub that silently succeeds. The runtime already filters
browser capabilities out of `getStatus()` when no backend exists, so clients do not
offer the affordance in the first place.

Also corrects a stale comment in `pty-renderer-surface.ts` that still described the
fake window as present tense; it was deleted two commits ago.

Verified: 451 files / 5,513 tests across `src/main/browser` and `src/main/runtime` —
the entire browser automation suite; the built-artifact acceptance smoke passes;
`pnpm typecheck` and `oxlint --format github` clean.

* refactor(host): extract the plugin client list and port two app lookups

Ratchet 8 → 5.

- `listPluginsForClients` moves to `src/main/plugins/plugin-client-list.ts`. It needed
  only three `plugins/*` helpers, none of them Electron — it was colocated with
  `ipcMain.handle` registrations, so the runtime's `plugins.list` RPC dragged all of
  Electron in to call a function that reads a lockfile. Same shape as preflight.
  Dropping it also releases `ipc/plugin-marketplaces.ts`.
- `agent-hooks/wsl-hook-relay-launch.ts` and `speech/stt-service.ts` read `getAppPath`
  and `isPackaged` through the AppEnvironment port.

The five that remain are all genuinely Chromium and need the HttpClient port or a
watcher split, not another mechanical swap: `browser/cdp-bridge` (webContents),
`ipc/filesystem-watcher` (ipcMain), `jira/authenticated-request` and
`network/proxy-settings` (net + session partitions), `speech/model-manager`
(`net.request`, which honors app proxy settings that Node https does not — replacing
it is a behaviour change, not a rename).

Verified: 219 files / 1,922 tests across plugins, speech, agent-hooks and the runtime
RPC methods; the built-artifact acceptance smoke passes; typecheck and
`oxlint --format github` clean.

* refactor(network): resolve the default proxy session lazily

Ratchet 5 → 4.

`proxy-settings.ts` needed exactly one Electron value: `session.defaultSession`, as
the fallback when a caller does not pass `options.proxySession`. Callers could already
inject a session; only the default was hard-wired. It now comes from a settable
resolver, so the module loads under plain Node.

**A resolver rather than a Session, because a Session eagerly throws.** The first
attempt installed `session.defaultSession` directly in pre-ready bootstrap and broke
startup outright — `TypeError: Session can only be received when app is ready`. The
acceptance smoke caught it before commit. Deferring to first use is always after ready.

Behaviour with no session is not a degradation: there is no Chromium proxy config to
discover, so `resolveProxy` is skipped and the environment variables become the whole
answer rather than a fallback. Applying rules to a session that does not exist is
likewise skipped; settings are still honoured because outbound requests read the env.

This reaches past Jira — a review round noted `ensureElectronProxyFromEnvironment` is
also on the Claude HTTP path via `oauth-refresh.ts` and `rate-limits/claude-fetcher.ts`.

Verified: 48 files / 526 tests across network, jira and rate-limits; the
built-artifact acceptance smoke passes; typecheck and `oxlint --format github` clean.

* fix(index): merge the duplicate proxy-settings import

CI's code-quality lint (`oxlint --config config/oxlint-code-quality-native-plugins.json
--deny-warnings`) flags a module imported twice in one file. My earlier insertion added
a second `./network/proxy-settings` import beside the existing one.

Verified with CI's exact invocation: exit 0.

* refactor(network): add the HttpClient port and lift BrowserError out of cdp-bridge

Ratchet 4 → 2.

Two unrelated couplings, both of the same shape — a small thing living inside a
Chromium-heavy file.

`BrowserError` is a seven-line error class with no dependencies, but it lived in
`browser/cdp-bridge.ts`, which imports `webContents`. The runtime catches that type on
paths with nothing to do with CDP, so one import kept a Node host from loading the
runtime at all. Moved to `browser/browser-error.ts`; cdp-bridge re-exports it.

`jira/authenticated-request.ts` fetches through `net.fetch` and reads
`session.defaultSession`. `network/http-client.ts` makes both settable. This one is a
**named port rather than a silent fallback, because the fallback is not transparent**:
Electron's net follows Chromium session/proxy state, avoids undici's stale keep-alive
sockets after a VPN path change, and sends a Chrome user agent that Jira's XSRF check
depends on. A Node host gets `globalThis.fetch`, reads proxy config from the
environment, and sends Node's user agent. That difference is documented at the port.

`session.defaultSession` is read per call, not captured at install — it throws before
the app is ready, which is the mistake the previous commit made and the acceptance
smoke caught.

Test wiring: `jira/client.test.ts` installs the port *inside* `loadClientModule`, after
its `vi.resetModules()`, since the reset gives the module a fresh singleton.

Verified: 461 files / 5,616 tests across jira, browser, network and runtime; the
built-artifact acceptance smoke passes; typecheck, `oxlint --format github` and the
code-quality lint with `--deny-warnings` all clean.

* fix(http-client): register the Node fetch fallback with the call-site audit

`global-fetch-call-site-audit.test.ts` guards every global-fetch use, because the
global runs on undici where an unread response body can crash the whole process
(orca#8695). The HttpClient port's Node fallback is a new such call site and was
unregistered — the guard caught it in a full-suite run.

Registered with the reasoning, and the port's doc comment now states the body-safety
contract explicitly: it hands the Response straight to its caller and never inspects
it, so the consume/cancel obligation stays exactly where it already was — with the
caller, unchanged from when they called Electron's net directly.

Two comments elsewhere mentioned the global by name and tripped the line scan as false
positives; reworded to describe the behaviour rather than name the API.

Verified: audit passes; typecheck and `oxlint --format github` clean.

* fix(app-environment): read hasAppEnvironment through the realm slot
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…73) (stablyai#16345)

* test(pty): pin the renderer-liveness guard STA-2373 relies on (STA-5373)

STA-5373 reported that stablyai#15927 dropped the `webContents.isDestroyed()` half of
the guard stablyai#10065 added for STA-2373, and that the app therefore dies when a
daemon death fans out to every pane. The guard is present on main: stablyai#15172
restored it at both senders when it split the PTY monolith, and a per-file
count across v1.4.188..HEAD shows only relocation (pty.ts:4 ->
write-input.ts:2 + bind-listeners.ts:2). The reported 4 -> 0 was scoped to
`src/main/ipc/pty.ts`, now a 39-line barrel. No production fix is needed.

What was real is that nothing pinned the guard — it survived stablyai#15927 only
because stablyai#15172 happened to re-expand it — and the shared PTY test fake made
that invisible: its `webContents` had no `isDestroyed` at all, so both guards
passed vacuously in every suite. That is also why they are written defensively
as `typeof ... === 'function' && ...`.

- Give the fake an `isDestroyed` mock, re-stubbed to `false` each beforeEach
  rather than left `undefined`, so "alive" is stated rather than accidental.
- Cover both senders red/green: the daemon-death fan-out
  (bind-listeners.ts:37) and the per-write reporter (write-input.ts:57).
  Verified red against a window-only guard and green with the real one.

The per-write case needs a chunked write. A single-chunk write is already
fenced by `isPtyWriteEventFromMainWindow`, which rejects the event once the
WebContents is gone; only the multi-chunk path yields a macrotask mid-write,
letting the renderer die after the sender check passes. That is the sole route
to this sender with a dead WebContents, and what makes its own guard
load-bearing.

Also deletes `src/main/ipc/pty-renderer-surface.ts`: zero importers repo-wide,
and its `isRendererGone` is exactly the weakened predicate. Its comment claims
the headless path "now passes null", but register-headless-runtime.ts:26 still
fakes `{ isDestroyed: () => true }` — stablyai#15172 rolled that back too. Adopting it
would reintroduce STA-5373 for real.

Verified: 17 tests across the two pty write suites; full src/main/ipc run 3156
pass (4 pre-existing @parcel/watcher failures in filesystem-watcher-real and
worktree-base-directory-poller, unrelated and failing identically on a
pristine tree); pnpm typecheck clean; oxlint clean.

* docs(pty): correct headless-path comments the stablyai#15172 rebase left stale

stablyai#15927 made `registerPtyHandlers` accept `BrowserWindow | null` so the headless
path could pass null instead of faking a window. stablyai#15172 reverted that signature
while splitting the PTY monolith, but the comments describing it survived, so
three of them now document an API that does not exist.

- orcad-entry.ts: the module docstring claimed orcad installs its controller via
  `registerPtyHandlers(null, …)`. It uses `registerHeadlessPtyRuntime`, and null
  is not accepted. It also claimed desktop surfaces are "declared rather than
  faked" — true except for the renderer window, which is still faked.
- register-headless-runtime.ts: record why the fake is safe rather than leaving
  `isDestroyed: () => true` looking arbitrary. It is load-bearing: every
  renderer-liveness guard reads it and skips, so no send is attempted.

Also gives the fake a `webContents.isDestroyed`. The real guards check both, and
a missing method reads as "alive" — the same gap this PR fixes in the test fake.
No behavior change: the window-level check already short-circuits.

Verified: 45 tests across the liveness-guard, startup-barrier, management and
kill/exit suites; pnpm typecheck clean; oxlint clean.
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.

1 participant