Skip to content

fix(computer-use): settle Screen Recording trust like Accessibility - #10373

Closed
Tamaz-sujashvili wants to merge 2 commits into
stablyai:mainfrom
Tamaz-sujashvili:fix/screen-recording-preflight-and-settle
Closed

Tamaz-sujashvili wants to merge 2 commits into
stablyai:mainfrom
Tamaz-sujashvili:fix/screen-recording-preflight-and-settle

Conversation

@Tamaz-sujashvili

@Tamaz-sujashvili Tamaz-sujashvili commented Jul 24, 2026 •

Copy link
Copy Markdown

Summary

Fixes / related: #10372 (also related to #9458).

Built on top of #10122 (AccessibilityTrustSettling) so both TCC preflight races are covered together.

Test plan

  • Unit: ScreenCaptureTrustSettlingTests + existing AccessibilityTrustSettlingTests
  • On macOS with Screen Recording already enabled for Orca Computer Use:
    • orca computer permissions --json → "screenshots": "granted"
    • permission setup UI does not keep asking to drag an already-listed app
    • orca computer get-app-state --app com.google.Chrome --json can capture (or report a non-permission error)
  • On a machine without Screen Recording grant, status still reports not-granted and setup UI still guides correctly

Made with Cursor

ELI5

macOS Screen Recording permission could look enabled in Settings while Orca still thought it was denied, looping the computer-use assistant. Permission checks now settle like Accessibility, including a real probe when preflight lies.

tomdebres and others added 2 commits July 23, 2026 07:59
… helper processes

