Skip to content

fix(computer-use): settle Accessibility trust before failing on fresh helper processes - #10122

Closed
tomdebres wants to merge 2 commits into
stablyai:mainfrom
tomdebres:fix/computer-use-ax-preflight-settle
Closed

tomdebres wants to merge 2 commits into
stablyai:mainfrom
tomdebres:fix/computer-use-ax-preflight-settle

Conversation

@tomdebres

@tomdebres tomdebres commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

orca computer permissions reports accessibility: granted while every windowed action (get-app-state, click, …) fails permission_denied — the diagnostic says healthy while the tool is unusable. Filed as #9159, consolidated into #9458.

Root cause (from the tccd IPC trace in #9458)

Every CLI invocation spawns a fresh, short-lived helper process. tccd answers a freshly spawned process with preflight_unknown / do_not_cache (auth_reason=5), so the first Accessibility answers a new pid sees can be denied while the grant is real — the same pid flips to granted moments later in the trace. One-shot checks therefore lose the race on every invocation:

  • AXIsProcessTrusted() one-shots gate buildSnapshot and the permission-status printers.
  • The AX window reads behind "app has visible windows but no accessibility window" hit the same uncached-denial window.

Fix

  • New AccessibilityTrustSettling.settle: probe immediately, then poll on 100 ms boundaries, capped at 1.5 s. Already-trusted processes pass on the first probe — zero added latency on the happy path; the cap only spends time in the exact state that used to hard-fail.
  • Wired into: the buildSnapshot trust gate, both permission-status printers, and the "visible windows but no accessibility window" path — which now retries the actual AX window lookup (not just the trust bit) and reports how long reads stayed blocked if it still fails.
  • Extracted lookupUsableWindow to dedupe the identical pre-/post-recovery lookup blocks.
  • Deterministic unit tests for the settle policy via injected sleep (no timing flake).

Validation

Fixes #9458 (and the already-consolidated #9159).

ELI5

macOS said Accessibility was allowed, but every computer-use click still failed right after a fresh helper start. The app now waits for that permission check to settle before giving up, so tools work once you have granted access.

@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a4a13baf-1325-4086-b778-618718c97774

📥 Commits

Reviewing files that changed from the base of the PR and between bc1e049 and 89174b5.

📒 Files selected for processing (3)
  • native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift
  • native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/AccessibilityTrustSettling.swift
  • native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AccessibilityTrustSettlingTests.swift
🚧 Files skipped from review as they are similar to previous changes (3)
  • native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/AccessibilityTrustSettling.swift
  • native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AccessibilityTrustSettlingTests.swift
  • native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift

📝 Walkthrough

Walkthrough

Adds a reusable Accessibility trust-settling poller with outcome tracking and tests for success, timeout, and interval clamping. Runtime snapshot and CLI permission checks now use settled trust results. Focused-window lookup gains recovery and trust-settling retries, with distinct permission_denied and window_not_found errors.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, root cause, fix, and validation, but it omits most required template sections and checklist details. Add the required Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections, including completed test checks and platform review confirmation.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary fix: settling Accessibility trust before rejecting fresh helper processes.
Linked Issues check ✅ Passed The changes address #9458 by retrying transient Accessibility trust failures, applying settling to window lookup, and adding deterministic regression tests.
Out of Scope Changes check ✅ Passed All changes support #9458 and remain limited to Accessibility settling, related window lookup handling, and focused unit tests.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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.

@tomdebres

Copy link
Copy Markdown
Contributor Author

Gentle bump on this one — small change (+160/−24, 3 files, all under native/computer-use-macos/) and it's been quiet since the 23rd.

track-community-pr passes and the status rollup is green. Still cleanly mergeable against current main, and nothing upstream has touched the files it changes, so no rebase needed.

Happy to split or rework it if the approach isn't the one you'd want.

@tomdebres
tomdebres force-pushed the fix/computer-use-ax-preflight-settle branch from 43ecfc4 to de872a5 Compare July 29, 2026 06:15
Comment on lines +1070 to +1086
if visibleWindowCount > 0 {
// Why: on a fresh helper process AX reads can be denied by tccd's
// uncached preflight answer for a moment even though trust is granted
// (#9458) — the "visible windows but no accessibility window" state.
// Give the AX session time to settle before declaring it broken.
var settledWindow: AXUIElement?
let outcome = AccessibilityTrustSettling.settle {
settledWindow = lookupUsableWindow(systemWide: systemWide, appElement: appElement, app: app)
return settledWindow != nil
}
if let window = settledWindow, outcome.settled {
return window
}
throw ProviderError.coded(
"permission_denied",
"app '\(app.name)' has visible windows but no accessibility window (AX reads stayed blocked for \(outcome.waitedMs)ms after retries). macOS Accessibility may need Orca Computer Use toggled off and on again in System Settings."
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Stacked settle timeouts can reach 3 s end-to-end

buildSnapshot first calls accessibilityTrustedSettled() (up to 1.5 s), and if that succeeds the focusedWindow settle loop can add another 1.5 s. Both phases run independently, so a request in the race window can block for up to 3 s total rather than the 1.5 s cap described in the PR.

In practice the two races are correlated — once tccd caches the trust answer for the pid, both AXIsProcessTrusted and the AX attribute reads should resolve together, so the second loop should rarely add significant time. But the theoretical ceiling is worth documenting in a comment alongside the defaultTimeoutMs constant or in focusedWindow, especially since the error message already surfaces outcome.waitedMs and users may be surprised by a longer-than-expected stall.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Documented on defaultTimeoutMs: a snapshot can run the two settle phases back-to-back, so the worst-case stall is 2x the cap; tccd's cached answer makes the second phase near-instant in practice.

Comment on lines +50 to +61
@Test("final interval is clamped so total wait never exceeds the timeout")
func clampsFinalInterval() {
var sleeps: [Int] = []
let outcome = AccessibilityTrustSettling.settle(
timeoutMs: 250,
intervalMs: 100,
sleepMs: { sleeps.append($0) },
probe: { false }
)
#expect(sleeps == [100, 100, 50])
#expect(outcome.waitedMs == 250)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 clampsFinalInterval leaves outcome.attempts unverified

The test confirms sleep durations ([100, 100, 50]) and waitedMs but not attempts. Based on the loop logic the expected count is 4 (three sleeps + one final probe after the last sleep hits the timeout). Adding #expect(outcome.attempts == 4) would fully pin the boundary condition and make it as tight as the neverGranted test immediately above it.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added #expect(outcome.attempts == 4) to clampsFinalInterval — all 4 suite tests pass.

@greptile-apps

greptile-apps Bot commented Jul 29, 2026

Copy link
Copy Markdown

Greptile Summary

This PR fixes a tccd race condition that caused fresh helper processes to receive preflight_unknown / do_not_cache responses for Accessibility trust, making every windowed action fail with permission_denied even when the grant was real. A new AccessibilityTrustSettling.settle polls until the trust answer stabilises (max 1.5 s, 100 ms intervals), with an immediate fast-path for already-trusted processes.

  • AccessibilityTrustSettling.swift: New retry/polling primitive with injectable sleepMs and probe closures, deterministically tested with four unit tests covering immediate success, late grant, never-granted timeout, and interval clamping.
  • main.swift: accessibilityTrustedSettled() replaces bare AXIsProcessTrusted() in buildSnapshot, printPermissionStatus, and writePermissionStatus; focusedWindow gains a dedicated settle loop for the "visible windows but no AX window" case plus a lookupUsableWindow helper to remove duplicated lookup blocks.
  • AccessibilityTrustSettlingTests.swift: Four new unit tests validate all boundary conditions of the settle loop using injected sleep/probe, with no real timing dependency.

Confidence Score: 4/5

Safe to merge — the settling loop is bounded, the happy path adds zero latency, and the unit tests are deterministic with injected sleep.

The core settle implementation is correct: interval clamping, the timeout boundary, and the probe-first ordering are all verified by the unit tests and confirmed by manual trace. The refactored lookupUsableWindow is a clean deduplication. Two observations worth a follow-up: the trust-check settle and the AX-read settle in focusedWindow are independent and can stack, theoretically reaching 3 s in the worst case; and the clampsFinalInterval test omits an attempts assertion. Neither affects correctness today.

Files Needing Attention: The stacked-timeout interaction in main.swift (lines 604 and 1070–1086) is the area most worth a second read before merging.

Important Files Changed

Filename Overview
native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/AccessibilityTrustSettling.swift New settling primitive: probe-then-poll loop with correct boundary conditions, interval clamping, and precondition guard against zero/negative intervals.
native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift Wires settling into three trust-gate sites and refactors focusedWindow with a dedicated settle loop for the AX-reads race; worst-case latency can stack across both settle phases in a single invocation.
native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AccessibilityTrustSettlingTests.swift Four deterministic unit tests cover all key settle-loop paths; clampsFinalInterval leaves outcome.attempts unchecked but the sleep-sequence and waitedMs assertions are sufficient coverage of the clamping logic.

Sequence Diagram

sequenceDiagram
    participant CLI as CLI Invocation
    participant main as main.swift
    participant settle as AccessibilityTrustSettling
    participant tccd as tccd (macOS)
    participant AX as AX APIs

    CLI->>main: buildSnapshot / printPermissionStatus
    main->>settle: settle(probe: AXIsProcessTrusted)
    loop until trusted or 1500ms elapsed
        settle->>tccd: AXIsProcessTrusted()
        tccd-->>settle: preflight_unknown (denied) OR granted
        alt granted
            settle-->>main: Outcome(settled: true, waitedMs: N)
        else still denied and timeout remaining
            settle->>settle: sleep 100ms
        end
    end
    settle-->>main: Outcome(settled: false) → throw permission_denied

    main->>AX: focusedWindow → lookupUsableWindow (fast path)
    AX-->>main: window OR nil

    alt "no window found AND visibleWindowCount > 0"
        main->>settle: settle(probe: lookupUsableWindow)
        loop until window found or 1500ms elapsed
            settle->>AX: lookupUsableWindow
            AX-->>settle: window OR nil
            alt window found
                settle-->>main: Outcome(settled: true)
                main-->>CLI: return window
            else still nil and timeout remaining
                settle->>settle: sleep 100ms
            end
        end
        settle-->>main: Outcome(settled: false)
        main-->>CLI: throw permission_denied with waitedMs
    end
Loading

Reviews (1): Last reviewed commit: "fix(computer-use): settle Accessibility ..." | Re-trigger Greptile

@tomdebres
tomdebres force-pushed the fix/computer-use-ax-preflight-settle branch from de872a5 to 2ec9487 Compare August 4, 2026 06:15
tomdebres and others added 2 commits August 7, 2026 18:29
… 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
(stablyai#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 (stablyai#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)
@tomdebres
tomdebres force-pushed the fix/computer-use-ax-preflight-settle branch from 2ec9487 to 89174b5 Compare August 7, 2026 17:29
@coderabbitai

coderabbitai Bot commented Aug 7, 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.

@tomdebres

Copy link
Copy Markdown
Contributor Author

Closing as superseded: #13025 (merged 2026-08-07) lands the same settle mechanism this PR proposed — the PermissionTrustSettling loop is line-for-line the AccessibilityTrustSettling core from here (same Outcome shape, defaults, and final-interval clamp) — generalized to screen-capture checks with broader tests, including coverage of the buildSnapshot double-settle path this PR's review discussed. Nothing in this branch remains that main doesn't now do better. Thanks to whoever carried it over the line.

@tomdebres tomdebres closed this Aug 9, 2026
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.

orca computer: Accessibility permission_denied persists despite granted TCC access (preflight-unknown race on fresh helper process)

3 participants