Skip to content

Make renderer delivery optional for headless terminals - #23117

Merged
OrcaWin merged 1 commit into
mainfrom
OrcaWin/np-headless-pty-renderer
Sep 26, 2026
Merged

OrcaWin merged 1 commit into
mainfrom
OrcaWin/np-headless-pty-renderer

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

ELI5

Headless Orca terminals now run without pretending an Electron window exists. Desktop terminals keep their existing delivery and lifecycle behavior.

What Changed

Replace the fabricated, destroyed BrowserWindow with an optional renderer delivery interface. Skip renderer sends and listeners when no renderer is registered, while keeping local and SSH terminal control, output, exits, attachment and buffer snapshots connected to the runtime.

Why

The fake window hid a required-looking dependency behind an unchecked cast. Making the actual dependency explicit lets TypeScript catch unguarded renderer access without duplicating the terminal controller for headless use.

Linked Issue

Follow-up to #22635. No separate issue.

Visual Proof

N/A — internal dependency cleanup; no intended visual or interaction changes.

Testing

  • Automated tests added/updated.
  • Four new integration-style unit cases cover renderer-less output/exits, local and SSH routing, renderer input rejection, and desktop → headless → desktop listener teardown and restored delivery.
  • Independent Codex review: 18 focused suites / 157 tests passed on macOS with Node 24 and ORCA_BACKGROUND_LAUNCH=1.
  • Independent Claude Opus review: 16 focused suites / 130 tests passed; its outdated-comment finding was corrected.
  • Node typecheck, scoped formatting/lint and changed-code quality gate passed.
  • Built the actual macOS ARM headless artifact with pinned Bun 1.4.2; build and worker smoke checks passed, with zero Electron imports.
  • No live desktop-window or SSH-server journey run for this cleanup. All reported CI checks passed or were intentionally skipped on 1beb35e.

Review

No introduced P0/P1/P2 code findings from either independent review. Checked renderer authorization, provider listener cleanup, SSH output credit handling and absent-provider behavior.

Agent skill upstream boundary

  • Not applicable; no upstream skill content is copied.

Checklist

  • This PR is small and focused.
  • Explained the before/after, mechanism and approach.
  • N/A visual proof with reason.
  • Self-reviewed correctness and performance.
  • Cross-platform, SSH and mobile runtime routing considered.
  • Focused tests, node types, changed quality and headless artifact build pass; CI is green on the PR head.

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 3a08e36e-efa5-479b-a88b-0aae7ec12a94

📥 Commits

Reviewing files that changed from the base of the PR and between 4cafa50 and 1beb35e.

📒 Files selected for processing (21)
  • src/main/ipc/pty/delivery/accept.ts
  • src/main/ipc/pty/delivery/accounting.ts
  • src/main/ipc/pty/delivery/debug-snapshot.ts
  • src/main/ipc/pty/delivery/exit.ts
  • src/main/ipc/pty/delivery/flush.ts
  • src/main/ipc/pty/delivery/lifecycle-reset.ts
  • src/main/ipc/pty/delivery/payload.ts
  • src/main/ipc/pty/ipc/resize-visibility.ts
  • src/main/ipc/pty/ipc/serialize-buffer.ts
  • src/main/ipc/pty/ipc/write-input.ts
  • src/main/ipc/pty/ipc/write.ts
  • src/main/ipc/pty/provider/bind-listeners.ts
  • src/main/ipc/pty/provider/listener-lifecycle.ts
  • src/main/ipc/pty/register-handlers.ts
  • src/main/ipc/pty/register-headless-runtime.test.ts
  • src/main/ipc/pty/register-headless-runtime.ts
  • src/main/ipc/pty/register-without-renderer.test.ts
  • src/main/ipc/pty/runtime/controller-deps.ts
  • src/main/ipc/pty/runtime/operations.ts
  • src/main/ipc/pty/session.ts
  • src/main/orcad/orcad-entry.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

PTY registration now accepts an optional renderer window, and headless registration passes no window instead of using a fake window. PTY delivery and IPC paths check for an unavailable renderer before accessing it or sending renderer messages. Tests cover headless PTY behavior and resumed renderer delivery after handlers are registered again.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 1beb3

No confirmed issue blocks merging; the headless provider-cleanup behavior remains unverified.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 1beb3