tccd answers a freshly spawned helper with preflight_unknown/do_not_cache,
so the first Accessibility answers a new process sees can read as denied
while the grant is real, flipping to granted moments later in the same pid
(#9458). Every CLI call spawns a fresh helper, so one-shot checks lose the
race on every invocation: permissions reports granted while every
get-app-state fails permission_denied (#9159).

- add AccessibilityTrustSettling.settle: immediate probe, then bounded
  100ms polls (1.5s cap); zero added latency when already trusted
- buildSnapshot trust gate, both permission-status printers, and the
  'visible windows but no accessibility window' path now settle before
  concluding denial; the latter retries the actual AX window lookup and
  reports how long reads stayed blocked
- extract lookupUsableWindow to dedupe the pre/post-recovery lookups
- deterministic unit tests for the settle policy (injected sleep)
CGPreflightScreenCaptureAccess() hits the same fresh-helper
preflight_unknown race as Accessibility (#9458): System Settings can
already show Orca Computer Use enabled for Screen Recording while
one-shot preflight stays false, so the drag-assistant keeps asking
users to add an app that is already listed.

Reuse AccessibilityTrustSettling for Screen Recording, fall back to one
real CGWindowListCreateImage probe to warm tccd, and drive permission
UI / status JSON / screenshot gating through the settled check.

Co-authored-by: Cursor <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

macOS permission handling now uses retry-based settled checks for Accessibility and Screen Recording trust. Snapshot creation, focused-window lookup, permission evaluation, and permission-status reporting use these checks. Screen Recording settling can perform a real window capture probe. Window lookup retries when visible windows exist and distinguishes permission denial from missing windows. A reusable settling utility and tests cover success, retries, timeout behavior, and interval clamping.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers summary and tests, but omits required template sections like Screenshots, AI Review Report, Security Audit, and Notes. Add the missing template sections, including Screenshots (or 'No visual change'), full Testing checklist, AI Review Report, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: settling Screen Recording trust like Accessibility.

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ScreenCaptureTrustSettlingTests.swift (1)

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

Test the Screen Recording fallback decision path.

This only re-tests generic retry behavior; it cannot catch regressions in the preflight → capture probe → final preflight flow. Extract that decision logic behind injectable probes and cover capture success and failure explicitly.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 63ab841a-6edc-4245-adaa-ad0d57fac2b0

📥 Commits

Reviewing files that changed from the base of the PR and between 1bd36ce and c4e9a3d.

📒 Files selected for processing (4)
  • native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift
  • native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/AccessibilityTrustSettling.swift
  • native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AccessibilityTrustSettlingTests.swift
  • native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ScreenCaptureTrustSettlingTests.swift

Comment on lines +1053 to +1068
private func screenCaptureTrustedByCaptureProbe() -> Bool {
guard let infos = CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]] else {
return false
}
for info in infos {
guard let layer = info[kCGWindowLayer as String] as? Int, layer == 0,
let number = info[kCGWindowNumber as String] as? NSNumber
else {
continue
}
let windowId = CGWindowID(number.uint32Value)
if CGWindowListCreateImage(.null, [.optionIncludingWindow], windowId, [.boundsIgnoreFraming]) != nil {
return true
}
// One real capture attempt is enough to settle tccd for this pid.
break

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate main.swift =="
fd -a 'main.swift' . | sed 's#^\./##'

echo "== relevant lines =="
if [ -f native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift ]; then
  nl -ba native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift | sed -n '1020,1090p'
fi

echo "== references to screenCaptureTrustedByCaptureProbe and permissions =="
rg -n "screenCaptureTrustedByCaptureProbe|permissions|Screen Recording|kCGWindowOwnerPID|CGWindowListCopyWindowInfo|CGWindowListCreateImage" native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift || true

echo "== diff stat/name-only =="
git diff --stat HEAD~1..HEAD 2>/dev/null || git diff --stat 2>/dev/null || true

Repository: stablyai/orca

Length of output: 384


🌐 Web query:

Apple developer documentation 2019 WWDC 701 Capture Screen macOS Screen Recording permission captures own windows without approval

💡 Result:

Yes — Apple’s WWDC 2019 session says apps can freely record the contents of their own windows, plus the menu bar and desktop background. User approval is required only to record the entire screen or windows belonging to other apps. (developer.apple.com)

Apple’s support docs also note that macOS has a Screen & System Audio Recording privacy setting where users can allow or deny apps access. (support.apple.com)

Citations:


🌐 Web query:

CGWindowOwnerPID CGWindowListCopyWindowInfo macOS reference

💡 Result:

CGWindowListCopyWindowInfo returns an array of window dictionaries, and kCGWindowOwnerPID is one of the required keys in those dictionaries. Apple documents kCGWindowOwnerPID as a CFNumber containing the process ID of the app that owns the window. (developer.apple.com)

If you want, I can also show a minimal Swift/Objective-C example for reading it.

Citations:


🌐 Web query:

CGWindowLayer kCGNullWindowID CGWindowListCreateImage macOS developer documentation

💡 Result:

On macOS, CGWindowListCreateImage(...) is the Core Graphics API for creating an image of windows on screen, and kCGNullWindowID is the “guaranteed invalid window ID” used when no reference window is needed. Apple’s docs also note that for options like kCGWindowListOptionOnScreenOnly, relativeToWindow should be kCGNullWindowID. kCGWindowLayer is the window’s layer value used when inspecting window info. [1][2][3][4][5]

If you want, I can also give you the typical Swift/Obj‑C call pattern for taking a screenshot with these APIs.


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift"

echo "== relevant lines with sed =="
sed -n '1020,1105p' "$FILE" | awk '{printf "%6d\t%s\n", NR+1019, $0}'

echo "== exact occurrences =="
python3 - <<'PY'
from pathlib import Path
p=Path("native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift")
text=p.read_text()
for needle in [
    "screenCaptureTrustedByCaptureProbe",
    "permissions --json",
    "kCGWindowOwnerPID",
    "CGWindowListCopyWindowInfo",
    "CGWindowListCreateImage",
    "ProcessInfo.processInfo.processIdentifier",
]:
    print(f"\n-- {needle} --")
    idx=0
    count=0
    while True:
        idx=text.find(needle, idx)
        if idx==-1: break
        start=max(0, text.rfind("\n", 0, idx-200))
        end=text.find("\n", idx+200)
        if start==-1: start=0
        print(f"{text[:idx].count(chr(10))+1}:{text.count(chr(10), 0, idx)+1} {text[start:end]}")
        idx=max(1, end)
        count += 1
    print("count", count)
PY

Repository: stablyai/orca

Length of output: 8483


🏁 Script executed:

#!/bin/bash
set, -euo pipefail

python3 - <<'PY'
from pathlib import Path
text = Path("native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift").read_text()

start = text.find("private func screenCaptureTrustedByCaptureProbe()")
if start == -1:
    print("function not found")
    raise SystemExit(1)

brace = text.find("{", start)
level = 0
end = None
for i in range(brace, len(text)):
    if text[i] == "{":
        level += 1
    elif text[i] == "}":
        level -= 1
        if level == 0:
            end = i + 1
            break

block = text[start:end]
print("ownerPID present in block:", "kCGWindowOwnerPID" in block)
print("self pid exclusion present in block:", "ProcessInfo.processInfo.processIdentifier" in block)
print("capture options include current process in block:", ".currentApplication" in block or ".optionIncludeApp" in block)
print("first 120 chars around owner PID references:")
for needle in ["kCGWindowOwnerPID", "CGWindowListCreateImage", "ProcessInfo.processInfo.processIdentifier"]:
    idx = text.find(needle)
    if idx != -1:
        lo = max(0, text.rfind("\n", 0, idx-150))
        hi = text.find("\n", idx+150)
        print(f"\n[{text[:idx].count(chr(10))+1}] {text[lo:hi]}")
PY

Repository: stablyai/orca

Length of output: 1180


Exclude this process’s windows from the capture probe.

macOS apps can capture their own windows without Screen Recording approval, so accepting an Orca-owned window image makes the settled Screen Recording probe return true from a local window. Filter kCGWindowOwnerPID to a different process before returning true; otherwise status/UI can report granted while capture operations that require cross-app access still fail.

Comment on lines +36 to +38
sleepMs: (Int) -> Void = { interval in
usleep(useconds_t(interval * 1000))
},

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and inspect the target file and any nearby usage/docs.
if [ -f native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/AccessibilityTrustSettling.swift ]; then
  echo "== file exists =="
  wc -l native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/AccessibilityTrustSettling.swift
  echo
  echo "== target file =="
  cat -n native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/AccessibilityTrustSettling.swift
else
  echo "Target file not found"
fi

echo
echo "== related files =="
git ls-files | rg 'AccessibilityTrustSettling|ComputerUse|MacOSCore' | head -100

Repository: stablyai/orca

Length of output: 4726


🌐 Web query:

Swift Int overflow behavior multiplication default Int max trap useconds_t usleep documentation

💡 Result:

Yes: in Swift, plain integer multiplication (*) does not overflow by default. If the result can’t fit in Int, Swift traps at runtime; use &* if you want wrapping overflow instead. (docs.swift.org)

usleep takes a useconds_t argument and sleeps for that many microseconds; on Linux, usec >= 1_000_000 can return EINVAL, and the call is obsolete in POSIX (use nanosleep instead when possible). (man7.org)

So if you’re doing something like seconds * 1_000_000 in Swift, guard/check first or use a wider type before converting to useconds_t.

Citations:


Prevent overflow before passing the sleep interval to usleep.

settle accepts unbounded positive Int values, and normal Swift multiplication traps on overflow. A caller with intervalMs near Int.max can have interval * 1000 crash before usleep runs; use a seconds-based sleep path or cap the supported interval before conversion.

Proposed fix
-            usleep(useconds_t(interval * 1000))
+            Thread.sleep(forTimeInterval: TimeInterval(interval) / 1_000)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
sleepMs: (Int) -> Void = { interval in
usleep(useconds_t(interval * 1000))
},
sleepMs: (Int) -> Void = { interval in
Thread.sleep(forTimeInterval: TimeInterval(interval) / 1_000)
},

@AmethystLiang
AmethystLiang requested a review from OrcaWin July 24, 2026 16:49
@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
@Tamaz-sujashvili
Tamaz-sujashvili deleted the fix/screen-recording-preflight-and-settle branch November 8, 2026 17:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants