Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

Spaces macOS: no permission prompt before the permissions step (CUA-2342) (#6002)

cua-agents[bot]99294f16c352
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift
index ae385c4f18..d6c226234f 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift
@@ -184,9 +184,7 @@ enum ServiceLauncher {
NSLog("cua-spaces service: Screen Recording and Accessibility are asked %@",
appAsks ? "by the app (its permissions screen)" : "here (macOS's prompts)")
if !spec.args.contains("--no-desktop") && !appAsks {
- if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() }
- let prompt = "AXTrustedCheckOptionPrompt" // kAXTrustedCheckOptionPrompt
- _ = AXIsProcessTrustedWithOptions([prompt: true] as CFDictionary)
+ PermissionRequester.requestScreenRecordingAndAccessibility()
}
guard let pid = spawn(spec.args, env: spec.env, logPath: spec.logPath, workingDir: spec.workingDir) else {
exit(1)
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
index d04edee951..5ef1c75eef 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
@@ -230,6 +230,8 @@ public final class AppModel {
}
self.host.onChange = { [weak self] in self?.recompose() }
followChecklist()
+ // No notification prompt before the first run is done.
+ PermissionRequester.firstRunDone = { [weak onboarding] in onboarding?.completed ?? false }
// Done's "Launch at login" checkbox is the user's choice.
onboarding.onLaunchAtLogin = { [weak self] on in self?.setLaunchAtLogin(on) }
// Which experiments are on: the day's `cua_app_active` carries them.
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift
index 73ff1cd4d2..71efbf5f87 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift
@@ -723,7 +723,6 @@ public final class DevicesModel {
@MainActor
final class DeviceNotifier: NSObject, UNUserNotificationCenterDelegate {
static let shared = DeviceNotifier()
- private var authorized: Bool?
/// A notification was clicked (its identifier): the app opens its main UI.
var onOpen: ((String) -> Void)?
@@ -739,10 +738,7 @@ final class DeviceNotifier: NSObject, UNUserNotificationCenterDelegate {
content.sound = .default
let request = UNNotificationRequest(identifier: "device-\(prompt.deviceId)", content: content, trigger: nil)
Task {
- if authorized == nil {
- authorized = (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false
- }
- guard authorized == true else { return }
+ guard await PermissionRequester.notificationsAuthorized(center) else { return }
try? await center.add(request)
}
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionGuide.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionGuide.swift
index 45dfbcb89f..4343ec77f6 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionGuide.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionGuide.swift
@@ -51,6 +51,13 @@ public enum PermissionGuide {
private static var controller: PermissionFlowController?
+ /// How a pane is opened, what the guide draws over it, and what runs on
+ /// a grant. Replaced in tests, which must not open System Settings or
+ /// draw panels.
+ nonisolated(unsafe) static var openPane: (URL) -> Void = { NSWorkspace.shared.open($0) }
+ nonisolated(unsafe) static var showsGuide = true
+ nonisolated(unsafe) static var grantedHook: ((PermissionFlowPane) -> Void)?
+
// MARK: - Listed or not (CUA-2283)
/// What the guide tells the person to do in a pane's list.
@@ -85,7 +92,34 @@ public enum PermissionGuide {
/// The line of the switch-on hint.
nonisolated static func switchOnText(appName: String) -> String {
- "Switch on \(appName) in the list."
+ "Turn on \(appName) in System Settings, then come back."
+ }
+
+ /// Where one permission stands. macOS never prompts again once it is
+ /// denied or switched off, so only the first ask may use its own prompt;
+ /// after that "Allow" means opening the pane.
+ enum State: Equatable {
+ case notDetermined, off, granted
+ }
+
+ /// Granted comes from the preflight call; the app having a row in the
+ /// list (seen granted once, see `isListed`) tells off from not asked.
+ nonisolated static func state(granted: Bool, listed: Bool) -> State {
+ granted ? .granted : (listed ? .off : .notDetermined)
+ }
+
+ /// Polls until `pane` reads as granted (true) or `deadline` passes (false),
+ /// so the step completes without a second click.
+ nonisolated static func waitForGrant(_ pane: PermissionFlowPane,
+ read: () async -> Set<PermissionFlowPane>,
+ interval: Duration, giveUpAfter: Duration) async -> Bool {
+ let clock = ContinuousClock()
+ let deadline = clock.now + giveUpAfter
+ while !Task.isCancelled, clock.now < deadline {
+ if await read().contains(pane) { return true }
+ try? await Task.sleep(for: interval)
+ }
+ return false
}
private static var hint: NSPanel?
@@ -175,8 +209,13 @@ public enum PermissionGuide {
// Already in the list: say "switch on", not "drag".
if instruction(for: pane, listed: isListed(pane)) == .switchOn, let u = URL(string: url) {
controller?.closePanel()
- NSWorkspace.shared.open(u)
- showSwitchOnHint(for: pane, url: url)
+ openPane(u)
+ if showsGuide { showSwitchOnHint(for: pane, url: url) }
+ watch(pane)
+ return true
+ }
+ guard showsGuide else {
+ if let u = URL(string: url) { openPane(u) }
watch(pane)
return true
}
@@ -239,7 +278,7 @@ public enum PermissionGuide {
/// The answer `preflight-permissions` gives (run by main.swift).
public nonisolated static func preflightReport() -> String {
- "screen-recording=\(CGPreflightScreenCaptureAccess() ? 1 : 0) accessibility=\(AXIsProcessTrusted() ? 1 : 0)"
+ "screen-recording=\(PermissionRequester.screenRecordingGranted() ? 1 : 0) accessibility=\(PermissionRequester.accessibilityGranted() ? 1 : 0)"
}
/// What follows a grant.
@@ -293,6 +332,7 @@ public enum PermissionGuide {
private static func granted(_ pane: PermissionFlowPane, others: Set<PermissionFlowPane>) {
watching = nil
reopening?.cancel()
+ if let hook = grantedHook { return hook(pane) }
controller?.closePanel()
closeHint()
let followUp = {
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionRequester.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionRequester.swift
new file mode 100644
index 0000000000..8c25ae29f0
--- /dev/null
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionRequester.swift
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import ApplicationServices
+import CoreGraphics
+import Foundation
+import UserNotifications
+
+/// The only place in the app that may raise a macOS permission prompt
+/// (Screen Recording, Accessibility, Notifications). Everything else reads
+/// status with the non-prompting preflight calls. PermissionPromptGuardTests
+/// fails the build when a prompting API appears in any other file.
+///
+/// Before the first run's permissions step nothing may prompt: macOS's bare
+/// popup would appear over the sign-in, ahead of the app's own guide.
+public enum PermissionRequester {
+ /// Set by the app: notifications may be asked for once the first run is done.
+ @MainActor public static var firstRunDone: () -> Bool = { false }
+
+ /// Screen Recording, shown without asking.
+ public static func screenRecordingGranted() -> Bool { CGPreflightScreenCaptureAccess() }
+
+ /// Accessibility, shown without asking.
+ public static func accessibilityGranted() -> Bool { AXIsProcessTrusted() }
+
+ /// macOS's Screen Recording and Accessibility prompts, for a host set up
+ /// without the app ever showing (ServiceLauncher). Never call this from
+ /// the app's UI process before its permissions step.
+ public static func requestScreenRecordingAndAccessibility() {
+ if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() }
+ let prompt = "AXTrustedCheckOptionPrompt" // kAXTrustedCheckOptionPrompt
+ _ = AXIsProcessTrustedWithOptions([prompt: true] as CFDictionary)
+ }
+
+ /// Whether a notification may be posted. Asks macOS only when the first
+ /// run is done; before that an undecided answer is "no", without a prompt.
+ @MainActor
+ public static func notificationsAuthorized(_ center: UNUserNotificationCenter) async -> Bool {
+ let settings = await center.notificationSettings()
+ switch settings.authorizationStatus {
+ case .authorized, .provisional, .ephemeral: return true
+ case .denied: return false
+ default:
+ guard firstRunDone() else { return false }
+ return (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false
+ }
+ }
+}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift
index dbb45bda21..67fc8d099b 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PersistentModel.swift
@@ -369,7 +369,6 @@ public final class PersistentModel {
@MainActor
final class AgentNotifier {
static let shared = AgentNotifier()
- private var authorized: Bool?
func post(_ note: AppSystemNote) {
guard DeviceNotifier.available else { return }
@@ -381,10 +380,7 @@ final class AgentNotifier {
content.body = note.body
let request = UNNotificationRequest(identifier: "agent-\(note.id)", content: content, trigger: nil)
Task {
- if authorized == nil {
- authorized = (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false
- }
- guard authorized == true else { return }
+ guard await PermissionRequester.notificationsAuthorized(center) else { return }
try? await center.add(request)
}
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpaceReadyNotifier.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpaceReadyNotifier.swift
index b3619e345c..37c2c3c5db 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpaceReadyNotifier.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/SpaceReadyNotifier.swift
@@ -47,7 +47,6 @@ struct SpaceReadyNote: Equatable {
@MainActor
final class SpaceReadyNotifier {
static let shared = SpaceReadyNotifier()
- private var authorized: Bool?
func post(_ note: SpaceReadyNote) {
guard DeviceNotifier.available else { return }
@@ -65,10 +64,7 @@ final class SpaceReadyNotifier {
}
let request = UNNotificationRequest(identifier: note.identifier, content: content, trigger: nil)
Task {
- if authorized == nil {
- authorized = (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false
- }
- guard authorized == true else { return }
+ guard await PermissionRequester.notificationsAuthorized(center) else { return }
try? await center.add(request)
}
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift
index 3f4fbcd4df..81f54435e0 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIWindow.swift
@@ -510,6 +510,12 @@ final class WebUIWebView: WKWebView {
var dragRegions: [CGRect]?
var titlebarLeftInset: CGFloat = WebUIWindowController.fallbackLeftInset
+ /// The first click on a window that is not frontmost (System Settings is,
+ /// or the app was reopened behind it) must reach the page. WKWebView
+ /// refuses it by default, so "Allow" on the permissions step only brought
+ /// the window forward and opened nothing (CUA-2342).
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+
override func mouseDown(with event: NSEvent) {
guard let window, isDragPoint(event) else { return super.mouseDown(with: event) }
if event.clickCount == 2 {
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionGuideTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionGuideTests.swift
index 3d33b30bd5..e4103ea1f6 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionGuideTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionGuideTests.swift
@@ -5,6 +5,7 @@
import Foundation
import PermissionFlow
import Testing
+import WebKit
/// `host.openSettings` guides Screen Recording and Accessibility (the panes
/// the host's permission hints and the first run's rows name); any other
@@ -56,7 +57,7 @@ struct PermissionGuideTests {
#expect(PermissionGuide.instruction(for: .accessibility, listed: PermissionGuide.isListed(.accessibility)) == .switchOn)
PermissionGuide.markListed(.accessibility, false)
#expect(PermissionGuide.instruction(for: .accessibility, listed: PermissionGuide.isListed(.accessibility)) == .drag)
- #expect(PermissionGuide.switchOnText(appName: "Cua Spaces Local") == "Switch on Cua Spaces Local in the list.")
+ #expect(PermissionGuide.switchOnText(appName: "Cua Spaces Local") == "Turn on Cua Spaces Local in System Settings, then come back.")
}
@Test func readsWhatAFreshProcessReports() {
@@ -66,4 +67,86 @@ struct PermissionGuideTests {
#expect(PermissionGuide.parseGrants("").isEmpty)
#expect(PermissionGuide.parseGrants("garbage=1").isEmpty)
}
+
+ @Test func tellsNotAskedFromSwitchedOffFromGranted() {
+ #expect(PermissionGuide.state(granted: false, listed: false) == .notDetermined)
+ #expect(PermissionGuide.state(granted: false, listed: true) == .off)
+ #expect(PermissionGuide.state(granted: true, listed: true) == .granted)
+ // An off permission is guided by opening its pane, never by a prompt.
+ #expect(PermissionGuide.instruction(for: .screenRecording, listed: true) == .switchOn)
+ }
+
+ @Test func deniedThenSettingsOpenedThenGrantedCompletesWithoutAnotherClick() async {
+ // Off for three polls, then the person turns it on in System Settings.
+ actor Reads { var n = 0; func next() -> Set<PermissionFlowPane> { n += 1; return n > 3 ? [.screenRecording] : [] } }
+ let reads = Reads()
+ let done = await PermissionGuide.waitForGrant(.screenRecording, read: { await reads.next() },
+ interval: .milliseconds(1), giveUpAfter: .seconds(5))
+ #expect(done)
+ #expect(PermissionGuide.needsReopen(after: .screenRecording))
+ #expect(PermissionGuide.settingsURL(for: .screenRecording)?.hasSuffix("Privacy_ScreenCapture") == true)
+ }
+
+ @Test func staysUndoneWhileItIsOff() async {
+ let done = await PermissionGuide.waitForGrant(.accessibility, read: { [] },
+ interval: .milliseconds(1), giveUpAfter: .milliseconds(30))
+ #expect(!done)
+ }
+
+ /// The page's Allow reaches System Settings through the bridge, and a
+ /// grant after that ends the watch (CUA-2342).
+ @MainActor
+ @Test func allowOpensThePaneThroughTheBridgeThenAGrantCompletes() async throws {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cua-allow-\(UUID().uuidString)")
+ let model = AppModel(backend: FixtureSpacesBackend(rows: []), keyvault: KeyvaultModel(client: nil),
+ onboarding: OnboardingModel(statePath: dir.appendingPathComponent("onboarding.json").path),
+ settingsPath: dir.appendingPathComponent("settings.json").path,
+ telemetry: FixtureTelemetry())
+ let bridge = WebUIBridge(model: model, allowedOrigins: [])
+ let (savedOpen, savedShows, savedHook, savedRead, savedStore) =
+ (PermissionGuide.openPane, PermissionGuide.showsGuide, PermissionGuide.grantedHook,
+ PermissionGuide.readGranted, PermissionGuide.listedStore)
+ defer {
+ (PermissionGuide.openPane, PermissionGuide.showsGuide, PermissionGuide.grantedHook,
+ PermissionGuide.readGranted, PermissionGuide.listedStore) = (savedOpen, savedShows, savedHook, savedRead, savedStore)
+ }
+ let suite = "PermissionGuideTests.bridge.\(UUID().uuidString)"
+ let store = UserDefaults(suiteName: suite)!
+ defer { store.removePersistentDomain(forName: suite) }
+ PermissionGuide.listedStore = store
+ var opened: [String] = []
+ var granted: [PermissionFlowPane] = []
+ PermissionGuide.openPane = { opened.append($0.absoluteString) }
+ PermissionGuide.showsGuide = false
+ PermissionGuide.grantedHook = { granted.append($0) }
+ // Denied: off for the first reads; then the person turns it on.
+ actor Reads {
+ var n = 0
+ func next() -> Set<PermissionFlowPane> { n += 1; return n > 2 ? [.accessibility] : [] }
+ func reset() { n = 0 }
+ }
+ let reads = Reads()
+ PermissionGuide.readGranted = { await reads.next() }
+
+ // Both a switched-off (listed) and a never-asked app go to the pane.
+ for listed in [true, false] {
+ opened = []
+ granted = []
+ PermissionGuide.markListed(.accessibility, listed)
+ let url = "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"
+ _ = try await bridge.handle("host.openSettings", ["url": url])
+ #expect(opened == [url], "listed: \(listed)")
+ for _ in 0..<200 where granted.isEmpty { try await Task.sleep(for: .milliseconds(50)) }
+ #expect(granted == [.accessibility], "listed: \(listed)")
+ await reads.reset()
+ }
+ }
+
+ /// WKWebView refuses a window's first click by default: with System
+ /// Settings in front, "Allow" then only brought the app forward.
+ @MainActor
+ @Test func theWebViewTakesTheClickThatActivatesItsWindow() {
+ let web = WebUIWebView(frame: .zero, configuration: WKWebViewConfiguration())
+ #expect(web.acceptsFirstMouse(for: nil))
+ }
}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionPromptGuardTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionPromptGuardTests.swift
new file mode 100644
index 0000000000..428ce4b6aa
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionPromptGuardTests.swift
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import Foundation
+import Testing
+
+/// No macOS permission prompt before the first run's permissions step: only
+/// PermissionRequester.swift may call an API that raises one. Status checks
+/// elsewhere use the preflight calls (CGPreflightScreenCaptureAccess,
+/// AXIsProcessTrusted, notificationSettings).
+@Suite("Permission prompts come from one file")
+struct PermissionPromptGuardTests {
+ static let prompting = [
+ "CGRequestScreenCaptureAccess", "CGRequestListenEventAccess", "CGRequestPostEventAccess",
+ "AXIsProcessTrustedWithOptions", "kAXTrustedCheckOptionPrompt", "AXTrustedCheckOptionPrompt",
+ "requestAuthorization(", "SCShareableContent", "SCScreenshotManager", "CGWindowListCreateImage",
+ "CGDisplayCreateImage", "CGDisplayStream", "AVCaptureDevice.requestAccess",
+ "CLLocationManager", "NWBrowser", "NetServiceBrowser", "NSAppleScript",
+ "AEDeterminePermissionToAutomateTarget", "CNContactStore", "EKEventStore", "PHPhotoLibrary",
+ ]
+
+ @Test("prompting APIs appear only in PermissionRequester.swift")
+ func onlyTheRequesterPrompts() throws {
+ let sources = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ .appendingPathComponent("Sources")
+ let files = try #require(FileManager.default.enumerator(at: sources, includingPropertiesForKeys: nil))
+ var offences: [String] = []
+ for case let url as URL in files where url.pathExtension == "swift"
+ && url.lastPathComponent != "PermissionRequester.swift" {
+ let text = try String(contentsOf: url, encoding: .utf8)
+ for line in text.split(separator: "\n") where !line.trimmingCharacters(in: .whitespaces).hasPrefix("//") {
+ for api in Self.prompting where line.contains(api) {
+ offences.append("\(url.lastPathComponent): \(api)")
+ }
+ }
+ }
+ #expect(offences.isEmpty, "move these into PermissionRequester: \(offences)")
+ }
+}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-desktop/src/macos_capture.rs b/libs/cua-spacesd/crates/cua-spacesd-desktop/src/macos_capture.rs
index c29c3e98b3..66c74b5123 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-desktop/src/macos_capture.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-desktop/src/macos_capture.rs
@@ -193,6 +193,10 @@ fn start_inner(
encoder: Option<Arc<MacosH264Encoder>>,
native_geometry: Arc<dyn Fn(u32, u32) + Send + Sync>,
) -> Result<Arc<dyn CaptureLease>, ProviderError> {
+ // `SCShareableContent::get` raises macOS's Screen Recording prompt when it
+ // is not granted. Only the app's permissions step may do that, so a
+ // capture asked for before it fails here without asking.
+ ensure_screen_recording(screen_recording_granted())?;
let content = SCShareableContent::get().map_err(capture_error)?;
let located = locate(&content, source).ok_or_else(|| {
ProviderError::new(
@@ -540,6 +544,27 @@ fn monotonic_sample_timestamp_us(timestamp: screencapturekit::cm::CMTime, last:
}
}
+/// Screen Recording is granted to this process, read without asking
+/// (`CGPreflightScreenCaptureAccess` never prompts).
+fn screen_recording_granted() -> bool {
+ #[link(name = "CoreGraphics", kind = "framework")]
+ unsafe extern "C" {
+ fn CGPreflightScreenCaptureAccess() -> bool;
+ }
+ // SAFETY: no arguments; reads this process's TCC state.
+ unsafe { CGPreflightScreenCaptureAccess() }
+}
+
+fn ensure_screen_recording(granted: bool) -> Result<(), ProviderError> {
+ if granted {
+ return Ok(());
+ }
+ Err(ProviderError::new(
+ ProviderErrorCode::ConsentRequired,
+ "Screen Recording is not granted to Cua Spaces yet",
+ ))
+}
+
fn capture_error(error: SCError) -> ProviderError {
ProviderError::new(
match screen_capture_error_reason(&error) {
@@ -569,6 +594,13 @@ fn screen_capture_error_reason(error: &SCError) -> &'static str {
mod tests {
use super::*;
+ #[test]
+ fn capture_without_screen_recording_fails_before_any_prompting_call() {
+ assert!(ensure_screen_recording(true).is_ok());
+ let err = ensure_screen_recording(false).unwrap_err();
+ assert_eq!(err.code, ProviderErrorCode::ConsentRequired);
+ }
+
#[test]
fn dimensions_preserve_aspect_ratio_and_cap_long_edge() {
assert_eq!(fit_dimensions(2560, 1440, 1280), (1280, 720));