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.

fix(spaces): the permissions guide closes itself once access is granted (CUA-2274) (#5927)

cua-agents[bot]80146f54f52b
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift
index fb3130c2a6..8075881c99 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift
@@ -44,6 +44,12 @@ if launchArgs.first == "--service-helper" {
if launchArgs.first == "check-permissions" {
ServiceLauncher.passthrough(launchArgs)
}
+// A new process's Screen Recording and Accessibility answers, for
+// PermissionGuide to close its panel once access is granted.
+if launchArgs.first == "preflight-permissions" {
+ print(PermissionGuide.preflightReport())
+ exit(0)
+}
// `CUA_ENV=staging`: this process and the daemon use the staging home (a
// Local build already settled its three variables above).
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionGuide.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionGuide.swift
index b236cf3d8b..7d8851eda4 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionGuide.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/PermissionGuide.swift
@@ -2,6 +2,8 @@
// Copyright (c) 2026 Cua AI, Inc.
import AppKit
+import ApplicationServices
+import CoreGraphics
import PermissionFlow
/// The app's own guide to a privacy pane of System Settings, so nobody
@@ -63,6 +65,163 @@ public enum PermissionGuide {
return w.frame.contains(mouse) ? CGRect(x: mouse.x - 20, y: mouse.y - 10, width: 40, height: 20) : w.frame
}
flow.authorize(pane: pane, suggestedAppURLs: [app], sourceFrameInScreen: from)
+ watch(pane)
return true
}
+
+ // MARK: - Closing itself once access is granted (CUA-2274)
+
+ /// PermissionFlow 2.11.4 has no completion callback: its panel stays on
+ /// System Settings until closed. So the guide watches for the grant and
+ /// closes the panel the moment its pane is granted.
+ ///
+ /// The check runs in a fresh copy of this executable
+ /// (`preflight-permissions`, main.swift), the way the permission rows
+ /// are answered: a running process keeps the Screen Recording answer it
+ /// had at launch until it reopens, so asking this process would never
+ /// see the grant. Replaceable in tests.
+ nonisolated(unsafe) static var readGranted: () async -> Set<PermissionFlowPane> = {
+ await Task.detached { freshProcessGrants() }.value
+ }
+
+ /// `CuaSpacesMac preflight-permissions` in a new process: the guided
+ /// panes macOS has granted this app.
+ nonisolated static func freshProcessGrants() -> Set<PermissionFlowPane> {
+ guard let exe = Bundle.main.executableURL else { return [] }
+ let p = Process()
+ p.executableURL = exe
+ p.arguments = ["preflight-permissions"]
+ let out = Pipe()
+ p.standardOutput = out
+ p.standardError = FileHandle.nullDevice
+ guard (try? p.run()) != nil else { return [] }
+ let data = out.fileHandleForReading.readDataToEndOfFile()
+ p.waitUntilExit()
+ return parseGrants(String(decoding: data, as: UTF8.self))
+ }
+
+ /// What `preflight-permissions` prints: `screen-recording=1 accessibility=0`.
+ nonisolated static func parseGrants(_ line: String) -> Set<PermissionFlowPane> {
+ var granted = Set<PermissionFlowPane>()
+ for field in line.split(whereSeparator: \.isWhitespace) where field.hasSuffix("=1") {
+ switch field.dropLast(2) {
+ case "screen-recording": granted.insert(.screenRecording)
+ case "accessibility": granted.insert(.accessibility)
+ default: break
+ }
+ }
+ return granted
+ }
+
+ /// The answer `preflight-permissions` gives (run by main.swift).
+ public nonisolated static func preflightReport() -> String {
+ "screen-recording=\(CGPreflightScreenCaptureAccess() ? 1 : 0) accessibility=\(AXIsProcessTrusted() ? 1 : 0)"
+ }
+
+ /// What follows a grant.
+ enum Next: Equatable {
+ /// The other permission is still missing: guide it next.
+ case guide(PermissionFlowPane)
+ /// Nothing left: back to Cua Spaces.
+ case finish
+ }
+
+ /// The two guided permissions, in the order the permissions screen lists
+ /// them.
+ nonisolated static let guided: [PermissionFlowPane] = [.screenRecording, .accessibility]
+
+ /// What comes after `granted`: the other guided permission when it is
+ /// still missing, else the end.
+ nonisolated static func next(after granted: PermissionFlowPane, isGranted: (PermissionFlowPane) -> Bool) -> Next {
+ guided.first { $0 != granted && !isGranted($0) }.map(Next.guide) ?? .finish
+ }
+
+ /// macOS applies a Screen Recording grant to a running app only after it
+ /// reopens (System Settings offers "Quit & Reopen"); Accessibility
+ /// applies at once.
+ nonisolated static func needsReopen(after granted: PermissionFlowPane) -> Bool { granted == .screenRecording }
+
+ private static var watching: Task<Void, Never>?
+ nonisolated static let pollInterval: Duration = .milliseconds(500)
+ nonisolated static let giveUpAfter: Duration = .seconds(15 * 60)
+
+ private static var reopening: Task<Void, Never>?
+
+ private static func watch(_ pane: PermissionFlowPane) {
+ watching?.cancel()
+ reopening?.cancel()
+ watching = Task { @MainActor in
+ let clock = ContinuousClock()
+ let deadline = clock.now + giveUpAfter
+ while !Task.isCancelled, clock.now < deadline {
+ let now = await readGranted()
+ guard !Task.isCancelled else { return }
+ if now.contains(pane) { granted(pane, others: now); return }
+ try? await Task.sleep(for: pollInterval)
+ }
+ }
+ }
+
+ private static func granted(_ pane: PermissionFlowPane, others: Set<PermissionFlowPane>) {
+ watching = nil
+ reopening?.cancel()
+ controller?.closePanel()
+ let followUp = {
+ switch next(after: pane, isGranted: others.contains) {
+ case .guide(let other):
+ guard let url = settingsURL(for: other) else { return }
+ guide(url)
+ // System Settings ignores a pane URL while macOS's own
+ // "Quit & Reopen" sheet is still up: ask again once it is gone.
+ if needsReopen(after: pane), let u = URL(string: url) {
+ reopening = Task { @MainActor in
+ for delay in [1, 3, 6] {
+ try? await Task.sleep(for: .seconds(delay))
+ guard !Task.isCancelled else { return }
+ NSWorkspace.shared.open(u)
+ }
+ }
+ }
+ case .finish:
+ bringAppForward()
+ }
+ }
+ guard needsReopen(after: pane) else { return followUp() }
+ // Give macOS's own "Quit & Reopen" a moment first: when it is
+ // answered, this app is already gone.
+ Task { @MainActor in
+ try? await Task.sleep(for: .seconds(1))
+ bringAppForward()
+ let alert = NSAlert()
+ alert.messageText = "Cua Spaces needs to reopen to finish"
+ alert.informativeText = "macOS applies Screen Recording after the app reopens. Your place is kept."
+ alert.addButton(withTitle: "Reopen Cua Spaces")
+ alert.addButton(withTitle: "Later")
+ if alert.runModal() == .alertFirstButtonReturn {
+ SparkleUpdater.relaunch(Bundle.main.bundleURL)
+ } else {
+ followUp()
+ }
+ }
+ }
+
+ /// Cua Spaces to the front, over System Settings. NSApp.activate() alone
+ /// is only a request that macOS 14+ declines while another app is in
+ /// front, so the app also asks Launch Services to open it, which brings
+ /// it forward the way a click on its Dock icon does.
+ static func bringAppForward() {
+ NSApp.activate()
+ let config = NSWorkspace.OpenConfiguration()
+ config.activates = true
+ NSWorkspace.shared.openApplication(at: Bundle.main.bundleURL, configuration: config)
+ NSApp.windows.first { $0.isVisible && $0.canBecomeMain }?.makeKeyAndOrderFront(nil)
+ }
+
+ nonisolated static func settingsURL(for pane: PermissionFlowPane) -> String? {
+ switch pane {
+ case .screenRecording: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"
+ case .accessibility: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"
+ default: nil
+ }
+ }
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swift
index c5f3f170ca..0ba87f16ee 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/UpdatesModel.swift
@@ -242,7 +242,7 @@ public final class SparkleUpdater: NSObject, UpdaterDriving, SPUUpdaterDelegate
}
/// Opens `bundle` again once this process has exited, then quits.
- private static func relaunch(_ bundle: URL) {
+ static func relaunch(_ bundle: URL) {
let pid = ProcessInfo.processInfo.processIdentifier
let waiter = Process()
waiter.executableURL = URL(fileURLWithPath: "/bin/sh")
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionGuideTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionGuideTests.swift
index cb093c07e7..9cc88a92c4 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionGuideTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/PermissionGuideTests.swift
@@ -16,4 +16,34 @@ struct PermissionGuideTests {
#expect(PermissionGuide.pane(for: "x-apple.systempreferences:com.apple.LoginItems-Settings.extension") == nil)
#expect(PermissionGuide.pane(for: "x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork") == nil)
}
+
+ @Test func offersTheOtherPermissionNextWhileItIsMissing() {
+ #expect(PermissionGuide.next(after: .screenRecording, isGranted: { _ in false }) == .guide(.accessibility))
+ #expect(PermissionGuide.next(after: .accessibility, isGranted: { _ in false }) == .guide(.screenRecording))
+ }
+
+ @Test func finishesWhenTheOtherPermissionIsAlreadyGranted() {
+ #expect(PermissionGuide.next(after: .screenRecording, isGranted: { $0 == .accessibility }) == .finish)
+ #expect(PermissionGuide.next(after: .accessibility, isGranted: { $0 == .screenRecording }) == .finish)
+ }
+
+ @Test func onlyScreenRecordingNeedsAReopen() {
+ #expect(PermissionGuide.needsReopen(after: .screenRecording))
+ #expect(!PermissionGuide.needsReopen(after: .accessibility))
+ }
+
+ @Test func everyGuidedPaneHasItsSettingsURL() {
+ for pane in PermissionGuide.guided {
+ let url = PermissionGuide.settingsURL(for: pane)
+ #expect(url.flatMap(PermissionGuide.pane(for:)) == pane)
+ }
+ }
+
+ @Test func readsWhatAFreshProcessReports() {
+ #expect(PermissionGuide.parseGrants("screen-recording=1 accessibility=0\n") == [.screenRecording])
+ #expect(PermissionGuide.parseGrants("screen-recording=0 accessibility=1") == [.accessibility])
+ #expect(PermissionGuide.parseGrants("screen-recording=1 accessibility=1") == [.screenRecording, .accessibility])
+ #expect(PermissionGuide.parseGrants("").isEmpty)
+ #expect(PermissionGuide.parseGrants("garbage=1").isEmpty)
+ }
}