Skip to content

fix(computer): supervise Linux and Windows desktop providers from main - #11468

Merged
nwparker merged 3 commits into
mainfrom
nwparker/computer-desktop-provider-supervisor
Jul 30, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/computer-desktop-provider-supervisor

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

Summary

Moves Linux and Windows desktop-provider process ownership out of the long-lived computer sidecar and into Electron main's domain-specific computer-provider supervisor.

This is the next prerequisite after #10256 and #11441 for replacing the trusted Electron-as-Node computer sidecar with a worker without allowing Python or PowerShell operations to survive worker termination.

What changed

Fixed supervisor boundary

  • adds one fixed desktop.execute supervisor method;
  • accepts only an exact, tool-specific BridgeRequest — never a command, executable path, script path, environment, argument list, timeout, output limit, or temporary path;
  • revalidates required action fields, finite numbers, window-target exclusivity, nested element/frame state, key/modifier syntax, the existing 16 MiB paste limit, and a 17 MiB serialized request cap in main;
  • validates the bounded { stdout, stderr, error } result again in the sidecar;
  • gives desktop execution a 40-second supervisor IPC timeout so the main-owned 30-second provider deadline and reap grace can complete, while preserving the existing 10-second macOS lifecycle timeout.

Main-owned operation lifecycle

  • registers each operation before asynchronous directory creation, permission setup, or request-file writes;
  • selects Linux/Windows, the bundled runtime, command, arguments, and environment in main and caches that immutable execution plan;
  • reuses the JSON produced by request-size validation, avoiding a second serialization for large paste payloads;
  • owns the private orca-computer-use-* directory, mode-0600 operation file, 20 MiB execFile output cap, child handle, deadline, termination, confirmed reap, and cleanup;
  • waits for both the execFile callback and confirmed child exit before returning a normal result;
  • retains the child and operation file after timeout or owner shutdown until exit is confirmed;
  • escalates SIGTERM to SIGKILL on POSIX, and uses immediate forceful termination on Windows where Node's process termination is already forceful;
  • binds responses to the sidecar owner generation so an old operation can never reply through a replacement sidecar's sender.

Sidecar responsibilities retained

The sidecar still owns capability caching, snapshot state, action verification, rendering, JSON response parsing, and provider error mapping. It now sends the domain request to main instead of creating temporary files and spawning Python/PowerShell itself.

Performance notes

  • removes process/timer/temp-file ownership from the isolate that will become a worker;
  • keeps directory setup and operation-file writes asynchronous;
  • caches main-selected invocation state and avoids duplicate large-request serialization;
  • intentionally adds a main → sidecar provider-result hop for Linux/Windows. Screenshot-sized structured-clone cost remains an explicit measurement item for the worker migration rather than being hidden in this prerequisite.

Failure and concurrency coverage

New deterministic tests cover:

  • arbitrary command/path/args/env/timeout injection rejection;
  • malformed, oversized, cyclic, and over-limit paste requests;
  • current modifier-click schema compatibility;
  • fixed Linux Python and Windows PowerShell invocations;
  • cancellation before directory creation and after directory creation but before spawn;
  • spawn results without a PID plus later asynchronous error events;
  • callback-before-exit and exit-before-callback ordering;
  • normal response delivery only after confirmed exit;
  • Linux graceful-to-force timeout escalation and force-timer cancellation;
  • Windows forceful timeout behavior;
  • child errors and owner shutdown after spawn;
  • directory retention until confirmed exit and cleanup afterward;
  • stale response suppression after sidecar owner replacement;
  • method-specific supervisor timeout and result-shape validation.

Verification

  • pnpm vitest run src/main/computer src/main/ipc/pty.test.ts — 24 files, 577 tests passed
  • pnpm typecheck
  • pnpm lint — includes oxlint, type-aware/native audits, reliability gates, max-lines ratchet, skill manifests, and localization checks
  • pnpm verify:computer-native — 44 macOS provider tests, Linux syntax, native argument guardrails, and bundle/signature verification passed; local Windows PowerShell checks were skipped because pwsh is unavailable
  • git diff --check

@greptile-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

Moves Linux and Windows desktop-provider process ownership from the computer sidecar into Electron main's DesktopScriptProviderSupervisor. The sidecar now sends a validated desktop.execute IPC request to main; main owns directory creation, file writes, child spawning, deadline enforcement, graceful-to-force kill escalation, confirmed-exit cleanup, and serialization caching.

  • Adds DesktopScriptProviderSupervisor (320 lines) with full operation lifecycle: prepareAndSpawn, spawnOperation, handleChildError/Exit/Deadline, completeAfterCallback, finishOperation, and termination-before-spawn cancellation.
  • Adds a comprehensive isDesktopScriptProviderRequest validator (277 lines) that enforces per-tool allowed-key sets, window-target exclusivity, finite numbers, element/frame shape, key/modifier syntax, the 16 MiB paste limit, and a 17 MiB serialized-request cap — with a WeakMap cache to avoid double-serializing large payloads.
  • Updates ComputerProviderSupervisorHost with owner-generation tracking so responses from cancelled or replaced operations are silently dropped; introduces a 40-second IPC timeout on the sidecar side to bracket the 30-second main deadline plus reap grace.

Confidence Score: 5/5

Safe to merge. The security boundary enforcement is well-reasoned and the process lifecycle is handled correctly at every edge.

The supervisor's dual callback+exit synchronization, cancellation-at-every-async-checkpoint, timeout escalation, and stale-response suppression are all exercised by deterministic tests with fake timers and mock deps. The request validator uses per-tool allowed-key whitelists that prevent injection of command, path, args, env, or timeout fields, and the owner-generation guard in the host correctly drops responses from operations that span a shutdown/reattach boundary. No incorrect behavior was found.

Files Needing Attention: No files require special attention. The highest-complexity code — desktop-script-provider-supervisor.ts and desktop-script-provider-request-validation.ts — has direct test coverage for every documented edge case.

Important Files Changed

Filename Overview
src/main/computer/desktop-script-provider-supervisor.ts New 320-line supervisor owning the full operation lifecycle: async directory creation, child spawning, deadline/force-kill escalation, confirmed-exit requirement before resolving, and idempotent cleanup. The dual callback+exit synchronization logic and cancellation-at-every-async-checkpoint are correct and well-tested.
src/main/computer/desktop-script-provider-request-validation.ts New 277-line whitelist validator covering per-tool allowed-key sets, element/frame shapes, key/modifier syntax, paste limit, and a 17 MiB cap with WeakMap serialization caching to avoid double-JSON on large payloads. Logic is thorough and the tests exercise injection paths and size limits.
src/main/computer/computer-provider-supervisor-protocol.ts Adds the desktop.execute request variant and SupervisedDesktopProviderResult type with strict shape validators. Also fixes messageRecord to reject arrays.
src/main/computer/computer-provider-supervisor-host.ts Adds DesktopScriptProviderSupervisor integration with owner-generation tracking so responses from operations spanning a shutdown+reattach cycle are silently dropped.
src/main/computer/computer-provider-supervisor-client.ts Adds executeDesktopProvider with a 40-second method-specific timeout and validates the returned result shape via isSupervisedDesktopProviderResult before resolving.
src/main/computer/desktop-script-provider-bridge.ts Replaced ~80 lines of local execFile/timeout/kill/temp-file logic with a single executeSupervisedDesktopProvider call. withoutUndefinedValues strips optional undefined fields before the IPC hop.
src/main/computer/desktop-script-provider-client.ts Removes constructor parameters, temp-dir mkdtemp/writeFile/rm calls, and platform/scriptPath helpers — those responsibilities moved to the supervisor.
src/main/computer/desktop-script-provider-process-invocation.ts New file extracting the execution plan, argument construction, and result-shape normalization into pure functions, plus the injectable deps interface for testability.
src/main/computer/desktop-script-provider-supervisor.test.ts New 317-line deterministic test suite covering callback/exit ordering, pre-spawn cancellation, timeout escalation, force-kill cancellation, Windows path, shutdown with live children, and pid-less child handling.
src/main/computer/desktop-script-provider-test-harness.ts Replaces execFile/fs mocks with a mock of executeSupervisedDesktopProvider. The inspectOperation callback now receives the BridgeRequest object directly instead of parsed JSON from the operation file.

Reviews (2): Last reviewed commit: "test(computer): flush stale supervisor r..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds validated desktop.execute supervisor requests and structured desktop execution results. Introduces platform-specific desktop provider process supervision with temporary operation files, timeout escalation, shutdown handling, and cleanup. Routes the desktop provider bridge and client through the supervisor, updates related error handling and test harnesses, and prevents stale host responses after ownership changes.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: moving desktop-provider supervision into main for Linux and Windows.
Description check ✅ Passed The description is detailed and covers summary, validation, tests, risks, and platform-specific behavior, though it doesn't mirror every template heading.
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.
✨ Finishing Touches 💡 1
📝 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: 2

🧹 Nitpick comments (4)
src/main/computer/desktop-script-provider-request-validation.ts (1)

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

Hidden cross-file coupling via SERIALIZED_REQUESTS cache.

