Skip to content

fix(computer-use): run the Windows runtime as one persistent helper - #17858

Merged
OrcaWin merged 12 commits into
mainfrom
OrcaWin/win-edr-computer-use-runtime-host
Sep 6, 2026
Merged

OrcaWin merged 12 commits into
mainfrom
OrcaWin/win-edr-computer-use-runtime-host

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1362 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1362
Prod 16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1113 $\color{#cf222e}{\Huge{\mathbf{−}}}$​34 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1079

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.ts created a fresh temp dir per operation, wrote operation.json, and desktop-script-provider-bridge.ts spawned:

powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File <runtime.ps1> <operation.json>

One PowerShell process per click, per keystroke batch, per screenshot — roughly ten short-lived powershell.exe PIDs in a burst. Because the process was new every time, runtime.ps1's Add-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

Before After
powershell.exe processes per session ~10 per burst, one per operation 1, reused
MSIL emission once per click once per session
Execution policy flag Bypass RemoteSigned, Bypass only as a logged one-time fallback
Request transport a temp operation.json per operation NDJSON over stdin/stdout

Persistent runtime host

runtime.ps1 gains a -Serve switch. In serve mode it performs all Add-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. -OperationPath one-shot mode is untouched — runtime-render.test.ps1, verify-computer-native.mjs and the existing bridge tests all still drive it, and it remains the fallback path.

src/main/computer/desktop-script-runtime-host.ts owns exactly one child: lazy spawn via spawnProcess (never node:child_process; the ratchet allowlist is unchanged), strict serialization, a 30s per-request timeout, restart on crash, 120s idle shutdown, and dispose() reached from DesktopScriptProviderClient.shutdown(). It is split into desktop-script-serve-channel.ts (one child, NDJSON framing) and desktop-script-runtime-availability.ts (failure counting, cooldown, policy escalation) to stay under max-lines without a disable.

The client-facing contract is the existing BridgeRequest/BridgeResponse; the only wire addition is an optional requestId. Linux stays on the existing one-shot python3 runtime.py path, 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 → RemoteSigned

Measured on Windows 11: -File <unsigned local .ps1> fails under Restricted but runs under RemoteSigned, and the installed packaged script carries no Mark-of-the-Web (NSIS extraction writes no Zone.Identifier), so RemoteSigned is sufficient in the shipping configuration.

Restricted is still the Windows client default, so both Windows spawn sites fall back once to Bypass on 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. runBridgeProcess rejects with a BridgeProcessFailure carrying the raw streams so that decision can never read a mapped message.

Proper long-term fix, not in this PR: Authenticode-sign runtime.ps1 in the inner-binary signing pass in .github/workflows/release-cut.yml. That pass currently stages only .exe/.dll/.node; adding .ps1 would 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.exe per click. Every plausible cause is transient — a Defender scan touching the script mid-launch, a locked CSC temp directory failing one Add-Type, memory pressure.

2. A replay must be provable, never inferred. -Serve announces {"ready":true} after its Add-Type work 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.ps1 synthesizes 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 $ErrorActionPreference and 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. A runtime.ps1 predating the announcement — reachable via ORCA_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

  • Diagnostics escape the sidecar. The provider runs inside a fork whose stdio is piped and never read, so console.warn was discarded — including the only signal that a machine had fallen back to Bypass. Warnings now travel over the sidecar's existing IPC channel and are printed by the main process.
  • close rather than exit, so stderr is drained before a failure is classified.
  • dispose() latches, so a request queued behind teardown cannot respawn a helper.
  • MAX_RESPONSE_CHARS named for the UTF-16 units it actually counts; per-line trim() replaced with an index-based CR strip that does not copy a megabyte payload; $ProgressPreference = 'SilentlyContinue' and -NoLogo so nothing else can reach the response stream.
  • The Windows SIGTERM/TerminateProcess teardown gap in sidecar-entry.ts is 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 and SendInput/mouse_event for 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.mjs still uses Bypass for its two dev/CI checks — deliberately left alone, since it runs on CI runners rather than user devices.

Verification

  • pnpm tc clean; oxlint clean; check-max-lines-ratchet clean; child-process-import-boundary ratchet clean
  • pnpm test src/main/computer/ — 22 files, 134 tests, all passing
  • node config/scripts/verify-computer-native.mjs — PowerShell parse, one-shot handshake and the snapshot renderer tests pass on Windows
  • desktop-script-runtime-host.win32.test.ts drives the real runtime.ps1 -Serve on a real Windows box: three operations, one spawn
  • Real-hardware protocol checks: a get_app_state response arrived as a single intact 484,565-character line with its requestId echoed, followed by a correlated second response on the same process
  • Every failure-path fix has a regression test that was confirmed to fail without it: no replay of a mutating tool after a pre-answer death; no replay once the helper announced readiness; bounded respawn under repeated desync and repeated timeout; one cooldown per outage

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-apps

greptile-apps Bot commented Sep 1, 2026

Copy link
Copy Markdown

Greptile Summary

The PR replaces per-operation Windows PowerShell processes with a serialized persistent NDJSON helper while retaining the one-shot bridge as a fallback.

  • Adds persistent helper startup, framing, timeout, restart, idle-shutdown, and execution-policy fallback behavior.
  • Routes Windows provider operations through the helper and adds lifecycle, protocol, routing, and real-Windows tests.
  • Extends runtime.ps1 with serve mode while preserving one-shot operation-file mode.

Confidence Score: 4/5

The 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

Important Files Changed

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
Loading

Reviews (1): Last reviewed commit: "fix(computer-use): run the Windows runti..." | Re-trigger Greptile

Comment on lines +100 to +106
dispose(): void {
this.clearIdleTimer()
this.stopChild()
this.rejectPending(
new RuntimeClientError('accessibility_error', 'desktop provider runtime host was shut down')
)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 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

@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The 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 34802

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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/… Add the missing template sections. Provide a linked issue after Fixes #, add visual proof or state N/A with a reason, complete the AI Disclosure section, Review section, Agent skill upstream boundary checkbox, Notes, and Checklist. Keep…
Docstring Coverage ⚠️ Warning 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:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: running the Windows runtime as one persistent helper.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

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 Fixes #, add visual proof or state N/A with a reason, complete the AI Disclosure section, Review section, Agent skill upstream boundary checkbox, Notes, and Checklist. Keep the existing implementation and testing details.

Full details: Docstring Coverage

Explanation

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.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 3efd5218-79eb-4f8c-9602-9d1fdc3487eb

📥 Commits

Reviewing files that changed from the base of the PR and between 0b2912b and cee7fed.

📒 Files selected for processing (9)
  • native/computer-use-windows/runtime.ps1
  • src/main/computer/desktop-script-provider-bridge.ts
  • src/main/computer/desktop-script-provider-client.ts
  • src/main/computer/desktop-script-provider-runtime-host-routing.test.ts
  • src/main/computer/desktop-script-provider-test-harness.ts
  • src/main/computer/desktop-script-runtime-host.test.ts
  • src/main/computer/desktop-script-runtime-host.ts
  • src/main/computer/desktop-script-runtime-host.win32.test.ts
  • src/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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 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.ts

Repository: 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 -120

Repository: 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — one rough edge worth a look.

Reviewed changes

  • Persistent runtime host — new DesktopScriptRuntimeHost drives one long-lived runtime.ps1 -Serve NDJSON child with strict request serialization, per-request timeout, crash restart, and idle shutdown.
  • Serve mode in runtime.ps1 — one-shot -OperationPath path 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 RemoteSigned with a single, logged Bypass fallback 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).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Orca Worker added 4 commits September 1, 2026 00:43
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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 retries runtime_host_unavailable up to MAX_START_ATTEMPTS with 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 — DesktopScriptServeChannel owns NDJSON framing, close-based teardown, and the buffer cap; the host keeps only queueing, retry policy, and correlation.
  • Recovery policy extracted — RuntimeHostAvailability centralizes attempt counts, cooldown, and RemoteSigned → Bypass escalation.
  • 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 — BridgeProcessFailure carries raw streams so the Bypass replay only happens when stdout was empty, and the policy regex drops the stdout-prone SecurityError token.

The dispose-terminality thread from the prior review is resolved (disposed flag checked at the top of send()).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: e7868614-95da-4169-bd87-79cf53fa92e8

📥 Commits

Reviewing files that changed from the base of the PR and between cee7fed and c041a46.

📒 Files selected for processing (17)
  • native/computer-use-windows/runtime.ps1
  • src/main/computer/computer-sidecar-diagnostics.test.ts
  • src/main/computer/computer-sidecar-diagnostics.ts
  • src/main/computer/desktop-script-action.ts
  • src/main/computer/desktop-script-provider-bridge.ts
  • src/main/computer/desktop-script-provider-client.ts
  • src/main/computer/desktop-script-provider-runtime-host-routing.test.ts
  • src/main/computer/desktop-script-provider-test-harness.ts
  • src/main/computer/desktop-script-provider-types.ts
  • src/main/computer/desktop-script-runtime-availability.ts
  • src/main/computer/desktop-script-runtime-host.test.ts
  • src/main/computer/desktop-script-runtime-host.ts
  • src/main/computer/desktop-script-serve-channel.test.ts
  • src/main/computer/desktop-script-serve-channel.ts
  • src/main/computer/sidecar-client.ts
  • src/main/computer/sidecar-entry.ts
  • src/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.

Comment on lines +146 to +149
if (this.availability.policyRetryPending) {
this.availability.escalateExecutionPolicy()
continue
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 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/computer

Repository: 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 || true

Repository: 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).

Comment on lines +261 to +271
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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Ready announcement — runtime.ps1 -Serve emits {"ready":true} after Add-Type and before its first read, so a caller can prove a helper never read a request.
  • Replay proof — mayReplay retries 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 as accessibility_error and is never replayed.
  • Observation allowlist — isReplayableTool whitelists handshake/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.

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

OrcaWin pushed a commit that referenced this pull request Sep 1, 2026
…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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Registered the win32 suite in CI — added src/main/computer/desktop-script-runtime-host.win32.test.ts to the package_windows vitest list in .github/workflows/pr.yml and to WINDOWS_PACKAGE_TESTS in config/scripts/pr-code-change-scope.mjs, so the real-runtime.ps1 -Serve suite 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.

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

Orca Worker added 2 commits September 5, 2026 18:26
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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Queued-request wait deadline — extracted the inline tail-chain into DesktopScriptRequestQueue; a request queued behind others now has its own requestTimeoutMs deadline and surfaces action_timeout (waiting for earlier operations) instead of a minutes-long hung await, while a request that reaches the helper still keeps its full execution budget.
  • Monotonic cooldown clock — RuntimeHostAvailability now stores a cooldownStartedAtMs sampled from performance.now() (with null as the no-cooldown sentinel, since performance.now() can legitimately return 0), 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.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Enforce the 20 MiB response cap in UTF-8 bytes. runtime.ps1 -Serve sends snapshot NDJSON through DesktopScriptServeChannel.readStdout(), which currently compares UTF-16 string length. A snapshot with multibyte UI Automation text can exceed the byte cap before onOverflow() aborts the channel. Track bytes at this framing boundary, including incomplete UTF-8 bytes held by StringDecoder, and compare against MAX_RESPONSE_BYTES; no runtime.ps1 change is required.

src/main/computer/desktop-script-runtime-host.ts (2)

115-194: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Guard execution-policy retries with mayReplay(request). handleGone() marks a pre-readiness execution-policy failure for retry, but send() then calls escalateExecutionPolicy() and writes the same BridgeRequest again without checking mayReplay(request). A mutating request sent to a custom ORCA_COMPUTER_DESKTOP_SCRIPT_PROVIDER_PATH helper 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 the Bypass retry and surface the original error when the request is not replayable.


248-281: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Reject non-object JSON before reading response fields. JSON.parse('null') returns null, and deliver() then reads parsed.ready, which throws inside the synchronous DesktopScriptServeChannel stdout callback. Validate non-null, non-array objects first, then call abortChannel() for malformed output.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: f859cd10-41fa-499f-ad38-e1060948dd61

📥 Commits

Reviewing files that changed from the base of the PR and between 6a6127d and 77eb826.

📒 Files selected for processing (4)
  • src/main/computer/desktop-script-request-queue.ts
  • src/main/computer/desktop-script-runtime-availability.ts
  • src/main/computer/desktop-script-runtime-host.test.ts
  • src/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.

Orca Worker added 3 commits September 5, 2026 18:49
…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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Execution-policy discriminator hardened — isExecutionPolicyBlocked now matches identifiers (\bUnauthorizedAccess\b, \bSecurityError\b, about_Execution_Policies, no /i) instead of English prose plus an unbounded UnauthorizedAccess alternative, so a locked or ACL-denied file (UnauthorizedAccessException) no longer escalates the session to Bypass.
  • Malformed-request routing — runtime.ps1 -Serve recovers the requestId from the raw line when ConvertFrom-Json throws 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 own error string 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.ps1 to 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.

Pullfrog  | View workflow run | Using 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.
@coderabbitai

coderabbitai Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

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 — RuntimeHostAvailability gains a fallbackPolicyUnproven flag set by escalateExecutionPolicy() and cleared by confirmExecutionPolicy() / recordSuccess(), so only a policy that actually started a helper stays sticky for the session.
  • Revert on a disproven diagnosis — abandonUnprovenFallback() returns to RemoteSigned when a Bypass spawn also fails to start, and enterCooldown() 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 surfaces runtime_host_unavailable; a policy-blocked start now rejects with runtime_host_unavailable so 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 Bypass command line, not one per attempt) and that the post-cooldown re-probe starts on RemoteSigned; the existing escalation test is tightened to assert no revert once Bypass is 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.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 0c23b90e-d985-4ab9-a47e-bc111c7bbc55