The terminal lifecycle changes, but the reviewed paths reject renderer input when no renderer is registered and retain provider ownership checks. No introduced security issue was established. Live desktop and SSH journeys remain unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The sensitive outcome on the examined input path is a write to a local or SSH PTY reachable through the current provider registry. The optional renderer does not itself grant a renderer sender that authority.

Trust Boundaries and Controls

  • observed — The examined renderer-input boundary validates the IPC sender against the currently registered, non-destroyed renderer before checking the payload and routing a write. An absent renderer cannot satisfy that sender check.

Resilience and Maintainability Implications

  • observed — On renderer re-registration, old delivery reset callbacks are neutralized before a new session and provider listeners are bound, limiting stale renderer state and paused-producer effects.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 21 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the change, rationale, testing, review status, and visual-proof decision. However, it does not provide the required linked issue and omits required template sections, includin… Provide a valid linked issue after “Fixes #” or explain the applicable issue reference. Complete the required template sections, including AI Disclosure, Notes, and the manual-testing checklist item.
✅ Passed checks (3 passed)
Check name Status Explanation
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 and concisely describes the main change: renderer delivery is optional for headless terminals.
Full details: Description check

Explanation

The description explains the change, rationale, testing, review status, and visual-proof decision. However, it does not provide the required linked issue and omits required template sections, including AI Disclosure, Notes, and the manual-testing checklist item.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Optional renderer delivery — PtyIpcSession.mainWindow is now PtyRendererDelivery | undefined, a structural type that picks the BrowserWindow/WebContents members the PTY layer actually uses.
  • Headless registration — registerHeadlessPtyRuntime passes undefined instead of a fabricated destroyed BrowserWindow; registerPtyHandlers now registers the renderer lifecycle/gate listeners and the local did-finish-load orphan sweep only when a window is present.
  • Delivery guards — every delivery path (accept, flush, exit, payload, accounting, debug-snapshot, serialize-buffer, write-input, operations, bind-listeners) treats a missing window exactly like a destroyed one and skips renderer sends.
  • clearBuffer hardening — clearBufferFromRuntimeController now guards its renderer send, so a destroyed window no longer throws before the provider-side clear runs.
  • Tests — new register-without-renderer.test.ts (4 cases: renderer-less output/exits, local+SSH control routing, renderer input rejection, desktop→headless→desktop listener teardown/restore) plus an assertion that undefined is threaded through registerHeadlessPtyRuntime.

Verified locally: both changed test files pass (5 tests) and pnpm tc:node is clean. Two independent passes found no mainWindow dereference reachable with mainWindow === undefined (including through casts or @ts-nocheck boundaries), and no change to SSH projection-credit accounting versus the old destroyed-window path.

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

@OrcaWin
OrcaWin merged commit 9700030 into main Sep 26, 2026
46 checks passed
sj900211 added a commit to sj900211/orcinus that referenced this pull request Oct 12, 2026
The stage the staged plan existed for. Measured from the post-stage-2 main this
cost 78 commits and 14 conflicts (13 in the PTY delivery subsystem) instead of
881 commits and 32 conflicts from the original base.

**The PTY wall was not what the 월드맵 feared.** It recorded
`pty-project-window-stream-routing` as a ~1,500-line feature-scale
re-implantation and deferred it twice. In fact all 14 conflicts come from three
upstream commits:

- `9700030689` refactor(pty): make renderer delivery optional for headless
  runtimes (stablyai#23117) — `session.mainWindow` becomes optional and every
  `isDestroyed()` guard gains a null check.
- `82412dab8b` Persist profile state in SQLite with background writes (stablyai#22612).
- `d443320af2` refactor(native-chat): remove the unused terminal handoff (stablyai#22783).

On the same lines the fork had already replaced the main-window guard with
owner-window routing (`resolvePtyOwnerWindow`, `sendToPtyOwner`,
`ownerFlowStateForPty`). The fork's guard is strictly finer: in headless mode no
window is registered with the router, the owner resolves to null, and the fork
takes the same early-return upstream's null check adds — while upstream's coarser
guard would drop or misroute project-window delivery when the main window is
gone. So most of the cluster resolves to ours, and nothing had to be reimplanted.

Conflicts resolved (14)
- `pty/delivery/{accept,accounting,exit,flush}.ts`, `pty/provider/bind-listeners.ts`:
  ours. Verified mechanically — resolving every hunk to ours produced a file
  byte-identical to main, so upstream has no other change in them.
- `pty/delivery/payload.ts`, `pty/runtime/operations.ts`: per hunk, never
  whole-file. A whole-file ours on operations.ts would have restored imports of
  two modules `d443320af2` deleted and a 3-arg `writePtyFromRuntimeController`
  while the merged `runtime/controller.ts` calls the 2-arg form.
- `pty/ipc/{resize-visibility,serialize-buffer,spawn-commit-persist,write-input,write}.ts`,
  `pty/register-handlers.ts`: combined, preserving every per-window router
  injection. A previous attempt at this merge failed its gates by dropping them.
- `persistence/loading-store/store.ts`: combined for `82412dab8b`'s SQLite
  authority.

Edits outside the 14 conflicted files (6)
Each one is a defect the conflict list could not show, because the file merged
cleanly while the meaning did not.
1. `pty/session.ts` + `pty/delivery/window-flow-state.ts`: `session.ts` merged
   cleanly into a crash. `mainWindow` is now optional, upstream's
   `register-headless-runtime.ts` passes `undefined` where it used to pass a fake
   destroyed window, and the fork's `createWindowFlowState(session,
   args.mainWindow.webContents)` therefore threw on every `orca serve` and orcad
   registration. Fixed by narrowing a flow state's `webContents` to
   `Pick<WebContents, 'id' | 'isDestroyed' | 'send'>` and passing a destroyed
   stand-in, with no cast. `window-flow-state.ts` stays at 297 of its 300
   permitted code lines.
2. `persistence/loading-store/store-domain-composition.ts`: added
   `SatelliteWindowSessionPersistence &` to `StoreDomainOperations`, without
   which four satellite-session methods disappear from the `Store` type.
3. `pty/register-without-renderer.test.ts`: two `registerPtyHandlers(renderer as
   never, …)` casts, matching the shape 274 existing calls in this repo use.
   This is an upstream-owned file, so the next sync touching it will conflict here.
4. Three usage test fixtures (`usage-custom-range-filters.test.ts`,
   `UsageNumberFormatToggle.test.tsx`, `usage-pane-test-state.ts`): added the
   fields upstream `297cfe0cf3` (stablyai#22073) made required. **These were already
   broken on main**: a fresh worktree at `e0686816e8` reports exactly these 4
   type errors. Stage 2's gate missed them because a warm `composite`
   `.tsbuildinfo` cache under-reported. Typecheck cold before trusting a pass.
5. `pty/register-handlers.ts` + the window-affinity router:
   `setMainWindowForRouting` widened to `BrowserWindow | null` and called
   unconditionally as `setMainWindowForRouting(mainWindow ?? null)`. Skipping it
   when `mainWindow` is undefined left a previously routed live window routed, so
   a desktop → headless re-registration would send `pty:exit`, `pty:spawned`,
   `pty:writeUnavailable`, `pty:clearBuffer:request`,
   `pty:serializeBuffer:request` and `pty:modelRestoreNeeded` to a stale window.
   Current call order prevents it in production; that is not a guarantee worth
   depending on. Restores parity with main.

Gates (each captured from the command's own exit code)
- typecheck, run cold after deleting `config/*.tsbuildinfo`: 0 errors. The same
  command on a main worktree reports its 4 pre-existing errors.
- oxlint: exit 0 on the full tree and on the touched files.
- verify-orcinus-identity: OK, upstreamRefs=0.
- electron-builder smoke: unsigned, update signature checks disabled.
- fork contract tests: 3 files / 24 tests.
- `register-without-renderer.test.ts` (upstream's new 231-line headless test): 4/4.
- router-referencing tests: 3 files / 70 tests.
- Broad conflict-area suite: 122 failures, none attributable. 121 fail
  identically on a main worktree; the remaining one, upstream's own
  `profile-state-crash-recovery.test.ts`, times out identically on a
  `da6d483ab9` worktree. Per-test JSON diff: 0 failures unique to main.

Reviewed by an independent critic: APPROVE, no blocking defects, every gate
re-measured, every fork-only and upstream-only file confirmed equal to its parent
apart from the six edits above, no IPC channel dropped. Non-blocking and
deliberately not addressed: `hasUnpricedModels: false` does not match its own
fixture's data (behaviour-neutral); the upstream-owned test file will re-conflict;
plan-B's satellite-session durability question is still open.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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