Skip to content

fix(computer): supervise macOS helper from main - #11441

Merged
nwparker merged 2 commits into
stablyai:mainfrom
nwparker:nwparker/computer-main-provider-supervisor
Jul 30, 2026
Merged

nwparker merged 2 commits into
stablyai:mainfrom
nwparker:nwparker/computer-main-provider-supervisor

Conversation

@nwparker

@nwparker nwparker commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This moves ownership of the native macOS computer-use helper from the long-lived computer sidecar into the Electron main process.

The sidecar can now request only three fixed lifecycle operations:

  • macos.start
  • macos.claim
  • macos.release

Main resolves the signed helper executable, creates the private socket directory and token, spawns the helper, registers its PID before replying, owns the unclaimed-start deadline, and reaps every registered helper if the sidecar dies. The sidecar remains the socket peer and continues to own the provider protocol/state, preserving the current peer-authorization boundary until the later sidecar worker migration.

This is prerequisite work for replacing the approximately 47 MiB Electron-as-Node computer sidecar with a worker without letting worker termination orphan native descendants. It does not add another process or change when computer use starts.

Ownership and race contract

  • Main owns executable resolution, fixed arguments, private filesystem state, process creation, PID registration, termination escalation, and cleanup.
  • The session is registered before a successful start response can be delivered.
  • The sidecar claims a session only after its authenticated socket connects.
  • Startup races are bounded by a main-owned 20-second claim deadline.
  • Supervisor response-delivery failure invalidates and kills the sidecar, which synchronously kills all registered helper sessions.
  • Forced termination keeps a session registered until the child emits exit; it is not forgotten merely because SIGKILL was requested.
  • Main-process exit synchronously shuts down the sidecar and supervisor because Electron app.exit() skips normal quit events.
  • Sidecar provider shutdown runs before its supervisor client is shut down.

Failure matrix

Failure point Result
Executable missing or token/directory setup fails No session is published; private state is removed and a typed error is returned
spawn() returns no PID and later emits error The asynchronous error is absorbed, the child is killed if possible, and private state is removed
Helper exits while the sidecar is connecting Main emits a typed termination event; the socket attempt aborts and the session is released
Start response never arrives / session is never claimed Main sends SIGTERM, removes private state, then escalates to SIGKILL after 1 second
Claimed socket closes, errors, times out, or is superseded Sidecar releases that exact session; main performs graceful-to-force termination
Sidecar exits, errors, times out, loses IPC, or cannot receive a supervisor response Main immediately sends SIGKILL to every registered helper and removes private state
Electron exits directly Synchronous sidecar/supervisor shutdown sends termination signals without relying on Electron quit events
Late helper event precedes its start response The client correlates it by session ID; stale unmatched events are capped to prevent unbounded retention

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — ran the complete computer subsystem suite instead
  • pnpm build — no bundle configuration or entry-point changes
  • Added or updated high-quality tests that would catch regressions

Additional verification:

  • pnpm vitest run src/main/computer — 22 files, 554 tests passed (including the PTY integration suite)
  • pnpm verify:computer-native
    • 43 macOS Swift tests passed
    • Linux provider syntax and argument guardrails passed
    • macOS helper bundle/signature verification passed
    • Windows PowerShell checks skipped because pwsh is unavailable on this host
  • git diff --check

Coverage includes protocol allowlisting, malformed metadata, request timeouts, early helper termination, setup/spawn failure, asynchronous spawn errors, claim/release behavior, unclaimed deadlines, graceful-to-force escalation, owner-death cleanup, sidecar queue invalidation, response-delivery failure, stale child/socket events, and large paste validation before startup.

AI Review Report

The review traced authority, IPC validation, session registration, cleanup, concurrency, stale state, partial startup, response delivery, and shutdown ordering.

It flagged and fixed three issues before publishing:

  1. A real spawn() failure can return no PID and emit error asynchronously. Without a temporary listener that would become an unhandled main-process exception. Failed/unowned children now retain a no-op error listener.
  2. Forced termination previously removed sessions immediately after requesting SIGKILL. Sessions now stay registered until the child actually emits exit, preserving the supervision contract.
  3. Termination events that beat delayed or lost start responses could accumulate. Early unmatched events now have a fixed bound.

Cross-platform review confirmed this new supervisor path is macOS-specific and runtime-selected. Existing Linux and Windows providers, windowsHide, SSH execution, and folder-workspace behavior are unchanged. New filesystem paths use Node path APIs; no shortcut, label, shell, Git, or provider-specific review behavior changed.