📥 Commits

Reviewing files that changed from the base of the PR and between 84432d3 and 3480242.

📒 Files selected for processing (22)
  • .github/workflows/pr.yml
  • config/scripts/pr-code-change-scope.mjs
  • native/computer-use-windows/runtime.ps1
  • src/main/computer/computer-sidecar-diagnostics.test.ts
  • src/main/computer/computer-sidecar-diagnostics.ts
  • src/main/computer/desktop-script-action.ts
  • src/main/computer/desktop-script-provider-bridge.ts
  • src/main/computer/desktop-script-provider-client.ts
  • src/main/computer/desktop-script-provider-runtime-host-routing.test.ts
  • src/main/computer/desktop-script-provider-test-harness.ts
  • src/main/computer/desktop-script-provider-types.ts
  • src/main/computer/desktop-script-request-queue.ts
  • src/main/computer/desktop-script-runtime-availability.ts
  • src/main/computer/desktop-script-runtime-host.test.ts
  • src/main/computer/desktop-script-runtime-host.ts
  • src/main/computer/desktop-script-runtime-host.win32.test.ts
  • src/main/computer/desktop-script-serve-channel.test.ts
  • src/main/computer/desktop-script-serve-channel.ts
  • src/main/computer/sidecar-client.ts
  • src/main/computer/sidecar-entry.ts
  • src/main/computer/windows-powershell-execution-policy.test.ts
  • src/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.

Comment on lines +146 to +149
if (!isRuntimeHostUnavailable(error) || !this.mayReplay(request)) {
if (this.availability.exhausted) {
this.availability.enterCooldown()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ 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.

Comment on lines +261 to +271
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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

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.

@OrcaWin
OrcaWin merged commit 687a22e into main Sep 6, 2026
32 checks passed
OrcaWin added a commit that referenced this pull request Sep 6, 2026
…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]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant