Repository navigation
fix(computer-use): run the Windows runtime as one persistent helper - #17858
Conversation
Microsoft Defender for Endpoint raised multi-stage Execution + Collection
incidents against Orca on Windows ("Screenshots were taken unexpectedly on
this device... Screen capture code was found in a script launched by
powershell.exe", factor "Executes suspicious MSIL code"). The desktop script
provider spawned a fresh powershell.exe per operation, so a single computer-use
session produced a burst of short-lived PIDs and re-emitted runtime.ps1's
inline Add-Type P/Invoke assembly on every click.
runtime.ps1 gains a -Serve mode that loads its assemblies once and then reads
NDJSON requests from stdin, and a new DesktopScriptRuntimeHost owns one
long-lived child: lazy spawn, strict serialization, a 30s per-request timeout,
restart on crash, a 120s idle shutdown, and dispose() on provider teardown. The
one-shot -OperationPath path stays as the fallback, and Linux keeps its python3
bridge unchanged.
Both Windows spawn sites now use -ExecutionPolicy RemoteSigned instead of
Bypass, falling back once to Bypass (and logging) when a Restricted host
refuses the unsigned script.
Greptile SummaryThe PR replaces per-operation Windows PowerShell processes with a serialized persistent NDJSON helper while retaining the one-shot bridge as a fallback.
Confidence Score: 4/5The PR should not merge until host disposal prevents queued automation requests from restarting PowerShell after provider teardown. The persistent host correctly serializes normal operations, but its disposal path only cancels the active request, so queued work can recreate the helper after lifecycle ownership has ended. Files Needing Attention: src/main/computer/desktop-script-runtime-host.ts
|
| Filename | Overview |
|---|---|
| src/main/computer/desktop-script-runtime-host.ts | Introduces the persistent helper and serialization lifecycle, but disposal leaves queued requests able to restart the helper after teardown. |
| src/main/computer/desktop-script-provider-client.ts | Routes Windows operations through the persistent host and degrades to one-shot execution when startup is unavailable. |
| native/computer-use-windows/runtime.ps1 | Adds a serialized NDJSON serve loop while retaining the existing one-shot mode. |
| src/main/computer/desktop-script-provider-bridge.ts | Changes Windows one-shot execution to prefer RemoteSigned with a logged Bypass retry for startup policy failures. |
| src/main/computer/windows-powershell-execution-policy.ts | Centralizes PowerShell execution-policy arguments and detection of policy-blocked startup errors. |
Sequence Diagram
sequenceDiagram
participant C as DesktopScriptProviderClient
participant H as DesktopScriptRuntimeHost
participant P as PowerShell runtime.ps1
C->>H: request(operation)
alt helper not running
H->>P: spawn -Serve (RemoteSigned)
end
H->>P: NDJSON request over stdin
P-->>H: NDJSON response over stdout
H-->>C: BridgeResponse
alt startup policy failure
H->>P: retry once with Bypass
else host unavailable
H-->>C: runtime_host_unavailable
C->>P: one-shot bridge
end
Reviews (1): Last reviewed commit: "fix(computer-use): run the Windows runti..." | Re-trigger Greptile
| dispose(): void { | ||
| this.clearIdleTimer() | ||
| this.stopChild() | ||
| this.rejectPending( | ||
| new RuntimeClientError('accessibility_error', 'desktop provider runtime host was shut down') | ||
| ) | ||
| } |
There was a problem hiding this comment.
Disposal leaves queued work active
If provider shutdown overlaps an active request and another queued request, dispose() rejects only the active request without closing the queue. The queued continuation then calls ensureChild() and starts a new PowerShell helper after teardown, allowing desktop automation to continue under a provider that no longer owns it.
Knowledge Base Used: Desktop application platform
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe Windows runtime script now supports persistent NDJSON serve mode with readiness announcements and request ID echoing. A runtime host serializes requests through one PowerShell process and manages framing, timeouts, failures, replay rules, cooldowns, idle shutdown, and disposal. The provider uses this host on Windows and retains one-shot Python execution on Linux. Execution-policy handling, sidecar diagnostics, request queuing, and Windows integration tests were added. Merge Risk: 🟡 Moderate · up to Windows computer-use actions may execute twice during policy fallback, and malformed helper output can terminate the application. These issues should be fixed before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives a detailed explanation of the implementation and verification, but it omits required template sections and information, including the linked issue, visual proof or an explicit N/A statement, AI disclosure, review section, agent skill boundary checkbox, notes, and checklist confirmations. Resolution Add the missing template sections. Provide a linked issue after Full details: Docstring CoverageExplanation Docstring coverage is 29.03% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 31 functions across 20 files. (2 skipped: 2 unsupported.)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 3efd5218-79eb-4f8c-9602-9d1fdc3487eb
📒 Files selected for processing (9)
native/computer-use-windows/runtime.ps1src/main/computer/desktop-script-provider-bridge.tssrc/main/computer/desktop-script-provider-client.tssrc/main/computer/desktop-script-provider-runtime-host-routing.test.tssrc/main/computer/desktop-script-provider-test-harness.tssrc/main/computer/desktop-script-runtime-host.test.tssrc/main/computer/desktop-script-runtime-host.tssrc/main/computer/desktop-script-runtime-host.win32.test.tssrc/main/computer/windows-powershell-execution-policy.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
|
|
||
| private readStdout(chunk: Buffer | string): void { | ||
| this.stdoutBuffer += typeof chunk === 'string' ? chunk : this.decoder.write(chunk) | ||
| if (this.stdoutBuffer.length > MAX_RESPONSE_BYTES) { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
printf '%s\n' '--- repository conventions and learnings ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print
printf '%s\n' '--- target source ---'
sed -n '1,260p' src/main/computer/desktop-script-runtime-host.tsRepository: stablyai/orca
Length of output: 12255
🏁 Script executed:
printf '%s\n' '--- repository-wide conventions ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/repo-wide.md
printf '%s\n' '--- remaining target source ---'
sed -n '240,420p' src/main/computer/desktop-script-runtime-host.ts
printf '%s\n' '--- related tests and references ---'
rg -n --glob '*.{ts,tsx,js}' 'DesktopScriptRuntimeHost|MAX_RESPONSE_BYTES|readStdout|runtime host buffer' src tests 2>/dev/null | head -120Repository: stablyai/orca
Length of output: 8842
Count UTF-8 bytes for the response limit.
readStdout decodes Buffer chunks with StringDecoder('utf8'), then compares UTF-16 code-unit length with MAX_RESPONSE_BYTES. Multibyte UTF-8 text can exceed the intended 20 MiB limit while this check still passes. Track buffered UTF-8 bytes and decrement the count as complete lines are removed.
There was a problem hiding this comment.
ℹ️ No critical issues — one rough edge worth a look.
Reviewed changes
- Persistent runtime host — new
DesktopScriptRuntimeHostdrives one long-livedruntime.ps1 -ServeNDJSON child with strict request serialization, per-request timeout, crash restart, and idle shutdown. - Serve mode in
runtime.ps1— one-shot-OperationPathpath untouched; serve loop reads a JSON line per request and writes one UTF-8 response line until stdin closes. - Client routing — Windows operations go through the host and degrade to the one-shot bridge only on
runtime_host_unavailable; operation errors still surface. - Execution-policy tightening — both spawn sites now prefer
RemoteSignedwith a single, loggedBypassfallback on a policy-blocked start.
The serialization, restart, and policy-fallback logic read correctly, and the test suite pins the failure modes it claims (single spawn across operations, chunk/split-codepoint reassembly, timeout, crash-restart, idle shutdown, policy fallback on both spawn sites).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Review follow-up on the persistent Windows computer-use helper. A helper that died before producing a line set an unavailable flag nothing ever cleared, and the client then dropped the host for the life of the session. One transient bad spawn — a Defender scan, a locked CSC temp directory — silently restored the per-click powershell.exe burst and per-operation MSIL emission this work exists to remove, with computer use still working so nothing looked wrong. Start failures are now retried, then cool down for 60s, then re-probed; the client keeps the host so it can come back. Repeated post-answer crashes cool down too, and a single reply no longer clears the failure count. The one-shot bridge decided its execution-policy retry from a message that fell back to stdout, so a window title containing "SecurityError" could replay a non-idempotent operation — a double click, keystroke or paste — and stick the session on Bypass. The retry now requires empty stdout and a matching stderr. Serve-mode replies carry an echoed request id. Without one a single stray stdout line would make every later response answer the previous request, acting on stale element indexes with no error raised; a mismatch now kills the child. Non-JSON noise is ignored rather than counted as the helper having answered. Also: warnings reach the main process over the sidecar's IPC channel rather than its piped, unread stdio; the child is watched on close rather than exit; dispose latches so a queued request cannot respawn during teardown; and the host is split into a serve channel and an availability policy to stay under max-lines.
…request
The retry that replaced the permanent-latch bug could deliver unrequested
input. send() re-sent the same request whenever the helper died without
replying, but "no reply came back" is not "the operation did not run":
runtime.ps1 synthesizes the click and only then builds the snapshot, which
allocates a full-window bitmap and walks the UIA tree — a native GDI+/UIA fault
there is uncatchable, and leaves the click already delivered. A deterministic
fault meant three clicks from the host plus a fourth from the one-shot bridge,
surfaced as a single failed operation.
-Serve now writes one {"ready":true} line after its Add-Type work and before
its first read, so "never started" is a fact rather than an inference. A request
is replayed only when the helper died before announcing. A runtime.ps1 that
predates the announcement — reachable through the provider path override — is
covered by an observation-tool allowlist until a ready line proves otherwise.
Host-detected aborts (timeout, desynchronised reply, oversized line) suppress
the exit handler, so they were bypassing failure accounting entirely and a
helper failing that way was respawned once per operation forever. They now
count and are logged.
Also stop charging twice for one outage: entering the cooldown resets the
failure count, so the first death after recovery no longer re-enters a full
cooldown and an interleaved workload cannot be stranded on the one-shot bridge.
stop() destroys stdin, so a write still queued at teardown calls back with ERR_STREAM_DESTROYED. The callback carried no channel or request identity and write() had no closed guard, so it ran abortChannel a second time: stopChannel no-opped but recordFailure and the warning did not, charging two failures for one operation and reaching the 3-strike cooldown at half the intended rate. That feeds the same accounting that keeps a persistently broken helper from respawning once per operation. The same root also allowed a late callback landing after a replacement channel existed to stop that channel and reject a different request with the previous one's error. Node fires the destroyed-stream callback on the next tick, well before a new request arrives, so the double-count is the reachable effect; binding the callback closes both. write() now drops payloads and error reports once closed, and the host ignores any report whose channel or request id is no longer current.
The channel's closed guard and the host's request-identity check are redundant by design, and the existing tests only failed when both were absent. Someone deleting one, believing the other was the covered one, would have got a green suite and a live regression — the same shape as a test that passes without the fix it was written for. Each is now pinned on its own. The channel's half is tested against the channel directly: after stop() it takes no writes and reports no error from one already queued, which the host cannot observe because it drops the channel at the same moment. The host's half is pinned by the case the channel cannot see — a live channel whose request was already answered, where backpressure delivers a write callback for a request that is no longer pending. Removing either guard alone now fails a test. Both carry a comment saying they are deliberately redundant and separately pinned, so the next reader does not have to rediscover this from the diff.
There was a problem hiding this comment.
Important
The new retry loop re-dispatches a non-idempotent operation after an ambiguous failure, which can replay synthetic input up to four times (see inline).
Reviewed changes
- Recover instead of latching off —
send()now retriesruntime_host_unavailableup toMAX_START_ATTEMPTSwith a 60s cooldown, replacing the previous permanent one-shot fallback. - Request-id correlation — serve-mode replies echo
requestId; a mismatched or unsolicited reply kills the helper instead of silently shifting responses. - Stream plumbing extracted —
DesktopScriptServeChannelowns NDJSON framing,close-based teardown, and the buffer cap; the host keeps only queueing, retry policy, and correlation. - Recovery policy extracted —
RuntimeHostAvailabilitycentralizes attempt counts, cooldown, andRemoteSigned→Bypassescalation. - Sidecar diagnostics — policy-fallback warnings now travel over IPC so they reach the main process instead of the sidecar's unread piped stdout.
- One-shot bridge hardening —
BridgeProcessFailurecarries raw streams so theBypassreplay only happens when stdout was empty, and the policy regex drops the stdout-proneSecurityErrortoken.
The dispose-terminality thread from the prior review is resolved (disposed flag checked at the top of send()).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: e7868614-95da-4169-bd87-79cf53fa92e8
📒 Files selected for processing (17)
native/computer-use-windows/runtime.ps1src/main/computer/computer-sidecar-diagnostics.test.tssrc/main/computer/computer-sidecar-diagnostics.tssrc/main/computer/desktop-script-action.tssrc/main/computer/desktop-script-provider-bridge.tssrc/main/computer/desktop-script-provider-client.tssrc/main/computer/desktop-script-provider-runtime-host-routing.test.tssrc/main/computer/desktop-script-provider-test-harness.tssrc/main/computer/desktop-script-provider-types.tssrc/main/computer/desktop-script-runtime-availability.tssrc/main/computer/desktop-script-runtime-host.test.tssrc/main/computer/desktop-script-runtime-host.tssrc/main/computer/desktop-script-serve-channel.test.tssrc/main/computer/desktop-script-serve-channel.tssrc/main/computer/sidecar-client.tssrc/main/computer/sidecar-entry.tssrc/main/computer/windows-powershell-execution-policy.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
| if (this.availability.policyRetryPending) { | ||
| this.availability.escalateExecutionPolicy() | ||
| continue | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Confirm whether runtime.ps1 announces readiness before reading its first request,
# and whether the escalation path is covered by a replay test.
fd -t f 'runtime.ps1' native | while IFS= read -r f; do
rg -n -C 5 'ready|Serve|ReadLine|Console\.In' "$f"
done
rg -n -C 4 'policyRetryPending|escalateExecutionPolicy|requestPolicyRetry' src/main/computerRepository: stablyai/orca
Length of output: 6131
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- scoped conventions ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print
printf '%s\n' '--- host implementation ---'
cat -n src/main/computer/desktop-script-runtime-host.ts | sed -n '1,180p'
cat -n src/main/computer/desktop-script-runtime-host.ts | sed -n '260,330p'
printf '%s\n' '--- availability implementation ---'
cat -n src/main/computer/desktop-script-runtime-availability.ts | sed -n '1,120p'
printf '%s\n' '--- readiness and provider-path references ---'
rg -n -C 5 'readyProtocolConfirmed|mayReplay|ORCA_COMPUTER_DESKTOP_SCRIPT_PROVIDER_PATH|policyRetryPending|requestPolicyRetry|escalateExecutionPolicy' src test native 2>/dev/null || trueRepository: stablyai/orca
Length of output: 29201
Apply mayReplay to the policy-retry branch.
If ORCA_COMPUTER_DESKTOP_SCRIPT_PROVIDER_PATH selects a helper without the ready protocol, it can perform a mutating operation before exiting with an UnauthorizedAccess-class error. The policy-retry branch currently escalates and replays that request before mayReplay runs. Gate escalation with this.mayReplay(request).
| let parsed: Record<string, unknown> | ||
| try { | ||
| parsed = JSON.parse(line) as Record<string, unknown> | ||
| } catch { | ||
| // Not a response at all — a PowerShell banner, a stray write. Dropping it | ||
| // is safe now that the id below is what decides which request is answered, | ||
| // and it keeps a chatty console from making the helper unusable. | ||
| return | ||
| } | ||
| // The readiness announcement carries no request id and answers nothing. | ||
| if (parsed.ready === true && parsed.requestId === undefined) { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Reject a non-object parse result before reading properties.
JSON.parse returns null for a null line, and the as Record<string, unknown> cast hides that. Line 271 then dereferences parsed.ready and throws a TypeError. deliver runs inside the channel stdout data handler, so the throw becomes an unhandled exception in the main process instead of a dropped line.
🛡️ Proposed fix
- let parsed: Record<string, unknown>
+ let parsed: unknown
try {
- parsed = JSON.parse(line) as Record<string, unknown>
+ parsed = JSON.parse(line)
} catch {
// Not a response at all — a PowerShell banner, a stray write. Dropping it
// is safe now that the id below is what decides which request is answered,
// and it keeps a chatty console from making the helper unusable.
return
}
+ if (typeof parsed !== 'object' || parsed === null) {
+ return
+ }
+ const message = parsed as Record<string, unknown>Use message for the ready, requestId, and spread reads that follow.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Ready announcement —
runtime.ps1 -Serveemits{"ready":true}afterAdd-Typeand before its first read, so a caller can prove a helper never read a request. - Replay proof —
mayReplayretries a dead helper only when it provably never read the request (!childReady && !childAnswered) and the script speaks the ready protocol, or the tool is observation-only (isReplayableTool); a helper killed after announcing ready surfaces asaccessibility_errorand is never replayed. - Observation allowlist —
isReplayableToolwhitelistshandshake/list_apps/list_windows/get_app_state; mutation tools opt in never by default. - Failure accounting for host-detected aborts —
abortChannel(timeout, desync, overflow, write error) now records a failure and warns, so a helper failing that way can no longer be respawned once per operation forever. - Cooldown counter reset —
enterCooldown()resets failure/success counts so one outage costs exactly one cooldown. - Stale write-callback guards — both the host (
this.channel !== channel || this.pending?.id !== id) and the channel (error && !this.closed) ignore late stdin callbacks, each pinned by its own test.
The replay-amplification concern from the prior review is resolved: a helper killed after synthesizing input is now surfaced as a crash rather than re-executed, with regression tests confirmed to fail without each guard.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…lure The per-process attempt cap added for the read-path storm was a permanent latch: one AV scan, momentary lock or %TEMP% blip and every later credential write in that session went unhardened, silently, on a host where hardening would now succeed. Same defect class as #17858's computer-use host, and worse here because what stops happening is security hardening on credential files and nothing said so. The retry budget now bounds the *rate*, not the lifetime: at most three attempts per path per minute, re-probing in every later window, forever. The transition is announced in both directions — `throttled` once per window on entry, `recovered` when a rate-limited path hardens again — so a host stuck in the degraded state is diagnosable rather than merely quiet. The reporter type covers both, and the main process ends the `recovered` span successfully rather than failing it. Extracted to secure-path-hardening-retry-budget.ts, which keeps secure-file.ts under its line cap without a max-lines disable. Also confirms the second flagged risk rather than assuming it: a real unwritable %TEMP% is now covered by a test proving verification fails closed, reports at the `verify` stage, and still leaves the ACL applied — so that path loses proof, not protection, and with the lifetime cap gone it can no longer combine into a permanent-off state.
The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Registered the win32 suite in CI — added
src/main/computer/desktop-script-runtime-host.win32.test.tsto thepackage_windowsvitestlist in.github/workflows/pr.ymland toWINDOWS_PACKAGE_TESTSinconfig/scripts/pr-code-change-scope.mjs, so the real-runtime.ps1 -Servesuite actually runs on Windows CI instead of self-skipping vacuously off-Windows.
The registration matches the existing cmd-shim pattern: both lists that must stay in sync are updated, and the suite's assertions (handshake capabilities, list_apps returning an array, one spawn across operations) exercise only Get-Process/handshake paths with no interactive-desktop dependency, so it should run stably on windows-2022. No prior Pullfrog threads remain open.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
The start-failure cooldown was a wall-clock deadline, so a backwards step — an NTP correction, a VM snapshot restore, a user changing the clock — left `remainingCooldown()` returning the cooldown plus the whole step. A one-hour step measured 3,660,000ms, and ten real minutes later still 3,060,000ms. Nothing shortens it from there. Only `recordSuccess()` clears the cooldown on a non-dispose path, and no request can reach a helper to succeed while it holds, so every `send()` throws `runtime_host_unavailable` first. The host is built with no `now` override and its lifecycle is a module-level singleton that shuts down at process exit, so the latch held for the sidecar's life — computer use kept working via the one-shot bridge while the per-click powershell.exe burst this host exists to remove came back silently. Store the instant the cooldown began and compare elapsed monotonic time, following the two fixes in #17884. The field is `number | null` rather than sentinel 0 because `performance.now()` legitimately returns 0. Both new tests leave `now` unset, because the bug was in the default the host picks and a test that injects a clock cannot see it.
The 30s request timeout was armed only in `sendOnce`, once a request reached a helper. A request behind N timing-out ones therefore waited roughly N times that with no deadline of its own: bounded, but the caller sees an `await` that looks hung for minutes and gets no error to act on. Move the serialization tail into its own class and arm a deadline at enqueue time. Only the wait is bounded — a request that reaches a helper still gets its full execution budget, so nothing that used to succeed now fails. An expired request is dropped rather than sent late: the caller has already been told it failed, and a click delivered after that is worse than no click. The tail keeps its never-rejecting shape and chains on the turn rather than on the raced promise, so a caller giving up early cannot release the next request while its predecessor is still in flight.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Queued-request wait deadline — extracted the inline tail-chain into
DesktopScriptRequestQueue; a request queued behind others now has its ownrequestTimeoutMsdeadline and surfacesaction_timeout(waiting for earlier operations) instead of a minutes-long hungawait, while a request that reaches the helper still keeps its full execution budget. - Monotonic cooldown clock —
RuntimeHostAvailabilitynow stores acooldownStartedAtMssampled fromperformance.now()(withnullas the no-cooldown sentinel, sinceperformance.now()can legitimately return0), so an NTP correction, VM snapshot restore, or user clock change can no longer stretch the 60s cooldown indefinitely and silently disable the persistent helper. - Regression tests for both — a request that spends its whole timeout queued is rejected without ever being handed to a helper; a queued request that reaches the head keeps its budget; a backwards wall-clock step neither stretches the cooldown nor blocks recovery.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
src/main/computer/desktop-script-serve-channel.ts (1)
111-137: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winEnforce the 20 MiB response cap in UTF-8 bytes.
runtime.ps1 -Servesends snapshot NDJSON throughDesktopScriptServeChannel.readStdout(), which currently compares UTF-16 string length. A snapshot with multibyte UI Automation text can exceed the byte cap beforeonOverflow()aborts the channel. Track bytes at this framing boundary, including incomplete UTF-8 bytes held byStringDecoder, and compare againstMAX_RESPONSE_BYTES; noruntime.ps1change is required.src/main/computer/desktop-script-runtime-host.ts (2)
115-194: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winGuard execution-policy retries with
mayReplay(request).handleGone()marks a pre-readiness execution-policy failure for retry, butsend()then callsescalateExecutionPolicy()and writes the sameBridgeRequestagain without checkingmayReplay(request). A mutating request sent to a customORCA_COMPUTER_DESKTOP_SCRIPT_PROVIDER_PATHhelper can therefore be written twice; if the helper processed it before exiting, the mutation can have duplicate side effects. Apply the pre-readiness replay guard before theBypassretry and surface the original error when the request is not replayable.
248-281: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winReject non-object JSON before reading response fields.
JSON.parse('null')returnsnull, anddeliver()then readsparsed.ready, which throws inside the synchronousDesktopScriptServeChannelstdout callback. Validate non-null, non-array objects first, then callabortChannel()for malformed output.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: f859cd10-41fa-499f-ad38-e1060948dd61
📒 Files selected for processing (4)
src/main/computer/desktop-script-request-queue.tssrc/main/computer/desktop-script-runtime-availability.tssrc/main/computer/desktop-script-runtime-host.test.tssrc/main/computer/desktop-script-runtime-host.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
…block `UnauthorizedAccess` is the FullyQualifiedErrorId PowerShell reports for a policy block, and it is also a strict prefix of `UnauthorizedAccessException`, which .NET raises for any ordinary locked or ACL-denied file. The predicate matched the token unanchored, so an AV scan holding runtime.ps1 or a locked CSC temp directory was read as a policy block. Two consequences, both bad. `escalateExecutionPolicy()` has no path back, so one false match spent the rest of the session on `-ExecutionPolicy Bypass` — the exact command line token this stack exists to stop emitting. And on the one-shot path `isPolicyBlockedStart` re-runs the operation: one-shot mode writes stdout only after the operation returns, so a crash partway through an action is indistinguishable from a helper that never started, and the click lands twice. Measured on Windows against all three records, which the test carries verbatim as fixtures: policy/Restricted FullyQualifiedErrorId: UnauthorizedAccess policy/RemoteSigned FullyQualifiedErrorId: UnauthorizedAccess genuine access denied FullyQualifiedErrorId: UnauthorizedAccessException `\b` is the whole discriminator: between `s` and `E` both sides are word characters, so no boundary exists there and the exception cannot match. Dropped two alternatives that measurement showed were wrong. `PSSecurityException` never appears — the record surfaces through a native-command wrapper and reports `ParentContainsErrorRecordException`. The prose is wrong three times over: it differs by policy, it is localized, and PowerShell hard-wraps it mid-sentence. Anchoring on the `FullyQualifiedErrorId:`/`CategoryInfo:` labels would be more precise again, but those labels are localized where the values are not, so it would lose a real block on a non-English host and strand it with no fallback. Matching the values with word boundaries keeps both directions; a fixture with translated labels pins it. The escalation stays sticky. With the predicate correct, it only fires on a machine that really does block, where re-probing the preferred policy would buy a guaranteed failed spawn per operation.
… caused it `ConvertFrom-Json` throws before `$requestId` is read, so the serve loop answered an unparseable request with an untagged error. On the client that is not an error at all: `deliver()` sees no matching id, calls `abortChannel`, kills the helper and charges a failure — and the helper's own message is discarded. A parse failure was reported as a stream desync with no trace of the real cause, and three of them walked into the 60s cooldown behind three misleading "did not match" messages. Recover the id from the raw line when the parse fails. No wire change: the response shape is untouched and `BridgeResponse.requestId` already documents this echo. It is the same shape the helper already returns for `not_a_tool`, where the id survives because it is read before the operation runs. Both mixed pairings degrade safely — a new script with an old client resolves the error normally, and an old script with a new client still aborts, but now reports what the helper said. When the line is mangled past recovering an id, the desync abort is the honest outcome, so keep it and carry the helper's text into it rather than replacing it. A line the helper could not tag is usually the only account of the cause. Proven against the real `runtime.ps1 -Serve`: the host can only write well-formed JSON, so the parse-failure branch is unreachable through it and the test drives the channel directly.
The branch was 505 commits behind while the rest of this stack had merged main during the conflict-resolution round. No textual conflicts, and the semantic checks that the drift put at risk were re-measured rather than assumed: both two-sided ratchet pins still equal reality at main's values (DIRECT_IMPORTER_PIN 158, UNHIDDEN_SPAWNER_PIN 66, this branch adds no direct importer and no unhidden spawner), the max-lines ratchet passes against main's smaller grandfathered set, and the whole computer and child-process suites and every typecheck project pass on the merged base.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Execution-policy discriminator hardened —
isExecutionPolicyBlockednow matches identifiers (\bUnauthorizedAccess\b,\bSecurityError\b,about_Execution_Policies, no/i) instead of English prose plus an unboundedUnauthorizedAccessalternative, so a locked or ACL-denied file (UnauthorizedAccessException) no longer escalates the session toBypass. - Malformed-request routing —
runtime.ps1 -Serverecovers therequestIdfrom the raw line whenConvertFrom-Jsonthrows before the id is read, tagging the error so the host resolves the waiting request instead of reading an untagged line as a desynchronised stream. - Desync diagnostics — the host's
deliver()carries the helper's ownerrorstring into the desync message, so a line it could not tag still surfaces its real cause rather than a bare "did not match". - Regression tests — the policy discriminator is pinned in both directions (block under either policy, plain access-denial rejected, localised labels, daily noise); the serve-mode suite drives the real
runtime.ps1to prove id recovery and the no-recoverable-id fallback.
The \b word boundary on UnauthorizedAccess is doing the real work and the tests pin exactly that, and the request-id recovery is correctly unreachable through the host's own well-formed JSON but exercised directly against the real PowerShell. Both commits read as careful, well-scoped fixes.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…ly works AppLocker and WDAC constrained language mode raise PSSecurityException under the same SecurityError category a real execution-policy block uses, so the predicate matches them - correctly, on the evidence available. But those block the script at parse time, which `-ExecutionPolicy Bypass` cannot lift. The escalation was sticky unconditionally, so on a WDAC host we misdiagnosed, retried, failed again, and then latched: every later command line carried the most heavily weighted MDE token there is, on exactly the hardened, monitored enterprise machine that is watching for it. Treat the escalation as the diagnosis it is. A fallback that cannot start a helper either disproves it - the policy was not what stopped the first attempt - so revert to RemoteSigned instead of latching. When Bypass does start a helper the diagnosis is confirmed and it stays sticky exactly as before, so a genuinely Restricted machine still never pays a re-probe per operation. The revert lands inside the outage rather than only at its end, so a misdiagnosis costs one Bypass command line instead of one per attempt, and an escalation that never proved itself does not outlive the cooldown that ends the outage. Deliberately not a permanent "fallback is useless" flag: a Bypass attempt that failed for a transient reason would then disable the fallback for the session, which is the same latch in the other direction. Only `runtime_host_unavailable` proves no helper started, so only that reverts; a helper that started and then died proves Bypass works. That also makes the policy branch reachable on a final attempt for the first time, so it now rejects as unavailable rather than a generic error - that code is what routes the operation to the one-shot bridge, which carries its own policy fallback, and without it an all-blocked host would fail operations outright instead of degrading. The pre-existing "reports itself unavailable when Bypass is also refused" test pins that.
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since the prior review is one commit (3480242) plus a merge of main. It refines the execution-policy escalation so a Bypass fallback that never starts a helper is taken back, instead of latching the session onto the most heavily weighted MDE token on exactly the hardened hosts (AppLocker / WDAC constrained language mode) that refuse the script at parse time.
- Unproven-escalation tracking —
RuntimeHostAvailabilitygains afallbackPolicyUnprovenflag set byescalateExecutionPolicy()and cleared byconfirmExecutionPolicy()/recordSuccess(), so only a policy that actually started a helper stays sticky for the session. - Revert on a disproven diagnosis —
abandonUnprovenFallback()returns toRemoteSignedwhen aBypassspawn also fails to start, andenterCooldown()invokes it so the next outage re-diagnoses from the preferred policy. - Host wiring —
deliver()confirms the policy on the ready announcement;send()abandons an unproven fallback when a start surfacesruntime_host_unavailable; a policy-blocked start now rejects withruntime_host_unavailableso the client routes the operation to the one-shot bridge rather than failing it outright. - Regression tests — a new test drives the real policy-block path to prove the revert lands inside the outage (one
Bypasscommand line, not one per attempt) and that the post-cooldown re-probe starts onRemoteSigned; the existing escalation test is tightened to assert no revert onceBypassis proven.
The unproven → proven → reverted state machine is internally consistent: runtime_host_unavailable is only produced by paths that prove the helper never ran the operation, so routing to the one-shot bridge never risks double-executing a mutation. The pr.yml / pr-code-change-scope.mjs test-list swap is base-branch content carried in by the merge, not part of this PR's logic.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 0c23b90e-d985-4ab9-a47e-bc111c7bbc55
📒 Files selected for processing (22)
.github/workflows/pr.ymlconfig/scripts/pr-code-change-scope.mjsnative/computer-use-windows/runtime.ps1src/main/computer/computer-sidecar-diagnostics.test.tssrc/main/computer/computer-sidecar-diagnostics.tssrc/main/computer/desktop-script-action.tssrc/main/computer/desktop-script-provider-bridge.tssrc/main/computer/desktop-script-provider-client.tssrc/main/computer/desktop-script-provider-runtime-host-routing.test.tssrc/main/computer/desktop-script-provider-test-harness.tssrc/main/computer/desktop-script-provider-types.tssrc/main/computer/desktop-script-request-queue.tssrc/main/computer/desktop-script-runtime-availability.tssrc/main/computer/desktop-script-runtime-host.test.tssrc/main/computer/desktop-script-runtime-host.tssrc/main/computer/desktop-script-runtime-host.win32.test.tssrc/main/computer/desktop-script-serve-channel.test.tssrc/main/computer/desktop-script-serve-channel.tssrc/main/computer/sidecar-client.tssrc/main/computer/sidecar-entry.tssrc/main/computer/windows-powershell-execution-policy.test.tssrc/main/computer/windows-powershell-execution-policy.ts
🚧 Files skipped from review as they are similar to previous changes (13)
- src/main/computer/sidecar-entry.ts
- src/main/computer/desktop-script-action.ts
- src/main/computer/computer-sidecar-diagnostics.test.ts
- config/scripts/pr-code-change-scope.mjs
- native/computer-use-windows/runtime.ps1
- src/main/computer/desktop-script-serve-channel.ts
- src/main/computer/computer-sidecar-diagnostics.ts
- src/main/computer/desktop-script-provider-runtime-host-routing.test.ts
- .github/workflows/pr.yml
- src/main/computer/desktop-script-provider-client.ts
- src/main/computer/desktop-script-provider-types.ts
- src/main/computer/desktop-script-serve-channel.test.ts
- src/main/computer/desktop-script-request-queue.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
| if (!isRuntimeHostUnavailable(error) || !this.mayReplay(request)) { | ||
| if (this.availability.exhausted) { | ||
| this.availability.enterCooldown() | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Gate the execution-policy retry with mayReplay(request).
ORCA_COMPUTER_DESKTOP_SCRIPT_PROVIDER_PATH accepts any existing script. The host writes the request before it receives readiness, and stderr policy text can classify an exited helper as policy-blocked. The current policyRetryPending branch then resends the same mutating BridgeRequest under Bypass. For actions such as click or type_text, this can repeat the operation. Apply mayReplay(request) before continuing to the fallback-policy retry.
| return | ||
| } | ||
| // The readiness announcement carries no request id and answers nothing. | ||
| if (parsed.ready === true && parsed.requestId === undefined) { | ||
| this.childReady = true | ||
| this.readyProtocolConfirmed = true | ||
| this.availability.confirmExecutionPolicy() | ||
| return | ||
| } | ||
| const pending = this.pending | ||
| if (!pending || parsed.requestId !== pending.id) { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Guard parsed helper output before reading response fields
JSON.parse('null') returns null, so deliver throws when it reads parsed.ready. The stdout event path does not catch this exception, and it can terminate the Electron main process. Reject null, arrays, and other non-object values before reading ready, requestId, or error, then call abortChannel(...) and return.
…17884) * fix(security): apply the Windows path-hardening ACL that never ran `buildWindowsRestrictAclArgs` invoked the hardening script as `powershell.exe -Command <script> <path> <sid> <isDir>`. `-Command` does not populate `$args`; it appends the trailing tokens to the command text. The script therefore read `$args[1]` as `$null`, threw `NullArrayIndex` at `$allowedSids[$sidText] = $true` under `$ErrorActionPreference = 'Stop'`, and exited 1. Both callers swallowed that: the async callback was empty and `applySecurePathRestriction` returned `true` regardless, while the sync `catch` returned `false` and nobody logged. Every Windows secure path has been left on its inherited ACL since the ACL was introduced (#5006), and nothing said so. Replace PowerShell with `icacls.exe`, which takes plain argv. That removes the quoting surface entirely rather than escaping it: interpolating a path into the command text would have turned a dead no-op into arbitrary PowerShell on a filesystem path, since `-Command` executes what it appends. It also drops the execution-policy dependency and the `powershell.exe` spawn an EDR flags, and runs ~25x faster than the PowerShell cold start. Hardening is now three passes: `/reset` to purge explicit ACEs that `/inheritance:r` leaves behind, `/inheritance:r` plus a `/grant:r` per allowed SID, then a read-back that checks the DACL is protected and grants only the intended rights. The predecessor's verification block was equally dead, and an apply that is never read back is only half a control. Failures stay non-fatal — non-NTFS volumes, network paths and restricted tokens fail legitimately and must not break startup — but they are no longer invisible: every failure is logged, and a failed async apply now evicts its cache entry so the next call retries instead of trusting a success that never happened. Routing through `runProcess`/`runProcessSync` also retires this file's `node:child_process` allowlist entry. * fix(security): verify the hardened ACL by identity, not by shape Review found the bug class this PR fixes surviving inside the fix. The verify pass checked rule count, absence of the inherited marker, and exact rights — never *who* the rules named. Granting Everyone full control satisfies all three, so hardening reported success on a DACL that handed the credential to every local account, and most of the real-filesystem tests still passed. Verification now reads the descriptor back with `icacls /save`, which emits SDDL with raw SIDs, and compares the principal set exactly. That is also locale-independent by construction: the previous parse read localized account names out of icacls' OEM-codepage stdout, where a non-ASCII path survived by accident rather than by the documented mechanism. SDDL parsing moves to `windows-security-descriptor.ts`. Two further self-inflicted problems, both measured: The post-rename re-harden led with `/reset`, which re-widened a DACL that was already correct — the staged file's protected DACL survives the rename, so the pass had nothing to do but open a window. Polling an external process during a write into a relocated root caught it: the e2ee keypair dropped to `BUILTIN\Users:(RX)` plus `Authenticated Users:(M)` — read *and* write — before tightening again. Hardening now verifies first and returns early when the DACL already reads back correct, which closes the window and cuts the steady state from three spawns to one. Re-measured: 158 samples, one DACL state, zero broad. Evicting the cache on every failed async apply reintroduced #4901. The env store re-hardens on the read path at ~2/s, so on a host where hardening cannot work (FAT32, network path, restricted token) that was two icacls spawns and two warnings a second, forever. Async retries now take a retry floor and a hard per-path attempt cap. The write path keeps retrying unthrottled — it is user-driven, and a failed credential ACL must still be retried on the next write. Also: failures route through a reporter hook that the main process points at the diagnostic tracer, because `console.warn` reaches nothing in a packaged GUI-subsystem build; `writeSecureFile` returns whether hardening took, and the async branch reports `pending` rather than claiming `applied`; a transient `whoami` failure no longer disables hardening for the process lifetime, and the SID is shape-validated; the `/c` guard now covers the synchronous runner too. * fix(security): re-probe hardening instead of latching a transient failure The per-process attempt cap added for the read-path storm was a permanent latch: one AV scan, momentary lock or %TEMP% blip and every later credential write in that session went unhardened, silently, on a host where hardening would now succeed. Same defect class as #17858's computer-use host, and worse here because what stops happening is security hardening on credential files and nothing said so. The retry budget now bounds the *rate*, not the lifetime: at most three attempts per path per minute, re-probing in every later window, forever. The transition is announced in both directions — `throttled` once per window on entry, `recovered` when a rate-limited path hardens again — so a host stuck in the degraded state is diagnosable rather than merely quiet. The reporter type covers both, and the main process ends the `recovered` span successfully rather than failing it. Extracted to secure-path-hardening-retry-budget.ts, which keeps secure-file.ts under its line cap without a max-lines disable. Also confirms the second flagged risk rather than assuming it: a real unwritable %TEMP% is now covered by a test proving verification fails closed, reports at the `verify` stage, and still leaves the ACL applied — so that path loses proof, not protection, and with the lifetime cap gone it can no longer combine into a permanent-off state. * fix(security): verify a directory's whole inheritance flag set The flag check tested only that `OI` was present — never that `CI` was, nor that nothing else was. That was harmless while `/reset` + `/grant` ran on every pass and repaired whatever was there. The verify-first short-circuit made it load-bearing: what verification accepts is now left alone, so a latent under-check went live because a different fix started depending on it. Two directory DACLs passed while being wrong — both protected, three non-inherited full-control rules, correct SIDs, differing from correct only in their flags: (OI)(F) - no CI, so subdirectories are left unprotected (OI)(CI)(IO) - inherit-only, so the directory object itself grants nobody anything; the next writeFileSync into it fails with EPERM, on a directory just cached as hardened Verification now compares the whole flag set, which also rejects IO and NP, and names the offending flags in the failure. Both shapes are planted in real-filesystem regression tests, including an assertion that a write into the repaired directory succeeds and its child inherits. Confirmed both tests fail against the old check and pass against this one. * fix(security): back the hardening retry off exponentially The fixed one-minute window bounded the retry rate but left a standing floor of three attempts per path per minute on a host where hardening can never succeed — FAT32/exFAT, a network path, a redirected profile. That budget is per path and there are several secure files, so the floor multiplied into tens of thousands of icacls spawns a day for work guaranteed to fail. The delay now doubles after each consecutive failure, from a one-minute floor to a thirty-minute ceiling, and the attempt cap is gone entirely: once the backoff elapses the path is re-probed however long it has been failing. A permanently incapable host settles at ~2 attempts/hour. Slowing the backstop costs almost nothing, because it is not the recovery mechanism: the synchronous write path is deliberately unthrottled, so a host that recovers hardens on its very next credential write regardless of what the read-path budget says. The `throttled`/`recovered` reports are unchanged and matter more here, since the quiet periods between probes are now much longer. The curve is pinned in a new unit test against the exported delay function rather than a copy of its constants, covering the doubling, the ceiling holding at 5000 consecutive failures, a 30-day failing path still re-probing, one announcement per degraded episode, and per-path isolation. The integration tests keep only what they uniquely prove: that the read path is wired to the budget, and that a day of failures still re-probes. Confirmed four of these fail against a reinstated lifetime cap. * ci(windows): run the real-icacls DACL suite in CI The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered. * fix(security): describe the cache's real cost, which is icacls now Both cache comments still justified themselves with PowerShell -- "~1-1.5s" and "a PowerShell spawn every read" -- in the same file whose PR removed PowerShell from this path. The caches are still right, but for different numbers, and the old ones are the kind an engineer would reasonably delete a cache over. The real shape: hardening verifies first and returns early, so an already-correct DACL costs one synchronous icacls spawn and a rewrite costs four (verify, reset, grant, verify). Still worth caching on the read path, which polls at ~2/s. * test(security): make the DACL suite safe to schedule Registering this spec in the Windows lane put it under two rules it had never been measured against. Teardown now goes through `removeTreeSync`, which the lane's boundary test requires, and repairs the DACLs the suite plants on purpose first: those retries only cover transient locks, so a regressed `(OI)(CI)(IO)` repair leaves the root un-removable and `afterAll` throws EPERM. And the no-permission case decides by elevation before it writes anything. `windows-2022` runs elevated, where hardening succeeds: the old branch asserted nothing about denial and instead replaced the `hosts` DACL, then `icacls /reset` -- which is not a restore, it drops the explicit `SYSTEM:(F)` that file ships with. Ephemeral in CI; permanent for a developer running the lane from an elevated shell. Now it asserts or it skips. The probe reads the token integrity SID rather than `icacls /save`, which succeeds unelevated (`BUILTIN\Users:(RX)` carries READ_CONTROL) and would have skipped the case on every machine. * fix(security): measure the hardening latches on a clock that cannot go backwards `mayAttemptHardening` compared wall-clock times, so any backwards step -- an NTP correction, a VM snapshot restore, a user changing the clock -- made the elapsed time negative and held every failing path below its delay until the clock caught up. Measured at the 30-minute ceiling with the clock stepped back a year, the path was refused at +0d, +1d, +30d, +180d and +364d, and re-probed only at +366d. That is the permanent latch the exponential backoff was added to remove, and it contradicts the module's own "bounds the rate without ever bounding the lifetime". The SID lookup's own one-minute window had the identical shape and is worse: a failed lookup makes `planFor` return null, which disables the synchronous *write* path too, so the write-path exemption that recovers the read-path budget cannot recover it. Both now measure elapsed monotonic time, following the repo's existing `monotonicNowMs` spelling. Two things the write path was not doing, both found in the same pass: - A successful synchronous apply now records the outcome. It is exempt from the budget, but it was also invisible to it, so a host that had demonstrably recovered kept the read path backing off for up to 30 minutes and no `recovered` transition ever came from that lane. Only success is recorded; recording failure would put the exempt lane back under the budget. - `writeSecureFile`'s JSDoc now says its boolean covers the file only. The directory harden is fire-and-forget and answers `pending` on Windows regardless, so a `true` says nothing about the directory's ACL. * fix(security): stop the hardening test doubles from faking a no-op Three CI failures on this branch, one failure shape: hardening silently does nothing and the check that should have caught it agrees. The auth critical-path test hand-rolled a `node:child_process` factory with `execFileSync`/`execFile`. The rewritten ACL path goes through `runProcessSync`, i.e. `spawnSync`, which the factory never returned — so every spawn threw into the SID lookup's bare catch, `planFor` returned null, and hardening no-opped. It mocks `child-process/run-process` now, the boundary production code actually calls and the one sibling ACL tests already mock: an export missing there fails loudly by name instead of returning undefined. Its fake icacls writes a real UTF-16LE SDDL file, so the pinned spawn count per write is a property of the ACL path rather than of the double. The test forces `platform='win32'`, so this failed on every platform, Linux CI included. `windowsSystem32Binary` is a production bug, not a test bug: it builds a Windows path with the host `join`, which off-platform yields the mixed `C:\Windows/System32/whoami.exe`. On Windows the two joins agree, which is why it survived; on Linux the SID lookup's whoami match missed and 27 of secure-file's 32 tests exercised a lane that never ran. These are always Windows paths, so `path.win32.join` is what it should have been. The import-boundary pin still read 160 after this branch migrated secure-path-windows-acl.ts off `node:child_process`; the ratchet correctly refuses a pin left above reality. * fix(security): resolve the machine-relative SDDL alias, and stop a denied read destroying the file Path hardening verified the DACL it wrote by comparing the SIDs `icacls /save` reports. SDDL substitutes two-letter aliases for well-known SIDs, and the resolution table could only hold constants -- but `LA` and `LG` name an account by RID inside the *machine's own* SID, so on a box whose user is the built-in Administrator (a CI runner, an Administrator-only install) the current user read back as `LA`, matched nothing, and hardening reported failure for every path. Resolve those two against the machine authority derived from the user SID; without one they stay unresolved and the comparison still fails closed. Three secret stores treated any read failure as "malformed -- regenerate" and overwrote. A hardened file granting a SID this process does not hold reads as EPERM while its directory stays writable, so the overwrite succeeds: renaming over an unreadable file needs FILE_DELETE_CHILD on the parent, not DELETE on the file. That destroyed the E2EE secret key, every paired device's bearer token, and the plugin vault. Distinguish EPERM/EACCES from a parse failure and refuse. Also close the async lane's unhandled rejection: `void p.then(onSettled)` turned a throw from `onSettled` into a dead main process, and the retry budget it calls threw whenever nothing had configured it -- a contract held only by import order. The budget now defaults its own bounds. * test(windows): say which ACEs icacls listed when a planted DACL fails `toHaveLength` reports only a count and vitest elides the array, so three preconditions failing on the CI runner said "expected 3, got 6" and nothing about what the sixth entry was. Name the entries in the failure. * fix(security): stop three more stores overwriting what they were denied Same swallow-default-overwrite shape as the readers already fixed, found by sweeping every store that reads under a hardened root. - plugin-storage-store.ts returned `{}` on any read failure and set()/delete() wrote it back, losing the plugin KV store. It is the secrets store's shape line for line, so the two now behave identically. - relay-revoke-outbox.ts returned [] and save() wrote it, dropping revocations that never reached the relay -- a revoked device stays live. - profile-cloud-session-store.ts mapped an EPERM read onto `decrypt-failed`, which fails the `status === 'found'` guard in clearCloudSessionIfUnchanged and falls through to an rmSync of the account session. A denied read now reports `unreadable`, which licenses nothing; the refresh path bails on it and the auth status surfaces it rather than reporting a bare reconnect. All reuse isPermissionDeniedError. The predicate stays an EPERM/EACCES allow list rather than "ENOENT defaults, everything else throws": these stores are meant to self-heal a truncated or malformed file, and inverting it would turn a corrupt keypair into an app that cannot start. The distinction that matters is "could not read it" versus "read it and it was garbage". * test(windows): plant fixture DACLs that cannot inherit what they did not plant %TEMP% grants [SYSTEM, Administrators, <user>] (OI)(CI)(F) by default, and those propagate into every fixture. Three preconditions read back 4 and 6 ACEs where 3 were planted, and the extras looked like Orca's own hardening because the shape is identical -- on a runner whose user is the built-in Administrator, the inherited trio IS the trio production grants. Combining /inheritance:r with /grant:r leaves the argument order to icacls, and that combined form drops the inherited ACEs on Windows 11 but keeps them as explicit ones on the Windows Server runner. Removing inheritance in its own invocation makes the grant the whole DACL on either host, and the fixture root is de-inherited once up front so nothing propagates in. Rooting the fixtures outside %TEMP% would not have fixed this: any directory inherits from wherever it lives. The fix is to stop inheriting, not to move. No assertion is relaxed -- the counts stay exact. * test(windows): pick a foreign SID that stays foreign on an elevated runner `S-1-5-32-544` is only foreign to a token that is not an administrator. The CI runner is elevated AND logged in as the built-in Administrator, so granting Administrators granted the reader full control: the file stayed readable, and all six preservation assertions went vacuous rather than proving anything. BUILTIN\Guests is resolvable everywhere and no interactive token is a member, so the read is denied on an unelevated developer box and on the runner alike. An unresolvable SID would have been the stronger choice but icacls rejects one with ERROR_NONE_MAPPED (1332). The premise guard is what caught this -- it asserted the file was actually unreadable instead of trusting the grant, and named elevation as the suspect. * fix(security): refuse on any read that never reached the contents, not just a denied one isPermissionDeniedError becomes isUnreadableError, because "permission denied" was never the concept -- "could not read it", as opposed to "read it and it was garbage", is. EBUSY, EMFILE, ENFILE and EIO say exactly as little about a file's contents as EACCES does, and they fell into the branch that regenerates and overwrites. On Windows EBUSY is the likelier of the two: antivirus holding a credential open at the moment of a startup read produces it, which makes it a commoner path to the same permanent loss than the ACL case that motivated the original fix. Still an allow list, deliberately: ENOENT keeps licensing a create, and a parse failure keeps self-healing. The stores are built to recover from a truncated write, and turning that into a refusal would trade a recoverable state for an unrecoverable one on the startup path. Also fixes the regression suite's own premise on an elevated runner: makeUnreadable combined /inheritance:r with /grant:r, and that form keeps %TEMP%'s inherited [SYSTEM, Administrators, user] as explicit ACEs on Windows Server -- so the file stayed readable and all six assertions were vacuous. Same split-the-invocation fix as the ACL suite's planter. * test(windows): skip the preservation suite where a read cannot be denied An elevated token logged in as the built-in Administrator reads straight through a DACL that grants it nothing -- confirmed on the CI runner against both BUILTIN\Administrators and BUILTIN\Guests, and with the grant split into its own icacls invocation so the DACL really was the planted one. On such a host the premise these tests rest on does not hold, and every assertion would pass while proving nothing. So probe once at module scope and skip rather than assert vacuously -- the same trade the ACL suite already makes for its unelevated-only case. The gate stays in the compound `<win32 check> && <flag>` form the win32 lane ratchet detects, so the file stays registered in both lane lists. Coverage is not lost where it counts: isUnreadableError has unit tests that run on every platform and every host, and the stores' refusal is exercised in full on any machine where a denial is reproducible -- which is every developer box. --------- Co-authored-by: Orca Worker <orca-worker@localhost> Co-authored-by: Neil <[email protected]>
…tablyai#17858) * fix(computer-use): run the Windows runtime as one persistent helper Microsoft Defender for Endpoint raised multi-stage Execution + Collection incidents against Orca on Windows ("Screenshots were taken unexpectedly on this device... Screen capture code was found in a script launched by powershell.exe", factor "Executes suspicious MSIL code"). The desktop script provider spawned a fresh powershell.exe per operation, so a single computer-use session produced a burst of short-lived PIDs and re-emitted runtime.ps1's inline Add-Type P/Invoke assembly on every click. runtime.ps1 gains a -Serve mode that loads its assemblies once and then reads NDJSON requests from stdin, and a new DesktopScriptRuntimeHost owns one long-lived child: lazy spawn, strict serialization, a 30s per-request timeout, restart on crash, a 120s idle shutdown, and dispose() on provider teardown. The one-shot -OperationPath path stays as the fallback, and Linux keeps its python3 bridge unchanged. Both Windows spawn sites now use -ExecutionPolicy RemoteSigned instead of Bypass, falling back once to Bypass (and logging) when a Restricted host refuses the unsigned script. * fix(computer-use): recover the runtime host instead of latching it off Review follow-up on the persistent Windows computer-use helper. A helper that died before producing a line set an unavailable flag nothing ever cleared, and the client then dropped the host for the life of the session. One transient bad spawn — a Defender scan, a locked CSC temp directory — silently restored the per-click powershell.exe burst and per-operation MSIL emission this work exists to remove, with computer use still working so nothing looked wrong. Start failures are now retried, then cool down for 60s, then re-probed; the client keeps the host so it can come back. Repeated post-answer crashes cool down too, and a single reply no longer clears the failure count. The one-shot bridge decided its execution-policy retry from a message that fell back to stdout, so a window title containing "SecurityError" could replay a non-idempotent operation — a double click, keystroke or paste — and stick the session on Bypass. The retry now requires empty stdout and a matching stderr. Serve-mode replies carry an echoed request id. Without one a single stray stdout line would make every later response answer the previous request, acting on stale element indexes with no error raised; a mismatch now kills the child. Non-JSON noise is ignored rather than counted as the helper having answered. Also: warnings reach the main process over the sidecar's IPC channel rather than its piped, unread stdio; the child is watched on close rather than exit; dispose latches so a queued request cannot respawn during teardown; and the host is split into a serve channel and an availability policy to stay under max-lines. * fix(computer-use): prove a helper never started before replaying its request The retry that replaced the permanent-latch bug could deliver unrequested input. send() re-sent the same request whenever the helper died without replying, but "no reply came back" is not "the operation did not run": runtime.ps1 synthesizes the click and only then builds the snapshot, which allocates a full-window bitmap and walks the UIA tree — a native GDI+/UIA fault there is uncatchable, and leaves the click already delivered. A deterministic fault meant three clicks from the host plus a fourth from the one-shot bridge, surfaced as a single failed operation. -Serve now writes one {"ready":true} line after its Add-Type work and before its first read, so "never started" is a fact rather than an inference. A request is replayed only when the helper died before announcing. A runtime.ps1 that predates the announcement — reachable through the provider path override — is covered by an observation-tool allowlist until a ready line proves otherwise. Host-detected aborts (timeout, desynchronised reply, oversized line) suppress the exit handler, so they were bypassing failure accounting entirely and a helper failing that way was respawned once per operation forever. They now count and are logged. Also stop charging twice for one outage: entering the cooldown resets the failure count, so the first death after recovery no longer re-enters a full cooldown and an interleaved workload cannot be stranded on the one-shot bridge. * fix(computer-use): ignore a stdin write callback from a torn-down helper stop() destroys stdin, so a write still queued at teardown calls back with ERR_STREAM_DESTROYED. The callback carried no channel or request identity and write() had no closed guard, so it ran abortChannel a second time: stopChannel no-opped but recordFailure and the warning did not, charging two failures for one operation and reaching the 3-strike cooldown at half the intended rate. That feeds the same accounting that keeps a persistently broken helper from respawning once per operation. The same root also allowed a late callback landing after a replacement channel existed to stop that channel and reject a different request with the previous one's error. Node fires the destroyed-stream callback on the next tick, well before a new request arrives, so the double-count is the reachable effect; binding the callback closes both. write() now drops payloads and error reports once closed, and the host ignores any report whose channel or request id is no longer current. * test(computer-use): pin each stale-write guard independently The channel's closed guard and the host's request-identity check are redundant by design, and the existing tests only failed when both were absent. Someone deleting one, believing the other was the covered one, would have got a green suite and a live regression — the same shape as a test that passes without the fix it was written for. Each is now pinned on its own. The channel's half is tested against the channel directly: after stop() it takes no writes and reports no error from one already queued, which the host cannot observe because it drops the channel at the same moment. The host's half is pinned by the case the channel cannot see — a live channel whose request was already answered, where backpressure delivers a write callback for a request that is no longer pending. Removing either guard alone now fails a test. Both carry a comment saying they are deliberately redundant and separately pinned, so the next reader does not have to rediscover this from the diff. * ci(windows): run the computer-use runtime host suite in CI The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered. * fix(computer-use): time the runtime host cooldown on a monotonic clock The start-failure cooldown was a wall-clock deadline, so a backwards step — an NTP correction, a VM snapshot restore, a user changing the clock — left `remainingCooldown()` returning the cooldown plus the whole step. A one-hour step measured 3,660,000ms, and ten real minutes later still 3,060,000ms. Nothing shortens it from there. Only `recordSuccess()` clears the cooldown on a non-dispose path, and no request can reach a helper to succeed while it holds, so every `send()` throws `runtime_host_unavailable` first. The host is built with no `now` override and its lifecycle is a module-level singleton that shuts down at process exit, so the latch held for the sidecar's life — computer use kept working via the one-shot bridge while the per-click powershell.exe burst this host exists to remove came back silently. Store the instant the cooldown began and compare elapsed monotonic time, following the two fixes in stablyai#17884. The field is `number | null` rather than sentinel 0 because `performance.now()` legitimately returns 0. Both new tests leave `now` unset, because the bug was in the default the host picks and a test that injects a clock cannot see it. * fix(computer-use): give a queued request its own deadline The 30s request timeout was armed only in `sendOnce`, once a request reached a helper. A request behind N timing-out ones therefore waited roughly N times that with no deadline of its own: bounded, but the caller sees an `await` that looks hung for minutes and gets no error to act on. Move the serialization tail into its own class and arm a deadline at enqueue time. Only the wait is bounded — a request that reaches a helper still gets its full execution budget, so nothing that used to succeed now fails. An expired request is dropped rather than sent late: the caller has already been told it failed, and a click delivered after that is worse than no click. The tail keeps its never-rejecting shape and chains on the turn rather than on the raced promise, so a caller giving up early cannot release the next request while its predecessor is still in flight. * fix(computer-use): stop reading a locked file as an execution policy block `UnauthorizedAccess` is the FullyQualifiedErrorId PowerShell reports for a policy block, and it is also a strict prefix of `UnauthorizedAccessException`, which .NET raises for any ordinary locked or ACL-denied file. The predicate matched the token unanchored, so an AV scan holding runtime.ps1 or a locked CSC temp directory was read as a policy block. Two consequences, both bad. `escalateExecutionPolicy()` has no path back, so one false match spent the rest of the session on `-ExecutionPolicy Bypass` — the exact command line token this stack exists to stop emitting. And on the one-shot path `isPolicyBlockedStart` re-runs the operation: one-shot mode writes stdout only after the operation returns, so a crash partway through an action is indistinguishable from a helper that never started, and the click lands twice. Measured on Windows against all three records, which the test carries verbatim as fixtures: policy/Restricted FullyQualifiedErrorId: UnauthorizedAccess policy/RemoteSigned FullyQualifiedErrorId: UnauthorizedAccess genuine access denied FullyQualifiedErrorId: UnauthorizedAccessException `\b` is the whole discriminator: between `s` and `E` both sides are word characters, so no boundary exists there and the exception cannot match. Dropped two alternatives that measurement showed were wrong. `PSSecurityException` never appears — the record surfaces through a native-command wrapper and reports `ParentContainsErrorRecordException`. The prose is wrong three times over: it differs by policy, it is localized, and PowerShell hard-wraps it mid-sentence. Anchoring on the `FullyQualifiedErrorId:`/`CategoryInfo:` labels would be more precise again, but those labels are localized where the values are not, so it would lose a real block on a non-English host and strand it with no fallback. Matching the values with word boundaries keeps both directions; a fixture with translated labels pins it. The escalation stays sticky. With the predicate correct, it only fires on a machine that really does block, where re-probing the preferred policy would buy a guaranteed failed spawn per operation. * fix(computer-use): route a malformed request back to the request that caused it `ConvertFrom-Json` throws before `$requestId` is read, so the serve loop answered an unparseable request with an untagged error. On the client that is not an error at all: `deliver()` sees no matching id, calls `abortChannel`, kills the helper and charges a failure — and the helper's own message is discarded. A parse failure was reported as a stream desync with no trace of the real cause, and three of them walked into the 60s cooldown behind three misleading "did not match" messages. Recover the id from the raw line when the parse fails. No wire change: the response shape is untouched and `BridgeResponse.requestId` already documents this echo. It is the same shape the helper already returns for `not_a_tool`, where the id survives because it is read before the operation runs. Both mixed pairings degrade safely — a new script with an old client resolves the error normally, and an old script with a new client still aborts, but now reports what the helper said. When the line is mangled past recovering an id, the desync abort is the honest outcome, so keep it and carry the helper's text into it rather than replacing it. A line the helper could not tag is usually the only account of the cause. Proven against the real `runtime.ps1 -Serve`: the host can only write well-formed JSON, so the parse-failure branch is unreachable through it and the test drives the channel directly. * fix(computer-use): keep the Bypass escalation only when Bypass actually works AppLocker and WDAC constrained language mode raise PSSecurityException under the same SecurityError category a real execution-policy block uses, so the predicate matches them - correctly, on the evidence available. But those block the script at parse time, which `-ExecutionPolicy Bypass` cannot lift. The escalation was sticky unconditionally, so on a WDAC host we misdiagnosed, retried, failed again, and then latched: every later command line carried the most heavily weighted MDE token there is, on exactly the hardened, monitored enterprise machine that is watching for it. Treat the escalation as the diagnosis it is. A fallback that cannot start a helper either disproves it - the policy was not what stopped the first attempt - so revert to RemoteSigned instead of latching. When Bypass does start a helper the diagnosis is confirmed and it stays sticky exactly as before, so a genuinely Restricted machine still never pays a re-probe per operation. The revert lands inside the outage rather than only at its end, so a misdiagnosis costs one Bypass command line instead of one per attempt, and an escalation that never proved itself does not outlive the cooldown that ends the outage. Deliberately not a permanent "fallback is useless" flag: a Bypass attempt that failed for a transient reason would then disable the fallback for the session, which is the same latch in the other direction. Only `runtime_host_unavailable` proves no helper started, so only that reverts; a helper that started and then died proves Bypass works. That also makes the policy branch reachable on a final attempt for the first time, so it now rejects as unavailable rather than a generic error - that code is what routes the operation to the one-shot bridge, which carries its own policy fallback, and without it an all-blocked host would fail operations outright instead of degrading. The pre-existing "reports itself unavailable when Bypass is also refused" test pins that. --------- Co-authored-by: Orca Worker <orca-worker@localhost>
…tablyai#17884) * fix(security): apply the Windows path-hardening ACL that never ran `buildWindowsRestrictAclArgs` invoked the hardening script as `powershell.exe -Command <script> <path> <sid> <isDir>`. `-Command` does not populate `$args`; it appends the trailing tokens to the command text. The script therefore read `$args[1]` as `$null`, threw `NullArrayIndex` at `$allowedSids[$sidText] = $true` under `$ErrorActionPreference = 'Stop'`, and exited 1. Both callers swallowed that: the async callback was empty and `applySecurePathRestriction` returned `true` regardless, while the sync `catch` returned `false` and nobody logged. Every Windows secure path has been left on its inherited ACL since the ACL was introduced (stablyai#5006), and nothing said so. Replace PowerShell with `icacls.exe`, which takes plain argv. That removes the quoting surface entirely rather than escaping it: interpolating a path into the command text would have turned a dead no-op into arbitrary PowerShell on a filesystem path, since `-Command` executes what it appends. It also drops the execution-policy dependency and the `powershell.exe` spawn an EDR flags, and runs ~25x faster than the PowerShell cold start. Hardening is now three passes: `/reset` to purge explicit ACEs that `/inheritance:r` leaves behind, `/inheritance:r` plus a `/grant:r` per allowed SID, then a read-back that checks the DACL is protected and grants only the intended rights. The predecessor's verification block was equally dead, and an apply that is never read back is only half a control. Failures stay non-fatal — non-NTFS volumes, network paths and restricted tokens fail legitimately and must not break startup — but they are no longer invisible: every failure is logged, and a failed async apply now evicts its cache entry so the next call retries instead of trusting a success that never happened. Routing through `runProcess`/`runProcessSync` also retires this file's `node:child_process` allowlist entry. * fix(security): verify the hardened ACL by identity, not by shape Review found the bug class this PR fixes surviving inside the fix. The verify pass checked rule count, absence of the inherited marker, and exact rights — never *who* the rules named. Granting Everyone full control satisfies all three, so hardening reported success on a DACL that handed the credential to every local account, and most of the real-filesystem tests still passed. Verification now reads the descriptor back with `icacls /save`, which emits SDDL with raw SIDs, and compares the principal set exactly. That is also locale-independent by construction: the previous parse read localized account names out of icacls' OEM-codepage stdout, where a non-ASCII path survived by accident rather than by the documented mechanism. SDDL parsing moves to `windows-security-descriptor.ts`. Two further self-inflicted problems, both measured: The post-rename re-harden led with `/reset`, which re-widened a DACL that was already correct — the staged file's protected DACL survives the rename, so the pass had nothing to do but open a window. Polling an external process during a write into a relocated root caught it: the e2ee keypair dropped to `BUILTIN\Users:(RX)` plus `Authenticated Users:(M)` — read *and* write — before tightening again. Hardening now verifies first and returns early when the DACL already reads back correct, which closes the window and cuts the steady state from three spawns to one. Re-measured: 158 samples, one DACL state, zero broad. Evicting the cache on every failed async apply reintroduced stablyai#4901. The env store re-hardens on the read path at ~2/s, so on a host where hardening cannot work (FAT32, network path, restricted token) that was two icacls spawns and two warnings a second, forever. Async retries now take a retry floor and a hard per-path attempt cap. The write path keeps retrying unthrottled — it is user-driven, and a failed credential ACL must still be retried on the next write. Also: failures route through a reporter hook that the main process points at the diagnostic tracer, because `console.warn` reaches nothing in a packaged GUI-subsystem build; `writeSecureFile` returns whether hardening took, and the async branch reports `pending` rather than claiming `applied`; a transient `whoami` failure no longer disables hardening for the process lifetime, and the SID is shape-validated; the `/c` guard now covers the synchronous runner too. * fix(security): re-probe hardening instead of latching a transient failure The per-process attempt cap added for the read-path storm was a permanent latch: one AV scan, momentary lock or %TEMP% blip and every later credential write in that session went unhardened, silently, on a host where hardening would now succeed. Same defect class as stablyai#17858's computer-use host, and worse here because what stops happening is security hardening on credential files and nothing said so. The retry budget now bounds the *rate*, not the lifetime: at most three attempts per path per minute, re-probing in every later window, forever. The transition is announced in both directions — `throttled` once per window on entry, `recovered` when a rate-limited path hardens again — so a host stuck in the degraded state is diagnosable rather than merely quiet. The reporter type covers both, and the main process ends the `recovered` span successfully rather than failing it. Extracted to secure-path-hardening-retry-budget.ts, which keeps secure-file.ts under its line cap without a max-lines disable. Also confirms the second flagged risk rather than assuming it: a real unwritable %TEMP% is now covered by a test proving verification fails closed, reports at the `verify` stage, and still leaves the ACL applied — so that path loses proof, not protection, and with the lifetime cap gone it can no longer combine into a permanent-off state. * fix(security): verify a directory's whole inheritance flag set The flag check tested only that `OI` was present — never that `CI` was, nor that nothing else was. That was harmless while `/reset` + `/grant` ran on every pass and repaired whatever was there. The verify-first short-circuit made it load-bearing: what verification accepts is now left alone, so a latent under-check went live because a different fix started depending on it. Two directory DACLs passed while being wrong — both protected, three non-inherited full-control rules, correct SIDs, differing from correct only in their flags: (OI)(F) - no CI, so subdirectories are left unprotected (OI)(CI)(IO) - inherit-only, so the directory object itself grants nobody anything; the next writeFileSync into it fails with EPERM, on a directory just cached as hardened Verification now compares the whole flag set, which also rejects IO and NP, and names the offending flags in the failure. Both shapes are planted in real-filesystem regression tests, including an assertion that a write into the repaired directory succeeds and its child inherits. Confirmed both tests fail against the old check and pass against this one. * fix(security): back the hardening retry off exponentially The fixed one-minute window bounded the retry rate but left a standing floor of three attempts per path per minute on a host where hardening can never succeed — FAT32/exFAT, a network path, a redirected profile. That budget is per path and there are several secure files, so the floor multiplied into tens of thousands of icacls spawns a day for work guaranteed to fail. The delay now doubles after each consecutive failure, from a one-minute floor to a thirty-minute ceiling, and the attempt cap is gone entirely: once the backoff elapses the path is re-probed however long it has been failing. A permanently incapable host settles at ~2 attempts/hour. Slowing the backstop costs almost nothing, because it is not the recovery mechanism: the synchronous write path is deliberately unthrottled, so a host that recovers hardens on its very next credential write regardless of what the read-path budget says. The `throttled`/`recovered` reports are unchanged and matter more here, since the quiet periods between probes are now much longer. The curve is pinned in a new unit test against the exported delay function rather than a copy of its constants, covering the doubling, the ceiling holding at 5000 consecutive failures, a 30-day failing path still re-probing, one announcement per degraded episode, and per-path isolation. The integration tests keep only what they uniquely prove: that the read path is wired to the budget, and that a day of failures still re-probes. Confirmed four of these fail against a reinstated lifetime cap. * ci(windows): run the real-icacls DACL suite in CI The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered. * fix(security): describe the cache's real cost, which is icacls now Both cache comments still justified themselves with PowerShell -- "~1-1.5s" and "a PowerShell spawn every read" -- in the same file whose PR removed PowerShell from this path. The caches are still right, but for different numbers, and the old ones are the kind an engineer would reasonably delete a cache over. The real shape: hardening verifies first and returns early, so an already-correct DACL costs one synchronous icacls spawn and a rewrite costs four (verify, reset, grant, verify). Still worth caching on the read path, which polls at ~2/s. * test(security): make the DACL suite safe to schedule Registering this spec in the Windows lane put it under two rules it had never been measured against. Teardown now goes through `removeTreeSync`, which the lane's boundary test requires, and repairs the DACLs the suite plants on purpose first: those retries only cover transient locks, so a regressed `(OI)(CI)(IO)` repair leaves the root un-removable and `afterAll` throws EPERM. And the no-permission case decides by elevation before it writes anything. `windows-2022` runs elevated, where hardening succeeds: the old branch asserted nothing about denial and instead replaced the `hosts` DACL, then `icacls /reset` -- which is not a restore, it drops the explicit `SYSTEM:(F)` that file ships with. Ephemeral in CI; permanent for a developer running the lane from an elevated shell. Now it asserts or it skips. The probe reads the token integrity SID rather than `icacls /save`, which succeeds unelevated (`BUILTIN\Users:(RX)` carries READ_CONTROL) and would have skipped the case on every machine. * fix(security): measure the hardening latches on a clock that cannot go backwards `mayAttemptHardening` compared wall-clock times, so any backwards step -- an NTP correction, a VM snapshot restore, a user changing the clock -- made the elapsed time negative and held every failing path below its delay until the clock caught up. Measured at the 30-minute ceiling with the clock stepped back a year, the path was refused at +0d, +1d, +30d, +180d and +364d, and re-probed only at +366d. That is the permanent latch the exponential backoff was added to remove, and it contradicts the module's own "bounds the rate without ever bounding the lifetime". The SID lookup's own one-minute window had the identical shape and is worse: a failed lookup makes `planFor` return null, which disables the synchronous *write* path too, so the write-path exemption that recovers the read-path budget cannot recover it. Both now measure elapsed monotonic time, following the repo's existing `monotonicNowMs` spelling. Two things the write path was not doing, both found in the same pass: - A successful synchronous apply now records the outcome. It is exempt from the budget, but it was also invisible to it, so a host that had demonstrably recovered kept the read path backing off for up to 30 minutes and no `recovered` transition ever came from that lane. Only success is recorded; recording failure would put the exempt lane back under the budget. - `writeSecureFile`'s JSDoc now says its boolean covers the file only. The directory harden is fire-and-forget and answers `pending` on Windows regardless, so a `true` says nothing about the directory's ACL. * fix(security): stop the hardening test doubles from faking a no-op Three CI failures on this branch, one failure shape: hardening silently does nothing and the check that should have caught it agrees. The auth critical-path test hand-rolled a `node:child_process` factory with `execFileSync`/`execFile`. The rewritten ACL path goes through `runProcessSync`, i.e. `spawnSync`, which the factory never returned — so every spawn threw into the SID lookup's bare catch, `planFor` returned null, and hardening no-opped. It mocks `child-process/run-process` now, the boundary production code actually calls and the one sibling ACL tests already mock: an export missing there fails loudly by name instead of returning undefined. Its fake icacls writes a real UTF-16LE SDDL file, so the pinned spawn count per write is a property of the ACL path rather than of the double. The test forces `platform='win32'`, so this failed on every platform, Linux CI included. `windowsSystem32Binary` is a production bug, not a test bug: it builds a Windows path with the host `join`, which off-platform yields the mixed `C:\Windows/System32/whoami.exe`. On Windows the two joins agree, which is why it survived; on Linux the SID lookup's whoami match missed and 27 of secure-file's 32 tests exercised a lane that never ran. These are always Windows paths, so `path.win32.join` is what it should have been. The import-boundary pin still read 160 after this branch migrated secure-path-windows-acl.ts off `node:child_process`; the ratchet correctly refuses a pin left above reality. * fix(security): resolve the machine-relative SDDL alias, and stop a denied read destroying the file Path hardening verified the DACL it wrote by comparing the SIDs `icacls /save` reports. SDDL substitutes two-letter aliases for well-known SIDs, and the resolution table could only hold constants -- but `LA` and `LG` name an account by RID inside the *machine's own* SID, so on a box whose user is the built-in Administrator (a CI runner, an Administrator-only install) the current user read back as `LA`, matched nothing, and hardening reported failure for every path. Resolve those two against the machine authority derived from the user SID; without one they stay unresolved and the comparison still fails closed. Three secret stores treated any read failure as "malformed -- regenerate" and overwrote. A hardened file granting a SID this process does not hold reads as EPERM while its directory stays writable, so the overwrite succeeds: renaming over an unreadable file needs FILE_DELETE_CHILD on the parent, not DELETE on the file. That destroyed the E2EE secret key, every paired device's bearer token, and the plugin vault. Distinguish EPERM/EACCES from a parse failure and refuse. Also close the async lane's unhandled rejection: `void p.then(onSettled)` turned a throw from `onSettled` into a dead main process, and the retry budget it calls threw whenever nothing had configured it -- a contract held only by import order. The budget now defaults its own bounds. * test(windows): say which ACEs icacls listed when a planted DACL fails `toHaveLength` reports only a count and vitest elides the array, so three preconditions failing on the CI runner said "expected 3, got 6" and nothing about what the sixth entry was. Name the entries in the failure. * fix(security): stop three more stores overwriting what they were denied Same swallow-default-overwrite shape as the readers already fixed, found by sweeping every store that reads under a hardened root. - plugin-storage-store.ts returned `{}` on any read failure and set()/delete() wrote it back, losing the plugin KV store. It is the secrets store's shape line for line, so the two now behave identically. - relay-revoke-outbox.ts returned [] and save() wrote it, dropping revocations that never reached the relay -- a revoked device stays live. - profile-cloud-session-store.ts mapped an EPERM read onto `decrypt-failed`, which fails the `status === 'found'` guard in clearCloudSessionIfUnchanged and falls through to an rmSync of the account session. A denied read now reports `unreadable`, which licenses nothing; the refresh path bails on it and the auth status surfaces it rather than reporting a bare reconnect. All reuse isPermissionDeniedError. The predicate stays an EPERM/EACCES allow list rather than "ENOENT defaults, everything else throws": these stores are meant to self-heal a truncated or malformed file, and inverting it would turn a corrupt keypair into an app that cannot start. The distinction that matters is "could not read it" versus "read it and it was garbage". * test(windows): plant fixture DACLs that cannot inherit what they did not plant %TEMP% grants [SYSTEM, Administrators, <user>] (OI)(CI)(F) by default, and those propagate into every fixture. Three preconditions read back 4 and 6 ACEs where 3 were planted, and the extras looked like Orca's own hardening because the shape is identical -- on a runner whose user is the built-in Administrator, the inherited trio IS the trio production grants. Combining /inheritance:r with /grant:r leaves the argument order to icacls, and that combined form drops the inherited ACEs on Windows 11 but keeps them as explicit ones on the Windows Server runner. Removing inheritance in its own invocation makes the grant the whole DACL on either host, and the fixture root is de-inherited once up front so nothing propagates in. Rooting the fixtures outside %TEMP% would not have fixed this: any directory inherits from wherever it lives. The fix is to stop inheriting, not to move. No assertion is relaxed -- the counts stay exact. * test(windows): pick a foreign SID that stays foreign on an elevated runner `S-1-5-32-544` is only foreign to a token that is not an administrator. The CI runner is elevated AND logged in as the built-in Administrator, so granting Administrators granted the reader full control: the file stayed readable, and all six preservation assertions went vacuous rather than proving anything. BUILTIN\Guests is resolvable everywhere and no interactive token is a member, so the read is denied on an unelevated developer box and on the runner alike. An unresolvable SID would have been the stronger choice but icacls rejects one with ERROR_NONE_MAPPED (1332). The premise guard is what caught this -- it asserted the file was actually unreadable instead of trusting the grant, and named elevation as the suspect. * fix(security): refuse on any read that never reached the contents, not just a denied one isPermissionDeniedError becomes isUnreadableError, because "permission denied" was never the concept -- "could not read it", as opposed to "read it and it was garbage", is. EBUSY, EMFILE, ENFILE and EIO say exactly as little about a file's contents as EACCES does, and they fell into the branch that regenerates and overwrites. On Windows EBUSY is the likelier of the two: antivirus holding a credential open at the moment of a startup read produces it, which makes it a commoner path to the same permanent loss than the ACL case that motivated the original fix. Still an allow list, deliberately: ENOENT keeps licensing a create, and a parse failure keeps self-healing. The stores are built to recover from a truncated write, and turning that into a refusal would trade a recoverable state for an unrecoverable one on the startup path. Also fixes the regression suite's own premise on an elevated runner: makeUnreadable combined /inheritance:r with /grant:r, and that form keeps %TEMP%'s inherited [SYSTEM, Administrators, user] as explicit ACEs on Windows Server -- so the file stayed readable and all six assertions were vacuous. Same split-the-invocation fix as the ACL suite's planter. * test(windows): skip the preservation suite where a read cannot be denied An elevated token logged in as the built-in Administrator reads straight through a DACL that grants it nothing -- confirmed on the CI runner against both BUILTIN\Administrators and BUILTIN\Guests, and with the grant split into its own icacls invocation so the DACL really was the planted one. On such a host the premise these tests rest on does not hold, and every assertion would pass while proving nothing. So probe once at module scope and skip rather than assert vacuously -- the same trade the ACL suite already makes for its unelevated-only case. The gate stays in the compound `<win32 check> && <flag>` form the win32 lane ratchet detects, so the file stays registered in both lane lists. Coverage is not lost where it counts: isUnreadableError has unit tests that run on every platform and every host, and the stores' refusal is exercised in full on any machine where a denial is reproducible -- which is every developer box. --------- Co-authored-by: Orca Worker <orca-worker@localhost> Co-authored-by: Neil <[email protected]>

What MDE flagged
Incidents E and F: multi-stage Defender for Endpoint incidents mapped to ATT&CK Execution + Collection, described as "Screenshots were taken unexpectedly on this device… Screen capture code was found in a script launched by powershell.exe", with the contributing factor "Executes suspicious MSIL code".
The cause was the shape of the computer-use provider, not the feature itself.
desktop-script-provider-client.tscreated a fresh temp dir per operation, wroteoperation.json, anddesktop-script-provider-bridge.tsspawned:One PowerShell process per click, per keystroke batch, per screenshot — roughly ten short-lived
powershell.exePIDs in a burst. Because the process was new every time,runtime.ps1'sAdd-Type -TypeDefinition @"…"(inline C# P/Invoke into user32.dll:SendInput,mouse_event,SetCursorPos) re-emitted MSIL on every single operation, which is what the "suspicious MSIL" factor was scoring.Behaviour change
powershell.exeprocesses per sessionBypassRemoteSigned,Bypassonly as a logged one-time fallbackoperation.jsonper operationPersistent runtime host
runtime.ps1gains a-Serveswitch. In serve mode it performs allAdd-Type/ assembly loading once, writes one{"ready":true}line, then loops on[Console]::In.ReadLine(), answering one compact JSON object per line on stdout until stdin closes.-OperationPathone-shot mode is untouched —runtime-render.test.ps1,verify-computer-native.mjsand the existing bridge tests all still drive it, and it remains the fallback path.src/main/computer/desktop-script-runtime-host.tsowns exactly one child: lazy spawn viaspawnProcess(nevernode:child_process; the ratchet allowlist is unchanged), strict serialization, a 30s per-request timeout, restart on crash, 120s idle shutdown, anddispose()reached fromDesktopScriptProviderClient.shutdown(). It is split intodesktop-script-serve-channel.ts(one child, NDJSON framing) anddesktop-script-runtime-availability.ts(failure counting, cooldown, policy escalation) to stay undermax-lineswithout a disable.The client-facing contract is the existing
BridgeRequest/BridgeResponse; the only wire addition is an optionalrequestId. Linux stays on the existing one-shotpython3 runtime.pypath, unchanged.Request correlation
Each request carries an id the helper echoes. Serialization alone would let a single stray stdout line answer every later request with the previous response — silently acting on stale element indexes, with no error raised. A mismatched or unsolicited reply is fatal to the child rather than merely logged. Non-JSON noise (a banner, a stray write) is ignored rather than fatal: with the id doing the real correlation, aborting on a banner would make a chatty host permanently unusable.
-ExecutionPolicy Bypass→RemoteSignedMeasured on Windows 11:
-File <unsigned local .ps1>fails underRestrictedbut runs underRemoteSigned, and the installed packaged script carries no Mark-of-the-Web (NSIS extraction writes noZone.Identifier), soRemoteSignedis sufficient in the shipping configuration.Restrictedis still the Windows client default, so both Windows spawn sites fall back once toBypasson a policy-blocked start, and log it. The retry requires empty stdout as well as a matching stderr: operations are not idempotent and responses embed window titles, so matching the policy pattern against a snapshot containing the words "SecurityError" or "UnauthorizedAccess" would have replayed the operation — a second click, keystroke or paste.runBridgeProcessrejects with aBridgeProcessFailurecarrying the raw streams so that decision can never read a mapped message.Proper long-term fix, not in this PR: Authenticode-sign
runtime.ps1in the inner-binary signing pass in.github/workflows/release-cut.yml. That pass currently stages only.exe/.dll/.node; adding.ps1would let the flag drop entirely.Degrading without silently undoing the fix
The failure handling is the part most worth reviewing, because every mistake in it is invisible: computer use keeps working while the process burst and per-operation MSIL emission come straight back. Three rules earn their complexity.
1. No permanent latch. A helper that dies before answering is retried, then cools down for 60s, then is re-probed. The client falls back per operation and keeps the host, so one bad spawn cannot strand a session on one
powershell.exeper click. Every plausible cause is transient — a Defender scan touching the script mid-launch, a locked CSC temp directory failing oneAdd-Type, memory pressure.2. A replay must be provable, never inferred.
-Serveannounces{"ready":true}after itsAdd-Typework and before its first read, and a request is replayed only when the helper died before announcing. "No reply came back" is not "the operation did not run":runtime.ps1synthesizes the input and only then builds the snapshot, allocating a full-window bitmap and walking the UIA tree — the heaviest, most fault-prone part, where a native GDI+/UIA fault is uncatchable by$ErrorActionPreferenceand leaves the click already delivered. Inferring "never started" from a missing response turned one requested click into three from the host plus a fourth from the one-shot bridge, reported as a single failed operation. Aruntime.ps1predating the announcement — reachable viaORCA_COMPUTER_DESKTOP_SCRIPT_PROVIDER_PATH— is covered by an observation-tool allowlist until a ready line proves otherwise.3. A single success must not excuse a helper that keeps dying.
recordSuccess()clears the failure count only after a clean run of three operations, not on any one reply. Resetting on a single success reads like the obvious simplification and is the bug: a helper that answers one operation and dies on the next would reset the count forever and be respawned once per operation — precisely the pattern this PR removes, reintroduced through its own recovery path. Relatedly,enterCooldown()resets the counters: the wait is the penalty, and leaving the count at the limit would let the first death after recovery re-enter a full cooldown, stranding an interleaved workload on the one-shot bridge.Host-detected aborts (timeout, desynchronised reply, oversized line) suppress the exit handler, so they are counted and logged explicitly — otherwise they bypassed the accounting entirely and a helper failing that way was respawned once per operation forever.
Other fixes from review
console.warnwas discarded — including the only signal that a machine had fallen back toBypass. Warnings now travel over the sidecar's existing IPC channel and are printed by the main process.closerather thanexit, so stderr is drained before a failure is classified.dispose()latches, so a request queued behind teardown cannot respawn a helper.MAX_RESPONSE_CHARSnamed for the UTF-16 units it actually counts; per-linetrim()replaced with an index-based CR strip that does not copy a megabyte payload;$ProgressPreference = 'SilentlyContinue'and-NoLogoso nothing else can reach the response stream.TerminateProcessteardown gap insidecar-entry.tsis documented where the handlers are registered.What this does not fix
The remaining Defender surface is the behaviour itself, not the process shape:
$graphics.CopyFromScreen(...)for screen capture andSendInput/mouse_eventfor synthetic input. The report says that is only reducible via a signed native helper owning those calls instead of PowerShell. Separate follow-up.config/scripts/verify-computer-native.mjsstill usesBypassfor its two dev/CI checks — deliberately left alone, since it runs on CI runners rather than user devices.Verification
pnpm tcclean;oxlintclean;check-max-lines-ratchetclean;child-process-import-boundaryratchet cleanpnpm test src/main/computer/— 22 files, 134 tests, all passingnode config/scripts/verify-computer-native.mjs— PowerShell parse, one-shot handshake and the snapshot renderer tests pass on Windowsdesktop-script-runtime-host.win32.test.tsdrives the realruntime.ps1 -Serveon a real Windows box: three operations, one spawnget_app_stateresponse arrived as a single intact 484,565-character line with itsrequestIdechoed, followed by a correlated second response on the same process