Security Audit

  • The child-to-parent protocol is domain-specific, not a command runner. It rejects extra executable-path and argument fields.
  • Main chooses the executable and complete fixed argument list; the sidecar cannot inject commands, paths, environment, or stdio configuration.
  • Session IDs and socket tokens are generated in main. Directories are mode 0700 and token files mode 0600.
  • Start responses are structurally validated before the sidecar uses session metadata.
  • Each lifecycle request is bounded, and unmatched early state is capped.
  • Main retains the concrete child object/PID until confirmed exit and owns cleanup across sidecar failure.
  • No secrets are logged or persisted beyond the existing private token file, which is removed after claim.
  • No dependency changes.

Notes

This PR intentionally preserves the sidecar process and current macOS socket-peer identity. Linux/Windows operation supervision, cross-platform death injection, the sidecar worker conversion, and packaged memory benchmarks remain separate follow-ups in the reviewed boundary migration sequence.

@nwparker
nwparker force-pushed the nwparker/computer-main-provider-supervisor branch from 492536e to e13a637 Compare July 30, 2026 00:32
@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds a supervisor IPC protocol and host/client implementation for supervised macOS provider sessions. A macOS supervisor now starts, claims, releases, and cleans up detached helpers while reporting termination events. Socket transport and native provider client lifecycle handling use session identifiers instead of direct directory cleanup. Sidecar orchestration moves into ComputerSidecarProcess, which forwards supervisor messages and handles child failures. Sidecar entry handling and related tests are updated for supervisor message routing and shutdown.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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 is concise and accurately summarizes the main change: moving macOS helper supervision into main.
Description check ✅ Passed The description matches the template well and includes summary, screenshots, testing, AI review, security audit, and notes.

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

🧹 Nitpick comments (7)
src/main/computer/computer-provider-supervisor-host.test.ts (1)

68-77: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test asserts less than its name claims. The "detaches delivery" half is unverified — send is attached but never asserted against.

♻️ Assert detachment after shutdown
     host.shutdown()
 
     expect(macOS.shutdown).toHaveBeenCalledTimes(1)
+    expect(
+      host.handle({
+        channel: COMPUTER_PROVIDER_SUPERVISOR_CHANNEL,
+        kind: 'request',
+        id: 2,
+        method: 'macos.start',
+        params: {}
+      })
+    ).toBe(true)
+    await vi.waitFor(() => expect(macOS.start).toHaveBeenCalledTimes(1))
+    expect(send).not.toHaveBeenCalled()

(make the test async for the waitFor.)

src/main/computer/computer-provider-supervisor-client.test.ts (1)

99-111: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider covering the ok: false response path. No test asserts that an error response rejects with the supervisor's code/message, or that shutdown() rejects in-flight requests.

src/main/computer/macos-native-provider-supervisor.ts (2)

150-162: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

onError can leave a permanent map entry. When spawn fails, Node emits 'error' with no subsequent 'exit', so finishSession never runs and the session lingers in this.sessions with its listeners attached.

♻️ Reap the session on the error path
       this.emitTermination(session, `native macOS helper app failed: ${error.message}`)
       session.terminating = true
-      this.deps.clearTimer(session.claimTimer)
-      this.removeSocketDirectory(session.socketDirectory)
       try {
         child.kill('SIGKILL')
       } catch {}
+      this.finishSession(session)

235-243: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the exported channel constant instead of the literal. Import COMPUTER_PROVIDER_SUPERVISOR_CHANNEL from ./computer-provider-supervisor-protocol (this file already type-imports from it) so the channel has one source of truth.

♻️ Proposed change
     this.emitEvent({
-      channel: 'orca:computer-provider-supervisor',
+      channel: COMPUTER_PROVIDER_SUPERVISOR_CHANNEL,
       kind: 'event',
-import type {
-  ComputerProviderSupervisorEvent,
-  StartedSupervisedMacOSProvider
-} from './computer-provider-supervisor-protocol'
+import {
+  COMPUTER_PROVIDER_SUPERVISOR_CHANNEL,
+  type ComputerProviderSupervisorEvent,
+  type StartedSupervisedMacOSProvider
+} from './computer-provider-supervisor-protocol'
src/main/computer/macos-native-provider-supervisor.test.ts (1)

191-219: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a case for 'error' on a registered session. The suite covers the pre-registration error (line 202) but not a live session emitting 'error', which is the path that emits sessionTerminated and where the session is currently left in the map (see the onError comment on macos-native-provider-supervisor.ts).

src/main/computer/macos-native-provider-client.ts (1)

184-204: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider re-checking the generation after the await before adopting the session.

isCurrent is evaluated inside startMacOSNativeProviderSocket, but the assignments here happen a microtask later. If shutdown() (which bumps socketStartGeneration and clears socketStartPromise) lands in that gap, this method still installs socketSessionId/socket for a session nobody will release — leaking the helper process. A guard here makes the ownership handoff self-contained.

♻️ Suggested guard
     })
