diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift index 7ecbdbf00..61ee27715 100644 --- a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift @@ -601,7 +601,7 @@ final class Provider { windowIndex: Int?, restoreWindow: Bool ) throws -> Snapshot { - guard accessibilityTrusted() else { + guard accessibilityTrustedSettled() else { // Why: agents retry failed observations. Only the explicit setup flow // should open macOS privacy prompts/settings; runtime calls stay quiet. throw ProviderError.coded( @@ -619,7 +619,7 @@ final class Provider { allowRecovery: restoreWindow ) let focusedTitle = stringAttribute(focused, kAXTitleAttribute as String) ?? app.name - let canCaptureScreenshot = includeScreenshot && screenCaptureTrusted() + let canCaptureScreenshot = includeScreenshot && screenCaptureTrustedSettled() guard let capture = WindowCapture.resolve( candidates: windowCandidates, titleHint: focusedTitle, @@ -1034,10 +1034,64 @@ private func accessibilityTrusted() -> Bool { AXIsProcessTrusted() } +private func accessibilityTrustedSettled() -> Bool { + // Fresh helper processes can receive transient TCC preflight denials before the real grant settles. + PermissionTrustSettling.settle(probe: accessibilityTrusted).settled +} + private func screenCaptureTrusted() -> Bool { CGPreflightScreenCaptureAccess() } +private func screenCaptureTrustedSettled() -> Bool { + PermissionTrustSettling.settleWithFallback( + finalTimeoutMs: 500, + probe: screenCaptureTrusted, + fallbackProbe: screenCaptureTrustedByCaptureProbe + ) +} + +private func permissionStatusSnapshotSettled() -> PermissionStatusSnapshot { + PermissionStatusSnapshotProbe.capture( + accessibilityProbe: accessibilityTrustedSettled, + screenshotsProbe: screenCaptureTrustedSettled + ) +} + +private func screenCaptureTrustedByCaptureProbe() -> Bool { + guard let infos = CGWindowListCopyWindowInfo( + [.optionOnScreenOnly], + kCGNullWindowID + ) as? [[String: Any]] else { + return false + } + let windows = infos.compactMap { info -> ScreenCaptureProbeWindow? in + guard let layer = info[kCGWindowLayer as String] as? Int, + let ownerPid = info[kCGWindowOwnerPID as String] as? NSNumber, + let number = info[kCGWindowNumber as String] as? NSNumber + else { + return nil + } + return ScreenCaptureProbeWindow( + layer: layer, + ownerPid: ownerPid.int32Value, + windowId: number.uint32Value + ) + } + guard let windowId = ScreenCaptureProbeWindowSelection.firstCrossProcessNormalWindow( + ownPid: ProcessInfo.processInfo.processIdentifier, + windows: windows + ) else { + return false + } + return CGWindowListCreateImage( + .null, + [.optionIncludingWindow], + CGWindowID(windowId), + [.boundsIgnoreFraming] + ) != nil +} + private func requestScreenCaptureAccess() -> Bool { CGRequestScreenCaptureAccess() } @@ -1065,6 +1119,38 @@ private func enableManualAccessibilityIfNeeded(_ appElement: AXUIElement, app: A private func focusedWindow(appElement: AXUIElement, app: AppDescriptor, visibleWindowCount: Int, allowRecovery: Bool) throws -> AXUIElement { let systemWide = AXUIElementCreateSystemWide() + if let window = lookupUsableWindow(systemWide: systemWide, appElement: appElement, app: app) { + return window + } + if allowRecovery { + recoverWindow(app) + if let window = lookupUsableWindow(systemWide: systemWide, appElement: appElement, app: app) { + return window + } + } + if visibleWindowCount > 0 { + var settledWindow: AXUIElement? + let outcome = PermissionTrustSettling.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.") + } + throw ProviderError.coded("window_not_found", "app '\(app.name)' has no accessibility window; make sure the app has a visible window, then retry with --restore-window.") +} + +private func lookupUsableWindow( + systemWide: AXUIElement, + appElement: AXUIElement, + app: AppDescriptor +) -> AXUIElement? { if let window = focusedSystemWindow(systemWide: systemWide, app: app) { return window } @@ -1072,31 +1158,9 @@ private func focusedWindow(appElement: AXUIElement, app: AppDescriptor, visibleW return window } if let windows = copyArray(appElement, kAXWindowsAttribute as String) { - if let window = windows.first(where: usableWindow) { - return window - } + return windows.first(where: usableWindow) } - if allowRecovery { - recoverWindow(app) - if let window = focusedSystemWindow(systemWide: systemWide, app: app) { - return window - } - if let window = copyElement(appElement, kAXFocusedWindowAttribute as String), usableWindow(window) { - return window - } - if let windows = copyArray(appElement, kAXWindowsAttribute as String) { - if let window = windows.first(where: usableWindow) { - return window - } - } - } - let permissionHint = visibleWindowCount > 0 - ? " The app has visible windows, so macOS Accessibility may need Orca Computer Use toggled off and on again in System Settings." - : "" - if visibleWindowCount > 0 { - throw ProviderError.coded("permission_denied", "app '\(app.name)' has visible windows but no accessibility window.\(permissionHint)") - } - throw ProviderError.coded("window_not_found", "app '\(app.name)' has no accessibility window; make sure the app has a visible window, then retry with --restore-window.") + return nil } private func focusedSystemWindow(systemWide: AXUIElement, app: AppDescriptor) -> AXUIElement? { @@ -2874,6 +2938,7 @@ private final class PermissionRuntime: NSObject, NSApplicationDelegate { windowController?.window?.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) } + windowController?.refreshPermissions() } func applicationDidBecomeActive(_ notification: Notification) { @@ -2890,6 +2955,7 @@ private final class PermissionWindowController: NSWindowController { private var dragAssistantPermission: PermissionKind? private let initialPermission: PermissionKind? private let terminateWhenDragAssistantCloses: Bool + private var permissionStatusRefresh: PermissionStatusRefreshCoordinator? convenience init(initialPermission: PermissionKind? = nil, terminateWhenDragAssistantCloses: Bool = false) { let window = NSWindow( @@ -2920,6 +2986,14 @@ private final class PermissionWindowController: NSWindowController { self.initialPermission = initialPermission self.terminateWhenDragAssistantCloses = terminateWhenDragAssistantCloses super.init(window: window) + permissionStatusRefresh = PermissionStatusRefreshCoordinator( + probe: permissionStatusSnapshotSettled, + handler: { [weak self] snapshot in + Task { @MainActor in + self?.applyPermissionStatus(snapshot) + } + } + ) } required init?(coder: NSCoder) { @@ -2976,21 +3050,25 @@ private final class PermissionWindowController: NSWindowController { } func refreshPermissions() { - if let initialPermission, initialPermission.isGranted { + permissionStatusRefresh?.refresh() + } + + private func applyPermissionStatus(_ snapshot: PermissionStatusSnapshot) { + if let initialPermission, initialPermission.isGranted(in: snapshot) { // Why: targeted permission helpers should finish once the requested // grant lands, even if other Computer Use permissions remain unset. completeDragAssistant() return } - if dragAssistantPermission?.isGranted == true { + if dragAssistantPermission?.isGranted(in: snapshot) == true { // Why: after one grant in full setup, the remaining missing permission // needs fresh guidance instead of the old assistant's instructions. closeDragAssistant() } - if PermissionKind.allCases.allSatisfy(\.isGranted) { + if PermissionKind.allCases.allSatisfy({ $0.isGranted(in: snapshot) }) { closeDragAssistant() } - (window?.contentView as? PermissionView)?.refreshPermissions() + (window?.contentView as? PermissionView)?.refreshPermissions(snapshot) } } @@ -3045,12 +3123,12 @@ private enum PermissionKind: CaseIterable { } } - var isGranted: Bool { + func isGranted(in snapshot: PermissionStatusSnapshot) -> Bool { switch self { case .accessibility: - accessibilityTrusted() + snapshot.accessibilityGranted case .screenshots: - screenCaptureTrusted() + snapshot.screenshotsGranted } } @@ -3071,6 +3149,7 @@ private final class PermissionView: NSView { private let close: () -> Void private var contentStack: NSStackView? private var contentConstraints: [NSLayoutConstraint] = [] + private var permissionStatus: PermissionStatusSnapshot? init(frame frameRect: NSRect, showDragAssistant: @escaping (PermissionKind) -> Void, close: @escaping () -> Void) { self.showDragAssistant = showDragAssistant @@ -3107,12 +3186,22 @@ private final class PermissionView: NSView { icon.heightAnchor.constraint(equalToConstant: 58) ]) - let missingPermissions = PermissionKind.allCases.filter { !$0.isGranted } - let ready = missingPermissions.isEmpty + let missingPermissions = permissionStatus.map { snapshot in + PermissionKind.allCases.filter { !$0.isGranted(in: snapshot) } + } ?? [] + let checking = permissionStatus == nil + let ready = !checking && missingPermissions.isEmpty - let title = label(ready ? "Computer Use is Ready" : "Enable Orca Computer Use", size: 22, weight: .bold) + let titleText = checking + ? "Checking Computer Use" + : (ready ? "Computer Use is Ready" : "Enable Orca Computer Use") + let title = label(titleText, size: 22, weight: .bold) let subtitle = label( - ready ? "Orca can use local apps when you ask." : "Grant permissions so Orca can use apps when you ask.", + checking + ? "Checking Accessibility and Screenshots." + : (ready + ? "Orca can use local apps when you ask." + : "Grant permissions so Orca can use apps when you ask."), size: 12, weight: .regular ) @@ -3129,7 +3218,16 @@ private final class PermissionView: NSView { header.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true subtitle.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -10).isActive = true - if ready { + if checking { + let progress = NSProgressIndicator() + progress.style = .spinning + progress.controlSize = .small + progress.translatesAutoresizingMaskIntoConstraints = false + progress.startAnimation(nil) + stack.addArrangedSubview(progress) + progress.setContentHuggingPriority(.required, for: .horizontal) + progress.centerXAnchor.constraint(equalTo: stack.centerXAnchor).isActive = true + } else if ready { stack.addArrangedSubview(doneButton()) } else { for permission in missingPermissions { @@ -3149,8 +3247,9 @@ private final class PermissionView: NSView { NSLayoutConstraint.activate(contentConstraints) } - func refreshPermissions() { - // Why: TCC grants can change in System Settings while this window stays open. + func refreshPermissions(_ snapshot: PermissionStatusSnapshot) { + guard permissionStatus != snapshot else { return } + permissionStatus = snapshot build() } @@ -4039,14 +4138,16 @@ private func runPermissionCheck(initialPermission: PermissionKind? = nil) { } private func printPermissionStatus() { - let accessibility = accessibilityTrusted() ? "granted" : "not-granted" - let screenshots = screenCaptureTrusted() ? "granted" : "not-granted" + let snapshot = permissionStatusSnapshotSettled() + let accessibility = snapshot.accessibilityGranted ? "granted" : "not-granted" + let screenshots = snapshot.screenshotsGranted ? "granted" : "not-granted" print(#"{"accessibility":"\#(accessibility)","screenshots":"\#(screenshots)"}"#) } private func writePermissionStatus(to path: String) { - let accessibility = accessibilityTrusted() ? "granted" : "not-granted" - let screenshots = screenCaptureTrusted() ? "granted" : "not-granted" + let snapshot = permissionStatusSnapshotSettled() + let accessibility = snapshot.accessibilityGranted ? "granted" : "not-granted" + let screenshots = snapshot.screenshotsGranted ? "granted" : "not-granted" let text = #"{"accessibility":"\#(accessibility)","screenshots":"\#(screenshots)"}"# do { try text.write(toFile: path, atomically: true, encoding: .utf8) diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/PermissionStatusSnapshot.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/PermissionStatusSnapshot.swift new file mode 100644 index 000000000..a1e71edeb --- /dev/null +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/PermissionStatusSnapshot.swift @@ -0,0 +1,116 @@ +import Dispatch +import Foundation + +public struct PermissionStatusSnapshot: Equatable, Sendable { + public let accessibilityGranted: Bool + public let screenshotsGranted: Bool + + public init(accessibilityGranted: Bool, screenshotsGranted: Bool) { + self.accessibilityGranted = accessibilityGranted + self.screenshotsGranted = screenshotsGranted + } +} + +public enum PermissionStatusSnapshotProbe { + public typealias Probe = @Sendable () -> Bool + + private static let probeQueue = DispatchQueue( + label: "com.stablyai.orca.computer-use-permission-status", + attributes: .concurrent + ) + + public static func capture( + accessibilityProbe: @escaping Probe, + screenshotsProbe: @escaping Probe + ) -> PermissionStatusSnapshot { + let result = PermissionStatusSnapshotResult() + let group = DispatchGroup() + + group.enter() + probeQueue.async { + result.recordAccessibility(accessibilityProbe()) + group.leave() + } + group.enter() + probeQueue.async { + result.recordScreenshots(screenshotsProbe()) + group.leave() + } + group.wait() + return result.snapshot + } +} + +public final class PermissionStatusRefreshCoordinator: @unchecked Sendable { + public typealias SnapshotProbe = @Sendable () -> PermissionStatusSnapshot + public typealias SnapshotHandler = @Sendable (PermissionStatusSnapshot) -> Void + + private let callbackQueue: DispatchQueue + private let handler: SnapshotHandler + private let probe: SnapshotProbe + private let stateLock = NSLock() + private let workerQueue: DispatchQueue + private var refreshInFlight = false + + public init( + workerQueue: DispatchQueue = DispatchQueue( + label: "com.stablyai.orca.computer-use-permission-refresh", + qos: .userInitiated + ), + callbackQueue: DispatchQueue = .main, + probe: @escaping SnapshotProbe, + handler: @escaping SnapshotHandler + ) { + self.workerQueue = workerQueue + self.callbackQueue = callbackQueue + self.probe = probe + self.handler = handler + } + + public func refresh() { + stateLock.lock() + guard !refreshInFlight else { + stateLock.unlock() + return + } + refreshInFlight = true + stateLock.unlock() + + workerQueue.async { [self] in + let snapshot = probe() + callbackQueue.async { [self] in + stateLock.lock() + refreshInFlight = false + stateLock.unlock() + handler(snapshot) + } + } + } +} + +private final class PermissionStatusSnapshotResult: @unchecked Sendable { + private let lock = NSLock() + private var accessibilityGranted = false + private var screenshotsGranted = false + + var snapshot: PermissionStatusSnapshot { + lock.lock() + defer { lock.unlock() } + return PermissionStatusSnapshot( + accessibilityGranted: accessibilityGranted, + screenshotsGranted: screenshotsGranted + ) + } + + func recordAccessibility(_ granted: Bool) { + lock.lock() + accessibilityGranted = granted + lock.unlock() + } + + func recordScreenshots(_ granted: Bool) { + lock.lock() + screenshotsGranted = granted + lock.unlock() + } +} diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/PermissionTrustSettling.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/PermissionTrustSettling.swift new file mode 100644 index 000000000..806126644 --- /dev/null +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/PermissionTrustSettling.swift @@ -0,0 +1,73 @@ +import Foundation + +public enum PermissionTrustSettling { + public struct Outcome: Equatable { + public let settled: Bool + public let attempts: Int + public let waitedMs: Int + + public init(settled: Bool, attempts: Int, waitedMs: Int) { + self.settled = settled + self.attempts = attempts + self.waitedMs = waitedMs + } + } + + public static let defaultTimeoutMs = 1_500 + public static let defaultIntervalMs = 100 + + public static func settle( + timeoutMs: Int = defaultTimeoutMs, + intervalMs: Int = defaultIntervalMs, + sleepMs: (Int) -> Void = { interval in + Thread.sleep(forTimeInterval: TimeInterval(interval) / 1_000) + }, + probe: () -> Bool + ) -> Outcome { + precondition(timeoutMs >= 0, "timeoutMs must not be negative") + precondition(intervalMs > 0, "intervalMs must be positive") + var attempts = 0 + var waitedMs = 0 + while true { + attempts += 1 + if probe() { + return Outcome(settled: true, attempts: attempts, waitedMs: waitedMs) + } + if waitedMs >= timeoutMs { + return Outcome(settled: false, attempts: attempts, waitedMs: waitedMs) + } + let interval = min(intervalMs, timeoutMs - waitedMs) + sleepMs(interval) + waitedMs += interval + } + } + + public static func settleWithFallback( + initialTimeoutMs: Int = defaultTimeoutMs, + finalTimeoutMs: Int, + intervalMs: Int = defaultIntervalMs, + sleepMs: (Int) -> Void = { interval in + Thread.sleep(forTimeInterval: TimeInterval(interval) / 1_000) + }, + probe: () -> Bool, + fallbackProbe: () -> Bool + ) -> Bool { + if settle( + timeoutMs: initialTimeoutMs, + intervalMs: intervalMs, + sleepMs: sleepMs, + probe: probe + ).settled { + return true + } + if fallbackProbe() { + return true + } + return settle( + timeoutMs: finalTimeoutMs, + intervalMs: intervalMs, + sleepMs: sleepMs, + probe: probe + ).settled + } +} diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/ScreenCaptureProbeWindowSelection.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/ScreenCaptureProbeWindowSelection.swift new file mode 100644 index 000000000..36b4346a8 --- /dev/null +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/ScreenCaptureProbeWindowSelection.swift @@ -0,0 +1,22 @@ +public struct ScreenCaptureProbeWindow: Equatable { + public let layer: Int + public let ownerPid: Int32 + public let windowId: UInt32 + + public init(layer: Int, ownerPid: Int32, windowId: UInt32) { + self.layer = layer + self.ownerPid = ownerPid + self.windowId = windowId + } +} + +public enum ScreenCaptureProbeWindowSelection { + public static func firstCrossProcessNormalWindow( + ownPid: Int32, + windows: [ScreenCaptureProbeWindow] + ) -> UInt32? { + windows.first { window in + window.layer == 0 && window.ownerPid != ownPid + }?.windowId + } +} diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/PermissionStatusSnapshotTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/PermissionStatusSnapshotTests.swift new file mode 100644 index 000000000..7aff74ee1 --- /dev/null +++ b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/PermissionStatusSnapshotTests.swift @@ -0,0 +1,126 @@ +import Dispatch +@testable import OrcaComputerUseMacOSCore +import XCTest + +final class PermissionStatusSnapshotTests: XCTestCase { + func testCapturesBothPermissionResults() { + let snapshot = PermissionStatusSnapshotProbe.capture( + accessibilityProbe: { true }, + screenshotsProbe: { false } + ) + + XCTAssertEqual( + snapshot, + PermissionStatusSnapshot(accessibilityGranted: true, screenshotsGranted: false) + ) + } + + func testRunsPermissionProbesConcurrently() { + let accessibilityStarted = DispatchSemaphore(value: 0) + let screenshotsStarted = DispatchSemaphore(value: 0) + let releaseProbes = DispatchSemaphore(value: 0) + let finished = expectation(description: "permission snapshot") + + DispatchQueue.global().async { + _ = PermissionStatusSnapshotProbe.capture( + accessibilityProbe: { + accessibilityStarted.signal() + releaseProbes.wait() + return true + }, + screenshotsProbe: { + screenshotsStarted.signal() + releaseProbes.wait() + return true + } + ) + finished.fulfill() + } + + XCTAssertEqual(accessibilityStarted.wait(timeout: .now() + 1), .success) + XCTAssertEqual(screenshotsStarted.wait(timeout: .now() + 1), .success) + releaseProbes.signal() + releaseProbes.signal() + wait(for: [finished], timeout: 1) + } + + func testCoalescesRefreshesWhileProbeIsRunning() { + let callbackQueue = DispatchQueue(label: "permission-status-test-callback") + let probeStarted = DispatchSemaphore(value: 0) + let releaseProbe = DispatchSemaphore(value: 0) + let handled = expectation(description: "snapshot handled") + let probeCount = LockedCounter() + let coordinator = PermissionStatusRefreshCoordinator( + callbackQueue: callbackQueue, + probe: { + probeCount.increment() + probeStarted.signal() + releaseProbe.wait() + return PermissionStatusSnapshot( + accessibilityGranted: true, + screenshotsGranted: true + ) + }, + handler: { _ in handled.fulfill() } + ) + + coordinator.refresh() + XCTAssertEqual(probeStarted.wait(timeout: .now() + 1), .success) + coordinator.refresh() + coordinator.refresh() + releaseProbe.signal() + + wait(for: [handled], timeout: 1) + XCTAssertEqual(probeCount.value, 1) + } + + func testAllowsRefreshAfterPreviousSnapshotWasHandled() { + let callbackQueue = DispatchQueue(label: "permission-status-test-callback") + let firstHandled = expectation(description: "first snapshot handled") + let secondHandled = expectation(description: "second snapshot handled") + let probeCount = LockedCounter() + let coordinator = PermissionStatusRefreshCoordinator( + callbackQueue: callbackQueue, + probe: { + let count = probeCount.increment() + return PermissionStatusSnapshot( + accessibilityGranted: count == 2, + screenshotsGranted: false + ) + }, + handler: { snapshot in + if snapshot.accessibilityGranted { + secondHandled.fulfill() + } else { + firstHandled.fulfill() + } + } + ) + + coordinator.refresh() + wait(for: [firstHandled], timeout: 1) + coordinator.refresh() + + wait(for: [secondHandled], timeout: 1) + XCTAssertEqual(probeCount.value, 2) + } +} + +private final class LockedCounter: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + + var value: Int { + lock.lock() + defer { lock.unlock() } + return count + } + + @discardableResult + func increment() -> Int { + lock.lock() + defer { lock.unlock() } + count += 1 + return count + } +} diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/PermissionTrustSettlingTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/PermissionTrustSettlingTests.swift new file mode 100644 index 000000000..c3f3956ac --- /dev/null +++ b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/PermissionTrustSettlingTests.swift @@ -0,0 +1,59 @@ +import Testing +@testable import OrcaComputerUseMacOSCore + +@Suite("PermissionTrustSettling") +struct PermissionTrustSettlingTests { + @Test("already-trusted probe returns immediately") + func immediateSuccess() { + var sleeps: [Int] = [] + let outcome = PermissionTrustSettling.settle( + sleepMs: { sleeps.append($0) }, + probe: { true } + ) + + #expect(outcome == .init(settled: true, attempts: 1, waitedMs: 0)) + #expect(sleeps.isEmpty) + } + + @Test("transient denial settles after retries") + func lateGrant() { + var calls = 0 + var sleeps: [Int] = [] + let outcome = PermissionTrustSettling.settle( + sleepMs: { sleeps.append($0) }, + probe: { + calls += 1 + return calls >= 4 + } + ) + + #expect(outcome == .init(settled: true, attempts: 4, waitedMs: 300)) + #expect(sleeps == [100, 100, 100]) + } + + @Test("persistent denial stops at the timeout") + func neverGranted() { + let outcome = PermissionTrustSettling.settle( + timeoutMs: 1_000, + intervalMs: 300, + sleepMs: { _ in }, + probe: { false } + ) + + #expect(outcome == .init(settled: false, attempts: 5, waitedMs: 1_000)) + } + + @Test("final interval is clamped to the timeout") + func clampsFinalInterval() { + var sleeps: [Int] = [] + let outcome = PermissionTrustSettling.settle( + timeoutMs: 250, + intervalMs: 100, + sleepMs: { sleeps.append($0) }, + probe: { false } + ) + + #expect(sleeps == [100, 100, 50]) + #expect(outcome == .init(settled: false, attempts: 4, waitedMs: 250)) + } +} diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ScreenCapturePermissionSettlingTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ScreenCapturePermissionSettlingTests.swift new file mode 100644 index 000000000..d53991d36 --- /dev/null +++ b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ScreenCapturePermissionSettlingTests.swift @@ -0,0 +1,79 @@ +import Testing +@testable import OrcaComputerUseMacOSCore + +@Suite("Screen Capture permission settling") +struct ScreenCapturePermissionSettlingTests { + @Test("initial preflight success skips fallback") + func initialSuccess() { + var fallbackCalls = 0 + let trusted = PermissionTrustSettling.settleWithFallback( + finalTimeoutMs: 500, + sleepMs: { _ in }, + probe: { true }, + fallbackProbe: { + fallbackCalls += 1 + return true + } + ) + + #expect(trusted) + #expect(fallbackCalls == 0) + } + + @Test("capture fallback can establish trust") + func fallbackSuccess() { + var fallbackCalls = 0 + let trusted = PermissionTrustSettling.settleWithFallback( + initialTimeoutMs: 200, + finalTimeoutMs: 200, + intervalMs: 100, + sleepMs: { _ in }, + probe: { false }, + fallbackProbe: { + fallbackCalls += 1 + return true + } + ) + + #expect(trusted) + #expect(fallbackCalls == 1) + } + + @Test("preflight is retried after fallback failure") + func finalPreflightSuccess() { + var probeCalls = 0 + let trusted = PermissionTrustSettling.settleWithFallback( + initialTimeoutMs: 100, + finalTimeoutMs: 200, + intervalMs: 100, + sleepMs: { _ in }, + probe: { + probeCalls += 1 + return probeCalls == 4 + }, + fallbackProbe: { false } + ) + + #expect(trusted) + #expect(probeCalls == 4) + } + + @Test("persistent denial remains denied") + func persistentDenial() { + var fallbackCalls = 0 + let trusted = PermissionTrustSettling.settleWithFallback( + initialTimeoutMs: 100, + finalTimeoutMs: 100, + intervalMs: 100, + sleepMs: { _ in }, + probe: { false }, + fallbackProbe: { + fallbackCalls += 1 + return false + } + ) + + #expect(!trusted) + #expect(fallbackCalls == 1) + } +} diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ScreenCaptureProbeWindowSelectionTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ScreenCaptureProbeWindowSelectionTests.swift new file mode 100644 index 000000000..96afd6fbc --- /dev/null +++ b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ScreenCaptureProbeWindowSelectionTests.swift @@ -0,0 +1,44 @@ +import Testing +@testable import OrcaComputerUseMacOSCore + +@Suite("Screen capture probe window selection") +struct ScreenCaptureProbeWindowSelectionTests { + @Test("own process windows cannot prove cross-app capture permission") + func excludesOwnWindows() { + let selected = ScreenCaptureProbeWindowSelection.firstCrossProcessNormalWindow( + ownPid: 42, + windows: [ + .init(layer: 0, ownerPid: 42, windowId: 1), + .init(layer: 0, ownerPid: 84, windowId: 2) + ] + ) + + #expect(selected == 2) + } + + @Test("non-normal windows are skipped") + func excludesNonNormalWindows() { + let selected = ScreenCaptureProbeWindowSelection.firstCrossProcessNormalWindow( + ownPid: 42, + windows: [ + .init(layer: 1, ownerPid: 84, windowId: 1), + .init(layer: 0, ownerPid: 84, windowId: 2) + ] + ) + + #expect(selected == 2) + } + + @Test("no cross-process normal window returns nil") + func noCandidate() { + let selected = ScreenCaptureProbeWindowSelection.firstCrossProcessNormalWindow( + ownPid: 42, + windows: [ + .init(layer: 0, ownerPid: 42, windowId: 1), + .init(layer: 1, ownerPid: 84, windowId: 2) + ] + ) + + #expect(selected == nil) + } +}