isWithinRequestLimit (a size-check predicate) has the side effect of populating SERIALIZED_REQUESTS, which serializeDesktopScriptProviderRequest later consumes when called from desktop-script-provider-supervisor.ts's prepareAndSpawn. This only works because the exact same BridgeRequest object reference is threaded from validation through to serialization — nothing documents or enforces that invariant, so a future refactor that clones/copies the request between those two points would silently degrade to a redundant JSON.stringify with no visible symptom, making the coupling easy to miss.

Consider either removing the implicit caching (letting both call sites stringify independently, since payload sizes here are small) or making the reuse explicit (e.g., a short comment stating the invariant, or a dedicated getOrSerialize(request) accessor used by both sites instead of two loosely-related functions touching a shared WeakMap).

Also applies to: 81-88, 218-231

src/main/computer/desktop-script-provider-supervisor.ts (1)

46-73: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

execute() can throw synchronously instead of returning a rejected promise.

desktopProviderExecutionPlan(this.deps) (Line 47) can throw a RuntimeClientError before the Promise executor is even constructed. Since execute() isn't async, that throw escapes as a synchronous exception rather than a promise rejection. It happens to be safely wrapped today because the only caller (dispatch in computer-provider-supervisor-host.ts) is async, but that's the caller's accident, not a guarantee of this method's own API contract — any .then()/.catch()-style caller added later would get an uncaught exception instead of a rejection.

🛡️ Proposed fix to always return a rejected promise
   execute(request: BridgeRequest): Promise<SupervisedDesktopProviderResult> {
-    const plan = this.executionPlan ?? desktopProviderExecutionPlan(this.deps)
-    this.executionPlan = plan
+    let plan: DesktopProviderExecutionPlan
+    try {
+      plan = this.executionPlan ?? desktopProviderExecutionPlan(this.deps)
+    } catch (error) {
+      return Promise.reject(error)
+    }
+    this.executionPlan = plan
src/main/computer/desktop-script-provider-supervisor.test.ts (2)

30-34: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Fixed 8-iteration microtask flush is a fragile magic number.

flushPreparation assumes exactly enough microtask hops to drain the mkdtemp/chmod/writeFile await chain in prepareAndSpawn. It works today, but if the implementation gains another await, this constant would need to grow, and until then assertions could silently run before state fully settles rather than failing clearly.


134-151: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test name promises "environment" reuse coverage that isn't asserted.

This test only checks platform/resolveScriptPath call counts and execFile call count; it doesn't verify that the cached plan's env (or the plan object itself) is actually reused across the two execute() calls, despite the test description. Consider asserting that both execFile calls received the same env reference to actually validate the "caches immutable execution plans" contract.

✅ Proposed strengthening
     expect(deps.platform).toHaveBeenCalledTimes(1)
     expect(deps.resolveScriptPath).toHaveBeenCalledTimes(1)
     expect(deps.execFile).toHaveBeenCalledTimes(2)
+    const firstEnv = vi.mocked(deps.execFile).mock.calls[0][2]?.env
+    const secondEnv = vi.mocked(deps.execFile).mock.calls[1][2]?.env
+    expect(secondEnv).toBe(firstEnv)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5d04aa2f-e4bf-45c3-a281-993b8c8c961a

📥 Commits

Reviewing files that changed from the base of the PR and between 3eddc46 and 3b2f6b2.

📒 Files selected for processing (14)
  • 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.test.ts
  • src/main/computer/computer-provider-supervisor-protocol.ts
  • src/main/computer/desktop-script-provider-bridge.ts
  • src/main/computer/desktop-script-provider-client.ts
  • src/main/computer/desktop-script-provider-errors.test.ts
  • src/main/computer/desktop-script-provider-process-invocation.ts
  • src/main/computer/desktop-script-provider-request-validation.ts
  • src/main/computer/desktop-script-provider-supervisor.test.ts
  • src/main/computer/desktop-script-provider-supervisor.ts
  • src/main/computer/desktop-script-provider-test-harness.ts

@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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a68f851a-b3b0-4569-9ef6-00e2d1707cd7

📥 Commits

Reviewing files that changed from the base of the PR and between 3b2f6b2 and 3490697.

📒 Files selected for processing (4)
  • src/main/computer/computer-provider-supervisor-host.test.ts
  • src/main/computer/desktop-script-provider-bridge.ts
  • src/main/computer/desktop-script-provider-errors.test.ts
  • src/main/computer/desktop-script-provider-test-harness.ts
💤 Files with no reviewable changes (1)
  • src/main/computer/desktop-script-provider-errors.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/computer/computer-provider-supervisor-host.test.ts

@nwparker
nwparker merged commit ef90f60 into main Jul 30, 2026
46 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
stablyai#11468)

* fix(computer): supervise desktop providers from main

* fix(computer): remove unreachable provider timeout mapping

* test(computer): flush stale supervisor response
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