Repository navigation
fix(computer-use): settle Screen Recording trust like Accessibility - #10373
Tamaz-sujashvili wants to merge 2 commits into
Conversation
… 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]>
📝 WalkthroughWalkthroughmacOS 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)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ScreenCaptureTrustSettlingTests.swift (1)
6-20: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTest 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
📒 Files selected for processing (4)
native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swiftnative/computer-use-macos/Sources/OrcaComputerUseMacOSCore/AccessibilityTrustSettling.swiftnative/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AccessibilityTrustSettlingTests.swiftnative/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ScreenCaptureTrustSettlingTests.swift
| 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 |
There was a problem hiding this comment.
🎯 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 || trueRepository: 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:
- 1: https://developer.apple.com/videos/play/wwdc2019/701/
- 2: https://support.apple.com/guide/mac-help/control-access-screen-system-audio-recording-mchld6aa7d23/mac
🌐 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)
PYRepository: 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]}")
PYRepository: 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.
| sleepMs: (Int) -> Void = { interval in | ||
| usleep(useconds_t(interval * 1000)) | ||
| }, |
There was a problem hiding this comment.
🩺 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 -100Repository: 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:
- 1: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/basicoperators/?utm_source=openai
- 2: https://man7.org/linux/man-pages/man3/usleep.3.html
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.
| sleepMs: (Int) -> Void = { interval in | |
| usleep(useconds_t(interval * 1000)) | |
| }, | |
| sleepMs: (Int) -> Void = { interval in | |
| Thread.sleep(forTimeInterval: TimeInterval(interval) / 1_000) | |
| }, |
Summary
CGPreflightScreenCaptureAccess()with the same fresh-helper retry used for Accessibility (orca computer: Accessibility permission_denied persists despite granted TCC access (preflight-unknown race on fresh helper process) #9458 / fix(computer-use): settle Accessibility trust before failing on fresh helper processes #10122).CGWindowListCreateImageprobe to warm tccd and detect grants that System Settings already shows as enabled.permissions --json, permission-UIisGranted, and screenshot gating through the settled check so the drag-assistant stops looping when Orca Computer Use is already listed/enabled.Fixes / related: #10372 (also related to #9458).
Built on top of #10122 (
AccessibilityTrustSettling) so both TCC preflight races are covered together.Test plan
ScreenCaptureTrustSettlingTests+ existingAccessibilityTrustSettlingTestsorca computer permissions --json→"screenshots": "granted"orca computer get-app-state --app com.google.Chrome --jsoncan capture (or report a non-permission error)not-grantedand setup UI still guides correctlyMade 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.