+    if (this.socketStartGeneration !== startGeneration) {
+      started.socket.destroy()
+      void releaseMacOSNativeProviderSocketSession(started.sessionId).catch(() => undefined)
+      throw new RuntimeClientError(
+        'accessibility_error',
+        'native macOS provider startup was superseded'
+      )
+    }
     this.socketSessionId = started.sessionId
src/main/computer/computer-sidecar-process.ts (1)

138-146: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Piped stdout/stderr are never consumed.

stdio: ['ignore', 'pipe', 'pipe', 'ipc'] creates pipes that nothing reads in this class, so a chatty sidecar can fill the OS pipe buffer (~64KB) and block on write. Either drain them into a logger or use 'ignore'/'inherit'.

♻️ Option: drain to the main-process logs
     const child = fork(this.entryPath, [], {
       stdio: ['ignore', 'pipe', 'pipe', 'ipc'],

…then after fork:

child.stdout?.resume()
child.stderr?.resume()

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8adfccc1-c2e4-4ac8-80f8-79c635846a10

📥 Commits

Reviewing files that changed from the base of the PR and between b339fe0 and 492536e0c0c9e600bc8de3eab9e8dbd2ec9e5bc7.

📒 Files selected for processing (15)
  • src/main/computer/computer-provider-supervisor-client.test.ts
  • src/main/computer/computer-provider-supervisor-client.ts
  • src/main/computer/computer-provider-supervisor-host.test.ts
  • src/main/computer/computer-provider-supervisor-host.ts
  • src/main/computer/computer-provider-supervisor-protocol.ts
  • src/main/computer/computer-sidecar-process.ts
  • src/main/computer/macos-native-provider-client.test.ts
  • src/main/computer/macos-native-provider-client.ts
  • src/main/computer/macos-native-provider-paste-validation.test.ts
  • src/main/computer/macos-native-provider-supervisor.test.ts
  • src/main/computer/macos-native-provider-supervisor.ts
  • src/main/computer/macos-native-provider-transport.ts
  • src/main/computer/sidecar-client.test.ts
  • src/main/computer/sidecar-client.ts
  • src/main/computer/sidecar-entry.ts

@nwparker
nwparker force-pushed the nwparker/computer-main-provider-supervisor branch from e13a637 to 7f0e9a9 Compare July 30, 2026 00:41
@nwparker

Copy link
Copy Markdown
Contributor Author

Follow-up review resolution:

  • Fixed the CI-discovered eager fs dependency lookup; the unrelated 397-test PTY suite now passes without weakening its full filesystem mock.
  • Closed the claimed-session adoption microtask race identified in review. A shutdown in that gap now destroys the socket and releases the exact main-owned session, with a deterministic regression test.
  • The supervisor host now rejects lifecycle requests while detached after owner shutdown.
  • Sidecar stdout/stderr are ignored instead of creating unread pipes that could backpressure the child.
  • Added coverage for typed supervisor errors and registered helper error events.
  • Replaced the supervisor channel literal with the protocol constant.

One suggestion was intentionally not applied: a registered session is not removed immediately on child error. It remains tracked until exit because removing it after a failed SIGKILL request would violate the core no-untracked-descendant contract. Spawn failures with no PID are never registered and retain a no-op error listener for the later asynchronous Node error.

Post-fix local verification: 552 computer + PTY tests, typecheck, lint/reliability/max-lines, and diff checks all pass.

@greptile-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR moves ownership of the native macOS computer-use helper process from the long-lived Electron sidecar into the Electron main process, introducing a typed three-operation IPC protocol (macos.start, macos.claim, macos.release) between them. The sidecar can no longer spawn, path-resolve, or configure the helper—those responsibilities now live exclusively in MacOSNativeProviderSupervisor inside main.

  • New supervisor layer: MacOSNativeProviderSupervisor (main) owns executable resolution, private socket-directory/token creation, spawn, PID registration, the 20-second unclaimed-start deadline, SIGTERM→SIGKILL escalation, and cleanup. ComputerProviderSupervisorHost routes IPC from the sidecar; ComputerProviderSupervisorClient is the sidecar-side peer.
  • Sidecar extracted to its own file: ComputerSidecarProcess is extracted from sidecar-client.ts with the supervisor host embedded, adding process.once('exit', …) for app.exit() safety and switching sidecar stdio from pipe to ignore to eliminate unconsumed-pipe backpressure.
  • Transport and client simplified: MacOSNativeProviderClient and macos-native-provider-transport.ts delegate start/claim/release to the supervisor client, removing all direct spawn/fs calls from the sidecar path.

Confidence Score: 5/5

Safe to merge. The ownership transfer is well-bounded and every failure path in the PR matrix is exercised by tests.

The supervision contract is enforced at every boundary: main chooses the executable and all fixed arguments, session IDs and tokens are generated in main, the protocol validator rejects extra fields, and each lifecycle transition is tested with a dedicated case. The three pre-publish fixes are all present and covered. No logic gaps or unhandled races were found.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/main/computer/macos-native-provider-supervisor.ts New file: core supervision logic. Owns spawn, PID registration, claim-timer deadline, SIGTERM to SIGKILL escalation, and cleanup. Handles no-PID spawn, pre-spawn token failure, async error listener, and retained-until-exit ownership after forced kill.
src/main/computer/computer-sidecar-process.ts New file: extracted ComputerSidecarProcess with integrated ComputerProviderSupervisorHost. Adds SIGTERM to SIGKILL escalation for the sidecar itself and switches stdio from pipe to ignore to prevent unconsumed-buffer backpressure.
src/main/computer/computer-provider-supervisor-host.ts New file: main-process IPC host routing only the three fixed supervisor operations. Returns false and drops requests after shutdown via sender=null guard.
src/main/computer/computer-provider-supervisor-client.ts New file: sidecar-side IPC client with request timeout, early-termination event buffering capped at 32 entries, and session state tracking.
src/main/computer/computer-provider-supervisor-protocol.ts New file: protocol type definitions with strict runtime validators blocking arbitrary executable/args injection at the IPC boundary.
src/main/computer/macos-native-provider-transport.ts Refactored to delegate spawn/token/dir management to the supervisor client. Adds post-claim isCurrent check for the shutdown-mid-claim race.
src/main/computer/macos-native-provider-client.ts Updated to use sessionId instead of socketDirectory for cleanup. Adds generation check after startMacOSNativeProviderSocket returns for the microtask-queue superseded race.
src/main/computer/sidecar-client.ts Simplified by extracting ComputerSidecarProcess. Adds process.once exit handler for app.exit() safety.
src/main/computer/sidecar-entry.ts Adds supervisor message routing and correct shutdown ordering: providers shut down before supervisor client.

Reviews (2): Last reviewed commit: "fix(computer): harden supervisor deadlin..." | Re-trigger Greptile

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5df5ac17-bf6b-4314-9e82-e92bfc535d96

📥 Commits

Reviewing files that changed from the base of the PR and between e13a637ab4864165d05ff216399b058b17bec280 and 7f0e9a9.

📒 Files selected for processing (15)
  • src/main/computer/computer-provider-supervisor-client.test.ts
  • src/main/computer/computer-provider-supervisor-client.ts
  • src/main/computer/computer-provider-supervisor-host.test.ts
  • src/main/computer/computer-provider-supervisor-host.ts
  • src/main/computer/computer-provider-supervisor-protocol.ts
  • src/main/computer/computer-sidecar-process.ts
  • src/main/computer/macos-native-provider-client.test.ts
  • src/main/computer/macos-native-provider-client.ts
  • src/main/computer/macos-native-provider-paste-validation.test.ts
  • src/main/computer/macos-native-provider-supervisor.test.ts
  • src/main/computer/macos-native-provider-supervisor.ts
  • src/main/computer/macos-native-provider-transport.ts
  • src/main/computer/sidecar-client.test.ts
  • src/main/computer/sidecar-client.ts
  • src/main/computer/sidecar-entry.ts

@nwparker

Copy link
Copy Markdown
Contributor Author

Final review disposition: Greptile rated the change safe to merge. Its map-clearing suggestion was rejected because sessions must remain owned until confirmed child exit; its timer-initialization observation cannot publish partial state because timer setup precedes registration. The sidecar SIGTERM and disconnect observations concern pre-existing general sidecar lifecycle behavior: this change synchronously reaps all registered native helpers before signaling the sidecar, and preserving natural disconnect drainage avoids cutting off the sidecar direct terminate fallback after an unexpected parent loss. No remaining finding changes this PR.

@nwparker
nwparker merged commit 48184b9 into stablyai:main Jul 30, 2026
46 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Move native macOS helper process ownership into Electron main while preserving the sidecar as the authenticated socket peer. Add fixed lifecycle IPC, bounded claim and release handling, confirmed-exit tracking, sidecar and helper force-kill escalation, cleanup across failure paths, and focused lifecycle coverage.
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