Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(computer-use): 完成 macOS 权限引导流程 (#248)

nanaco49bf600d7e67
diff --git a/appicon/computer.png b/appicon/computer.png
new file mode 100644
index 0000000000..36a0be4f15
Binary files /dev/null and b/appicon/computer.png differ
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index df167ed49a..d474de6076 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -819,6 +819,7 @@ function isMacForgePlatform(platform: ForgePlatform): boolean {
const MACOS_VOICE_HELPER_DEPLOYMENT_TARGET = 'macos10.15';
const MACOS_AGENT_ISLAND_HELPER_DEPLOYMENT_TARGET = 'macos14.0';
+const MACOS_COMPUTER_PERMISSION_GUIDE_HELPER_DEPLOYMENT_TARGET = 'macos13.0';
function swiftTargetTriple(cpuArch: 'arm64' | 'x86_64', deploymentTarget: string): string {
return `${cpuArch}-apple-${deploymentTarget}`;
@@ -964,6 +965,33 @@ function buildMacAgentIslandHelper(platform: ForgePlatform, arch: ForgeArch): vo
console.log(`[forge:prePackage] macOS agent island helper (${swiftArchLabel(arch, MACOS_AGENT_ISLAND_HELPER_DEPLOYMENT_TARGET)}) -> ${dest} (${sizeMb} MB)`);
}
+function buildMacComputerPermissionGuideHelper(platform: ForgePlatform, arch: ForgeArch): void {
+ if (process.platform !== 'darwin' || !isMacForgePlatform(platform)) return;
+ const src = path.join(
+ __dirname,
+ 'native',
+ 'computer-permission-guide',
+ 'macos-computer-permission-guide-helper.swift',
+ );
+ const destDir = path.join(__dirname, 'resources', 'tools', 'computer-permission-guide');
+ const dest = path.join(destDir, 'xdt-macos-computer-permission-guide-helper');
+ if (!fs.existsSync(src)) {
+ throw new Error(`[forge] macOS computer permission guide helper source missing at ${src}`);
+ }
+ fs.mkdirSync(destDir, { recursive: true });
+ buildSwiftHelperForForgeArch(
+ src,
+ dest,
+ arch,
+ MACOS_COMPUTER_PERMISSION_GUIDE_HELPER_DEPLOYMENT_TARGET,
+ ['-O'],
+ 'computer permission guide helper',
+ );
+ fs.chmodSync(dest, 0o755);
+ const sizeMb = (fs.statSync(dest).size / (1024 * 1024)).toFixed(2);
+ console.log(`[forge:prePackage] macOS computer permission guide helper (${swiftArchLabel(arch, MACOS_COMPUTER_PERMISSION_GUIDE_HELPER_DEPLOYMENT_TARGET)}) -> ${dest} (${sizeMb} MB)`);
+}
+
// MakerNSIS is Windows-only (native dependency), conditionally require to
// avoid import errors on macOS / Linux.
const makers: ForgeConfig['makers'] = [
@@ -1218,6 +1246,7 @@ const config: ForgeConfig = {
buildMacVoiceInputTextInsertionHelper(platform, arch);
buildMacVoiceInputModifierShortcutListener(platform, arch);
buildMacAgentIslandHelper(platform, arch);
+ buildMacComputerPermissionGuideHelper(platform, arch);
},
// packaged dir 产出后、makers 跑之前签内部 .exe。这样 NSIS 包出来的
// Setup.exe 内嵌的、和 publish 阶段从同一 packagedDir 打的热更 ZIP 内嵌的,
diff --git a/apps/desktop/native/computer-permission-guide/macos-computer-permission-guide-helper.swift b/apps/desktop/native/computer-permission-guide/macos-computer-permission-guide-helper.swift
new file mode 100644
index 0000000000..3cea797789
--- /dev/null
+++ b/apps/desktop/native/computer-permission-guide/macos-computer-permission-guide-helper.swift
@@ -0,0 +1,1338 @@
+import AppKit
+import ApplicationServices
+import Foundation
+
+private let systemSettingsBundleIdentifier = "com.apple.systempreferences"
+private let hostSize = NSSize(width: 500, height: 226)
+private let cardFrame = NSRect(x: 68, y: 12, width: 432, height: 152)
+private let switchGuideSize = NSSize(width: 196, height: 44)
+private let switchTargetGap: CGFloat = 28
+private let trackingInterval: TimeInterval = 0.16
+
+private enum GuideLocale: String {
+ case zhCN = "zh-CN"
+ case en
+ case ja
+ case ko
+}
+
+/** Localized native copy selected from the renderer-synchronized app locale. */
+private struct GuideCopy {
+ let close: String
+ let turnThisOn: String
+ let pointsToSwitch: String
+ let accessibility: String
+ let screenRecording: String
+ let completeEyebrow: String
+ let readyTitle: String
+ let step: String
+ let turnOnAppTitle: String
+ let waiting: String
+ let dragTitle: String
+ let dragHint: String
+
+ func interpolated(_ template: String, permission: String) -> String {
+ template.replacingOccurrences(of: "{{permission}}", with: permission)
+ }
+
+ static func resolve(_ locale: GuideLocale) -> GuideCopy {
+ switch locale {
+ case .zhCN:
+ return GuideCopy(
+ close: "关闭",
+ turnThisOn: "打开这一项",
+ pointsToSwitch: "指向开关",
+ accessibility: "辅助功能",
+ screenRecording: "屏幕录制",
+ completeEyebrow: "权限已完成",
+ readyTitle: "Computer Use 已就绪",
+ step: "打开自动操作电脑",
+ turnOnAppTitle: "在「{{permission}}」中打开 CuaDriver",
+ waiting: "等待你开启",
+ dragTitle: "将 CuaDriver 拖入「{{permission}}」",
+ dragHint: "拖拽"
+ )
+ case .ja:
+ return GuideCopy(
+ close: "閉じる",
+ turnThisOn: "この項目をオンにする",
+ pointsToSwitch: "スイッチを指す",
+ accessibility: "アクセシビリティ",
+ screenRecording: "画面収録",
+ completeEyebrow: "権限の設定完了",
+ readyTitle: "Computer Use の準備ができました",
+ step: "コンピュータ操作を有効にする",
+ turnOnAppTitle: "「{{permission}}」で CuaDriver をオンにする",
+ waiting: "操作待ち",
+ dragTitle: "CuaDriver を「{{permission}}」にドラッグ",
+ dragHint: "ドラッグ"
+ )
+ case .ko:
+ return GuideCopy(
+ close: "닫기",
+ turnThisOn: "이 항목 켜기",
+ pointsToSwitch: "스위치를 가리킴",
+ accessibility: "손쉬운 사용",
+ screenRecording: "화면 기록",
+ completeEyebrow: "권한 설정 완료",
+ readyTitle: "Computer Use 준비 완료",
+ step: "컴퓨터 자동화 켜기",
+ turnOnAppTitle: "{{permission}}에서 CuaDriver 켜기",
+ waiting: "켜기 대기",
+ dragTitle: "CuaDriver를 {{permission}}으로 드래그",
+ dragHint: "드래그"
+ )
+ case .en:
+ return GuideCopy(
+ close: "Close",
+ turnThisOn: "Turn this on",
+ pointsToSwitch: "Points to the switch",
+ accessibility: "Accessibility",
+ screenRecording: "Screen Recording",
+ completeEyebrow: "Permissions complete",
+ readyTitle: "Computer Use is ready",
+ step: "Open computer automation",
+ turnOnAppTitle: "Turn on CuaDriver in {{permission}}",
+ waiting: "Waiting for you",
+ dragTitle: "Drag CuaDriver into {{permission}}",
+ dragHint: "Drag"
+ )
+ }
+ }
+}
+
+/** Emits one compact JSON object per line to the Electron main process. */
+private func emit(_ payload: [String: Any]) {
+ guard JSONSerialization.isValidJSONObject(payload),
+ let data = try? JSONSerialization.data(withJSONObject: payload),
+ var line = String(data: data, encoding: .utf8) else { return }
+ line.append("\n")
+ FileHandle.standardOutput.write(Data(line.utf8))
+}
+
+/** Permission state sent by Electron; the helper owns presentation only. */
+private struct PermissionUpdate: Decodable {
+ let type: String
+ let accessibilityGranted: Bool?
+ let screenRecordingGranted: Bool?
+ let draggedAccessibility: Bool?
+ let draggedScreenRecording: Bool?
+ let switchTargetX: Double?
+ let switchTargetY: Double?
+ let switchWindowWidth: Double?
+ let switchWindowHeight: Double?
+}
+
+/** A panel that can receive a first click without ever becoming key or main. */
+private final class PermissionAccessoryPanel: NSPanel {
+ override var canBecomeKey: Bool { false }
+ override var canBecomeMain: Bool { false }
+}
+
+/** Clear host view; only the visible material card participates in hit testing. */
+private final class PassthroughHostView: NSView {
+ weak var interactiveView: NSView?
+
+ override func hitTest(_ point: NSPoint) -> NSView? {
+ guard let interactiveView else { return nil }
+ let localPoint = convert(point, to: interactiveView)
+ guard interactiveView.bounds.contains(localPoint) else { return nil }
+ return interactiveView.hitTest(localPoint)
+ }
+}
+
+/** Close control that remains clickable while System Settings stays frontmost. */
+private final class NonactivatingCloseButton: NSButton {
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+
+ override func mouseDown(with event: NSEvent) {
+ // Keep the click inside this non-activating panel instead of ordering the
+ // helper application in front of System Settings after an auth sheet closes.
+ NSApp.preventWindowOrdering()
+ super.mouseDown(with: event)
+ }
+}
+
+/** Native app row that starts an AppKit file drag for the real .app bundle. */
+private final class DraggableApplicationView: NSView, NSDraggingSource {
+ private let appURL: URL
+ private let appIcon: NSImage
+ private var mouseDownEvent: NSEvent?
+ private var didBeginDrag = false
+ var dragEnabled = true
+ var onDragBegan: (() -> Void)?
+ var onDragEnded: ((NSDragOperation) -> Void)?
+
+ init(appURL: URL, appIcon: NSImage) {
+ self.appURL = appURL
+ self.appIcon = appIcon
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.cornerRadius = 12
+ layer?.cornerCurve = .continuous
+ layer?.borderWidth = 1
+ layer?.shadowColor = NSColor.black.cgColor
+ layer?.shadowOpacity = 0.28
+ layer?.shadowRadius = 14
+ layer?.shadowOffset = NSSize(width: 0, height: -5)
+ updateLayerColors()
+ setAccessibilityElement(true)
+ setAccessibilityRole(.button)
+ setAccessibilityLabel("CuaDriver")
+ }
+
+ required init?(coder: NSCoder) { nil }
+
+ override var acceptsFirstResponder: Bool { false }
+
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+
+ override func viewDidChangeEffectiveAppearance() {
+ super.viewDidChangeEffectiveAppearance()
+ updateLayerColors()
+ }
+
+ override func layout() {
+ super.layout()
+ layer?.shadowPath = CGPath(
+ roundedRect: bounds,
+ cornerWidth: 12,
+ cornerHeight: 12,
+ transform: nil
+ )
+ }
+
+ private func updateLayerColors() {
+ effectiveAppearance.performAsCurrentDrawingAppearance {
+ layer?.backgroundColor = NSColor.controlBackgroundColor.cgColor
+ layer?.borderColor = NSColor.separatorColor.cgColor
+ }
+ }
+
+ override func mouseDown(with event: NSEvent) {
+ guard dragEnabled else { return }
+ NSApp.preventWindowOrdering()
+ mouseDownEvent = event
+ didBeginDrag = false
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.12
+ animator().alphaValue = 0.82
+ }
+ }
+
+ override func mouseDragged(with event: NSEvent) {
+ guard dragEnabled, !didBeginDrag, let mouseDownEvent else { return }
+ let dx = event.locationInWindow.x - mouseDownEvent.locationInWindow.x
+ let dy = event.locationInWindow.y - mouseDownEvent.locationInWindow.y
+ guard hypot(dx, dy) >= 4 else { return }
+ didBeginDrag = true
+
+ // Reassert the real drop target before entering AppKit's nested drag loop.
+ NSRunningApplication.runningApplications(withBundleIdentifier: systemSettingsBundleIdentifier)
+ .first?
+ .activate()
+
+ let item = NSDraggingItem(pasteboardWriter: appURL as NSURL)
+ let imageSize = NSSize(width: 64, height: 64)
+ item.setDraggingFrame(
+ NSRect(
+ x: event.locationInWindow.x - imageSize.width / 2,
+ y: event.locationInWindow.y - imageSize.height / 2,
+ width: imageSize.width,
+ height: imageSize.height
+ ),
+ contents: appIcon
+ )
+ onDragBegan?()
+ beginDraggingSession(with: [item], event: event, source: self)
+ }
+
+ override func mouseUp(with event: NSEvent) {
+ if !didBeginDrag {
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.12
+ animator().alphaValue = 1
+ }
+ }
+ mouseDownEvent = nil
+ }
+
+ func draggingSession(
+ _ session: NSDraggingSession,
+ sourceOperationMaskFor context: NSDraggingContext
+ ) -> NSDragOperation {
+ .copy
+ }
+
+ func ignoreModifierKeys(for session: NSDraggingSession) -> Bool { true }
+
+ func draggingSession(
+ _ session: NSDraggingSession,
+ endedAt screenPoint: NSPoint,
+ operation: NSDragOperation
+ ) {
+ mouseDownEvent = nil
+ didBeginDrag = false
+ alphaValue = 1
+ onDragEnded?(operation)
+ }
+}
+
+/** Compact pointer shown after the app has been added but its switch is still off. */
+private final class SwitchGuideController: NSViewController {
+ private let copy: GuideCopy
+ private let closeButton = NonactivatingCloseButton()
+ private let instructionLabel = NSTextField(labelWithString: "")
+ private let arrowView = NSImageView()
+ var onClose: (() -> Void)?
+
+ init(locale: GuideLocale) {
+ copy = GuideCopy.resolve(locale)
+ super.init(nibName: nil, bundle: nil)
+ }
+
+ required init?(coder: NSCoder) { nil }
+
+ override func loadView() {
+ let root = NSView(frame: NSRect(origin: .zero, size: switchGuideSize))
+ root.wantsLayer = true
+ view = root
+
+ closeButton.translatesAutoresizingMaskIntoConstraints = false
+ closeButton.image = NSImage(
+ systemSymbolName: "xmark.circle.fill",
+ accessibilityDescription: copy.close
+ )
+ closeButton.imageScaling = .scaleProportionallyDown
+ closeButton.isBordered = false
+ closeButton.contentTintColor = .tertiaryLabelColor
+ closeButton.target = self
+ closeButton.action = #selector(closeRequested)
+ root.addSubview(closeButton)
+
+ instructionLabel.translatesAutoresizingMaskIntoConstraints = false
+ instructionLabel.stringValue = copy.turnThisOn
+ instructionLabel.font = .systemFont(ofSize: 13, weight: .semibold)
+ instructionLabel.textColor = .controlAccentColor
+ instructionLabel.alignment = .right
+ root.addSubview(instructionLabel)
+
+ arrowView.translatesAutoresizingMaskIntoConstraints = false
+ arrowView.wantsLayer = true
+ arrowView.image = NSImage(
+ systemSymbolName: "arrow.right",
+ accessibilityDescription: copy.pointsToSwitch
+ )
+ arrowView.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 19, weight: .semibold)
+ arrowView.contentTintColor = .controlAccentColor
+ root.addSubview(arrowView)
+
+ NSLayoutConstraint.activate([
+ closeButton.leadingAnchor.constraint(equalTo: root.leadingAnchor),
+ closeButton.centerYAnchor.constraint(equalTo: root.centerYAnchor),
+ closeButton.widthAnchor.constraint(equalToConstant: 24),
+ closeButton.heightAnchor.constraint(equalToConstant: 24),
+
+ instructionLabel.leadingAnchor.constraint(equalTo: closeButton.trailingAnchor, constant: 8),
+ instructionLabel.centerYAnchor.constraint(equalTo: root.centerYAnchor),
+
+ arrowView.leadingAnchor.constraint(equalTo: instructionLabel.trailingAnchor, constant: 10),
+ arrowView.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -4),
+ arrowView.centerYAnchor.constraint(equalTo: root.centerYAnchor),
+ arrowView.widthAnchor.constraint(equalToConstant: 28),
+ arrowView.heightAnchor.constraint(equalToConstant: 28),
+ ])
+ }
+
+ func prepareForDisplay() {
+ guard isViewLoaded else { return }
+ startGuidanceAnimation()
+ }
+
+ func prepareForDismissal() {
+ guard isViewLoaded else { return }
+ arrowView.layer?.removeAllAnimations()
+ }
+
+ private func startGuidanceAnimation() {
+ arrowView.layer?.removeAllAnimations()
+ guard !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion else { return }
+
+ // One small compositor-only motion guides the eye without obscuring the switch.
+ let movement = CAKeyframeAnimation(keyPath: "transform.translation.x")
+ movement.values = [0, 6, 0, 0]
+ movement.keyTimes = [0, 0.24, 0.48, 1]
+ movement.duration = 1.6
+ movement.repeatCount = .infinity
+ movement.timingFunctions = [
+ CAMediaTimingFunction(name: .easeInEaseOut),
+ CAMediaTimingFunction(name: .easeInEaseOut),
+ CAMediaTimingFunction(name: .linear),
+ ]
+ arrowView.layer?.add(movement, forKey: "switchGuideMovement")
+ }
+
+ @objc private func closeRequested() {
+ onClose?()
+ }
+}
+
+/** Composes the Apple-native material, typography, controls, and drag coach. */
+private final class PermissionCardController: NSViewController {
+ enum Permission: String {
+ case accessibility
+ case screenRecording
+ case complete
+ }
+
+ private let appURL: URL
+ private let copy: GuideCopy
+ private let materialView = NSVisualEffectView()
+ private let eyebrowLabel = NSTextField(labelWithString: "")
+ private let titleLabel = NSTextField(labelWithString: "")
+ private let statusLabel = NSTextField(labelWithString: "")
+ private let appNameLabel = NSTextField(labelWithString: "CuaDriver")
+ private let dragCoach = NSView()
+ private let dragCoachIcon = NSImageView()
+ private let dragCoachPill = NSVisualEffectView()
+ private let dragCoachLabel = NSTextField(labelWithString: "")
+ private let appIconView = NSImageView()
+ private let appRow: DraggableApplicationView
+ private var permission: Permission = .accessibility
+ private var hasBeenDragged = false
+ private var closeTimer: Timer?
+ var onComplete: (() -> Void)?
+ var onDragBegan: ((Permission) -> Void)?
+ var onDragEnded: ((Permission, NSDragOperation) -> Void)?
+
+ init(appURL: URL, locale: GuideLocale) {
+ self.appURL = appURL
+ self.copy = GuideCopy.resolve(locale)
+ let icon = NSWorkspace.shared.icon(forFile: appURL.path)
+ icon.size = NSSize(width: 64, height: 64)
+ self.appRow = DraggableApplicationView(appURL: appURL, appIcon: icon)
+ super.init(nibName: nil, bundle: nil)
+ }
+
+ required init?(coder: NSCoder) { nil }
+
+ override func loadView() {
+ let root = NSView(frame: NSRect(origin: .zero, size: cardFrame.size))
+ root.wantsLayer = true
+ view = root
+
+ materialView.translatesAutoresizingMaskIntoConstraints = false
+ materialView.material = .hudWindow
+ materialView.blendingMode = .behindWindow
+ materialView.state = .active
+ materialView.wantsLayer = true
+ materialView.layer?.cornerRadius = 14
+ materialView.layer?.cornerCurve = .continuous
+ materialView.layer?.masksToBounds = true
+ materialView.layer?.borderWidth = 0.5
+ materialView.layer?.borderColor = NSColor.white.withAlphaComponent(0.13).cgColor
+ root.addSubview(materialView)
+
+ titleLabel.translatesAutoresizingMaskIntoConstraints = false
+ titleLabel.font = .systemFont(ofSize: 20, weight: .semibold)
+ titleLabel.textColor = .labelColor
+ titleLabel.lineBreakMode = .byTruncatingTail
+ materialView.addSubview(titleLabel)
+
+ eyebrowLabel.translatesAutoresizingMaskIntoConstraints = false
+ eyebrowLabel.font = .monospacedSystemFont(ofSize: 11, weight: .medium)
+ eyebrowLabel.textColor = .tertiaryLabelColor
+ eyebrowLabel.lineBreakMode = .byTruncatingTail
+ materialView.addSubview(eyebrowLabel)
+
+ appRow.translatesAutoresizingMaskIntoConstraints = false
+ materialView.addSubview(appRow)
+
+ appIconView.translatesAutoresizingMaskIntoConstraints = false
+ appIconView.image = NSWorkspace.shared.icon(forFile: appURL.path)
+ appIconView.imageScaling = .scaleProportionallyUpOrDown
+ appRow.addSubview(appIconView)
+
+ appNameLabel.translatesAutoresizingMaskIntoConstraints = false
+ appNameLabel.font = .systemFont(ofSize: 15, weight: .medium)
+ appNameLabel.textColor = .labelColor
+ appRow.addSubview(appNameLabel)
+
+ statusLabel.translatesAutoresizingMaskIntoConstraints = false
+ statusLabel.font = .systemFont(ofSize: 12, weight: .regular)
+ statusLabel.textColor = .secondaryLabelColor
+ statusLabel.alignment = .right
+ appRow.addSubview(statusLabel)
+
+ root.addSubview(dragCoach)
+ configureDragCoach(in: root)
+
+ NSLayoutConstraint.activate([
+ materialView.leadingAnchor.constraint(equalTo: root.leadingAnchor),
+ materialView.trailingAnchor.constraint(equalTo: root.trailingAnchor),
+ materialView.topAnchor.constraint(equalTo: root.topAnchor),
+ materialView.bottomAnchor.constraint(equalTo: root.bottomAnchor),
+
+ titleLabel.leadingAnchor.constraint(equalTo: materialView.leadingAnchor, constant: 16),
+ titleLabel.trailingAnchor.constraint(equalTo: materialView.trailingAnchor, constant: -16),
+ titleLabel.topAnchor.constraint(equalTo: eyebrowLabel.bottomAnchor, constant: 3),
+ titleLabel.heightAnchor.constraint(equalToConstant: 28),
+
+ eyebrowLabel.leadingAnchor.constraint(equalTo: materialView.leadingAnchor, constant: 16),
+ eyebrowLabel.trailingAnchor.constraint(equalTo: materialView.trailingAnchor, constant: -16),
+ eyebrowLabel.topAnchor.constraint(equalTo: materialView.topAnchor, constant: 12),
+ eyebrowLabel.heightAnchor.constraint(equalToConstant: 15),
+
+ appRow.leadingAnchor.constraint(equalTo: materialView.leadingAnchor, constant: 16),
+ appRow.trailingAnchor.constraint(equalTo: materialView.trailingAnchor, constant: -16),
+ appRow.bottomAnchor.constraint(equalTo: materialView.bottomAnchor, constant: -18),
+ appRow.heightAnchor.constraint(equalToConstant: 64),
+
+ appIconView.leadingAnchor.constraint(equalTo: appRow.leadingAnchor, constant: 12),
+ appIconView.centerYAnchor.constraint(equalTo: appRow.centerYAnchor),
+ appIconView.widthAnchor.constraint(equalToConstant: 44),
+ appIconView.heightAnchor.constraint(equalToConstant: 44),
+
+ appNameLabel.leadingAnchor.constraint(equalTo: appIconView.trailingAnchor, constant: 12),
+ appNameLabel.centerYAnchor.constraint(equalTo: appRow.centerYAnchor),
+
+ statusLabel.leadingAnchor.constraint(greaterThanOrEqualTo: appNameLabel.trailingAnchor, constant: 8),
+ statusLabel.trailingAnchor.constraint(equalTo: appRow.trailingAnchor, constant: -14),
+ statusLabel.centerYAnchor.constraint(equalTo: appRow.centerYAnchor),
+ ])
+
+ appRow.onDragBegan = { [weak self] in
+ guard let self else { return }
+ stopDragCoachAnimation()
+ dragCoach.isHidden = true
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.16
+ self.materialView.animator().alphaValue = 0.18
+ }
+ onDragBegan?(permission)
+ }
+ appRow.onDragEnded = { [weak self] operation in
+ guard let self else { return }
+ hasBeenDragged = true
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.18
+ self.materialView.animator().alphaValue = 1
+ }
+ updateCopy()
+ onDragEnded?(permission, operation)
+ }
+ }
+
+ override func viewDidAppear() {
+ super.viewDidAppear()
+ updateCopy()
+ }
+
+ func update(
+ accessibilityGranted: Bool,
+ screenRecordingGranted: Bool,
+ draggedAccessibility: Bool,
+ draggedScreenRecording: Bool
+ ) {
+ closeTimer?.invalidate()
+ if !accessibilityGranted {
+ permission = .accessibility
+ hasBeenDragged = draggedAccessibility
+ } else if !screenRecordingGranted {
+ permission = .screenRecording
+ hasBeenDragged = draggedScreenRecording
+ } else {
+ permission = .complete
+ hasBeenDragged = true
+ closeTimer = Timer.scheduledTimer(withTimeInterval: 1.1, repeats: false) { [weak self] _ in
+ self?.onComplete?()
+ }
+ }
+ updateCopy()
+ }
+
+ private func configureDragCoach(in root: NSView) {
+ dragCoach.translatesAutoresizingMaskIntoConstraints = false
+ dragCoach.wantsLayer = true
+
+ dragCoachIcon.translatesAutoresizingMaskIntoConstraints = false
+ dragCoachIcon.image = NSImage(
+ systemSymbolName: "cursorarrow",
+ accessibilityDescription: nil
+ )
+ dragCoachIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 17, weight: .medium)
+ dragCoachIcon.contentTintColor = .labelColor
+ dragCoach.addSubview(dragCoachIcon)
+
+ dragCoachPill.translatesAutoresizingMaskIntoConstraints = false
+ dragCoachPill.material = .popover
+ dragCoachPill.blendingMode = .withinWindow
+ dragCoachPill.state = .active
+ dragCoachPill.wantsLayer = true
+ dragCoachPill.layer?.cornerRadius = 13
+ dragCoachPill.layer?.cornerCurve = .continuous
+ dragCoach.addSubview(dragCoachPill)
+
+ dragCoachLabel.translatesAutoresizingMaskIntoConstraints = false
+ dragCoachLabel.font = .systemFont(ofSize: 12, weight: .medium)
+ dragCoachLabel.textColor = .labelColor
+ dragCoachPill.addSubview(dragCoachLabel)
+
+ NSLayoutConstraint.activate([
+ dragCoach.widthAnchor.constraint(equalToConstant: 92),
+ dragCoach.heightAnchor.constraint(equalToConstant: 40),
+ dragCoach.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -24),
+ dragCoach.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -30),
+
+ dragCoachIcon.leadingAnchor.constraint(equalTo: dragCoach.leadingAnchor),
+ dragCoachIcon.centerYAnchor.constraint(equalTo: dragCoach.centerYAnchor),
+ dragCoachIcon.widthAnchor.constraint(equalToConstant: 34),
+ dragCoachIcon.heightAnchor.constraint(equalToConstant: 34),
+
+ dragCoachPill.leadingAnchor.constraint(equalTo: dragCoachIcon.trailingAnchor, constant: 4),
+ dragCoachPill.centerYAnchor.constraint(equalTo: dragCoach.centerYAnchor),
+ dragCoachPill.heightAnchor.constraint(equalToConstant: 26),
+ dragCoachPill.widthAnchor.constraint(equalToConstant: 52),
+
+ dragCoachLabel.centerXAnchor.constraint(equalTo: dragCoachPill.centerXAnchor),
+ dragCoachLabel.centerYAnchor.constraint(equalTo: dragCoachPill.centerYAnchor),
+ ])
+ }
+
+ private func updateCopy() {
+ guard isViewLoaded else { return }
+ let permissionName: String
+ switch permission {
+ case .accessibility:
+ permissionName = copy.accessibility
+ case .screenRecording:
+ permissionName = copy.screenRecording
+ case .complete:
+ permissionName = ""
+ }
+
+ if permission == .complete {
+ eyebrowLabel.stringValue = copy.completeEyebrow
+ titleLabel.stringValue = copy.readyTitle
+ statusLabel.stringValue = ""
+ appRow.dragEnabled = false
+ dragCoach.isHidden = true
+ stopDragCoachAnimation()
+ return
+ }
+
+ eyebrowLabel.stringValue = copy.step
+ appRow.dragEnabled = !hasBeenDragged
+ if hasBeenDragged {
+ titleLabel.stringValue = copy.interpolated(
+ copy.turnOnAppTitle,
+ permission: permissionName
+ )
+ statusLabel.stringValue = copy.waiting
+ dragCoach.isHidden = true
+ stopDragCoachAnimation()
+ } else {
+ titleLabel.stringValue = copy.interpolated(
+ copy.dragTitle,
+ permission: permissionName
+ )
+ statusLabel.stringValue = ""
+ dragCoachLabel.stringValue = copy.dragHint
+ dragCoach.isHidden = false
+ startDragCoachAnimation()
+ }
+ }
+
+ private func startDragCoachAnimation() {
+ dragCoach.layer?.opacity = 1
+ guard !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion else {
+ dragCoach.layer?.removeAllAnimations()
+ return
+ }
+ guard dragCoach.layer?.animation(forKey: "dragCoachPosition") == nil else { return }
+ view.layoutSubtreeIfNeeded()
+ let base = dragCoach.layer?.position ?? .zero
+
+ // Keep the coach fully visible and make the gesture unmistakable:
+ // engage, travel directly toward the app row, hold, then reset softly.
+ let position = CAKeyframeAnimation(keyPath: "position")
+ position.values = [
+ NSValue(point: base),
+ NSValue(point: CGPoint(x: base.x - 5, y: base.y + 9)),
+ NSValue(point: CGPoint(x: base.x - 32, y: base.y + 62)),
+ NSValue(point: CGPoint(x: base.x - 32, y: base.y + 62)),
+ NSValue(point: base),
+ ]
+ position.keyTimes = [0, 0.12, 0.46, 0.62, 1]
+ position.duration = 2.0
+ position.repeatCount = .infinity
+ position.timingFunctions = [
+ CAMediaTimingFunction(name: .easeOut),
+ CAMediaTimingFunction(name: .easeInEaseOut),
+ CAMediaTimingFunction(name: .linear),
+ CAMediaTimingFunction(name: .easeInEaseOut),
+ ]
+ dragCoach.layer?.add(position, forKey: "dragCoachPosition")
+
+ let pickup = CAKeyframeAnimation(keyPath: "transform.scale")
+ pickup.values = [1, 1.05, 1.05, 1.05, 1]
+ pickup.keyTimes = position.keyTimes
+ pickup.duration = position.duration
+ pickup.repeatCount = .infinity
+ pickup.timingFunctions = position.timingFunctions
+ dragCoach.layer?.add(pickup, forKey: "dragCoachPickup")
+ }
+
+ private func stopDragCoachAnimation() {
+ dragCoach.layer?.removeAnimation(forKey: "dragCoachPosition")
+ dragCoach.layer?.removeAnimation(forKey: "dragCoachPickup")
+ dragCoach.layer?.opacity = 1
+ }
+
+}
+
+/** Tracks the real System Settings window and attaches a non-activating panel. */
+private final class PermissionGuideCoordinator {
+ private enum Presentation {
+ case hidden
+ case drag
+ case switchGuide
+ case complete
+ }
+
+ private let panel: PermissionAccessoryPanel
+ private let switchPanel: PermissionAccessoryPanel
+ private let hostView: PassthroughHostView
+ private let cardController: PermissionCardController
+ private let switchGuideController: SwitchGuideController
+ private var timer: Timer?
+ private var hasActivatedSettings = false
+ private var settingsMissingSince: Date?
+ private var didNotifySettingsClosed = false
+ private var isDragging = false
+ private var presentation: Presentation = .hidden
+ private var switchTarget: NSPoint?
+ private var switchWindowSize: NSSize?
+ private var authSheetVisible = false
+ private var didEstablishFallbackWindowBaseline = false
+ private var knownFallbackWindowIDs = Set<CGWindowID>()
+ private var fallbackModalWindowIDs = Set<CGWindowID>()
+
+ init(appURL: URL, locale: GuideLocale) {
+ panel = PermissionAccessoryPanel(
+ contentRect: NSRect(origin: .zero, size: hostSize),
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered,
+ defer: false
+ )
+ switchPanel = PermissionAccessoryPanel(
+ contentRect: NSRect(origin: .zero, size: switchGuideSize),
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered,
+ defer: false
+ )
+ hostView = PassthroughHostView(frame: NSRect(origin: .zero, size: hostSize))
+ cardController = PermissionCardController(appURL: appURL, locale: locale)
+ switchGuideController = SwitchGuideController(locale: locale)
+
+ panel.isOpaque = false
+ panel.backgroundColor = .clear
+ panel.hasShadow = true
+ panel.level = .normal
+ panel.isFloatingPanel = false
+ panel.hidesOnDeactivate = false
+ panel.becomesKeyOnlyIfNeeded = true
+ panel.worksWhenModal = true
+ panel.collectionBehavior = [
+ .canJoinAllSpaces,
+ .fullScreenAuxiliary,
+ .transient,
+ .ignoresCycle,
+ ]
+ panel.contentView = hostView
+
+ switchPanel.isOpaque = false
+ switchPanel.backgroundColor = .clear
+ switchPanel.hasShadow = false
+ switchPanel.level = .normal
+ switchPanel.isFloatingPanel = false
+ switchPanel.hidesOnDeactivate = false
+ switchPanel.becomesKeyOnlyIfNeeded = true
+ switchPanel.worksWhenModal = true
+ switchPanel.collectionBehavior = [
+ .canJoinAllSpaces,
+ .fullScreenAuxiliary,
+ .transient,
+ .ignoresCycle,
+ ]
+ switchPanel.contentViewController = switchGuideController
+
+ let card = cardController.view
+ card.frame = cardFrame
+ card.autoresizingMask = []
+ hostView.addSubview(card)
+ hostView.interactiveView = card
+
+ switchGuideController.onClose = { [weak self] in
+ self?.dismiss(reason: "close-requested")
+ emit(["type": "close-requested"])
+ }
+ cardController.onComplete = { [weak self] in
+ self?.dismiss(reason: "permissions-complete")
+ emit(["type": "completed"])
+ NSApp.terminate(nil)
+ }
+ cardController.onDragBegan = { [weak self] permission in
+ self?.isDragging = true
+ emit(["type": "drag-began", "permission": permission.rawValue])
+ }
+ cardController.onDragEnded = { [weak self] permission, operation in
+ guard let self else { return }
+ isDragging = false
+ if operation.contains(.copy) {
+ presentation = .switchGuide
+ }
+ emit([
+ "type": "drag-ended",
+ "permission": permission.rawValue,
+ "operation": operation.rawValue,
+ ])
+ refreshAttachment()
+ }
+ }
+
+ func start() {
+ refreshAttachment()
+ timer = Timer.scheduledTimer(withTimeInterval: trackingInterval, repeats: true) { [weak self] _ in
+ self?.refreshAttachment()
+ }
+ }
+
+ func apply(_ update: PermissionUpdate) {
+ if let x = update.switchTargetX,
+ let y = update.switchTargetY,
+ x.isFinite,
+ y.isFinite,
+ x >= 0,
+ y >= 0 {
+ switchTarget = NSPoint(x: x, y: y)
+ } else {
+ switchTarget = nil
+ }
+ if let width = update.switchWindowWidth,
+ let height = update.switchWindowHeight,
+ width.isFinite,
+ height.isFinite,
+ width > 0,
+ height > 0 {
+ switchWindowSize = NSSize(width: width, height: height)
+ } else {
+ switchWindowSize = nil
+ }
+ if update.accessibilityGranted != true {
+ presentation = update.draggedAccessibility == true ? .switchGuide : .drag
+ } else if update.screenRecordingGranted != true {
+ presentation = update.draggedScreenRecording == true ? .switchGuide : .drag
+ } else {
+ presentation = .complete
+ }
+ cardController.update(
+ accessibilityGranted: update.accessibilityGranted == true,
+ screenRecordingGranted: update.screenRecordingGranted == true,
+ draggedAccessibility: update.draggedAccessibility == true,
+ draggedScreenRecording: update.draggedScreenRecording == true
+ )
+ refreshAttachment()
+ }
+
+ func dismiss(reason: String) {
+ timer?.invalidate()
+ timer = nil
+ panel.orderOut(nil)
+ switchGuideController.prepareForDismissal()
+ switchPanel.orderOut(nil)
+ emit(["type": "dismissed", "reason": reason])
+ }
+
+ private func refreshAttachment() {
+ guard let settingsApp = NSRunningApplication
+ .runningApplications(withBundleIdentifier: systemSettingsBundleIdentifier)
+ .first,
+ let settingsInfo = systemSettingsWindowInfo(pid: settingsApp.processIdentifier)
+ else {
+ if !isDragging {
+ didEstablishFallbackWindowBaseline = false
+ knownFallbackWindowIDs.removeAll()
+ fallbackModalWindowIDs.removeAll()
+ if settingsMissingSince == nil {
+ settingsMissingSince = Date()
+ }
+ if hasActivatedSettings,
+ !didNotifySettingsClosed,
+ let missingSince = settingsMissingSince,
+ Date().timeIntervalSince(missingSince) >= 0.6 {
+ didNotifySettingsClosed = true
+ emit(["type": "close-requested"])
+ NSApp.terminate(nil)
+ return
+ }
+ }
+ if !isDragging {
+ panel.orderOut(nil)
+ switchGuideController.prepareForDismissal()
+ switchPanel.orderOut(nil)
+ }
+ return
+ }
+ let settingsFrame = settingsInfo.frame
+ settingsMissingSince = nil
+ didNotifySettingsClosed = false
+ let hasModalSheet = resolveModalSheetState(settingsInfo)
+
+ if !hasActivatedSettings {
+ hasActivatedSettings = true
+ settingsApp.activate()
+ }
+
+ let frontmostBundle = NSWorkspace.shared.frontmostApplication?.bundleIdentifier
+ guard isDragging || frontmostBundle == systemSettingsBundleIdentifier else {
+ panel.orderOut(nil)
+ switchGuideController.prepareForDismissal()
+ switchPanel.orderOut(nil)
+ return
+ }
+
+ // When the auth sheet dismisses (fingerprint/password completed),
+ // tell Electron so it can re-probe the permission state immediately.
+ if authSheetVisible && !hasModalSheet {
+ authSheetVisible = false
+ emit(["type": "auth-sheet-dismissed"])
+ } else if !authSheetVisible && hasModalSheet {
+ authSheetVisible = true
+ }
+
+ // Hide while System Settings shows a modal sheet (auth dialog).
+ // The panel reappears automatically on the next tick after dismissal.
+ if hasModalSheet && !isDragging {
+ panel.orderOut(nil)
+ switchGuideController.prepareForDismissal()
+ switchPanel.orderOut(nil)
+ return
+ }
+
+ switch presentation {
+ case .hidden, .complete:
+ panel.orderOut(nil)
+ switchGuideController.prepareForDismissal()
+ switchPanel.orderOut(nil)
+ return
+ case .switchGuide:
+ if let desiredFrame = attachedSwitchGuideFrame(settingsFrame: settingsFrame) {
+ panel.orderOut(nil)
+ if !NSEqualRects(switchPanel.frame, desiredFrame) {
+ switchPanel.setFrame(desiredFrame, display: switchPanel.isVisible, animate: false)
+ }
+ if !switchPanel.isVisible {
+ switchGuideController.prepareForDisplay()
+ switchPanel.order(.above, relativeTo: settingsInfo.windowNumber)
+ emit([
+ "type": "attached",
+ "systemX": settingsFrame.origin.x,
+ "systemY": settingsFrame.origin.y,
+ "systemWidth": settingsFrame.width,
+ "systemHeight": settingsFrame.height,
+ "panelX": desiredFrame.origin.x,
+ "panelY": desiredFrame.origin.y,
+ ])
+ }
+ return
+ } else {
+ // The row may exist before Accessibility can inspect its
+ // checkbox. Keep the full "turn on CuaDriver" card visible
+ // until a precise switch target becomes available.
+ switchGuideController.prepareForDismissal()
+ switchPanel.orderOut(nil)
+ }
+ case .drag:
+ switchGuideController.prepareForDismissal()
+ switchPanel.orderOut(nil)
+ }
+
+ let desiredFrame = attachedPanelFrame(settingsFrame: settingsFrame)
+ if !NSEqualRects(panel.frame, desiredFrame) {
+ panel.setFrame(desiredFrame, display: panel.isVisible, animate: false)
+ }
+ if !panel.isVisible && !isDragging {
+ panel.order(.above, relativeTo: settingsInfo.windowNumber)
+ emit([
+ "type": "attached",
+ "systemX": settingsFrame.origin.x,
+ "systemY": settingsFrame.origin.y,
+ "systemWidth": settingsFrame.width,
+ "systemHeight": settingsFrame.height,
+ "panelX": desiredFrame.origin.x,
+ "panelY": desiredFrame.origin.y,
+ ])
+ }
+ }
+
+ /**
+ * Prefer explicit AX modal relationships. When AX is unavailable, baseline
+ * every existing Settings window and only treat a newly appearing,
+ * top-attached sheet candidate during the switch step as modal.
+ */
+ private func resolveModalSheetState(_ info: SystemSettingsWindowInfo) -> Bool {
+ if let hasModalSheet = info.axHasModalSheet {
+ didEstablishFallbackWindowBaseline = true
+ if hasModalSheet {
+ // Seed the geometry fallback while AX is authoritative. If an
+ // AX attribute is temporarily unavailable on the next tick,
+ // keep the confirmed sheet visible until its window vanishes.
+ fallbackModalWindowIDs = info.attachedSheetCandidateWindowIDs
+ knownFallbackWindowIDs.formUnion(
+ info.layerZeroWindowIDs.subtracting(fallbackModalWindowIDs)
+ )
+ } else {
+ knownFallbackWindowIDs.formUnion(info.layerZeroWindowIDs)
+ fallbackModalWindowIDs.removeAll()
+ }
+ return hasModalSheet
+ }
+ if authSheetVisible {
+ let hadTrackedFallbackModal = !fallbackModalWindowIDs.isEmpty
+ if !hadTrackedFallbackModal {
+ fallbackModalWindowIDs = info.attachedSheetCandidateWindowIDs
+ }
+ fallbackModalWindowIDs.formIntersection(info.layerZeroWindowIDs)
+ if !hadTrackedFallbackModal && fallbackModalWindowIDs.isEmpty {
+ // AX confirmed the sheet, but Quartz could not identify its
+ // window. Do not invent a dismissal from an unknown AX sample.
+ return true
+ }
+ return !fallbackModalWindowIDs.isEmpty
+ }
+ if !didEstablishFallbackWindowBaseline {
+ didEstablishFallbackWindowBaseline = true
+ knownFallbackWindowIDs = info.layerZeroWindowIDs
+ fallbackModalWindowIDs.removeAll()
+ return false
+ }
+ guard presentation == .switchGuide, !isDragging else {
+ knownFallbackWindowIDs.formUnion(info.layerZeroWindowIDs)
+ fallbackModalWindowIDs.removeAll()
+ return false
+ }
+ fallbackModalWindowIDs.formUnion(
+ info.attachedSheetCandidateWindowIDs.subtracting(knownFallbackWindowIDs)
+ )
+ fallbackModalWindowIDs.formIntersection(info.layerZeroWindowIDs)
+ if fallbackModalWindowIDs.isEmpty {
+ knownFallbackWindowIDs.formUnion(info.layerZeroWindowIDs)
+ }
+ return !fallbackModalWindowIDs.isEmpty
+ }
+
+ private func attachedPanelFrame(settingsFrame: NSRect) -> NSRect {
+ var origin = NSPoint(
+ x: settingsFrame.maxX - hostSize.width,
+ y: settingsFrame.midY - cardFrame.midY
+ )
+ if let screen = NSScreen.screens.first(where: { $0.frame.intersects(settingsFrame) }) {
+ origin.x = min(max(origin.x, screen.visibleFrame.minX), screen.visibleFrame.maxX - hostSize.width)
+ origin.y = min(max(origin.y, screen.visibleFrame.minY), screen.visibleFrame.maxY - hostSize.height)
+ }
+ return NSRect(origin: origin, size: hostSize)
+ }
+
+ /** Convert CuaDriver's window-local, top-left switch point into AppKit space. */
+ private func attachedSwitchGuideFrame(settingsFrame: NSRect) -> NSRect? {
+ guard let switchTarget else { return nil }
+ let scaleX = coordinateScale(
+ external: switchWindowSize?.width,
+ native: settingsFrame.width
+ )
+ let scaleY = coordinateScale(
+ external: switchWindowSize?.height,
+ native: settingsFrame.height
+ )
+ let target = NSPoint(
+ x: settingsFrame.minX + switchTarget.x / scaleX,
+ y: settingsFrame.maxY - switchTarget.y / scaleY
+ )
+ var origin = NSPoint(
+ x: target.x - switchTargetGap - switchGuideSize.width,
+ y: target.y - switchGuideSize.height / 2
+ )
+ if let screen = NSScreen.screens.first(where: { $0.frame.intersects(settingsFrame) }) {
+ origin.x = min(
+ max(origin.x, screen.visibleFrame.minX),
+ screen.visibleFrame.maxX - switchGuideSize.width
+ )
+ origin.y = min(
+ max(origin.y, screen.visibleFrame.minY),
+ screen.visibleFrame.maxY - switchGuideSize.height
+ )
+ }
+ return NSRect(origin: origin, size: switchGuideSize)
+ }
+
+ private func coordinateScale(external: CGFloat?, native: CGFloat) -> CGFloat {
+ guard let external, native > 0 else { return 1 }
+ let ratio = external / native
+ // CuaDriver may report Retina window coordinates in backing pixels,
+ // while AppKit positions panels in points. Keep normal layouts at 1x
+ // and only normalize a clear backing-scale mismatch.
+ return ratio > 1.25 ? ratio : 1
+ }
+}
+
+private struct SystemSettingsWindowInfo {
+ let frame: NSRect
+ let windowNumber: Int
+ let axHasModalSheet: Bool?
+ let layerZeroWindowIDs: Set<CGWindowID>
+ let attachedSheetCandidateWindowIDs: Set<CGWindowID>
+}
+
+/** Read an AX array without treating an unavailable accessibility tree as modal. */
+private func accessibilityElements(
+ of element: AXUIElement,
+ attribute: CFString
+) -> [AXUIElement]? {
+ var value: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(element, attribute, &value) == .success,
+ let elements = value as? [AXUIElement] else { return nil }
+ return elements
+}
+
+private func accessibilityRole(of element: AXUIElement) -> String? {
+ var value: CFTypeRef?
+ guard AXUIElementCopyAttributeValue(
+ element,
+ kAXRoleAttribute as CFString,
+ &value
+ ) == .success else { return nil }
+ return value as? String
+}
+
+/** Detect actual System Settings sheets when this helper can read the AX tree. */
+private func systemSettingsHasModalPresentation(pid: pid_t) -> Bool? {
+ guard AXIsProcessTrusted() else { return nil }
+ let application = AXUIElementCreateApplication(pid)
+ guard let windows = accessibilityElements(
+ of: application,
+ attribute: kAXWindowsAttribute as CFString
+ ) else { return nil }
+ var didEncounterUnavailableAttribute = false
+ for window in windows {
+ if let role = accessibilityRole(of: window) {
+ if role == kAXSheetRole as String {
+ return true
+ }
+ } else {
+ didEncounterUnavailableAttribute = true
+ }
+ if let children = accessibilityElements(
+ of: window,
+ attribute: kAXChildrenAttribute as CFString
+ ) {
+ for child in children {
+ guard let role = accessibilityRole(of: child) else {
+ didEncounterUnavailableAttribute = true
+ continue
+ }
+ if role == kAXSheetRole as String {
+ return true
+ }
+ }
+ } else {
+ didEncounterUnavailableAttribute = true
+ }
+ var modalValue: CFTypeRef?
+ if AXUIElementCopyAttributeValue(
+ window,
+ kAXModalAttribute as CFString,
+ &modalValue
+ ) == .success,
+ let isModal = modalValue as? Bool {
+ if isModal {
+ return true
+ }
+ } else {
+ didEncounterUnavailableAttribute = true
+ }
+ }
+ return didEncounterUnavailableAttribute ? nil : false
+}
+
+/**
+ * AX is normally unavailable to this accessory helper because the user grants
+ * Accessibility to CuaDriver, not to the helper. Return only strict AppKit
+ * sheet-shaped candidates here; the coordinator separately requires that the
+ * candidate is new and appears during the switch step.
+ */
+private func systemSettingsAttachedSheetCandidates(
+ windows: [(id: CGWindowID, frame: CGRect)],
+ mainWindowID: CGWindowID,
+ mainFrame: CGRect
+) -> Set<CGWindowID> {
+ let mainArea = mainFrame.width * mainFrame.height
+ guard mainArea > 0 else { return [] }
+ return Set(windows.compactMap { candidate -> CGWindowID? in
+ guard candidate.id != mainWindowID else { return nil }
+ let frame = candidate.frame
+ let area = frame.width * frame.height
+ guard frame.width >= 180,
+ frame.height >= 100,
+ area < mainArea * 0.9 else { return nil }
+ let intersection = frame.intersection(mainFrame)
+ guard !intersection.isNull else { return nil }
+ let intersectionArea = intersection.width * intersection.height
+ let center = CGPoint(x: frame.midX, y: frame.midY)
+ let topAttachmentLimit = mainFrame.minY + min(140, mainFrame.height * 0.25)
+ guard mainFrame.contains(center),
+ intersectionArea >= area * 0.9,
+ abs(frame.midX - mainFrame.midX) <= mainFrame.width * 0.18,
+ frame.minY >= mainFrame.minY - 8,
+ frame.minY <= topAttachmentLimit else { return nil }
+ return candidate.id
+ })
+}
+
+/** Finds the largest visible layer-zero window owned by System Settings. */
+private func systemSettingsWindowInfo(pid: pid_t) -> SystemSettingsWindowInfo? {
+ guard let rawList = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID)
+ as? [[String: Any]] else { return nil }
+ var bestArea: CGFloat = 0
+ var bestRect: CGRect?
+ var bestWindowID: CGWindowID = 0
+ var layerZeroWindows: [(id: CGWindowID, frame: CGRect)] = []
+ for info in rawList {
+ guard let ownerPID = info[kCGWindowOwnerPID as String] as? NSNumber,
+ ownerPID.int32Value == pid,
+ let layer = info[kCGWindowLayer as String] as? NSNumber,
+ layer.intValue == 0,
+ let bounds = info[kCGWindowBounds as String] as? [String: Any],
+ let rect = CGRect(dictionaryRepresentation: bounds as CFDictionary),
+ let windowID = info[kCGWindowNumber as String] as? NSNumber else { continue }
+ let cgWindowID = CGWindowID(windowID.intValue)
+ layerZeroWindows.append((id: cgWindowID, frame: rect))
+ guard rect.width > 360, rect.height > 260 else { continue }
+ let area = rect.width * rect.height
+ guard area > bestArea else { continue }
+ bestArea = area
+ bestRect = rect
+ bestWindowID = cgWindowID
+ }
+ guard let cgFrame = bestRect else { return nil }
+ return SystemSettingsWindowInfo(
+ frame: appKitRect(fromQuartz: cgFrame),
+ windowNumber: Int(bestWindowID),
+ axHasModalSheet: systemSettingsHasModalPresentation(pid: pid),
+ layerZeroWindowIDs: Set(layerZeroWindows.map(\.id)),
+ attachedSheetCandidateWindowIDs: systemSettingsAttachedSheetCandidates(
+ windows: layerZeroWindows,
+ mainWindowID: bestWindowID,
+ mainFrame: cgFrame
+ )
+ )
+}
+
+/** Converts Quartz top-left coordinates through the matching physical display. */
+private func appKitRect(fromQuartz quartzRect: CGRect) -> NSRect {
+ for screen in NSScreen.screens {
+ guard let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")]
+ as? NSNumber else { continue }
+ let displayBounds = CGDisplayBounds(CGDirectDisplayID(number.uint32Value))
+ guard displayBounds.intersects(quartzRect) else { continue }
+ let scale = max(
+ 1,
+ min(
+ screen.backingScaleFactor,
+ displayBounds.width / max(screen.frame.width, 1)
+ )
+ )
+ return NSRect(
+ x: screen.frame.minX + (quartzRect.minX - displayBounds.minX) / scale,
+ y: screen.frame.maxY - (quartzRect.minY - displayBounds.minY) / scale
+ - quartzRect.height / scale,
+ width: quartzRect.width / scale,
+ height: quartzRect.height / scale
+ )
+ }
+ let desktopTop = NSScreen.screens.map(\.frame.maxY).max() ?? 0
+ return NSRect(
+ x: quartzRect.minX,
+ y: desktopTop - quartzRect.maxY,
+ width: quartzRect.width,
+ height: quartzRect.height
+ )
+}
+
+/** AppKit process entry point and newline-delimited command reader. */
+private final class PermissionGuideApplicationDelegate: NSObject, NSApplicationDelegate {
+ private var coordinator: PermissionGuideCoordinator?
+ private var inputBuffer = Data()
+
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ NSApp.setActivationPolicy(.accessory)
+ guard CommandLine.arguments.count >= 2 else {
+ emit(["type": "error", "message": "Missing Computer Use.app path."])
+ NSApp.terminate(nil)
+ return
+ }
+ let appURL = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true)
+ let locale = CommandLine.arguments.count >= 3
+ ? GuideLocale(rawValue: CommandLine.arguments[2]) ?? .en
+ : .en
+ guard FileManager.default.fileExists(atPath: appURL.path) else {
+ emit(["type": "error", "message": "Computer Use.app is unavailable."])
+ NSApp.terminate(nil)
+ return
+ }
+ let coordinator = PermissionGuideCoordinator(appURL: appURL, locale: locale)
+ self.coordinator = coordinator
+ coordinator.start()
+ beginReadingCommands()
+ emit(["type": "ready"])
+ }
+
+ func applicationWillTerminate(_ notification: Notification) {
+ FileHandle.standardInput.readabilityHandler = nil
+ coordinator?.dismiss(reason: "terminated")
+ }
+
+ private func beginReadingCommands() {
+ FileHandle.standardInput.readabilityHandler = { [weak self] handle in
+ let data = handle.availableData
+ if data.isEmpty {
+ DispatchQueue.main.async { NSApp.terminate(nil) }
+ return
+ }
+ DispatchQueue.main.async { self?.consume(data) }
+ }
+ }
+
+ private func consume(_ data: Data) {
+ inputBuffer.append(data)
+ while let newline = inputBuffer.firstIndex(of: 0x0A) {
+ let line = inputBuffer.prefix(upTo: newline)
+ inputBuffer.removeSubrange(...newline)
+ guard !line.isEmpty,
+ let update = try? JSONDecoder().decode(PermissionUpdate.self, from: line) else { continue }
+ if update.type == "dismiss" {
+ coordinator?.dismiss(reason: "electron-dismissed")
+ NSApp.terminate(nil)
+ } else if update.type == "update" {
+ coordinator?.apply(update)
+ }
+ }
+ }
+}
+
+private let application = NSApplication.shared
+private let delegate = PermissionGuideApplicationDelegate()
+application.delegate = delegate
+application.setActivationPolicy(.accessory)
+application.finishLaunching()
+application.run()
diff --git a/apps/desktop/scripts/ci/lib.mjs b/apps/desktop/scripts/ci/lib.mjs
index 46bee4746d..121577ce90 100644
--- a/apps/desktop/scripts/ci/lib.mjs
+++ b/apps/desktop/scripts/ci/lib.mjs
@@ -560,11 +560,12 @@ export function adhocSignMacApp(appPath, helperEntitlementsPath, mainEntitlement
const resourceToolsDir = path.join(appPath, 'Contents', 'Resources', 'tools');
if (fs.existsSync(resourceToolsDir)) {
exec(`find "${resourceToolsDir}" -type f | while IFS= read -r f; do if file "$f" | grep -qE "Mach-O"; then ${signBase} "$f"; fi; done`);
+ exec(`find "${resourceToolsDir}" -depth -type d -name "*.app" -exec ${signBase} "{}" \\;`);
}
exec(`find "${frameworksDir}" -type f | while IFS= read -r f; do if file "$f" | grep -qE "Mach-O"; then ${signBase} "$f"; fi; done`);
- exec(`find "${frameworksDir}" -name "*.app" -exec ${signBase} --entitlements "${helperEntitlementsPath}" {} \\;`);
- exec(`find "${frameworksDir}" -maxdepth 1 -name "*.framework" -exec ${signBase} {} \\;`);
+ exec(`find "${frameworksDir}" -name "*.app" -exec ${signBase} --entitlements "${helperEntitlementsPath}" "{}" \\;`);
+ exec(`find "${frameworksDir}" -maxdepth 1 -name "*.framework" -exec ${signBase} "{}" \\;`);
exec(`${signBase} --entitlements "${mainEntitlementsPath}" "${appPath}"`);
exec(`/usr/bin/codesign --verify --deep --strict "${appPath}"`);
verifyMacContactsPermissions(appPath);
@@ -598,6 +599,8 @@ export function signMacAppWithIdentity(appPath, helperEntitlementsPath, mainEnti
if (fs.existsSync(resourceToolsDir)) {
console.log(' Signing bundled CLI tools in Contents/Resources/tools/...');
exec(`find "${resourceToolsDir}" -type f | while IFS= read -r f; do if file "$f" | grep -qE "Mach-O"; then ${signBase} "$f"; fi; done`);
+ console.log(' Signing bundled resource app bundles...');
+ exec(`find "${resourceToolsDir}" -depth -type d -name "*.app" -exec ${signBase} "{}" \\;`);
}
// 1. 全部 Mach-O(库、chrome_crashpad_handler、ShipIt 等)
@@ -606,11 +609,11 @@ export function signMacAppWithIdentity(appPath, helperEntitlementsPath, mainEnti
// 2. Helper apps(V8 JIT entitlements)
console.log(' Signing helper apps...');
- exec(`find "${frameworksDir}" -name "*.app" -exec ${signBase} --entitlements "${helperEntitlementsPath}" {} \\;`);
+ exec(`find "${frameworksDir}" -name "*.app" -exec ${signBase} --entitlements "${helperEntitlementsPath}" "{}" \\;`);
// 3. Framework bundles
console.log(' Signing frameworks...');
- exec(`find "${frameworksDir}" -maxdepth 1 -name "*.framework" -exec ${signBase} {} \\;`);
+ exec(`find "${frameworksDir}" -maxdepth 1 -name "*.framework" -exec ${signBase} "{}" \\;`);
// 4. 主 app bundle
console.log(' Signing main app...');
diff --git a/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts b/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts
index 2ee5db1ac6..e34b993521 100644
--- a/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts
+++ b/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts
@@ -112,6 +112,58 @@ describe('computer use plugin IPC invariants', () => {
"context?.agentKind === 'codex' || pluginRegistry.isEnabled('computer')",
);
});
+
+ it('revalidates Computer Use guide requests at the Main IPC boundary', () => {
+ const registerSource = fs.readFileSync(
+ path.resolve(__dirname, '../maker-ipc/register.ts'),
+ 'utf-8',
+ );
+ const handlerStart = registerSource.indexOf(
+ 'ipcMain.handle(MAKER_INVOKE.COMPUTER_GRANT_PERMISSIONS',
+ );
+ const handlerEnd = registerSource.indexOf(
+ 'ipcMain.handle(MAKER_INVOKE.COMPUTER_DRIVER_ICON',
+ handlerStart,
+ );
+ const handlerBody = registerSource.slice(handlerStart, handlerEnd);
+
+ expect(handlerStart).toBeGreaterThanOrEqual(0);
+ expect(handlerEnd).toBeGreaterThan(handlerStart);
+ expect(handlerBody).toContain('assertTrustedAppRendererEvent(_event)');
+ expect(handlerBody).toContain('parseComputerPermissionGrantRequest(payload)');
+ expect(handlerBody).toContain("throwIpcError('INVALID_PARAMS'");
+ expect(handlerBody).toContain('freshPermissionProbe: true');
+ expect(handlerBody).toContain('bypassPermissionProbeCache: true');
+ expect(handlerBody).not.toContain('options?.initialStatus');
+ expect(handlerBody.indexOf('getComputerDriverStatus({')).toBeLessThan(
+ handlerBody.indexOf('openComputerPermissionPaneForStatus(initialStatus)'),
+ );
+ });
+
+ it('guards Computer Use guide cancellation before mutating Main state', () => {
+ const registerSource = fs.readFileSync(
+ path.resolve(__dirname, '../maker-ipc/register.ts'),
+ 'utf-8',
+ );
+ const handlerStart = registerSource.indexOf(
+ 'ipcMain.handle(MAKER_INVOKE.COMPUTER_CANCEL_PERMISSION_GRANT',
+ );
+ const handlerEnd = registerSource.indexOf(
+ 'ipcMain.handle(MAKER_INVOKE.COMPUTER_CHECK_UPDATE',
+ handlerStart,
+ );
+ const handlerBody = registerSource.slice(handlerStart, handlerEnd);
+
+ expect(handlerStart).toBeGreaterThanOrEqual(0);
+ expect(handlerEnd).toBeGreaterThan(handlerStart);
+ expect(handlerBody).toContain(
+ 'isComputerPermissionGuideWebContents(_event.sender)',
+ );
+ expect(handlerBody).toContain('assertTrustedAppRendererEvent(_event)');
+ expect(handlerBody.indexOf('assertTrustedAppRendererEvent(_event)')).toBeLessThan(
+ handlerBody.indexOf('cancelComputerDriverPermissionGrant()'),
+ );
+ });
});
describe('computer use UI feedback invariants', () => {
@@ -136,6 +188,96 @@ describe('computer use UI feedback invariants', () => {
expect(successToast).toBeGreaterThanOrEqual(0);
expect(deferredWarning).toBeGreaterThan(successToast);
});
+
+ it('keeps a live permission poll for legacy CLI-only grants', () => {
+ const sectionSource = fs.readFileSync(
+ path.resolve(__dirname, '../../renderer/components/settings/ComputerUseSection.tsx'),
+ 'utf-8',
+ );
+
+ expect(sectionSource).toContain("refreshComputerPermissionStatus('permission-poll'");
+ expect(sectionSource).toContain('bypassCache: true');
+ expect(sectionSource).toContain('computerPermissionGrantInProgressRef.current');
+ expect(sectionSource).toContain('COMPUTER_PERMISSION_POLL_TIMEOUT_MS');
+ });
+
+ it('refreshes mutable macOS permission state before enabling Computer Use', () => {
+ const sectionSource = fs.readFileSync(
+ path.resolve(__dirname, '../../renderer/components/settings/ComputerUseSection.tsx'),
+ 'utf-8',
+ );
+ const toggleStart = sectionSource.indexOf(
+ 'const handleToggleComputer',
+ );
+ const enableCall = sectionSource.indexOf(
+ 'await persistComputerEnabled(next)',
+ toggleStart,
+ );
+
+ expect(toggleStart).toBeGreaterThanOrEqual(0);
+ expect(sectionSource.slice(toggleStart, enableCall)).toContain(
+ "refreshComputerPermissionStatus('toggle-fresh-preflight'",
+ );
+ expect(sectionSource.slice(toggleStart, enableCall)).toContain('fresh: true');
+ expect(sectionSource.slice(toggleStart, enableCall)).toContain('bypassCache: true');
+ expect(enableCall).toBeGreaterThan(toggleStart);
+ });
+
+ it('preserves the deferred Codex refresh warning after native onboarding', () => {
+ const sectionSource = fs.readFileSync(
+ path.resolve(__dirname, '../../renderer/components/settings/ComputerUseSection.tsx'),
+ 'utf-8',
+ );
+ const listenerStart = sectionSource.indexOf(
+ 'onPermissionGuideStatusChanged((status)',
+ );
+ const listenerEnd = sectionSource.indexOf(
+ 'const refreshComputerPermissionStatus',
+ listenerStart,
+ );
+ const listenerBody = sectionSource.slice(listenerStart, listenerEnd);
+
+ expect(listenerStart).toBeGreaterThanOrEqual(0);
+ expect(listenerEnd).toBeGreaterThan(listenerStart);
+ expect(listenerBody).toContain('result.codexMcpRefreshed === false');
+ expect(listenerBody).toContain("toast.warning(t('settings.computerUse.codexRefreshDeferred'))");
+ });
+
+ it('invalidates the whole Computer Use enable attempt when Settings unmounts', () => {
+ const sectionSource = fs.readFileSync(
+ path.resolve(__dirname, '../../renderer/components/settings/ComputerUseSection.tsx'),
+ 'utf-8',
+ );
+ const cleanupStart = sectionSource.indexOf(
+ '// Leaving Settings / Plugin detail invalidates the whole enable attempt',
+ );
+ const cleanupEnd = sectionSource.indexOf(
+ '// 引导弹窗的取消',
+ cleanupStart,
+ );
+ const toggleStart = sectionSource.indexOf('const handleToggleComputer');
+ const toggleEnd = sectionSource.indexOf(
+ 'const handleOpenComputerPermission',
+ toggleStart,
+ );
+ const cleanupBody = sectionSource.slice(cleanupStart, cleanupEnd);
+ const toggleBody = sectionSource.slice(toggleStart, toggleEnd);
+
+ expect(cleanupStart).toBeGreaterThanOrEqual(0);
+ expect(cleanupBody).toContain('computerUseSectionMountedRef.current = false');
+ expect(cleanupBody).toContain('computerPermissionFlowSeqRef.current += 1');
+ expect(cleanupBody).toContain('computerTogglePendingRef.current');
+ expect(cleanupBody).toContain('cancelNativeComputerPermissionGrant()');
+ expect(toggleStart).toBeGreaterThanOrEqual(0);
+ expect(toggleBody).toContain('const flowSeq = computerPermissionFlowSeqRef.current');
+ expect(toggleBody).toContain('if (!isCurrentFlow()) return');
+ expect(toggleBody.indexOf('const flowSeq')).toBeLessThan(
+ toggleBody.indexOf('await window.electronAPI.maker.computer.installDriver()'),
+ );
+ expect(toggleBody.indexOf('if (!isCurrentFlow()) return')).toBeLessThan(
+ toggleBody.indexOf("requestComputerPermissionGrant('toggle')"),
+ );
+ });
});
describe('computer use platform copy invariants', () => {
@@ -144,10 +286,16 @@ describe('computer use platform copy invariants', () => {
path.resolve(__dirname, '../../renderer/components/settings/ComputerUseSection.tsx'),
'utf-8',
);
- expect(sectionSource).toContain("nextStatus?.permissionState?.platform === 'macos'");
- expect(sectionSource).toContain(
- "? 'settings.computerUse.directControl.permissionIntro.macosDescription'",
+ expect(sectionSource).toContain("nextStatus.permissionState?.platform === 'macos'");
+ const macPermissionBlockStart = sectionSource.indexOf(
+ "{window.electronAPI.platform === 'darwin' ? (",
+ );
+ const permissionTitle = sectionSource.indexOf(
+ "t('settings.computerUse.directControl.permissions.title')",
+ macPermissionBlockStart,
);
+ expect(macPermissionBlockStart).toBeGreaterThanOrEqual(0);
+ expect(permissionTitle).toBeGreaterThan(macPermissionBlockStart);
for (const locale of ['en', 'ja', 'ko', 'zh-CN']) {
const messages = JSON.parse(
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 9ebc85eb71..4e92e9550c 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -36,6 +36,7 @@ import {
markDesktopDevStartupFailed,
markDesktopDevWindowReady,
} from './devStartupStatus';
+import { prewarmMacComputerPermissionGuideHelper } from './computer-permission-guide/MacComputerPermissionGuideNativeHost.js';
const PROCESS_STARTED_AT_MS = Date.now();
// Official Linux binaries total hundreds of MB. Keep one shared deadline for
@@ -5561,6 +5562,10 @@ app.on('ready', async () => {
// 端点清单已就绪、IPC 已注册,此后 second-instance / activate 允许按需建窗。
startupWindowCreationAllowed = true;
createWindow();
+ // 预热仅服务 dev macOS,延迟执行避免和启动关键路径争用 CPU;失败由入口内部吞掉。
+ setTimeout(() => {
+ prewarmMacComputerPermissionGuideHelper();
+ }, 3_000);
initUpdateService();
// 在线人数心跳:App 启动即上报,内部走 deviceId / userId 兜底,登录前后都活
initHeartbeatService();
diff --git a/apps/desktop/src/main/computer-permission-guide/MacComputerPermissionGuideNativeHost.ts b/apps/desktop/src/main/computer-permission-guide/MacComputerPermissionGuideNativeHost.ts
new file mode 100644
index 0000000000..cb3c3aaf3f
--- /dev/null
+++ b/apps/desktop/src/main/computer-permission-guide/MacComputerPermissionGuideNativeHost.ts
@@ -0,0 +1,380 @@
+import { execFile, spawn, type ChildProcessByStdio } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import type { Readable, Writable } from 'node:stream';
+import { app } from 'electron';
+
+import { createLogger } from '../logger.js';
+import type { SupportedLocale } from '../../shared/locale.js';
+
+const log = createLogger('computer-permission-guide/native');
+const HELPER_RESOURCE = path.join(
+ 'tools',
+ 'computer-permission-guide',
+ 'xdt-macos-computer-permission-guide-helper',
+);
+const HELPER_SOURCE_RELATIVE = path.join(
+ 'native',
+ 'computer-permission-guide',
+ 'macos-computer-permission-guide-helper.swift',
+);
+const HELPER_START_TIMEOUT_MS = 3_000;
+const HELPER_BUILD_TIMEOUT_MS = 30_000;
+let helperBinaryPromise: Promise<string> | null = null;
+
+type NativeProcess = ChildProcessByStdio<Writable, Readable, Readable>;
+
+/** State that affects the native coach without moving permission logic into Swift. */
+export interface ComputerPermissionGuideNativeState {
+ accessibilityGranted: boolean;
+ screenRecordingGranted: boolean;
+ draggedAccessibility: boolean;
+ draggedScreenRecording: boolean;
+ switchTargetX?: number;
+ switchTargetY?: number;
+ /** CuaDriver's coordinate-space size, used to normalize Retina bounds. */
+ switchWindowWidth?: number;
+ switchWindowHeight?: number;
+}
+
+/** Events emitted by the AppKit panel and its native dragging session. */
+export interface MacComputerPermissionGuideNativeHostOptions {
+ onCloseRequested: () => void;
+ onCompleted: () => void;
+ onAttached?: () => void;
+ onExited?: () => void;
+ onAuthSheetDismissed?: () => void;
+ onDragBegan: (permission: 'accessibility' | 'screenRecording') => void;
+ onDragEnded: (
+ permission: 'accessibility' | 'screenRecording',
+ operation: number,
+ ) => void;
+}
+
+interface NativePayload {
+ type?: unknown;
+ message?: unknown;
+ permission?: unknown;
+ operation?: unknown;
+ systemX?: unknown;
+ systemY?: unknown;
+ systemWidth?: unknown;
+ systemHeight?: unknown;
+ panelX?: unknown;
+ panelY?: unknown;
+}
+
+/**
+ * Owns the one-shot AppKit helper used by the macOS permission flow.
+ *
+ * Electron retains permission state and cancellation. The helper exclusively
+ * owns the non-activating NSPanel and NSDraggingSession, so clicking the coach
+ * never makes the Electron application frontmost.
+ */
+export class MacComputerPermissionGuideNativeHost {
+ private child: NativeProcess | null = null;
+ private stdoutBuffer = '';
+ private ready = false;
+ private starting: Promise<boolean> | null = null;
+ private pendingState: ComputerPermissionGuideNativeState | null = null;
+ private closeTimer: ReturnType<typeof setTimeout> | null = null;
+ private dismissed = false;
+
+ constructor(private readonly options: MacComputerPermissionGuideNativeHostOptions) {}
+
+ async show(
+ appBundlePath: string,
+ state: ComputerPermissionGuideNativeState,
+ locale: SupportedLocale = 'en',
+ ): Promise<boolean> {
+ if (this.dismissed) return false;
+ this.pendingState = state;
+ if (this.ready && this.child) {
+ this.flushState();
+ return true;
+ }
+ if (!this.starting) {
+ this.starting = this.start(appBundlePath, locale).finally(() => {
+ this.starting = null;
+ });
+ }
+ return this.starting;
+ }
+
+ update(state: ComputerPermissionGuideNativeState): void {
+ if (this.dismissed) return;
+ this.pendingState = state;
+ this.flushState();
+ }
+
+ dismiss(): void {
+ this.dismissed = true;
+ this.pendingState = null;
+ this.ready = false;
+ const child = this.child;
+ this.child = null;
+ if (!child || child.killed) return;
+ try {
+ child.stdin.write(`${JSON.stringify({ type: 'dismiss' })}\n`);
+ } catch {
+ // The helper may have already closed itself.
+ }
+ this.clearCloseTimer();
+ this.closeTimer = setTimeout(() => {
+ this.closeTimer = null;
+ if (!child.killed) child.kill();
+ }, 350);
+ }
+
+ private async start(appBundlePath: string, locale: SupportedLocale): Promise<boolean> {
+ let binary: string;
+ try {
+ binary = await resolveMacComputerPermissionGuideHelperBinary();
+ } catch (error) {
+ log.warn('native permission guide helper could not be prepared', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return false;
+ }
+ if (this.dismissed) return false;
+
+ return new Promise<boolean>((resolve) => {
+ let settled = false;
+ const child = spawn(binary, [appBundlePath, locale], {
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ this.child = child;
+ this.ready = false;
+ this.stdoutBuffer = '';
+
+ const settle = (ok: boolean): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(startTimer);
+ resolve(ok);
+ };
+ const startTimer = setTimeout(() => {
+ log.warn('native permission guide helper did not become ready in time');
+ settle(false);
+ if (this.child === child) this.child = null;
+ if (!child.killed) child.kill();
+ }, HELPER_START_TIMEOUT_MS);
+
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk: string) => {
+ this.stdoutBuffer += chunk;
+ let newline = this.stdoutBuffer.indexOf('\n');
+ while (newline >= 0) {
+ const line = this.stdoutBuffer.slice(0, newline).trim();
+ this.stdoutBuffer = this.stdoutBuffer.slice(newline + 1);
+ if (line) this.handlePayloadLine(line, child, settle);
+ newline = this.stdoutBuffer.indexOf('\n');
+ }
+ });
+
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk: string) => {
+ const text = chunk.trim();
+ if (text) log.debug('native permission guide helper stderr', { text });
+ });
+
+ child.stdin.on('error', (error) => {
+ log.debug('native permission guide helper stdin closed', { error: error.message });
+ });
+
+ child.on('error', (error) => {
+ log.warn('native permission guide helper process error', { error: error.message });
+ if (this.child === child) {
+ this.child = null;
+ this.ready = false;
+ }
+ settle(false);
+ });
+
+ child.on('exit', (code, signal) => {
+ this.clearCloseTimer();
+ if (this.child === child) {
+ this.child = null;
+ this.ready = false;
+ }
+ settle(false);
+ log.debug('native permission guide helper exited', { code, signal });
+ if (!this.dismissed) {
+ this.options.onExited?.();
+ }
+ });
+ });
+ }
+
+ private handlePayloadLine(
+ line: string,
+ child: NativeProcess,
+ settle: (ok: boolean) => void,
+ ): void {
+ let payload: NativePayload;
+ try {
+ payload = JSON.parse(line) as NativePayload;
+ } catch {
+ log.debug('native permission guide helper emitted invalid JSON');
+ return;
+ }
+
+ if (payload.type === 'auth-sheet-dismissed' && this.child === child) {
+ log.info('System Settings auth sheet dismissed; triggering permission recheck');
+ this.options.onAuthSheetDismissed?.();
+ return;
+ }
+ if (payload.type === 'ready' && this.child === child) {
+ this.ready = true;
+ settle(true);
+ this.flushState();
+ log.info('native permission guide helper ready');
+ return;
+ }
+ if (payload.type === 'error') {
+ log.warn('native permission guide helper error', {
+ message: typeof payload.message === 'string' ? payload.message : 'Unknown error',
+ });
+ if (this.child === child) {
+ this.child = null;
+ this.ready = false;
+ }
+ settle(false);
+ if (!child.killed) child.kill();
+ return;
+ }
+ if (payload.type === 'attached' && this.child === child) {
+ this.options.onAttached?.();
+ log.debug('native permission guide attached to System Settings', {
+ systemBounds: {
+ x: payload.systemX,
+ y: payload.systemY,
+ width: payload.systemWidth,
+ height: payload.systemHeight,
+ },
+ panelOrigin: { x: payload.panelX, y: payload.panelY },
+ });
+ return;
+ }
+ if (payload.type === 'close-requested' && this.child === child) {
+ this.options.onCloseRequested();
+ return;
+ }
+ if (payload.type === 'completed' && this.child === child) {
+ this.options.onCompleted();
+ return;
+ }
+ if (
+ payload.type === 'drag-began'
+ && this.child === child
+ && isPermission(payload.permission)
+ ) {
+ this.options.onDragBegan(payload.permission);
+ return;
+ }
+ if (
+ payload.type === 'drag-ended'
+ && this.child === child
+ && isPermission(payload.permission)
+ ) {
+ this.options.onDragEnded(
+ payload.permission,
+ typeof payload.operation === 'number' ? payload.operation : 0,
+ );
+ }
+ }
+
+ private flushState(): void {
+ if (!this.ready || !this.child || !this.pendingState) return;
+ try {
+ this.child.stdin.write(`${JSON.stringify({ type: 'update', ...this.pendingState })}\n`);
+ } catch (error) {
+ log.warn('failed to update native permission guide helper', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
+ private clearCloseTimer(): void {
+ if (!this.closeTimer) return;
+ clearTimeout(this.closeTimer);
+ this.closeTimer = null;
+ }
+}
+
+function isPermission(value: unknown): value is 'accessibility' | 'screenRecording' {
+ return value === 'accessibility' || value === 'screenRecording';
+}
+
+function resolveMacComputerPermissionGuideHelperBinary(): Promise<string> {
+ if (helperBinaryPromise) return helperBinaryPromise;
+ helperBinaryPromise = buildMacComputerPermissionGuideHelperBinary().finally(() => {
+ // 编译完成后释放 memo,避免缓存过期路径阻塞后续源码变更后的重试。
+ helperBinaryPromise = null;
+ });
+ return helperBinaryPromise;
+}
+
+async function buildMacComputerPermissionGuideHelperBinary(): Promise<string> {
+ if (app.isPackaged) return path.join(process.resourcesPath, HELPER_RESOURCE);
+ const source = resolveDevHelperSource();
+ const binary = path.join(
+ app.getPath('userData'),
+ 'computer-permission-guide',
+ 'xdt-macos-computer-permission-guide-helper',
+ );
+ const hashFile = `${binary}.sha256`;
+ if (!fs.existsSync(source)) {
+ throw new Error(`Computer permission guide helper source missing at ${source}`);
+ }
+ const sourceHash = createHash('sha256').update(fs.readFileSync(source)).digest('hex');
+ if (
+ fs.existsSync(binary)
+ && fs.existsSync(hashFile)
+ && fs.readFileSync(hashFile, 'utf8').trim() === sourceHash
+ ) {
+ return binary;
+ }
+
+ fs.mkdirSync(path.dirname(binary), { recursive: true });
+ await execFilePromise('swiftc', [source, '-O', '-o', binary], HELPER_BUILD_TIMEOUT_MS);
+ fs.chmodSync(binary, 0o755);
+ fs.writeFileSync(hashFile, `${sourceHash}\n`, 'utf8');
+ log.info('built dev macOS computer permission guide helper', { path: binary });
+ return binary;
+}
+
+/**
+ * Starts preparing the dev helper without making startup depend on compilation.
+ *
+ * The packaged helper is already present in resources, so prewarming it is
+ * intentionally limited to the dev macOS path.
+ */
+export function prewarmMacComputerPermissionGuideHelper(): void {
+ if (process.platform !== 'darwin' || app.isPackaged) return;
+ void resolveMacComputerPermissionGuideHelperBinary().catch((error) => {
+ log.warn('failed to prewarm dev macOS computer permission guide helper', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+}
+
+function resolveDevHelperSource(): string {
+ const fromAppPath = path.join(app.getAppPath(), HELPER_SOURCE_RELATIVE);
+ if (fs.existsSync(fromAppPath)) return fromAppPath;
+ return path.join(__dirname, '..', '..', HELPER_SOURCE_RELATIVE);
+}
+
+function execFilePromise(command: string, args: string[], timeoutMs: number): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const child = execFile(command, args, { timeout: timeoutMs }, (error, _stdout, stderr) => {
+ if (error) {
+ reject(new Error(stderr?.trim() ? `${error.message}: ${stderr.trim()}` : error.message));
+ return;
+ }
+ resolve();
+ });
+ child.on('error', reject);
+ });
+}
diff --git a/apps/desktop/src/main/computer-permission-guide/__tests__/MacComputerPermissionGuideNativeHost.test.ts b/apps/desktop/src/main/computer-permission-guide/__tests__/MacComputerPermissionGuideNativeHost.test.ts
new file mode 100644
index 0000000000..eeff980e24
--- /dev/null
+++ b/apps/desktop/src/main/computer-permission-guide/__tests__/MacComputerPermissionGuideNativeHost.test.ts
@@ -0,0 +1,343 @@
+import { EventEmitter } from 'node:events';
+import fs from 'node:fs';
+import { PassThrough } from 'node:stream';
+import type { ChildProcessByStdio } from 'node:child_process';
+import type { Readable, Writable } from 'node:stream';
+import { app } from 'electron';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ spawn: vi.fn(),
+ execFile: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ app: {
+ isPackaged: true,
+ getAppPath: vi.fn(),
+ getPath: vi.fn(),
+ },
+}));
+
+vi.mock('node:child_process', () => ({
+ spawn: h.spawn,
+ execFile: h.execFile,
+}));
+
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+type FakeNativeProcess = Omit<
+ ChildProcessByStdio<Writable, Readable, Readable>,
+ 'stdin' | 'stdout' | 'stderr'
+> & {
+ stdin: PassThrough;
+ stdout: PassThrough;
+ stderr: PassThrough;
+ emit(event: 'exit', code: number | null, signal: NodeJS.Signals | null): boolean;
+ emit(event: 'error', error: Error): boolean;
+};
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ Object.defineProperty(process, 'resourcesPath', {
+ value: '/Applications/XDMaker.app/Contents/Resources',
+ configurable: true,
+ });
+ h.spawn.mockReset();
+ h.execFile.mockReset();
+});
+
+afterEach(() => {
+ Object.defineProperty(app, 'isPackaged', { value: true, configurable: true });
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe('MacComputerPermissionGuideNativeHost', () => {
+ it('keeps the native app row below the title and names the setup action', () => {
+ const source = fs.readFileSync(
+ new URL(
+ '../../../../native/computer-permission-guide/macos-computer-permission-guide-helper.swift',
+ import.meta.url,
+ ),
+ 'utf8',
+ );
+
+ expect(source).toContain('hostSize = NSSize(width: 500, height: 226)');
+ expect(source).toContain('cardFrame = NSRect(x: 68, y: 12, width: 432, height: 152)');
+ expect(source).toContain('"Open computer automation"');
+ expect(source).toContain('setAccessibilityLabel("CuaDriver")');
+ expect(source).not.toContain('setAccessibilityLabel("Computer Use")');
+ expect(source).not.toContain('"Computer Use · Step');
+ expect(source).toContain(
+ 'if let desiredFrame = attachedSwitchGuideFrame(settingsFrame: settingsFrame)',
+ );
+ expect(source).toContain(
+ '// until a precise switch target becomes available.',
+ );
+ expect(source).not.toContain(
+ 'guard let desiredFrame = attachedSwitchGuideFrame(settingsFrame: settingsFrame) else',
+ );
+ });
+
+ it('detects auth modals from AX modal relationships instead of window count', () => {
+ const source = fs.readFileSync(
+ new URL(
+ '../../../../native/computer-permission-guide/macos-computer-permission-guide-helper.swift',
+ import.meta.url,
+ ),
+ 'utf8',
+ );
+
+ expect(source).toContain('kAXChildrenAttribute');
+ expect(source).toContain('kAXSheetRole');
+ expect(source).toContain('kAXModalAttribute');
+ expect(source).toContain('AXIsProcessTrusted()');
+ expect(source).toContain('systemSettingsAttachedSheetCandidates');
+ expect(source).toContain('didEstablishFallbackWindowBaseline');
+ expect(source).toContain('presentation == .switchGuide');
+ expect(source).toContain('intersectionArea >= area * 0.9');
+ expect(source).toContain('didEncounterUnavailableAttribute = true');
+ expect(source).toContain('return didEncounterUnavailableAttribute ? nil : false');
+ expect(source).not.toContain('attribute: kAXChildrenAttribute as CFString\n ) ?? []');
+ expect(source).not.toContain('layerZeroCount');
+
+ const resolver = source.slice(
+ source.indexOf('private func resolveModalSheetState'),
+ source.indexOf('private func attachedPanelFrame'),
+ );
+ expect(resolver).toContain(
+ 'fallbackModalWindowIDs = info.attachedSheetCandidateWindowIDs',
+ );
+ expect(resolver).toContain(
+ 'if !hadTrackedFallbackModal && fallbackModalWindowIDs.isEmpty',
+ );
+ expect(resolver.indexOf('if authSheetVisible')).toBeLessThan(
+ resolver.indexOf('if !didEstablishFallbackWindowBaseline'),
+ );
+ });
+
+ it('uses app locale copy and appearance-aware colors in the native helper', () => {
+ const source = fs.readFileSync(
+ new URL(
+ '../../../../native/computer-permission-guide/macos-computer-permission-guide-helper.swift',
+ import.meta.url,
+ ),
+ 'utf8',
+ );
+
+ expect(source).toContain('case ja');
+ expect(source).toContain('case ko');
+ expect(source).toContain('GuideLocale(rawValue: CommandLine.arguments[2])');
+ expect(source).not.toContain('usesChineseCopy');
+ expect(source).toContain('NSColor.controlBackgroundColor.cgColor');
+ expect(source).toContain('NSColor.separatorColor.cgColor');
+ expect(source).toContain('viewDidChangeEffectiveAppearance()');
+ expect(source).not.toContain('layer?.backgroundColor = NSColor.white.cgColor');
+ });
+
+ it('quotes bundle paths passed from find to both macOS signing flows', () => {
+ const source = fs.readFileSync(
+ new URL('../../../../scripts/ci/lib.mjs', import.meta.url),
+ 'utf8',
+ );
+
+ expect(source).toContain('${signBase} "{}" \\\\;');
+ expect(source).toContain('"${helperEntitlementsPath}" "{}" \\\\;');
+ expect(source).not.toContain('${signBase} {} \\\\;');
+ expect(source).not.toContain('"${helperEntitlementsPath}" {} \\\\;');
+ });
+
+ it('starts the packaged helper and sends permission state after ready', async () => {
+ const child = createFakeChild();
+ const writes: string[] = [];
+ child.stdin.on('data', (chunk) => writes.push(chunk.toString()));
+ h.spawn.mockReturnValue(child);
+ const { MacComputerPermissionGuideNativeHost } = await import(
+ '../MacComputerPermissionGuideNativeHost.js'
+ );
+ const host = new MacComputerPermissionGuideNativeHost(createOptions());
+ const showPromise = host.show('/tmp/Computer Use.app', {
+ accessibilityGranted: false,
+ screenRecordingGranted: false,
+ draggedAccessibility: true,
+ draggedScreenRecording: false,
+ }, 'ja');
+
+ await vi.advanceTimersByTimeAsync(0);
+ expect(h.spawn).toHaveBeenCalledWith(
+ '/Applications/XDMaker.app/Contents/Resources/tools/computer-permission-guide/xdt-macos-computer-permission-guide-helper',
+ ['/tmp/Computer Use.app', 'ja'],
+ { stdio: ['pipe', 'pipe', 'pipe'] },
+ );
+ child.stdout.write('{"type":"ready"}\n');
+ await expect(showPromise).resolves.toBe(true);
+ expect(writes).toContain(`${JSON.stringify({
+ type: 'update',
+ accessibilityGranted: false,
+ screenRecordingGranted: false,
+ draggedAccessibility: true,
+ draggedScreenRecording: false,
+ })}\n`);
+ });
+
+ it('forwards native drag lifecycle and close events', async () => {
+ const child = createFakeChild();
+ h.spawn.mockReturnValue(child);
+ const options = createOptions();
+ const { MacComputerPermissionGuideNativeHost } = await import(
+ '../MacComputerPermissionGuideNativeHost.js'
+ );
+ const host = new MacComputerPermissionGuideNativeHost(options);
+ const showPromise = host.show('/tmp/Computer Use.app', emptyState());
+ await vi.advanceTimersByTimeAsync(0);
+ child.stdout.write('{"type":"ready"}\n');
+ await showPromise;
+
+ child.stdout.write('{"type":"drag-began","permission":"accessibility"}\n');
+ child.stdout.write('{"type":"drag-ended","permission":"accessibility","operation":1}\n');
+ child.stdout.write('{"type":"attached","systemX":10,"systemY":20,"systemWidth":900,"systemHeight":600}\n');
+ child.stdout.write('{"type":"close-requested"}\n');
+
+ expect(options.onDragBegan).toHaveBeenCalledWith('accessibility');
+ expect(options.onDragEnded).toHaveBeenCalledWith('accessibility', 1);
+ expect(options.onAttached).toHaveBeenCalledOnce();
+ expect(options.onCloseRequested).toHaveBeenCalledOnce();
+ });
+
+ it('fails closed when the helper never becomes ready', async () => {
+ const child = createFakeChild();
+ h.spawn.mockReturnValue(child);
+ const { MacComputerPermissionGuideNativeHost } = await import(
+ '../MacComputerPermissionGuideNativeHost.js'
+ );
+ const host = new MacComputerPermissionGuideNativeHost(createOptions());
+ const showPromise = host.show('/tmp/Computer Use.app', emptyState());
+
+ await vi.advanceTimersByTimeAsync(3_000);
+
+ await expect(showPromise).resolves.toBe(false);
+ expect(child.kill).toHaveBeenCalledOnce();
+ });
+
+ it('joins concurrent dev helper preparation and retries after a failed build', async () => {
+ Object.defineProperty(app, 'isPackaged', { value: false, configurable: true });
+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ vi.mocked(app.getAppPath).mockReturnValue('/tmp/cindy-app');
+ vi.mocked(app.getPath).mockReturnValue('/tmp/cindy-user-data');
+ vi.spyOn(fs, 'existsSync').mockImplementation((target) => String(target).endsWith('.swift'));
+ vi.spyOn(fs, 'readFileSync').mockReturnValue(Buffer.from('swift-source'));
+ vi.spyOn(fs, 'mkdirSync').mockImplementation(() => undefined);
+ vi.spyOn(fs, 'chmodSync').mockImplementation(() => undefined);
+ vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
+
+ let finishBuild:
+ | ((error: Error | null, stdout?: string, stderr?: string) => void)
+ | null = null;
+ h.execFile.mockImplementation((_command, _args, _options, callback) => {
+ finishBuild = callback as (error: Error | null, stdout?: string, stderr?: string) => void;
+ return new EventEmitter();
+ });
+ const child = createFakeChild();
+ h.spawn.mockReturnValue(child);
+ const { MacComputerPermissionGuideNativeHost, prewarmMacComputerPermissionGuideHelper } =
+ await import('../MacComputerPermissionGuideNativeHost.js');
+
+ prewarmMacComputerPermissionGuideHelper();
+ const showPromise = new MacComputerPermissionGuideNativeHost(createOptions()).show(
+ '/tmp/Computer Use.app',
+ emptyState(),
+ );
+ expect(h.execFile).toHaveBeenCalledOnce();
+ const buildCallback = finishBuild as unknown as ((
+ error: Error | null,
+ stdout?: string,
+ stderr?: string,
+ ) => void);
+ buildCallback(new Error('swiftc failed'), '', '');
+ await expect(showPromise).resolves.toBe(false);
+
+ prewarmMacComputerPermissionGuideHelper();
+ expect(h.execFile).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not spawn a helper after dismissal while binary preparation is pending', async () => {
+ Object.defineProperty(app, 'isPackaged', { value: false, configurable: true });
+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ vi.mocked(app.getAppPath).mockReturnValue('/tmp/cindy-app');
+ vi.mocked(app.getPath).mockReturnValue('/tmp/cindy-user-data');
+ vi.spyOn(fs, 'existsSync').mockImplementation((target) => String(target).endsWith('.swift'));
+ vi.spyOn(fs, 'readFileSync').mockReturnValue(Buffer.from('swift-source'));
+ vi.spyOn(fs, 'mkdirSync').mockImplementation(() => undefined);
+ vi.spyOn(fs, 'chmodSync').mockImplementation(() => undefined);
+ vi.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);
+
+ let finishBuild:
+ | ((error: Error | null, stdout?: string, stderr?: string) => void)
+ | null = null;
+ h.execFile.mockImplementation((_command, _args, _options, callback) => {
+ finishBuild = callback as (error: Error | null, stdout?: string, stderr?: string) => void;
+ return new EventEmitter();
+ });
+ const { MacComputerPermissionGuideNativeHost } = await import(
+ '../MacComputerPermissionGuideNativeHost.js'
+ );
+ const host = new MacComputerPermissionGuideNativeHost(createOptions());
+ const showPromise = host.show('/tmp/Computer Use.app', emptyState());
+ await Promise.resolve();
+ expect(h.execFile).toHaveBeenCalledOnce();
+
+ host.dismiss();
+ const buildCallback = finishBuild as unknown as ((
+ error: Error | null,
+ stdout?: string,
+ stderr?: string,
+ ) => void);
+ buildCallback(null, '', '');
+
+ await expect(showPromise).resolves.toBe(false);
+ expect(h.spawn).not.toHaveBeenCalled();
+ });
+});
+
+function emptyState() {
+ return {
+ accessibilityGranted: false,
+ screenRecordingGranted: false,
+ draggedAccessibility: false,
+ draggedScreenRecording: false,
+ };
+}
+
+function createOptions() {
+ return {
+ onCloseRequested: vi.fn(),
+ onCompleted: vi.fn(),
+ onAttached: vi.fn(),
+ onDragBegan: vi.fn(),
+ onDragEnded: vi.fn(),
+ };
+}
+
+function createFakeChild(): FakeNativeProcess {
+ const emitter = new EventEmitter() as FakeNativeProcess;
+ Object.assign(emitter, {
+ stdin: new PassThrough(),
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ killed: false,
+ kill: vi.fn(() => {
+ Object.assign(emitter, { killed: true });
+ return true;
+ }),
+ });
+ return emitter;
+}
diff --git a/apps/desktop/src/main/computer-permission-guide/__tests__/electron-window.test.ts b/apps/desktop/src/main/computer-permission-guide/__tests__/electron-window.test.ts
new file mode 100644
index 0000000000..d9b36b27f2
--- /dev/null
+++ b/apps/desktop/src/main/computer-permission-guide/__tests__/electron-window.test.ts
@@ -0,0 +1,1524 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import type { BrowserWindowConstructorOptions, WebContents } from 'electron';
+
+const originalPlatform = process.platform;
+const VALID_PNG_DATA_URL = 'data:image/png;base64,iVBORw0KGgo=';
+
+const harness = vi.hoisted(() => {
+ const windows: FakeWindow[] = [];
+ const nativeHostState: {
+ options: Record<string, (...args: unknown[]) => void> | null;
+ allOptions: Array<Record<string, (...args: unknown[]) => void>>;
+ } = { options: null, allOptions: [] };
+ const nativeShow = vi.fn();
+ const nativeUpdate = vi.fn();
+ const nativeDismiss = vi.fn();
+ const cancelComputerDriverPermissionGrant = vi.fn();
+ const closeComputerUseSwitchLocator = vi.fn(async () => undefined);
+ let nextGuideLoadError: Error | null = null;
+ const computerStatus = (permissionState: Partial<{
+ status: 'missing' | 'granted' | 'unknown';
+ accessibility: 'missing' | 'granted' | 'unknown';
+ screenRecording: 'missing' | 'granted' | 'unknown';
+ screenRecordingCapturable: 'missing' | 'granted' | 'unknown';
+ }> = {}) => ({
+ installed: true,
+ executablePath: '/tmp/cua-driver',
+ version: 'test',
+ daemonRunning: true,
+ installCommand: 'test',
+ docsUrl: 'https://cua.ai/docs/cua-driver',
+ permissionState: {
+ platform: 'macos' as const,
+ required: true,
+ status: 'missing' as const,
+ accessibility: 'missing' as const,
+ screenRecording: 'missing' as const,
+ screenRecordingCapturable: 'missing' as const,
+ canGrant: true,
+ ...permissionState,
+ },
+ });
+ const getComputerDriverStatus = vi.fn(async (
+ options?: { bypassPermissionProbeCache?: boolean },
+ ) => {
+ void options;
+ return computerStatus();
+ });
+ const resumeComputerDriverPermissionProbe = vi.fn();
+ const broadcastSend = vi.fn();
+ const openExternal = vi.fn(async () => undefined);
+ let deferWindowClosedEvents = false;
+ let nextId = 100;
+ const broadcastRecipient = {
+ isDestroyed: () => false,
+ webContents: { send: broadcastSend },
+ };
+
+ class FakeWindow {
+ readonly webContents = {
+ id: nextId++,
+ once: vi.fn((event: string, callback: () => void) => {
+ this.listeners.set(event, callback);
+ }),
+ on: vi.fn((event: string, callback: (...args: unknown[]) => void) => {
+ this.listeners.set(event, callback);
+ }),
+ setWindowOpenHandler: vi.fn(),
+ send: vi.fn(),
+ startDrag: vi.fn(),
+ };
+ readonly listeners = new Map<string, (...args: unknown[]) => void>();
+ readonly loadURL = vi.fn(async (url?: string) => {
+ if (nextGuideLoadError && url?.includes('view=computer-permission-guide')) {
+ const error = nextGuideLoadError;
+ nextGuideLoadError = null;
+ throw error;
+ }
+ this.listeners.get('did-finish-load')?.();
+ });
+ readonly loadFile = vi.fn(async () => {
+ this.listeners.get('did-finish-load')?.();
+ });
+ readonly setIgnoreMouseEvents = vi.fn();
+ readonly setAlwaysOnTop = vi.fn();
+ readonly setVisibleOnAllWorkspaces = vi.fn();
+ readonly showInactive = vi.fn();
+ readonly setBounds = vi.fn();
+ readonly getBounds = vi.fn(() => ({ x: 0, y: 0, width: 900, height: 700 }));
+ readonly close = vi.fn(() => {
+ this.destroyed = true;
+ if (!deferWindowClosedEvents) this.listeners.get('closed')?.();
+ });
+ destroyed = false;
+
+ constructor(readonly options: BrowserWindowConstructorOptions) {
+ windows.push(this);
+ }
+
+ once(event: string, callback: (...args: unknown[]) => void): void {
+ this.listeners.set(event, callback);
+ }
+
+ isDestroyed(): boolean {
+ return this.destroyed;
+ }
+
+ static getAllWindows(): Array<FakeWindow | typeof broadcastRecipient> {
+ return [...windows, broadcastRecipient];
+ }
+ }
+
+ class FakeNativeHost {
+ constructor(options: Record<string, (...args: unknown[]) => void>) {
+ nativeHostState.options = options;
+ nativeHostState.allOptions.push(options);
+ }
+
+ show(...args: unknown[]): Promise<boolean> {
+ return nativeShow(...args);
+ }
+
+ update(...args: unknown[]): void {
+ nativeUpdate(...args);
+ }
+
+ dismiss(): void {
+ nativeDismiss();
+ }
+ }
+
+ return {
+ FakeWindow,
+ FakeNativeHost,
+ windows,
+ nativeHostState,
+ nativeShow,
+ nativeUpdate,
+ nativeDismiss,
+ cancelComputerDriverPermissionGrant,
+ closeComputerUseSwitchLocator,
+ computerStatus,
+ getComputerDriverStatus,
+ resumeComputerDriverPermissionProbe,
+ broadcastSend,
+ openExternal,
+ setNextGuideLoadError: (error: Error | null) => {
+ nextGuideLoadError = error;
+ },
+ setDeferWindowClosedEvents: (defer: boolean) => {
+ deferWindowClosedEvents = defer;
+ },
+ app: { getPath: () => '/tmp/cindy-computer-permission-guide-test' },
+ nativeImage: {
+ createFromDataURL: vi.fn(() => ({ isEmpty: () => false })),
+ },
+ locateComputerUseSwitchTarget: vi.fn(async () => (
+ { status: 'unavailable' } as
+ | {
+ status: 'unavailable' | 'not-found';
+ systemWindowBounds?: { x: number; y: number; width: number; height: number };
+ }
+ | {
+ status: 'found';
+ target: {
+ x: number;
+ y: number;
+ permission: 'accessibility' | 'screenRecording';
+ enabled: boolean | null;
+ };
+ systemWindowBounds?: { x: number; y: number; width: number; height: number };
+ }
+ )),
+ isComputerDriverPermissionProbePaused: vi.fn(() => false),
+ screen: {
+ getDisplayMatching: vi.fn(() => ({
+ workArea: { x: 0, y: 0, width: 1440, height: 900 },
+ })),
+ getDisplayNearestPoint: vi.fn(() => ({
+ workArea: { x: 0, y: 0, width: 1440, height: 900 },
+ })),
+ getCursorScreenPoint: vi.fn(() => ({ x: 10, y: 10 })),
+ },
+ };
+});
+
+vi.mock('electron', () => ({
+ app: harness.app,
+ BrowserWindow: harness.FakeWindow,
+ nativeImage: harness.nativeImage,
+ shell: { openExternal: harness.openExternal },
+ screen: harness.screen,
+}));
+
+vi.mock('../../appPresence.js', () => ({
+ scheduleMainAppPresenceRestore: vi.fn(),
+}));
+
+vi.mock('../../i18n.js', () => ({
+ getResolvedMainLocale: vi.fn(() => 'ja'),
+}));
+
+vi.mock('../../mcp-integrations/computer.js', () => ({
+ getComputerDriverAppBundlePath: vi.fn(() => '/Applications/CuaDriver.app'),
+ getComputerDriverStatus: harness.getComputerDriverStatus,
+ isComputerDriverPermissionProbePaused: harness.isComputerDriverPermissionProbePaused,
+ resumeComputerDriverPermissionProbe: harness.resumeComputerDriverPermissionProbe,
+ cancelComputerDriverPermissionGrant: harness.cancelComputerDriverPermissionGrant,
+}));
+
+vi.mock('../switch-target.js', () => ({
+ locateComputerUseSwitchTarget: harness.locateComputerUseSwitchTarget,
+ closeComputerUseSwitchLocator: harness.closeComputerUseSwitchLocator,
+}));
+
+vi.mock('../MacComputerPermissionGuideNativeHost.js', () => ({
+ MacComputerPermissionGuideNativeHost: harness.FakeNativeHost,
+}));
+
+function createDeferred<T>(): {
+ promise: Promise<T>;
+ resolve: (value: T) => void;
+} {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+ return { promise, resolve };
+}
+
+function finishTestDrag(guide: typeof import('../window')): void {
+ const sender = harness.windows[1].webContents as unknown as WebContents;
+ guide.startComputerPermissionAppDrag(sender, VALID_PNG_DATA_URL);
+ guide.finishComputerPermissionAppDrag(sender, true);
+}
+
+function writeDragState(state: {
+ accessibility: boolean;
+ screenRecording: boolean;
+}): void {
+ const directory = '/tmp/cindy-computer-permission-guide-test/computer-permission-guide';
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(
+ `${directory}/cua-driver-drag-state-v2.json`,
+ `${JSON.stringify(state)}\n`,
+ 'utf8',
+ );
+}
+
+function permissionProbeCalls(bypass: boolean): unknown[][] {
+ return harness.getComputerDriverStatus.mock.calls.filter(
+ ([options]) => Boolean(options?.bypassPermissionProbeCache) === bypass,
+ );
+}
+
+const fullPermissionProbeCalls = (): unknown[][] => permissionProbeCalls(true);
+const normalPermissionProbeCalls = (): unknown[][] => permissionProbeCalls(false);
+
+type SwitchLocation = Awaited<
+ ReturnType<typeof harness.locateComputerUseSwitchTarget>
+>;
+
+function foundSwitchLocation(
+ enabled: boolean | null,
+ {
+ x = 901,
+ y = 442,
+ permission = 'accessibility',
+ }: {
+ x?: number;
+ y?: number;
+ permission?: 'accessibility' | 'screenRecording';
+ } = {},
+): SwitchLocation {
+ return {
+ status: 'found',
+ target: { x, y, permission, enabled },
+ };
+}
+
+async function expectPermissionProbeCounts(
+ full: number,
+ normal?: number,
+): Promise<void> {
+ await vi.waitFor(() => {
+ expect(fullPermissionProbeCalls()).toHaveLength(full);
+ if (normal !== undefined) {
+ expect(normalPermissionProbeCalls()).toHaveLength(normal);
+ }
+ });
+}
+
+async function startObserverThrottleTest(
+ firstLocation: SwitchLocation,
+ ...nextLocations: SwitchLocation[]
+): Promise<typeof import('../window')> {
+ vi.useFakeTimers();
+ vi.setSystemTime(10_000);
+ const locations = [firstLocation, ...nextLocations];
+ for (const location of locations.slice(0, -1)) {
+ harness.locateComputerUseSwitchTarget.mockResolvedValueOnce(location);
+ }
+ harness.locateComputerUseSwitchTarget.mockResolvedValue(
+ nextLocations.at(-1) ?? firstLocation,
+ );
+
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null, harness.computerStatus());
+ finishTestDrag(guide);
+ await expectPermissionProbeCounts(1, 0);
+ return guide;
+}
+
+describe('Electron Computer Use permission guide window', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ harness.windows.splice(0);
+ harness.nativeHostState.options = null;
+ harness.nativeHostState.allOptions.splice(0);
+ harness.setDeferWindowClosedEvents(false);
+ harness.nativeShow.mockReset();
+ harness.nativeShow.mockResolvedValue(true);
+ harness.nativeUpdate.mockReset();
+ harness.nativeDismiss.mockReset();
+ harness.cancelComputerDriverPermissionGrant.mockReset();
+ harness.closeComputerUseSwitchLocator.mockReset();
+ harness.closeComputerUseSwitchLocator.mockResolvedValue(undefined);
+ harness.getComputerDriverStatus.mockReset();
+ harness.getComputerDriverStatus.mockResolvedValue(harness.computerStatus());
+ harness.resumeComputerDriverPermissionProbe.mockReset();
+ harness.broadcastSend.mockReset();
+ harness.openExternal.mockReset();
+ harness.openExternal.mockResolvedValue(undefined);
+ harness.setNextGuideLoadError(null);
+ harness.locateComputerUseSwitchTarget.mockResolvedValue({ status: 'unavailable' });
+ harness.locateComputerUseSwitchTarget.mockClear();
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(false);
+ fs.rmSync(
+ '/tmp/cindy-computer-permission-guide-test/computer-permission-guide',
+ { recursive: true, force: true },
+ );
+ vi.stubGlobal('MAIN_WINDOW_VITE_DEV_SERVER_URL', 'http://127.0.0.1:5173');
+ vi.stubGlobal('MAIN_WINDOW_VITE_NAME', 'main_window');
+ Object.defineProperty(process, 'platform', {
+ configurable: true,
+ value: 'darwin',
+ });
+ });
+
+ afterEach(async () => {
+ const guide = await import('../window');
+ guide.closeComputerPermissionGuideWindow();
+ vi.useRealTimers();
+ Object.defineProperty(process, 'platform', {
+ configurable: true,
+ value: originalPlatform,
+ });
+ });
+
+ it('creates the guide and mouse-transparent backdrop routes', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+
+ expect(harness.windows).toHaveLength(2);
+ expect(harness.windows[0].loadURL).toHaveBeenCalledWith(
+ expect.stringContaining('view=computer-permission-backdrop'),
+ );
+ expect(harness.windows[1].loadURL).toHaveBeenCalledWith(
+ expect.stringContaining('view=computer-permission-guide'),
+ );
+ const requiredSecurityPreferences = {
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ experimentalFeatures: false,
+ plugins: false,
+ navigateOnDragDrop: false,
+ };
+ expect(harness.windows[0].options.webPreferences).toMatchObject(
+ requiredSecurityPreferences,
+ );
+ expect(harness.windows[1].options.webPreferences).toMatchObject(
+ requiredSecurityPreferences,
+ );
+ for (const permissionWindow of harness.windows) {
+ expect(permissionWindow.webContents.setWindowOpenHandler).toHaveBeenCalledOnce();
+ const preventDefault = vi.fn();
+ permissionWindow.listeners.get('will-navigate')?.({ preventDefault });
+ expect(preventDefault).toHaveBeenCalledOnce();
+ }
+ expect(guide.isComputerPermissionGuideWebContents(
+ harness.windows[1].webContents as unknown as WebContents,
+ )).toBe(true);
+ expect(guide.isComputerPermissionGuideWebContents(
+ harness.windows[0].webContents as unknown as WebContents,
+ )).toBe(false);
+ expect(guide.getComputerPermissionGuideStatus(
+ harness.windows[1].webContents as unknown as WebContents,
+ )).toEqual(harness.computerStatus());
+ expect(guide.getComputerPermissionGuideStatus(
+ harness.windows[0].webContents as unknown as WebContents,
+ )).toBeNull();
+ });
+
+ it('closes the persistent switch locator when the whole guide closes', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+
+ guide.closeComputerPermissionGuideWindow();
+
+ expect(harness.closeComputerUseSwitchLocator).toHaveBeenCalledOnce();
+ });
+
+ it('selects and deduplicates the System Settings permission pane URL', async () => {
+ const guide = await import('../window');
+ const status = (permissionState: Record<string, string>) =>
+ ({ permissionState } as unknown as Parameters<typeof guide.getComputerPermissionPaneUrl>[0]);
+
+ expect(guide.getComputerPermissionPaneUrl(status({
+ accessibility: 'missing',
+ screenRecording: 'missing',
+ }))).toBe(
+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility',
+ );
+ expect(guide.getComputerPermissionPaneUrl(status({
+ accessibility: 'granted',
+ screenRecording: 'missing',
+ }))).toBe(
+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture',
+ );
+ expect(guide.getComputerPermissionPaneUrl(status({
+ accessibility: 'granted',
+ screenRecording: 'granted',
+ screenRecordingCapturable: 'granted',
+ }))).toBeNull();
+
+ await guide.openComputerPermissionPaneForStatus(status({
+ accessibility: 'missing',
+ screenRecording: 'missing',
+ }));
+ await guide.openComputerPermissionPaneForStatus(status({
+ accessibility: 'missing',
+ screenRecording: 'missing',
+ }));
+ expect(harness.openExternal).toHaveBeenCalledOnce();
+ });
+
+ it('retries opening a permission pane after shell launch failure', async () => {
+ harness.openExternal
+ .mockRejectedValueOnce(new Error('launch failed'))
+ .mockResolvedValueOnce(undefined);
+ const guide = await import('../window');
+ const missingAccessibility = {
+ permissionState: {
+ accessibility: 'missing',
+ screenRecording: 'missing',
+ },
+ } as unknown as Parameters<typeof guide.openComputerPermissionPaneForStatus>[0];
+
+ await guide.openComputerPermissionPaneForStatus(missingAccessibility);
+ await guide.openComputerPermissionPaneForStatus(missingAccessibility);
+
+ expect(harness.openExternal).toHaveBeenCalledTimes(2);
+ });
+
+ it('starts the native guide at the first missing permission without showing the old fallback', async () => {
+ vi.useFakeTimers();
+ const guide = await import('../window');
+ const initialStatus = harness.computerStatus({ accessibility: 'granted' });
+
+ await guide.showComputerPermissionGuideWindow(null, initialStatus);
+ await vi.waitFor(() => {
+ expect(harness.nativeShow).toHaveBeenCalledWith(
+ '/Applications/CuaDriver.app',
+ expect.objectContaining({
+ accessibilityGranted: true,
+ screenRecordingGranted: false,
+ }),
+ 'ja',
+ );
+ });
+
+ expect(harness.windows[0].showInactive).not.toHaveBeenCalled();
+ expect(harness.windows[1].showInactive).not.toHaveBeenCalled();
+
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ harness.nativeHostState.options?.onAttached?.();
+ expect(harness.closeComputerUseSwitchLocator).not.toHaveBeenCalled();
+ harness.nativeUpdate.mockClear();
+ harness.nativeHostState.options?.onDragEnded?.('screenRecording', 0);
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenCalledWith(expect.objectContaining({
+ accessibilityGranted: true,
+ screenRecordingGranted: false,
+ }));
+ });
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(harness.nativeDismiss).not.toHaveBeenCalled();
+ });
+
+ it('routes native cancellation and completion through whole-guide locator teardown', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ await vi.waitFor(() => {
+ expect(harness.nativeShow).toHaveBeenCalled();
+ });
+
+ harness.nativeHostState.options?.onCloseRequested?.();
+ expect(harness.cancelComputerDriverPermissionGrant).toHaveBeenCalledOnce();
+ expect(harness.closeComputerUseSwitchLocator).toHaveBeenCalledOnce();
+
+ await guide.showComputerPermissionGuideWindow(null);
+ await vi.waitFor(() => {
+ expect(harness.nativeShow).toHaveBeenCalledTimes(2);
+ });
+ harness.nativeHostState.options?.onCompleted?.();
+ expect(harness.closeComputerUseSwitchLocator).toHaveBeenCalledTimes(2);
+ });
+
+ it('cancels an unattached native guide after the Electron safety timeout', async () => {
+ vi.useFakeTimers();
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ await vi.waitFor(() => {
+ expect(harness.nativeShow).toHaveBeenCalled();
+ });
+
+ await vi.advanceTimersByTimeAsync(30_000);
+
+ expect(harness.nativeDismiss).toHaveBeenCalledOnce();
+ expect(harness.closeComputerUseSwitchLocator).toHaveBeenCalledOnce();
+ expect(harness.broadcastSend).toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-cancelled',
+ );
+ });
+
+ it('keeps the attach timeout armed when the locator finds window bounds first', async () => {
+ vi.useFakeTimers();
+ const nativeStarted = createDeferred<boolean>();
+ harness.nativeShow.mockReturnValueOnce(nativeStarted.promise);
+ harness.locateComputerUseSwitchTarget.mockResolvedValue({
+ status: 'not-found',
+ systemWindowBounds: { x: 200, y: 100, width: 1000, height: 500 },
+ });
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ const guide = await import('../window');
+ const show = guide.showComputerPermissionGuideWindow(null);
+
+ await vi.waitFor(() => {
+ expect(harness.nativeShow).toHaveBeenCalledOnce();
+ });
+ finishTestDrag(guide);
+ await vi.waitFor(() => {
+ expect(harness.locateComputerUseSwitchTarget).toHaveBeenCalled();
+ });
+ nativeStarted.resolve(true);
+ await show;
+
+ await vi.advanceTimersByTimeAsync(30_000);
+
+ expect(harness.nativeDismiss).toHaveBeenCalledOnce();
+ expect(harness.broadcastSend).toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-cancelled',
+ );
+ });
+
+ it('shows the Electron fallback only when the native guide cannot start', async () => {
+ harness.nativeShow.mockResolvedValueOnce(false);
+ const guide = await import('../window');
+
+ await guide.showComputerPermissionGuideWindow(null);
+
+ await vi.waitFor(() => {
+ expect(harness.windows[0].showInactive).toHaveBeenCalledOnce();
+ expect(harness.windows[1].showInactive).toHaveBeenCalledOnce();
+ });
+ });
+
+ it('fully tears down the lifecycle when the Electron fallback closes normally', async () => {
+ harness.nativeShow.mockResolvedValueOnce(false);
+ const guide = await import('../window');
+ const initialStatus = harness.computerStatus();
+
+ await guide.showComputerPermissionGuideWindow(null, initialStatus);
+ await vi.waitFor(() => {
+ expect(harness.windows[1].showInactive).toHaveBeenCalledOnce();
+ });
+ harness.resumeComputerDriverPermissionProbe.mockClear();
+ harness.closeComputerUseSwitchLocator.mockClear();
+ harness.openExternal.mockClear();
+
+ harness.windows[1].close();
+
+ expect(harness.resumeComputerDriverPermissionProbe).toHaveBeenCalledOnce();
+ expect(harness.closeComputerUseSwitchLocator).toHaveBeenCalledOnce();
+ expect(harness.windows[0].close).toHaveBeenCalledOnce();
+ expect(harness.nativeDismiss).not.toHaveBeenCalled();
+ expect(harness.cancelComputerDriverPermissionGrant).toHaveBeenCalledOnce();
+ expect(harness.broadcastSend).toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-cancelled',
+ );
+
+ await guide.openComputerPermissionPaneForStatus(initialStatus);
+ expect(harness.openExternal).toHaveBeenCalledOnce();
+ });
+
+ it('does not report cancellation when the completed Electron fallback closes', async () => {
+ harness.nativeShow.mockResolvedValueOnce(false);
+ const guide = await import('../window');
+ const completeStatus = harness.computerStatus({
+ status: 'granted',
+ accessibility: 'granted',
+ screenRecording: 'granted',
+ screenRecordingCapturable: 'granted',
+ });
+
+ await guide.showComputerPermissionGuideWindow(null, completeStatus);
+ await vi.waitFor(() => {
+ expect(harness.windows[1].showInactive).toHaveBeenCalledOnce();
+ });
+ harness.cancelComputerDriverPermissionGrant.mockClear();
+ harness.broadcastSend.mockClear();
+
+ harness.windows[1].close();
+
+ expect(harness.cancelComputerDriverPermissionGrant).not.toHaveBeenCalled();
+ expect(harness.broadcastSend).not.toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-cancelled',
+ );
+ expect(harness.closeComputerUseSwitchLocator).toHaveBeenCalled();
+ });
+
+ it('shows the Electron fallback when the native guide exits before attaching', async () => {
+ const nativeStarted = createDeferred<boolean>();
+ harness.nativeShow.mockReturnValueOnce(nativeStarted.promise);
+ const guide = await import('../window');
+
+ await guide.showComputerPermissionGuideWindow(null);
+ harness.nativeHostState.options?.onExited?.();
+
+ await vi.waitFor(() => {
+ expect(harness.windows[0].showInactive).toHaveBeenCalledOnce();
+ expect(harness.windows[1].showInactive).toHaveBeenCalledOnce();
+ });
+ expect(harness.closeComputerUseSwitchLocator).not.toHaveBeenCalled();
+ expect(harness.broadcastSend).not.toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-cancelled',
+ );
+
+ nativeStarted.resolve(false);
+ await Promise.resolve();
+ expect(harness.windows[0].showInactive).toHaveBeenCalledOnce();
+ expect(harness.windows[1].showInactive).toHaveBeenCalledOnce();
+ });
+
+ it('keeps the fallback alive when a started native guide exits before attaching', async () => {
+ vi.useFakeTimers();
+ harness.nativeShow.mockResolvedValueOnce(true);
+ const guide = await import('../window');
+
+ await guide.showComputerPermissionGuideWindow(null);
+ await vi.waitFor(() => {
+ expect(harness.nativeShow).toHaveBeenCalledOnce();
+ });
+ harness.nativeHostState.options?.onExited?.();
+ await vi.waitFor(() => {
+ expect(harness.windows[0].showInactive).toHaveBeenCalledOnce();
+ expect(harness.windows[1].showInactive).toHaveBeenCalledOnce();
+ });
+
+ await vi.advanceTimersByTimeAsync(30_000);
+
+ expect(harness.windows[0].close).not.toHaveBeenCalled();
+ expect(harness.windows[1].close).not.toHaveBeenCalled();
+ expect(harness.broadcastSend).not.toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-cancelled',
+ );
+ });
+
+ it('closes the guide and resumes permission probes when its renderer exits', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ harness.resumeComputerDriverPermissionProbe.mockClear();
+ harness.closeComputerUseSwitchLocator.mockClear();
+ harness.broadcastSend.mockClear();
+
+ harness.windows[1].listeners.get('render-process-gone')?.(
+ {},
+ { reason: 'crashed' },
+ );
+
+ expect(harness.resumeComputerDriverPermissionProbe).toHaveBeenCalledOnce();
+ expect(harness.nativeDismiss).toHaveBeenCalledOnce();
+ expect(harness.closeComputerUseSwitchLocator).toHaveBeenCalledOnce();
+ expect(harness.broadcastSend).toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-cancelled',
+ );
+ });
+
+ it('closes the guide and resumes permission probes when its renderer fails to load', async () => {
+ harness.setNextGuideLoadError(new Error('load failed'));
+ const guide = await import('../window');
+
+ await guide.showComputerPermissionGuideWindow(null);
+
+ await vi.waitFor(() => {
+ expect(harness.resumeComputerDriverPermissionProbe).toHaveBeenCalledOnce();
+ expect(harness.closeComputerUseSwitchLocator).toHaveBeenCalledOnce();
+ expect(harness.broadcastSend).toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-cancelled',
+ );
+ });
+ expect(harness.windows[0].close).toHaveBeenCalledOnce();
+ expect(harness.windows[1].close).toHaveBeenCalledOnce();
+ });
+
+ it('cancels the guide when the attached native guide exits unexpectedly', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ harness.nativeHostState.options?.onAttached?.();
+ harness.closeComputerUseSwitchLocator.mockClear();
+ harness.broadcastSend.mockClear();
+
+ harness.nativeHostState.options?.onExited?.();
+
+ expect(harness.closeComputerUseSwitchLocator).toHaveBeenCalledOnce();
+ expect(harness.broadcastSend).toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-cancelled',
+ );
+ });
+
+ it('does not reuse a persisted drag from an earlier guide lifecycle', async () => {
+ writeDragState({ accessibility: true, screenRecording: true });
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+
+ await vi.waitFor(() => {
+ expect(harness.windows).toHaveLength(2);
+ });
+ expect(harness.locateComputerUseSwitchTarget).not.toHaveBeenCalled();
+ expect(guide.readPermissionDragState()).toEqual({
+ accessibility: false,
+ screenRecording: false,
+ });
+ });
+
+ it('reuses an observer-provided location instead of locating twice', async () => {
+ const nativeStarted = createDeferred<boolean>();
+ harness.nativeShow.mockReturnValueOnce(nativeStarted.promise);
+ harness.locateComputerUseSwitchTarget.mockResolvedValue({
+ status: 'found',
+ target: {
+ x: 901,
+ y: 442,
+ permission: 'accessibility',
+ enabled: false,
+ },
+ systemWindowBounds: { x: 200, y: 100, width: 1000, height: 500 },
+ });
+ const guide = await import('../window');
+ const initialStatus = harness.computerStatus();
+
+ await guide.showComputerPermissionGuideWindow(null, initialStatus);
+ finishTestDrag(guide);
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenCalled();
+ });
+ harness.nativeUpdate.mockClear();
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ nativeStarted.resolve(true);
+
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenCalledWith(expect.objectContaining({
+ switchTargetX: 901,
+ switchTargetY: 442,
+ }));
+ });
+ expect(harness.locateComputerUseSwitchTarget).toHaveBeenCalledOnce();
+ });
+
+ it('establishes the first full bypass on drag completion', async () => {
+ await startObserverThrottleTest(foundSwitchLocation(false));
+ });
+
+ it('coalesces an observer burst into one immediate and one trailing full bypass', async () => {
+ await startObserverThrottleTest(
+ foundSwitchLocation(false),
+ foundSwitchLocation(true, { x: 902 }),
+ { status: 'not-found' },
+ );
+ await vi.advanceTimersByTimeAsync(1_800);
+ await expectPermissionProbeCounts(1, 2);
+
+ await vi.advanceTimersByTimeAsync(200);
+ await expectPermissionProbeCounts(2, 2);
+ });
+
+ it('runs the trailing observer probe with current lifecycle state', async () => {
+ await startObserverThrottleTest(
+ foundSwitchLocation(false),
+ foundSwitchLocation(true, { x: 902 }),
+ foundSwitchLocation(false, {
+ x: 950,
+ y: 460,
+ permission: 'screenRecording',
+ }),
+ );
+ await vi.advanceTimersByTimeAsync(900);
+ await expectPermissionProbeCounts(1, 1);
+
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ await vi.advanceTimersByTimeAsync(1_100);
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenLastCalledWith(expect.objectContaining({
+ switchTargetX: 950,
+ switchTargetY: 460,
+ }));
+ });
+ expect(harness.locateComputerUseSwitchTarget).toHaveBeenCalledTimes(3);
+ expect(fullPermissionProbeCalls()).toHaveLength(2);
+ });
+
+ it('invalidates trailing work armed by an older queued observer at the explicit issue boundary', async () => {
+ const blockedRefresh = createDeferred<Awaited<ReturnType<
+ typeof harness.getComputerDriverStatus
+ >>>();
+ const guide = await startObserverThrottleTest(
+ foundSwitchLocation(false),
+ foundSwitchLocation(false),
+ );
+ harness.getComputerDriverStatus.mockImplementationOnce(() => blockedRefresh.promise);
+ guide.refreshComputerPermissionGuideWindow();
+ await expectPermissionProbeCounts(1, 1);
+
+ await vi.advanceTimersByTimeAsync(900);
+ const explicitRefresh = guide.showComputerPermissionGuideWindow(null);
+ await vi.advanceTimersByTimeAsync(600);
+ blockedRefresh.resolve(harness.computerStatus());
+ await explicitRefresh;
+ await expectPermissionProbeCounts(2, 2);
+
+ await vi.advanceTimersByTimeAsync(500);
+ await expectPermissionProbeCounts(2, 2);
+ });
+
+ it('lets an explicit bypass supersede a fired-but-queued observer trailing callback', async () => {
+ const blockedRefresh = createDeferred<Awaited<ReturnType<
+ typeof harness.getComputerDriverStatus
+ >>>();
+ const guide = await startObserverThrottleTest(
+ foundSwitchLocation(false),
+ foundSwitchLocation(false),
+ );
+ await vi.advanceTimersByTimeAsync(900);
+ await expectPermissionProbeCounts(1, 1);
+
+ harness.getComputerDriverStatus.mockImplementationOnce(() => blockedRefresh.promise);
+ guide.refreshComputerPermissionGuideWindow();
+ await expectPermissionProbeCounts(1, 2);
+ await vi.advanceTimersByTimeAsync(1_100);
+ const explicitRefresh = guide.showComputerPermissionGuideWindow(null);
+ blockedRefresh.resolve(harness.computerStatus());
+ await explicitRefresh;
+ await expectPermissionProbeCounts(2, 2);
+
+ await vi.advanceTimersByTimeAsync(2_000);
+ await expectPermissionProbeCounts(2, 2);
+ });
+
+ it('invalidates a fired-but-queued lifecycle-A trailing callback on close and reopen', async () => {
+ const blockedRefresh = createDeferred<Awaited<ReturnType<
+ typeof harness.getComputerDriverStatus
+ >>>();
+ const guide = await startObserverThrottleTest(
+ foundSwitchLocation(false),
+ foundSwitchLocation(false),
+ );
+ await vi.advanceTimersByTimeAsync(900);
+ await expectPermissionProbeCounts(1, 1);
+
+ harness.getComputerDriverStatus.mockImplementationOnce(() => blockedRefresh.promise);
+ guide.refreshComputerPermissionGuideWindow();
+ await expectPermissionProbeCounts(1, 2);
+ await vi.advanceTimersByTimeAsync(1_100);
+
+ guide.closeComputerPermissionGuideWindow();
+ await guide.showComputerPermissionGuideWindow(null, harness.computerStatus());
+ await expectPermissionProbeCounts(1, 2);
+
+ blockedRefresh.resolve(harness.computerStatus());
+ await vi.advanceTimersByTimeAsync(900);
+ await expectPermissionProbeCounts(1, 2);
+ });
+
+ it('keeps observer probing across the 2,000ms throttle boundary', async () => {
+ const unchangedLocation = foundSwitchLocation(false);
+ await startObserverThrottleTest(
+ unchangedLocation,
+ unchangedLocation,
+ foundSwitchLocation(true, { x: 903 }),
+ );
+ await vi.advanceTimersByTimeAsync(2_700);
+ await expectPermissionProbeCounts(2, 2);
+ });
+
+ it('keeps probing when the located switch state remains unknown', async () => {
+ await startObserverThrottleTest(
+ foundSwitchLocation(null),
+ foundSwitchLocation(null),
+ foundSwitchLocation(null),
+ foundSwitchLocation(null),
+ foundSwitchLocation(null),
+ );
+
+ await vi.advanceTimersByTimeAsync(4_000);
+ await expectPermissionProbeCounts(3);
+ });
+
+ it('serializes explicit and observer refreshes in invocation order', async () => {
+ const nativeStarted = createDeferred<boolean>();
+ const olderLocation = createDeferred<{
+ status: 'found';
+ target: {
+ x: number;
+ y: number;
+ permission: 'accessibility';
+ enabled: boolean;
+ };
+ }>();
+ harness.nativeShow.mockReturnValueOnce(nativeStarted.promise);
+ harness.locateComputerUseSwitchTarget
+ .mockImplementationOnce(() => olderLocation.promise)
+ .mockResolvedValueOnce({
+ status: 'found',
+ target: {
+ x: 920,
+ y: 450,
+ permission: 'accessibility',
+ enabled: false,
+ },
+ });
+ const guide = await import('../window');
+ const initialStatus = harness.computerStatus();
+
+ await guide.showComputerPermissionGuideWindow(null, initialStatus);
+ finishTestDrag(guide);
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenCalled();
+ });
+ harness.nativeUpdate.mockClear();
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ guide.refreshComputerPermissionGuideWindow();
+ await vi.waitFor(() => {
+ expect(harness.locateComputerUseSwitchTarget).toHaveBeenCalledOnce();
+ });
+
+ nativeStarted.resolve(true);
+ await Promise.resolve();
+ expect(harness.locateComputerUseSwitchTarget).toHaveBeenCalledOnce();
+
+ olderLocation.resolve({
+ status: 'found',
+ target: {
+ x: 700,
+ y: 410,
+ permission: 'accessibility',
+ enabled: false,
+ },
+ });
+
+ await vi.waitFor(() => {
+ expect(harness.locateComputerUseSwitchTarget).toHaveBeenCalledTimes(2);
+ expect(harness.nativeUpdate).toHaveBeenLastCalledWith(expect.objectContaining({
+ switchTargetX: 920,
+ switchTargetY: 450,
+ }));
+ });
+ });
+
+ it('ignores an old lifecycle refresh result after close and reopen', async () => {
+ const oldStatus = createDeferred<Awaited<ReturnType<
+ typeof harness.getComputerDriverStatus
+ >>>();
+ const reopenedNativeStarted = createDeferred<boolean>();
+ const guide = await import('../window');
+ const initialStatus = harness.computerStatus();
+ await guide.showComputerPermissionGuideWindow(null, initialStatus);
+ await vi.waitFor(() => {
+ expect(harness.nativeShow).toHaveBeenCalledOnce();
+ });
+
+ harness.getComputerDriverStatus.mockImplementationOnce(() => oldStatus.promise);
+ guide.refreshComputerPermissionGuideWindow();
+ await vi.waitFor(() => {
+ expect(harness.getComputerDriverStatus).toHaveBeenCalledOnce();
+ });
+ guide.closeComputerPermissionGuideWindow();
+
+ harness.nativeShow.mockReturnValueOnce(reopenedNativeStarted.promise);
+ await guide.showComputerPermissionGuideWindow(null, initialStatus);
+ harness.nativeUpdate.mockClear();
+ harness.broadcastSend.mockClear();
+ oldStatus.resolve(harness.computerStatus({
+ status: 'granted',
+ accessibility: 'granted',
+ screenRecording: 'granted',
+ screenRecordingCapturable: 'granted',
+ }));
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(harness.nativeUpdate).not.toHaveBeenCalled();
+ expect(harness.broadcastSend).not.toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-status-changed',
+ expect.objectContaining({
+ permissionState: expect.objectContaining({ status: 'granted' }),
+ }),
+ );
+ });
+
+ it('does not continue an old show after its preflight settles following close and reopen', async () => {
+ const oldStatus = createDeferred<Awaited<ReturnType<
+ typeof harness.getComputerDriverStatus
+ >>>();
+ harness.getComputerDriverStatus.mockImplementationOnce(() => oldStatus.promise);
+ const guide = await import('../window');
+ const oldShow = guide.showComputerPermissionGuideWindow(null);
+ await vi.waitFor(() => {
+ expect(harness.getComputerDriverStatus).toHaveBeenCalledOnce();
+ });
+
+ guide.closeComputerPermissionGuideWindow();
+ await guide.showComputerPermissionGuideWindow(null, harness.computerStatus());
+ await vi.waitFor(() => {
+ expect(harness.nativeShow).toHaveBeenCalledOnce();
+ });
+
+ oldStatus.resolve(harness.computerStatus());
+ await oldShow;
+ await Promise.resolve();
+
+ expect(harness.nativeShow).toHaveBeenCalledOnce();
+ expect(harness.nativeHostState.allOptions).toHaveLength(1);
+ });
+
+ it('ignores callbacks from a native host owned by a closed lifecycle', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null, harness.computerStatus());
+ await vi.waitFor(() => {
+ expect(harness.nativeHostState.allOptions).toHaveLength(1);
+ });
+ const staleOptions = harness.nativeHostState.allOptions[0];
+
+ guide.closeComputerPermissionGuideWindow();
+ await guide.showComputerPermissionGuideWindow(null, harness.computerStatus());
+ await vi.waitFor(() => {
+ expect(harness.nativeHostState.allOptions).toHaveLength(2);
+ });
+ const reopenedBackdrop = harness.windows[2];
+ const reopenedGuide = harness.windows[3];
+ harness.nativeDismiss.mockClear();
+ harness.nativeUpdate.mockClear();
+ harness.cancelComputerDriverPermissionGrant.mockClear();
+ harness.closeComputerUseSwitchLocator.mockClear();
+
+ staleOptions.onDragBegan?.('accessibility');
+ staleOptions.onDragEnded?.('accessibility', 1);
+ staleOptions.onAttached?.();
+ staleOptions.onCompleted?.();
+ staleOptions.onCloseRequested?.();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(harness.nativeUpdate).not.toHaveBeenCalled();
+ expect(harness.nativeDismiss).not.toHaveBeenCalled();
+ expect(harness.cancelComputerDriverPermissionGrant).not.toHaveBeenCalled();
+ expect(harness.closeComputerUseSwitchLocator).not.toHaveBeenCalled();
+ expect(reopenedBackdrop.close).not.toHaveBeenCalled();
+ expect(reopenedGuide.close).not.toHaveBeenCalled();
+ });
+
+ it('ignores a delayed closed event from the previous Electron lifecycle', async () => {
+ harness.setDeferWindowClosedEvents(true);
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null, harness.computerStatus());
+ const staleGuide = harness.windows[1];
+
+ guide.closeComputerPermissionGuideWindow();
+ await guide.showComputerPermissionGuideWindow(null, harness.computerStatus());
+ const reopenedBackdrop = harness.windows[2];
+ const reopenedGuide = harness.windows[3];
+ staleGuide.listeners.get('closed')?.();
+
+ expect(reopenedBackdrop.close).not.toHaveBeenCalled();
+ expect(reopenedGuide.setIgnoreMouseEvents).not.toHaveBeenCalledWith(false);
+ });
+
+ it('does not locate an active second permission before its drag when probing is resumed', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(
+ null,
+ harness.computerStatus({ accessibility: 'granted' }),
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(harness.isComputerDriverPermissionProbePaused).toHaveReturnedWith(false);
+ expect(harness.locateComputerUseSwitchTarget).not.toHaveBeenCalled();
+ });
+
+ it('applies an active re-show status before starting an observer during native startup', async () => {
+ writeDragState({ accessibility: true, screenRecording: false });
+ const nativeStarted = createDeferred<boolean>();
+ harness.nativeShow.mockReturnValueOnce(nativeStarted.promise);
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null, harness.computerStatus());
+
+ await guide.showComputerPermissionGuideWindow(
+ null,
+ harness.computerStatus({ accessibility: 'granted' }),
+ );
+ await Promise.resolve();
+
+ expect(harness.locateComputerUseSwitchTarget).not.toHaveBeenCalled();
+ });
+
+ it('updates the active native guide with a newer same-lifecycle re-show status', async () => {
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ const deferredPreflight = createDeferred<{ status: 'unavailable' }>();
+ harness.locateComputerUseSwitchTarget.mockReturnValueOnce(deferredPreflight.promise);
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(
+ null,
+ harness.computerStatus(),
+ );
+ finishTestDrag(guide);
+ await vi.waitFor(() => {
+ expect(harness.locateComputerUseSwitchTarget).toHaveBeenCalledOnce();
+ });
+
+ const showB = guide.showComputerPermissionGuideWindow(
+ null,
+ harness.computerStatus({ accessibility: 'granted' }),
+ );
+ deferredPreflight.resolve({ status: 'unavailable' });
+ await showB;
+
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenCalledWith(expect.objectContaining({
+ accessibilityGranted: true,
+ screenRecordingGranted: false,
+ }));
+ });
+ });
+
+ it('keeps an older observer bound to its status snapshot when an active guide is re-shown', async () => {
+ const nativeStarted = createDeferred<boolean>();
+ const olderLocation = createDeferred<{ status: 'not-found' }>();
+ harness.nativeShow.mockReturnValueOnce(nativeStarted.promise);
+ harness.locateComputerUseSwitchTarget.mockImplementationOnce(() => olderLocation.promise);
+ const guide = await import('../window');
+ const accessibilityStatus = harness.computerStatus();
+ await guide.showComputerPermissionGuideWindow(null, accessibilityStatus);
+ harness.nativeHostState.options?.onDragEnded?.('accessibility', 1);
+ harness.nativeHostState.options?.onDragEnded?.('screenRecording', 1);
+ await vi.waitFor(() => {
+ expect(guide.readPermissionDragState()).toEqual({
+ accessibility: true,
+ screenRecording: true,
+ });
+ });
+
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ nativeStarted.resolve(true);
+ await vi.waitFor(() => {
+ expect(harness.locateComputerUseSwitchTarget).toHaveBeenCalledOnce();
+ });
+
+ const screenRecordingStatus = harness.computerStatus({ accessibility: 'granted' });
+ const reshow = guide.showComputerPermissionGuideWindow(null, screenRecordingStatus);
+ olderLocation.resolve({ status: 'not-found' });
+ await reshow;
+
+ expect(harness.nativeUpdate).toHaveBeenLastCalledWith(expect.objectContaining({
+ accessibilityGranted: true,
+ draggedAccessibility: false,
+ draggedScreenRecording: true,
+ }));
+ });
+
+ it('keeps a valid location when a paused refresh has no confirmed drag for the active pane', async () => {
+ const nativeStarted = createDeferred<boolean>();
+ harness.nativeShow.mockReturnValueOnce(nativeStarted.promise);
+ harness.locateComputerUseSwitchTarget.mockResolvedValueOnce({
+ status: 'found',
+ target: {
+ x: 905,
+ y: 446,
+ permission: 'accessibility',
+ enabled: false,
+ },
+ });
+ const guide = await import('../window');
+ const accessibilityMissingStatus = harness.computerStatus();
+
+ await guide.showComputerPermissionGuideWindow(null, accessibilityMissingStatus);
+ finishTestDrag(guide);
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenCalled();
+ });
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ guide.refreshComputerPermissionGuideWindow();
+ await vi.waitFor(() => {
+ expect(harness.locateComputerUseSwitchTarget).toHaveBeenCalledOnce();
+ });
+ harness.locateComputerUseSwitchTarget.mockResolvedValueOnce({ status: 'unavailable' });
+ harness.nativeUpdate.mockClear();
+ guide.refreshComputerPermissionGuideWindow();
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenCalledWith(expect.objectContaining({
+ switchTargetX: 905,
+ switchTargetY: 446,
+ }));
+ });
+ guide.refreshComputerPermissionGuideWindow({
+ ...accessibilityMissingStatus,
+ permissionState: {
+ ...accessibilityMissingStatus.permissionState,
+ accessibility: 'granted',
+ },
+ });
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenCalledWith(expect.objectContaining({
+ accessibilityGranted: true,
+ }));
+ });
+ harness.nativeUpdate.mockClear();
+ guide.refreshComputerPermissionGuideWindow();
+
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenCalledWith(expect.objectContaining({
+ draggedScreenRecording: false,
+ switchTargetX: 905,
+ switchTargetY: 446,
+ }));
+ });
+ expect(harness.locateComputerUseSwitchTarget).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps the preflight guide step when a paused status refresh is synthetic', async () => {
+ const nativeStarted = createDeferred<boolean>();
+ harness.nativeShow.mockReturnValueOnce(nativeStarted.promise);
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ const guide = await import('../window');
+ const preflightStatus = harness.computerStatus({ accessibility: 'granted' });
+ const show = guide.showComputerPermissionGuideWindow(null, preflightStatus);
+ await vi.waitFor(() => {
+ expect(harness.nativeShow).toHaveBeenCalledOnce();
+ });
+ harness.nativeUpdate.mockClear();
+ harness.broadcastSend.mockClear();
+ harness.windows[1].webContents.send.mockClear();
+
+ const pausedStatus = harness.computerStatus({
+ screenRecording: 'unknown',
+ screenRecordingCapturable: 'unknown',
+ });
+ guide.refreshComputerPermissionGuideWindow(pausedStatus);
+
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenCalledWith(expect.objectContaining({
+ accessibilityGranted: true,
+ screenRecordingGranted: false,
+ draggedScreenRecording: false,
+ }));
+ });
+ expect(harness.broadcastSend).toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-status-changed',
+ pausedStatus,
+ );
+ expect(harness.windows[1].webContents.send).toHaveBeenCalledWith(
+ 'maker:computer:permission-guide-status-changed',
+ preflightStatus,
+ );
+ expect(guide.getComputerPermissionGuideStatus(
+ harness.windows[1].webContents as unknown as WebContents,
+ )).toBe(preflightStatus);
+ expect(harness.locateComputerUseSwitchTarget).not.toHaveBeenCalled();
+
+ nativeStarted.resolve(true);
+ await show;
+ });
+
+ it('clears a historical drag hint when the live System Settings row is absent', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ await vi.waitFor(() => {
+ expect(harness.nativeShow).toHaveBeenCalled();
+ });
+
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ harness.locateComputerUseSwitchTarget.mockResolvedValue({ status: 'not-found' });
+ const sender = harness.windows[1].webContents as unknown as WebContents;
+ guide.startComputerPermissionAppDrag(sender, VALID_PNG_DATA_URL);
+ await expect(guide.finishComputerPermissionAppDrag(sender, true)).resolves.toBe(false);
+
+ await vi.waitFor(() => {
+ expect(harness.nativeUpdate).toHaveBeenCalledWith(expect.objectContaining({
+ accessibilityGranted: false,
+ draggedAccessibility: false,
+ }));
+ });
+ });
+
+ it('accepts a copied drag only after the live System Settings row appears', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ await vi.waitFor(() => {
+ expect(harness.nativeShow).toHaveBeenCalled();
+ });
+
+ harness.isComputerDriverPermissionProbePaused.mockReturnValue(true);
+ harness.locateComputerUseSwitchTarget.mockResolvedValue(foundSwitchLocation(false));
+ const sender = harness.windows[1].webContents as unknown as WebContents;
+ guide.startComputerPermissionAppDrag(sender, VALID_PNG_DATA_URL);
+
+ await expect(guide.finishComputerPermissionAppDrag(sender, true)).resolves.toBe(true);
+ });
+
+ it('starts the real app drag only for the guide renderer and restores it on drag end', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ const guideWindow = harness.windows[1];
+
+ const sender = guideWindow.webContents as unknown as WebContents;
+ guide.startComputerPermissionAppDrag(sender, VALID_PNG_DATA_URL);
+ expect(guideWindow.webContents.startDrag).toHaveBeenCalledWith({
+ file: '/Applications/CuaDriver.app',
+ icon: expect.anything(),
+ });
+ expect(guideWindow.setIgnoreMouseEvents).toHaveBeenCalledWith(true, { forward: true });
+
+ guide.finishComputerPermissionAppDrag(sender, true);
+ expect(guideWindow.setIgnoreMouseEvents).toHaveBeenCalledWith(false);
+ });
+
+ it('rejects malformed and oversized drag icons before decoding', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ const guideWindow = harness.windows[1];
+ const sender = guideWindow.webContents as unknown as WebContents;
+ harness.nativeImage.createFromDataURL.mockClear();
+
+ guide.startComputerPermissionAppDrag(sender, 'data:text/plain;base64,aGVsbG8=');
+ guide.startComputerPermissionAppDrag(sender, 'data:image/png;base64,aGVsbG8=');
+ guide.startComputerPermissionAppDrag(
+ sender,
+ `data:image/png;base64,iVBORw0KGgo${'A'.repeat(256 * 1024)}`,
+ );
+
+ expect(harness.nativeImage.createFromDataURL).not.toHaveBeenCalled();
+ expect(guideWindow.webContents.startDrag).not.toHaveBeenCalled();
+ });
+
+ it('does not start a drag when the validated icon cannot be decoded', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ const guideWindow = harness.windows[1];
+ const sender = guideWindow.webContents as unknown as WebContents;
+ harness.nativeImage.createFromDataURL.mockImplementationOnce(() => {
+ throw new Error('decode failed');
+ });
+
+ guide.startComputerPermissionAppDrag(sender, VALID_PNG_DATA_URL);
+
+ expect(guideWindow.webContents.startDrag).not.toHaveBeenCalled();
+ });
+
+ it('centers the guide vertically on the real System Settings window', async () => {
+ harness.locateComputerUseSwitchTarget.mockResolvedValue({
+ status: 'not-found',
+ systemWindowBounds: { x: 200, y: 100, width: 1000, height: 500 },
+ });
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ finishTestDrag(guide);
+ const guideWindow = harness.windows[1];
+
+ await vi.waitFor(() => {
+ expect(guideWindow.setBounds).toHaveBeenCalledWith(
+ { x: 736, y: 190, width: 480, height: 272 },
+ false,
+ );
+ });
+ });
+
+ it('uses guide dimensions from the shared placement module', async () => {
+ const { PERMISSION_GUIDE_WINDOW_WIDTH, PERMISSION_GUIDE_WINDOW_HEIGHT } =
+ await import('../placement');
+ expect(PERMISSION_GUIDE_WINDOW_WIDTH).toBe(480);
+ expect(PERMISSION_GUIDE_WINDOW_HEIGHT).toBe(272);
+
+ harness.locateComputerUseSwitchTarget.mockResolvedValue({
+ status: 'not-found',
+ systemWindowBounds: { x: 200, y: 100, width: 1000, height: 500 },
+ });
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ finishTestDrag(guide);
+
+ await vi.waitFor(() => {
+ expect(harness.windows[1].setBounds).toHaveBeenCalledWith(
+ expect.objectContaining({
+ width: PERMISSION_GUIDE_WINDOW_WIDTH,
+ height: PERMISSION_GUIDE_WINDOW_HEIGHT,
+ }),
+ false,
+ );
+ });
+ });
+
+ it('does not write drag state when Electron startDrag throws', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ const guideWindow = harness.windows[1];
+ guideWindow.webContents.startDrag.mockImplementation(() => {
+ throw new Error('drag failed');
+ });
+
+ const sender = guideWindow.webContents as unknown as WebContents;
+ guide.startComputerPermissionAppDrag(sender, VALID_PNG_DATA_URL);
+
+ const dragState = guide.readPermissionDragState();
+ expect(dragState.accessibility).toBe(false);
+ expect(dragState.screenRecording).toBe(false);
+ });
+
+ it('does not infer a successful drop when Chromium omits dragend', async () => {
+ vi.useFakeTimers();
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ const guideWindow = harness.windows[1];
+
+ const sender = guideWindow.webContents as unknown as WebContents;
+ guide.startComputerPermissionAppDrag(sender, VALID_PNG_DATA_URL);
+
+ await vi.advanceTimersByTimeAsync(12_000);
+
+ const dragState = guide.readPermissionDragState();
+ expect(dragState.accessibility).toBe(false);
+ expect(dragState.screenRecording).toBe(false);
+ expect(guideWindow.setIgnoreMouseEvents).toHaveBeenCalledWith(false);
+ expect(harness.locateComputerUseSwitchTarget).not.toHaveBeenCalled();
+ });
+
+ it('does not persist or inspect after a cancelled Electron drag', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ const sender = harness.windows[1].webContents as unknown as WebContents;
+
+ guide.startComputerPermissionAppDrag(sender, VALID_PNG_DATA_URL);
+ guide.finishComputerPermissionAppDrag(sender, false);
+
+ expect(guide.readPermissionDragState().accessibility).toBe(false);
+ expect(harness.locateComputerUseSwitchTarget).not.toHaveBeenCalled();
+ });
+
+ it('does not write drag state when the guide closes during a drag', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ const guideWindow = harness.windows[1];
+
+ const sender = guideWindow.webContents as unknown as WebContents;
+ guide.startComputerPermissionAppDrag(sender, VALID_PNG_DATA_URL);
+
+ guide.closeComputerPermissionGuideWindow();
+
+ const dragState = guide.readPermissionDragState();
+ expect(dragState.accessibility).toBe(false);
+ expect(dragState.screenRecording).toBe(false);
+ });
+
+ it('keeps the in-memory drag state when persistence is unavailable', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null);
+ vi.spyOn(fs, 'writeFileSync').mockImplementationOnce(() => {
+ throw new Error('disk unavailable');
+ });
+
+ finishTestDrag(guide);
+
+ await vi.waitFor(() => {
+ expect(guide.readPermissionDragState().accessibility).toBe(true);
+ });
+ });
+
+ it('writes drag state only after a confirmed native copy drag', async () => {
+ const guide = await import('../window');
+ await guide.showComputerPermissionGuideWindow(null, harness.computerStatus());
+ await vi.waitFor(() => {
+ expect(harness.nativeHostState.options).not.toBeNull();
+ });
+
+ harness.nativeHostState.options?.onDragBegan?.('accessibility');
+ let dragState = guide.readPermissionDragState();
+ expect(dragState.accessibility).toBe(false);
+
+ harness.nativeHostState.options?.onDragEnded?.('accessibility', 0);
+ await Promise.resolve();
+ await Promise.resolve();
+ dragState = guide.readPermissionDragState();
+ expect(dragState.accessibility).toBe(false);
+
+ harness.nativeHostState.options?.onDragEnded?.('accessibility', 1);
+ await vi.waitFor(() => {
+ expect(guide.readPermissionDragState().accessibility).toBe(true);
+ });
+ });
+});
diff --git a/apps/desktop/src/main/computer-permission-guide/__tests__/request.test.ts b/apps/desktop/src/main/computer-permission-guide/__tests__/request.test.ts
new file mode 100644
index 0000000000..b528323936
--- /dev/null
+++ b/apps/desktop/src/main/computer-permission-guide/__tests__/request.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ MAC_ACCESSIBILITY_SETTINGS_URL,
+ MAC_SCREEN_RECORDING_SETTINGS_URL,
+ parseComputerPermissionGrantRequest,
+} from '../request.js';
+
+describe('Computer Use permission guide request', () => {
+ it('accepts only the supported runtime-validated fields', () => {
+ expect(parseComputerPermissionGrantRequest(undefined)).toEqual({
+ showGuide: false,
+ });
+ expect(parseComputerPermissionGrantRequest({
+ showGuide: true,
+ openedPaneUrl: MAC_ACCESSIBILITY_SETTINGS_URL,
+ })).toEqual({
+ showGuide: true,
+ openedPaneUrl: MAC_ACCESSIBILITY_SETTINGS_URL,
+ });
+ expect(parseComputerPermissionGrantRequest({
+ showGuide: true,
+ openedPaneUrl: MAC_SCREEN_RECORDING_SETTINGS_URL,
+ })).toEqual({
+ showGuide: true,
+ openedPaneUrl: MAC_SCREEN_RECORDING_SETTINGS_URL,
+ });
+ });
+
+ it('rejects forged permission snapshots and malformed values', () => {
+ expect(parseComputerPermissionGrantRequest(null)).toBeNull();
+ expect(parseComputerPermissionGrantRequest({ showGuide: 'yes' })).toBeNull();
+ expect(parseComputerPermissionGrantRequest({
+ showGuide: true,
+ initialStatus: { permissionState: { status: 'granted' } },
+ })).toBeNull();
+ expect(parseComputerPermissionGrantRequest({
+ showGuide: true,
+ openedPaneUrl: 'https://attacker.example/',
+ })).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/computer-permission-guide/__tests__/switch-target.test.ts b/apps/desktop/src/main/computer-permission-guide/__tests__/switch-target.test.ts
new file mode 100644
index 0000000000..2e89a03383
--- /dev/null
+++ b/apps/desktop/src/main/computer-permission-guide/__tests__/switch-target.test.ts
@@ -0,0 +1,364 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const {
+ callToolMock,
+ clientCloseMock,
+ clientConnectMock,
+ clientCtorMock,
+ existsSyncMock,
+ transportCtorMock,
+} = vi.hoisted(() => ({
+ callToolMock: vi.fn(),
+ clientCloseMock: vi.fn(),
+ clientConnectMock: vi.fn(),
+ clientCtorMock: vi.fn(),
+ existsSyncMock: vi.fn(),
+ transportCtorMock: vi.fn(),
+}));
+
+const originalPlatform = process.platform;
+
+function setPlatform(platform: NodeJS.Platform): void {
+ Object.defineProperty(process, 'platform', {
+ value: platform,
+ configurable: true,
+ });
+}
+
+vi.mock('node:fs', async () => {
+ const actual = await vi.importActual<typeof import('node:fs')>('node:fs');
+ return {
+ ...actual,
+ default: {
+ ...actual,
+ existsSync: existsSyncMock,
+ },
+ existsSync: existsSyncMock,
+ };
+});
+
+vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
+ Client: vi.fn().mockImplementation((...args: unknown[]) => {
+ clientCtorMock(...args);
+ return {
+ callTool: callToolMock,
+ close: clientCloseMock,
+ connect: clientConnectMock,
+ };
+ }),
+}));
+
+vi.mock('@modelcontextprotocol/sdk/client/stdio.js', () => ({
+ StdioClientTransport: vi.fn().mockImplementation((...args: unknown[]) => {
+ transportCtorMock(...args);
+ return {};
+ }),
+}));
+
+import {
+ closeComputerUseSwitchLocator,
+ findComputerUseSwitchTarget,
+ locateComputerUseSwitchTarget,
+} from '../switch-target.js';
+
+const windowsResult = {
+ structuredContent: {
+ windows: [{
+ app_name: 'System Settings',
+ bounds: { x: 466, y: 210, width: 723, height: 527 },
+ pid: 100,
+ window_id: 200,
+ }],
+ },
+};
+
+const stateResult = {
+ structuredContent: {
+ element_count: 2,
+ elements: [{
+ role: 'AXCheckBox',
+ label: 'CuaDriver_Toggle',
+ value: false,
+ frame: { x: 1_123, y: 474, w: 36, h: 16 },
+ }],
+ },
+};
+
+const toolErrorResult = {
+ isError: true,
+ content: [{ type: 'text', text: 'session failed' }],
+};
+
+function mockSuccessfulLocate(): void {
+ callToolMock.mockImplementation(async ({ name }: { name: string }) => (
+ name === 'list_windows' ? windowsResult : stateResult
+ ));
+}
+
+beforeEach(async () => {
+ await closeComputerUseSwitchLocator();
+ vi.clearAllMocks();
+ setPlatform('darwin');
+ existsSyncMock.mockReturnValue(true);
+ clientConnectMock.mockResolvedValue(undefined);
+ clientCloseMock.mockResolvedValue(undefined);
+ mockSuccessfulLocate();
+});
+
+afterAll(() => {
+ setPlatform(originalPlatform);
+});
+
+describe('persistent switch locator connection', () => {
+ it('does not connect during isolated module import and connects on first locate', async () => {
+ vi.resetModules();
+
+ const switchTarget = await import('../switch-target.js');
+
+ try {
+ expect(clientCtorMock).not.toHaveBeenCalled();
+ expect(transportCtorMock).not.toHaveBeenCalled();
+ expect(clientConnectMock).not.toHaveBeenCalled();
+
+ await expect(switchTarget.locateComputerUseSwitchTarget()).resolves.toMatchObject({
+ status: 'found',
+ });
+
+ expect(clientCtorMock).toHaveBeenCalledTimes(1);
+ expect(transportCtorMock).toHaveBeenCalledTimes(1);
+ expect(clientConnectMock).toHaveBeenCalledTimes(1);
+ } finally {
+ await switchTarget.closeComputerUseSwitchLocator();
+ }
+ });
+
+ it('reuses one client, transport, and session', async () => {
+ await expect(locateComputerUseSwitchTarget()).resolves.toMatchObject({ status: 'found' });
+ await expect(locateComputerUseSwitchTarget()).resolves.toMatchObject({ status: 'found' });
+
+ expect(clientCtorMock).toHaveBeenCalledTimes(1);
+ expect(transportCtorMock).toHaveBeenCalledTimes(1);
+ expect(clientConnectMock).toHaveBeenCalledTimes(1);
+ expect(clientCloseMock).not.toHaveBeenCalled();
+
+ const sessions = callToolMock.mock.calls.map(
+ ([request]) => request.arguments.session as string,
+ );
+ expect(sessions).toHaveLength(4);
+ expect(new Set(sessions)).toEqual(new Set([sessions[0]]));
+ });
+
+ it('filters the AX snapshot by the stable CuaDriver row label', async () => {
+ await expect(locateComputerUseSwitchTarget()).resolves.toMatchObject({ status: 'found' });
+
+ const stateRequest = callToolMock.mock.calls
+ .map(([request]) => request)
+ .find((request) => request.name === 'get_window_state');
+ expect(stateRequest?.arguments).toMatchObject({
+ query: 'CuaDriver',
+ });
+ });
+
+ it('serializes overlapping locate operations', async () => {
+ const {
+ promise: firstState,
+ resolve: resolveFirstState,
+ } = Promise.withResolvers<typeof stateResult>();
+ callToolMock
+ .mockResolvedValueOnce(windowsResult)
+ .mockReturnValueOnce(firstState)
+ .mockResolvedValueOnce(windowsResult)
+ .mockResolvedValueOnce(stateResult);
+
+ const firstLocate = locateComputerUseSwitchTarget();
+ const secondLocate = locateComputerUseSwitchTarget();
+
+ await vi.waitFor(() => expect(callToolMock).toHaveBeenCalledTimes(2));
+ expect(callToolMock).toHaveBeenCalledTimes(2);
+ expect(clientCtorMock).toHaveBeenCalledTimes(1);
+
+ resolveFirstState(stateResult);
+ await expect(Promise.all([firstLocate, secondLocate])).resolves.toEqual([
+ expect.objectContaining({ status: 'found' }),
+ expect.objectContaining({ status: 'found' }),
+ ]);
+ expect(callToolMock.mock.calls.map(([request]) => request.name)).toEqual([
+ 'list_windows',
+ 'get_window_state',
+ 'list_windows',
+ 'get_window_state',
+ ]);
+ });
+
+ it('discards a failed connection and reconnects on the next locate', async () => {
+ clientConnectMock
+ .mockRejectedValueOnce(new Error('connect failed'))
+ .mockResolvedValueOnce(undefined);
+
+ await expect(locateComputerUseSwitchTarget()).rejects.toThrow('connect failed');
+ await expect(locateComputerUseSwitchTarget()).resolves.toMatchObject({ status: 'found' });
+
+ expect(clientCtorMock).toHaveBeenCalledTimes(2);
+ expect(transportCtorMock).toHaveBeenCalledTimes(2);
+ expect(clientConnectMock).toHaveBeenCalledTimes(2);
+ expect(clientCloseMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('discards a connection after a tool failure and reconnects', async () => {
+ callToolMock
+ .mockRejectedValueOnce(new Error('tool failed'))
+ .mockResolvedValueOnce(windowsResult)
+ .mockResolvedValueOnce(stateResult);
+
+ await expect(locateComputerUseSwitchTarget()).rejects.toThrow('tool failed');
+ await expect(locateComputerUseSwitchTarget()).resolves.toMatchObject({ status: 'found' });
+
+ expect(clientCtorMock).toHaveBeenCalledTimes(2);
+ expect(transportCtorMock).toHaveBeenCalledTimes(2);
+ expect(clientConnectMock).toHaveBeenCalledTimes(2);
+ expect(clientCloseMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('discards and reconnects when list_windows resolves with an MCP error', async () => {
+ callToolMock
+ .mockResolvedValueOnce(toolErrorResult)
+ .mockResolvedValueOnce(windowsResult)
+ .mockResolvedValueOnce(stateResult);
+
+ await expect(locateComputerUseSwitchTarget()).rejects.toThrow('list_windows');
+ await expect(locateComputerUseSwitchTarget()).resolves.toMatchObject({ status: 'found' });
+
+ expect(clientCtorMock).toHaveBeenCalledTimes(2);
+ expect(transportCtorMock).toHaveBeenCalledTimes(2);
+ expect(clientConnectMock).toHaveBeenCalledTimes(2);
+ expect(clientCloseMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('discards and reconnects when get_window_state resolves with an MCP error', async () => {
+ callToolMock
+ .mockResolvedValueOnce(windowsResult)
+ .mockResolvedValueOnce(toolErrorResult)
+ .mockResolvedValueOnce(windowsResult)
+ .mockResolvedValueOnce(stateResult);
+
+ await expect(locateComputerUseSwitchTarget()).rejects.toThrow('get_window_state');
+ await expect(locateComputerUseSwitchTarget()).resolves.toMatchObject({ status: 'found' });
+
+ expect(clientCtorMock).toHaveBeenCalledTimes(2);
+ expect(transportCtorMock).toHaveBeenCalledTimes(2);
+ expect(clientConnectMock).toHaveBeenCalledTimes(2);
+ expect(clientCloseMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('serializes close with locate work and closes idempotently', async () => {
+ const {
+ promise: pendingState,
+ resolve: resolveState,
+ } = Promise.withResolvers<typeof stateResult>();
+ callToolMock
+ .mockResolvedValueOnce(windowsResult)
+ .mockReturnValueOnce(pendingState);
+
+ const locate = locateComputerUseSwitchTarget();
+ await vi.waitFor(() => expect(callToolMock).toHaveBeenCalledTimes(2));
+ const firstClose = closeComputerUseSwitchLocator();
+ const secondClose = closeComputerUseSwitchLocator();
+
+ expect(clientCloseMock).not.toHaveBeenCalled();
+
+ resolveState(stateResult);
+ await locate;
+ await expect(Promise.all([firstClose, secondClose])).resolves.toEqual([undefined, undefined]);
+ expect(clientCloseMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('swallows close errors and reconnects on the next locate', async () => {
+ await locateComputerUseSwitchTarget();
+ clientCloseMock.mockRejectedValueOnce(new Error('close failed'));
+
+ await expect(closeComputerUseSwitchLocator()).resolves.toBeUndefined();
+ await expect(locateComputerUseSwitchTarget()).resolves.toMatchObject({ status: 'found' });
+
+ expect(clientCloseMock).toHaveBeenCalledTimes(1);
+ expect(clientCtorMock).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('findComputerUseSwitchTarget', () => {
+ it('targets the exact CuaDriver checkbox instead of other computer-use rows', () => {
+ const result = findComputerUseSwitchTarget(
+ [{
+ app_name: 'System Settings',
+ bounds: { x: 466, y: 210, width: 723, height: 527 },
+ pid: 100,
+ window_id: 200,
+ }],
+ {
+ elements: [
+ {
+ role: 'AXCheckBox',
+ label: 'Codex Computer Use_Toggle',
+ frame: { x: 1_123, y: 433, w: 36, h: 16 },
+ },
+ {
+ role: 'AXCheckBox',
+ label: 'CuaDriver_Toggle',
+ value: false,
+ frame: { x: 1_123, y: 474, w: 36, h: 16 },
+ },
+ ],
+ },
+ );
+
+ expect(result).toEqual({ x: 675, y: 272, enabled: false });
+ });
+
+ it('returns null when the branded row is absent or virtualized', () => {
+ const windows = [{
+ app_name: 'System Settings',
+ bounds: { x: 100, y: 100, width: 800, height: 600 },
+ }];
+
+ expect(findComputerUseSwitchTarget(windows, {
+ elements: [{
+ role: 'AXCheckBox',
+ label: 'Codex Computer Use_Toggle',
+ frame: { x: 700, y: 300, w: 36, h: 16 },
+ }],
+ })).toBeNull();
+ expect(findComputerUseSwitchTarget(windows, {
+ elements: [{
+ role: 'AXCheckBox',
+ label: 'CuaDriver_Toggle',
+ frame: { x: 700, y: 300, w: 36, h: 1 },
+ }],
+ })).toBeNull();
+ });
+
+ it('identifies the permission pane when the AX snapshot includes its heading', () => {
+ const result = findComputerUseSwitchTarget(
+ [{
+ app_name: 'System Settings',
+ bounds: { x: 0, y: 0, width: 800, height: 600 },
+ }],
+ {
+ elements: [
+ { role: 'AXStaticText', label: 'Screen Recording' },
+ {
+ role: 'AXCheckBox',
+ label: 'CuaDriver_Toggle',
+ value: true,
+ frame: { x: 700, y: 300, w: 36, h: 16 },
+ },
+ ],
+ },
+ );
+
+ expect(result).toEqual({
+ x: 718,
+ y: 308,
+ enabled: true,
+ permission: 'screenRecording',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/computer-permission-guide/__tests__/window.test.ts b/apps/desktop/src/main/computer-permission-guide/__tests__/window.test.ts
new file mode 100644
index 0000000000..b676c2d75d
--- /dev/null
+++ b/apps/desktop/src/main/computer-permission-guide/__tests__/window.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ computeComputerPermissionGuideBounds,
+ findSystemSettingsWindowBounds,
+} from '../placement';
+
+describe('computeComputerPermissionGuideBounds', () => {
+ it('right-aligns the visible card and centers it vertically on System Settings', () => {
+ const systemWindow = { x: 200, y: 100, width: 1000, height: 500 };
+ const result = computeComputerPermissionGuideBounds(
+ systemWindow,
+ { x: 0, y: 25, width: 1440, height: 875 },
+ );
+
+ expect(result).toEqual({ x: 736, y: 190, width: 480, height: 272 });
+ expect(result.x + result.width - 16).toBe(systemWindow.x + systemWindow.width);
+ const visibleCardCenterY = result.y + 48 + (result.height - 48) / 2;
+ const systemCenterY = systemWindow.y + systemWindow.height / 2;
+ expect(visibleCardCenterY).toBe(systemCenterY);
+ });
+
+ it('supports a System Settings window on a display with negative coordinates', () => {
+ expect(computeComputerPermissionGuideBounds(
+ { x: -1200, y: 60, width: 1000, height: 500 },
+ { x: -1440, y: 25, width: 1440, height: 875 },
+ )).toEqual({ x: -664, y: 150, width: 480, height: 272 });
+ });
+
+ it('clamps the transparent guide window inside the matching work area', () => {
+ expect(computeComputerPermissionGuideBounds(
+ { x: 1300, y: 800, width: 500, height: 500 },
+ { x: 0, y: 25, width: 1440, height: 875 },
+ )).toEqual({ x: 960, y: 628, width: 480, height: 272 });
+ });
+
+ it('shrinks safely when the work area is smaller than the guide window', () => {
+ expect(computeComputerPermissionGuideBounds(
+ { x: -800, y: 0, width: 320, height: 200 },
+ { x: -800, y: 0, width: 320, height: 200 },
+ )).toEqual({ x: -800, y: 0, width: 320, height: 200 });
+ });
+});
+
+describe('findSystemSettingsWindowBounds', () => {
+ it('selects the visible titled System Settings window over helper surfaces', () => {
+ expect(findSystemSettingsWindowBounds({
+ windows: [
+ {
+ app_name: 'System Settings',
+ title: '',
+ is_on_screen: true,
+ layer: 25,
+ bounds: { x: 0, y: 0, width: 1440, height: 25 },
+ },
+ {
+ app_name: 'System Settings',
+ title: '',
+ is_on_screen: true,
+ layer: 0,
+ bounds: { x: 120, y: 90, width: 440, height: 320 },
+ },
+ {
+ app_name: 'System Settings',
+ title: 'Privacy & Security',
+ is_on_screen: true,
+ layer: 0,
+ bounds: { x: 160, y: 80, width: 1000, height: 720 },
+ },
+ ],
+ })).toEqual({ x: 160, y: 80, width: 1000, height: 720 });
+ });
+
+ it('recognizes a localized window through its process executable', () => {
+ expect(findSystemSettingsWindowBounds({
+ windows: [{
+ app_name: '系统设置',
+ title: '隐私与安全性',
+ is_on_screen: true,
+ layer: 0,
+ bounds: { x: 80, y: 40, width: 920, height: 680 },
+ process: {
+ executable: '/System/Applications/System Settings.app/Contents/MacOS/System Settings',
+ },
+ }],
+ })).toEqual({ x: 80, y: 40, width: 920, height: 680 });
+ });
+});
diff --git a/apps/desktop/src/main/computer-permission-guide/placement.ts b/apps/desktop/src/main/computer-permission-guide/placement.ts
new file mode 100644
index 0000000000..717b9092f0
--- /dev/null
+++ b/apps/desktop/src/main/computer-permission-guide/placement.ts
@@ -0,0 +1,129 @@
+/** BrowserWindow bounds shape used by the permission-guide placement helper. */
+export interface PermissionGuideRectangle {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+interface ExternalWindowSnapshot {
+ app_name?: unknown;
+ title?: unknown;
+ is_on_screen?: unknown;
+ layer?: unknown;
+ bounds?: unknown;
+ process?: unknown;
+}
+
+export const PERMISSION_GUIDE_WINDOW_WIDTH = 480;
+export const PERMISSION_GUIDE_WINDOW_HEIGHT = 272;
+
+// The visible card lives inside a larger transparent BrowserWindow. The extra
+// space above the card is intentional: the animated cursor can travel outside
+// the card without being clipped by the native window bounds.
+const CARD_RIGHT_INSET = 16;
+const CARD_TOP_INSET = 48;
+
+function clamp(value: number, min: number, max: number): number {
+ return Math.min(Math.max(value, min), Math.max(min, max));
+}
+
+function rectangleFromUnknown(value: unknown): PermissionGuideRectangle | null {
+ if (!value || typeof value !== 'object') return null;
+ const candidate = value as Record<string, unknown>;
+ if (
+ typeof candidate.x !== 'number'
+ || typeof candidate.y !== 'number'
+ || typeof candidate.width !== 'number'
+ || typeof candidate.height !== 'number'
+ || candidate.width <= 0
+ || candidate.height <= 0
+ ) {
+ return null;
+ }
+ return {
+ x: candidate.x,
+ y: candidate.y,
+ width: candidate.width,
+ height: candidate.height,
+ };
+}
+
+function stringValue(value: unknown): string {
+ return typeof value === 'string' ? value : '';
+}
+
+function isSystemSettingsWindow(window: ExternalWindowSnapshot): boolean {
+ const process = window.process && typeof window.process === 'object'
+ ? window.process as Record<string, unknown>
+ : null;
+ const identityText = [
+ stringValue(window.app_name),
+ stringValue(window.title),
+ stringValue(process?.name),
+ stringValue(process?.command),
+ stringValue(process?.executable),
+ ].join('\n').toLowerCase();
+ return (
+ identityText.includes('system settings')
+ || identityText.includes('系统设置')
+ || identityText.includes('システム設定')
+ || identityText.includes('시스템 설정')
+ || identityText.includes('/system settings.app/')
+ );
+}
+
+/**
+ * Select the real, visible System Settings window from cua-driver's window
+ * snapshot. Empty helper windows and menu-bar surfaces are ignored.
+ */
+export function findSystemSettingsWindowBounds(result: unknown): PermissionGuideRectangle | null {
+ if (!result || typeof result !== 'object') return null;
+ const windows = (result as { windows?: unknown }).windows;
+ if (!Array.isArray(windows)) return null;
+
+ const candidates = windows
+ .filter((item): item is ExternalWindowSnapshot => Boolean(item && typeof item === 'object'))
+ .filter(isSystemSettingsWindow)
+ .filter((item) => item.is_on_screen !== false && item.layer !== 25)
+ .map((item) => ({
+ bounds: rectangleFromUnknown(item.bounds),
+ hasTitle: stringValue(item.title).trim().length > 0,
+ }))
+ .filter((item): item is { bounds: PermissionGuideRectangle; hasTitle: boolean } => (
+ item.bounds !== null && item.bounds.width >= 360 && item.bounds.height >= 280
+ ))
+ .sort((a, b) => (
+ Number(b.hasTitle) - Number(a.hasTitle)
+ || b.bounds.width * b.bounds.height - a.bounds.width * a.bounds.height
+ ));
+
+ return candidates[0]?.bounds ?? null;
+}
+
+/**
+ * Center the visible guide card vertically on the System Settings window, with
+ * the card's right edge aligned to the system window. The transparent native
+ * window remains clamped to the current display work area.
+ */
+export function computeComputerPermissionGuideBounds(
+ systemWindow: PermissionGuideRectangle,
+ workArea: PermissionGuideRectangle,
+): PermissionGuideRectangle {
+ const width = Math.min(PERMISSION_GUIDE_WINDOW_WIDTH, workArea.width);
+ const height = Math.min(PERMISSION_GUIDE_WINDOW_HEIGHT, workArea.height);
+ const rightInset = Math.min(CARD_RIGHT_INSET, Math.max(0, width / 8));
+ const topInset = Math.min(CARD_TOP_INSET, Math.max(0, height / 5));
+
+ const targetX = systemWindow.x + systemWindow.width - (width - rightInset);
+ const visibleCardHeight = height - topInset;
+ const centerY = systemWindow.y + systemWindow.height / 2;
+ const targetY = centerY - visibleCardHeight / 2 - topInset;
+
+ return {
+ x: clamp(targetX, workArea.x, workArea.x + workArea.width - width),
+ y: clamp(targetY, workArea.y, workArea.y + workArea.height - height),
+ width,
+ height,
+ };
+}
diff --git a/apps/desktop/src/main/computer-permission-guide/request.ts b/apps/desktop/src/main/computer-permission-guide/request.ts
new file mode 100644
index 0000000000..fc5fc31567
--- /dev/null
+++ b/apps/desktop/src/main/computer-permission-guide/request.ts
@@ -0,0 +1,48 @@
+/** Trusted, runtime-validated request shape for starting the macOS permission guide. */
+export interface ComputerPermissionGrantRequest {
+ showGuide: boolean;
+ openedPaneUrl?: string;
+}
+
+export const MAC_ACCESSIBILITY_SETTINGS_URL =
+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility';
+export const MAC_SCREEN_RECORDING_SETTINGS_URL =
+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture';
+
+/** Only the two static System Settings targets used by the Computer Use UI are allowed. */
+export function isComputerPermissionPaneUrl(value: unknown): value is string {
+ return (
+ value === MAC_ACCESSIBILITY_SETTINGS_URL
+ || value === MAC_SCREEN_RECORDING_SETTINGS_URL
+ );
+}
+
+/**
+ * Parse the untrusted Renderer payload without accepting permission snapshots
+ * or other fields that Main must derive itself.
+ */
+export function parseComputerPermissionGrantRequest(
+ value: unknown,
+): ComputerPermissionGrantRequest | null {
+ if (value === undefined) return { showGuide: false };
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
+
+ const record = value as Record<string, unknown>;
+ if (Object.keys(record).some((key) => !['showGuide', 'openedPaneUrl'].includes(key))) {
+ return null;
+ }
+ if (record.showGuide !== undefined && typeof record.showGuide !== 'boolean') return null;
+ if (
+ record.openedPaneUrl !== undefined
+ && !isComputerPermissionPaneUrl(record.openedPaneUrl)
+ ) {
+ return null;
+ }
+
+ return {
+ showGuide: record.showGuide === true,
+ ...(typeof record.openedPaneUrl === 'string'
+ ? { openedPaneUrl: record.openedPaneUrl }
+ : {}),
+ };
+}
diff --git a/apps/desktop/src/main/computer-permission-guide/switch-target.ts b/apps/desktop/src/main/computer-permission-guide/switch-target.ts
new file mode 100644
index 0000000000..fb06ae21ec
--- /dev/null
+++ b/apps/desktop/src/main/computer-permission-guide/switch-target.ts
@@ -0,0 +1,379 @@
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { findSystemSettingsWindowBounds } from './placement.js';
+
+const SYSTEM_CUA_DRIVER_APP_EXECUTABLE = path.join(
+ '/Applications',
+ 'CuaDriver.app',
+ 'Contents',
+ 'MacOS',
+ 'cua-driver',
+);
+const SYSTEM_CUA_DRIVER_CLI_EXECUTABLE = path.join(
+ os.homedir(),
+ '.local',
+ 'bin',
+ 'cua-driver',
+);
+const CONNECT_TIMEOUT_MS = 4_000;
+const TOOL_TIMEOUT_MS = 8_000;
+const CLOSE_TIMEOUT_MS = 1_000;
+
+interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export type ComputerUseSystemWindowBounds = Rect;
+
+/** Switch center relative to the System Settings window's top-left corner. */
+export interface ComputerUseSwitchTarget {
+ x: number;
+ y: number;
+ /** Current AX checkbox value when the driver exposes it. */
+ enabled: boolean | null;
+ /** Best-effort pane identity from the returned AX tree. */
+ permission?: 'accessibility' | 'screenRecording';
+}
+
+export type ComputerUseSwitchLocationResult =
+ | {
+ status: 'found';
+ target: ComputerUseSwitchTarget;
+ systemWindowBounds?: ComputerUseSystemWindowBounds;
+ }
+ | { status: 'not-found'; systemWindowBounds?: ComputerUseSystemWindowBounds }
+ | { status: 'unavailable'; systemWindowBounds?: ComputerUseSystemWindowBounds };
+
+interface SwitchLocatorConnection {
+ client: Client;
+ transport: StdioClientTransport;
+ session: string;
+}
+
+let switchLocatorConnection: SwitchLocatorConnection | null = null;
+let switchLocatorOperationQueue: Promise<void> = Promise.resolve();
+
+function serializeSwitchLocatorOperation<T>(operation: () => Promise<T>): Promise<T> {
+ const result = switchLocatorOperationQueue.then(operation);
+ switchLocatorOperationQueue = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ return result;
+}
+
+function objectValue(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null;
+}
+
+function finiteNumber(value: unknown): number | null {
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
+}
+
+function readRect(value: unknown): Rect | null {
+ const object = objectValue(value);
+ if (!object) return null;
+ const x = finiteNumber(object.x);
+ const y = finiteNumber(object.y);
+ const width = finiteNumber(object.width ?? object.w);
+ const height = finiteNumber(object.height ?? object.h);
+ if (x === null || y === null || width === null || height === null) return null;
+ return { x, y, width, height };
+}
+
+function readArray(value: unknown, key: string): unknown[] {
+ if (Array.isArray(value)) return value;
+ const object = objectValue(value);
+ return object && Array.isArray(object[key]) ? object[key] : [];
+}
+
+function parseMcpResult(result: unknown): unknown {
+ const object = objectValue(result);
+ const structured = objectValue(object?.structuredContent);
+ if (structured && Object.keys(structured).length > 0) return structured;
+ const content = Array.isArray(object?.content) ? object.content : [];
+ for (const item of content) {
+ const row = objectValue(item);
+ if (row?.type !== 'text' || typeof row.text !== 'string') continue;
+ try {
+ return JSON.parse(row.text) as unknown;
+ } catch {
+ continue;
+ }
+ }
+ return null;
+}
+
+function parseSuccessfulMcpResult(result: unknown, toolName: string): unknown {
+ if (objectValue(result)?.isError === true) {
+ throw new Error(`CuaDriver MCP tool ${toolName} returned an error`);
+ }
+ return parseMcpResult(result);
+}
+
+function isExactCuaDriverSwitch(element: Record<string, unknown>): boolean {
+ if (element.role !== 'AXCheckBox') return false;
+ const label = typeof element.label === 'string' ? element.label : '';
+ return label.replace(/_Toggle$/i, '').trim().toLocaleLowerCase() === 'cuadriver';
+}
+
+function readCheckboxValue(element: Record<string, unknown>): boolean | null {
+ const candidates = [element.value, element.checked, element.is_checked, element.selected];
+ for (const candidate of candidates) {
+ if (typeof candidate === 'boolean') return candidate;
+ if (typeof candidate === 'number' && Number.isFinite(candidate)) return candidate !== 0;
+ if (typeof candidate === 'string') {
+ const normalized = candidate.trim().toLocaleLowerCase();
+ if (['1', 'true', 'on', 'yes', 'checked'].includes(normalized)) return true;
+ if (['0', 'false', 'off', 'no', 'unchecked'].includes(normalized)) return false;
+ }
+ }
+ return null;
+}
+
+function permissionFromText(value: unknown): ComputerUseSwitchTarget['permission'] {
+ if (typeof value !== 'string') return undefined;
+ const normalized = value.trim().toLocaleLowerCase();
+ if (normalized.includes('screen recording') || normalized.includes('screen capture')) {
+ return 'screenRecording';
+ }
+ if (normalized.includes('accessibility')) return 'accessibility';
+ return undefined;
+}
+
+function detectPermissionPane(value: unknown): ComputerUseSwitchTarget['permission'] {
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ const detected = detectPermissionPane(item);
+ if (detected) return detected;
+ }
+ return undefined;
+ }
+ const object = objectValue(value);
+ if (!object) return permissionFromText(value);
+ for (const key of ['label', 'title', 'name', 'value', 'description']) {
+ const detected = permissionFromText(object[key]);
+ if (detected) return detected;
+ }
+ for (const child of Object.values(object)) {
+ const detected = detectPermissionPane(child);
+ if (detected) return detected;
+ }
+ return undefined;
+}
+
+function findSystemSettingsWindow(
+ listWindowsResult: unknown,
+): { window: Record<string, unknown>; bounds: ComputerUseSystemWindowBounds } | null {
+ const windows = readArray(listWindowsResult, 'windows');
+ const bounds = findSystemSettingsWindowBounds({ windows });
+ if (!bounds) return null;
+ const window = windows
+ .map(objectValue)
+ .find((candidate) => {
+ const candidateBounds = readRect(candidate?.bounds);
+ return Boolean(
+ candidateBounds
+ && candidateBounds.x === bounds.x
+ && candidateBounds.y === bounds.y
+ && candidateBounds.width === bounds.width
+ && candidateBounds.height === bounds.height
+ );
+ });
+ return window ? { window, bounds } : null;
+}
+
+/** Resolve the exact branded row without confusing it with Codex Computer Use. */
+export function findComputerUseSwitchTarget(
+ listWindowsResult: unknown,
+ windowStateResult: unknown,
+): ComputerUseSwitchTarget | null {
+ const settingsWindow = findSystemSettingsWindow(listWindowsResult);
+ if (!settingsWindow) return null;
+ const windowBounds = settingsWindow.bounds;
+
+ const target = readArray(windowStateResult, 'elements')
+ .map(objectValue)
+ .find((element) => element && isExactCuaDriverSwitch(element));
+ if (!target) return null;
+ const targetFrame = readRect(target.frame);
+ if (!targetFrame || targetFrame.width <= 0 || targetFrame.height <= 1) return null;
+
+ const x = targetFrame.x + targetFrame.width / 2 - windowBounds.x;
+ const y = targetFrame.y + targetFrame.height / 2 - windowBounds.y;
+ if (x < 0 || y < 0 || x > windowBounds.width || y > windowBounds.height) return null;
+ const permission = detectPermissionPane(windowStateResult);
+ return {
+ x,
+ y,
+ enabled: readCheckboxValue(target),
+ ...(permission ? { permission } : {}),
+ };
+}
+
+function resolveSystemCuaDriverExecutable(): string | null {
+ if (fs.existsSync(SYSTEM_CUA_DRIVER_APP_EXECUTABLE)) {
+ return SYSTEM_CUA_DRIVER_APP_EXECUTABLE;
+ }
+ if (fs.existsSync(SYSTEM_CUA_DRIVER_CLI_EXECUTABLE)) {
+ return SYSTEM_CUA_DRIVER_CLI_EXECUTABLE;
+ }
+ return null;
+}
+
+function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs);
+ promise.then(
+ (value) => {
+ clearTimeout(timer);
+ resolve(value);
+ },
+ (error) => {
+ clearTimeout(timer);
+ reject(error);
+ },
+ );
+ });
+}
+
+async function closeSwitchLocatorConnection(connection: SwitchLocatorConnection): Promise<void> {
+ try {
+ await withTimeout(
+ connection.client.close(),
+ CLOSE_TIMEOUT_MS,
+ 'switch locator close',
+ );
+ } catch {
+ // Shutdown is best-effort; the cached connection has already been discarded.
+ }
+}
+
+async function discardSwitchLocatorConnection(
+ connection: SwitchLocatorConnection,
+): Promise<void> {
+ if (switchLocatorConnection === connection) {
+ switchLocatorConnection = null;
+ }
+ await closeSwitchLocatorConnection(connection);
+}
+
+async function connectSwitchLocator(executable: string): Promise<SwitchLocatorConnection> {
+ const transport = new StdioClientTransport({
+ command: executable,
+ args: ['mcp'],
+ stderr: 'ignore',
+ });
+ const client = new Client({
+ name: 'xdt-computer-permission-switch-locator',
+ version: '0.1.0',
+ });
+ const connection = {
+ client,
+ transport,
+ session: `xdt-permission-switch-${Date.now()}`,
+ };
+ try {
+ await withTimeout(client.connect(transport), CONNECT_TIMEOUT_MS, 'switch locator startup');
+ switchLocatorConnection = connection;
+ return connection;
+ } catch (error) {
+ await closeSwitchLocatorConnection(connection);
+ throw error;
+ }
+}
+
+async function getSwitchLocatorConnection(executable: string): Promise<SwitchLocatorConnection> {
+ return switchLocatorConnection ?? connectSwitchLocator(executable);
+}
+
+async function locateComputerUseSwitchTargetSerialized(): Promise<ComputerUseSwitchLocationResult> {
+ if (process.platform !== 'darwin') return { status: 'unavailable' };
+ const executable = resolveSystemCuaDriverExecutable();
+ if (!executable) return { status: 'unavailable' };
+
+ const connection = await getSwitchLocatorConnection(executable);
+ try {
+ const windowsResult = parseSuccessfulMcpResult(await withTimeout(
+ connection.client.callTool({
+ name: 'list_windows',
+ arguments: { on_screen_only: true, session: connection.session },
+ }),
+ TOOL_TIMEOUT_MS,
+ 'System Settings window lookup',
+ ), 'list_windows');
+ const settingsWindow = findSystemSettingsWindow(windowsResult);
+ const pid = finiteNumber(settingsWindow?.window.pid);
+ const windowId = finiteNumber(settingsWindow?.window.window_id);
+ if (pid === null || windowId === null) {
+ return {
+ status: 'unavailable',
+ ...(settingsWindow ? { systemWindowBounds: settingsWindow.bounds } : {}),
+ };
+ }
+
+ const stateResult = parseSuccessfulMcpResult(await withTimeout(
+ connection.client.callTool({
+ name: 'get_window_state',
+ arguments: {
+ pid,
+ window_id: windowId,
+ include_screenshot: false,
+ // Match the stable app row instead of the localized permission-pane
+ // title, while avoiding a walk of the full 400-500 element tree.
+ max_elements: 180,
+ max_depth: 6,
+ query: 'CuaDriver',
+ session: connection.session,
+ },
+ }),
+ TOOL_TIMEOUT_MS,
+ 'Computer Use switch lookup',
+ ), 'get_window_state');
+ const target = findComputerUseSwitchTarget(windowsResult, stateResult);
+ if (target) {
+ return {
+ status: 'found',
+ target,
+ ...(settingsWindow ? { systemWindowBounds: settingsWindow.bounds } : {}),
+ };
+ }
+ const stateObject = objectValue(stateResult);
+ const elementCount = finiteNumber(stateObject?.element_count);
+ return elementCount !== null && elementCount > 0
+ ? {
+ status: 'not-found',
+ ...(settingsWindow ? { systemWindowBounds: settingsWindow.bounds } : {}),
+ }
+ : {
+ status: 'unavailable',
+ ...(settingsWindow ? { systemWindowBounds: settingsWindow.bounds } : {}),
+ };
+ } catch (error) {
+ await discardSwitchLocatorConnection(connection);
+ throw error;
+ }
+}
+
+/** Read-only probe through the phase-one CuaDriver identity. */
+export function locateComputerUseSwitchTarget(): Promise<ComputerUseSwitchLocationResult> {
+ return serializeSwitchLocatorOperation(locateComputerUseSwitchTargetSerialized);
+}
+
+export function closeComputerUseSwitchLocator(): Promise<void> {
+ return serializeSwitchLocatorOperation(async () => {
+ const connection = switchLocatorConnection;
+ switchLocatorConnection = null;
+ if (!connection) return;
+ await closeSwitchLocatorConnection(connection);
+ });
+}
diff --git a/apps/desktop/src/main/computer-permission-guide/window.ts b/apps/desktop/src/main/computer-permission-guide/window.ts
new file mode 100644
index 0000000000..e81fd89be8
--- /dev/null
+++ b/apps/desktop/src/main/computer-permission-guide/window.ts
@@ -0,0 +1,1217 @@
+/**
+ * Electron Computer Use permission coach.
+ *
+ * System Settings covers the main Cindy window, so the macOS onboarding lives
+ * in its own always-on-top BrowserWindow. A second mouse-transparent window is
+ * kept behind it so renderer effects are never clipped while System Settings
+ * remains fully interactive.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {
+ app,
+ BrowserWindow,
+ nativeImage,
+ screen,
+ shell,
+} from 'electron';
+import type { Rectangle, WebContents } from 'electron';
+
+import { scheduleMainAppPresenceRestore } from '../appPresence.js';
+import { getResolvedMainLocale } from '../i18n.js';
+import { createLogger } from '../logger.js';
+import { MAKER_PUSH } from '../maker-ipc/channels.js';
+import {
+ cancelComputerDriverPermissionGrant,
+ getComputerDriverAppBundlePath,
+ getComputerDriverStatus,
+ isComputerDriverPermissionProbePaused,
+ resumeComputerDriverPermissionProbe,
+} from '../mcp-integrations/computer.js';
+import {
+ closeComputerUseSwitchLocator,
+ locateComputerUseSwitchTarget,
+ type ComputerUseSwitchLocationResult,
+ type ComputerUseSystemWindowBounds,
+} from './switch-target.js';
+import {
+ computeComputerPermissionGuideBounds,
+ PERMISSION_GUIDE_WINDOW_WIDTH,
+ PERMISSION_GUIDE_WINDOW_HEIGHT,
+} from './placement.js';
+import {
+ MacComputerPermissionGuideNativeHost,
+ type ComputerPermissionGuideNativeState,
+} from './MacComputerPermissionGuideNativeHost.js';
+import {
+ isComputerPermissionPaneUrl,
+ MAC_ACCESSIBILITY_SETTINGS_URL,
+ MAC_SCREEN_RECORDING_SETTINGS_URL,
+} from './request.js';
+
+const log = createLogger('computer-permission-guide');
+// v1 was also used as evidence that the row existed. That is not safe: a
+// stale record survives when the user removes CuaDriver from System Settings,
+// and the old locator can then re-register the app while checking the page.
+// v2 is an interaction hint only and is written after a confirmed copy drag.
+// It is reset whenever a new guide lifecycle starts.
+const DRAG_STATE_FILE_NAME = 'cua-driver-drag-state-v2.json';
+const SWITCH_OBSERVER_INTERVAL_MS = 900;
+const PERMISSION_PROBE_BYPASS_MIN_INTERVAL_MS = 2_000;
+const DRAG_RESTORE_TIMEOUT_MS = 12_000;
+const NATIVE_ATTACH_TIMEOUT_MS = 30_000;
+const DRAG_ICON_DATA_URL_PREFIX = 'data:image/png;base64,';
+const MAX_DRAG_ICON_BASE64_LENGTH = 256 * 1024;
+const PNG_SIGNATURE_BASE64_PREFIX = 'iVBORw0KGgo';
+const GUIDE_WINDOW_MARGIN = 16;
+
+type ComputerStatus = Awaited<ReturnType<typeof getComputerDriverStatus>>;
+type PermissionKind = 'accessibility' | 'screenRecording';
+interface PermissionGuideRefreshOptions {
+ bypassPermissionProbeCache?: boolean;
+ freshPermissionProbe?: boolean;
+ knownStatus?: ComputerStatus;
+ forceBroadcast?: boolean;
+ observedLocation?: ComputerUseSwitchLocationResult;
+}
+
+let guideWindow: BrowserWindow | null = null;
+let backdropWindow: BrowserWindow | null = null;
+let guideOwner: BrowserWindow | null = null;
+let guideStatus: ComputerStatus | null = null;
+let switchObserverTimer: ReturnType<typeof setInterval> | null = null;
+let switchObserverPendingGeneration: number | null = null;
+let lastSwitchObservation = '';
+let permissionGuideUpdateQueue: Promise<void> = Promise.resolve();
+let guideLifecycleGeneration = 0;
+let lastPermissionProbeBypassAt: number | null = null;
+let pendingObserverTrailingProbe: ReturnType<typeof setTimeout> | null = null;
+let dragRestoreTimer: ReturnType<typeof setTimeout> | null = null;
+let dragInProgress = false;
+let draggedPermission: PermissionKind | null = null;
+let permissionDragStateCache: PermissionDragState | null = null;
+let nativeHost: MacComputerPermissionGuideNativeHost | null = null;
+let lastSwitchLocation: ComputerUseSwitchLocationResult | null = null;
+let nativeAttachTimeout: ReturnType<typeof setTimeout> | null = null;
+let nativeGuideAttached = false;
+let lastOpenedPermissionPaneUrl: string | null = null;
+
+/** Per-pane lifecycle state that public macOS permission APIs do not expose. */
+export interface PermissionDragState {
+ accessibility: boolean;
+ screenRecording: boolean;
+}
+
+function getPermissionDragStatePath(): string {
+ return path.join(app.getPath('userData'), 'computer-permission-guide', DRAG_STATE_FILE_NAME);
+}
+
+/** Read whether the user has already attempted the app drag for each pane. */
+export function readPermissionDragState(): PermissionDragState {
+ if (permissionDragStateCache) return { ...permissionDragStateCache };
+ try {
+ const parsed = JSON.parse(
+ fs.readFileSync(getPermissionDragStatePath(), 'utf8'),
+ ) as Partial<PermissionDragState>;
+ permissionDragStateCache = {
+ accessibility: parsed.accessibility === true,
+ screenRecording: parsed.screenRecording === true,
+ };
+ } catch {
+ permissionDragStateCache = { accessibility: false, screenRecording: false };
+ }
+ return { ...permissionDragStateCache };
+}
+
+function writePermissionDragState(state: PermissionDragState): void {
+ permissionDragStateCache = { ...state };
+ try {
+ const filePath = getPermissionDragStatePath();
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, `${JSON.stringify(state)}\n`, 'utf8');
+ } catch (error) {
+ log.warn('failed to persist Computer Use permission drag state', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
+
+function clearPermissionDragState(permission: PermissionKind): void {
+ const state = readPermissionDragState();
+ if (!state[permission]) return;
+ state[permission] = false;
+ writePermissionDragState(state);
+ log.debug('cleared stale permission drag state because the row is absent', { permission });
+}
+
+function loadPermissionView(
+ window: BrowserWindow,
+ view: 'computer-permission-guide' | 'computer-permission-backdrop',
+): Promise<void> {
+ if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
+ const url = new URL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
+ url.searchParams.set('view', view);
+ return window.loadURL(url.toString());
+ }
+ return window.loadFile(
+ path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
+ { query: { view } },
+ );
+}
+
+function preventPermissionGuideNavigation(webContents: WebContents): void {
+ webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
+ webContents.on('will-navigate', (event) => {
+ event.preventDefault();
+ });
+}
+
+function closeWindow(window: BrowserWindow | null): void {
+ if (window && !window.isDestroyed()) window.close();
+}
+
+function guideBoundsForWorkArea(workArea: Rectangle): Rectangle {
+ const width = Math.min(PERMISSION_GUIDE_WINDOW_WIDTH, workArea.width);
+ const height = Math.min(PERMISSION_GUIDE_WINDOW_HEIGHT, workArea.height);
+ return {
+ x: workArea.x + workArea.width - width - Math.min(GUIDE_WINDOW_MARGIN, workArea.width - width),
+ y: workArea.y + workArea.height - height - Math.min(GUIDE_WINDOW_MARGIN, workArea.height - height),
+ width,
+ height,
+ };
+}
+
+function currentDisplay(): Electron.Display {
+ if (guideOwner && !guideOwner.isDestroyed()) {
+ return screen.getDisplayMatching(guideOwner.getBounds());
+ }
+ return screen.getDisplayNearestPoint(screen.getCursorScreenPoint());
+}
+
+function positionGuideAtSystemSettings(systemWindowBounds: ComputerUseSystemWindowBounds): void {
+ if (!guideWindow || guideWindow.isDestroyed()) return;
+ const display = screen.getDisplayMatching(systemWindowBounds);
+ const guideBounds = computeComputerPermissionGuideBounds(
+ systemWindowBounds,
+ display.workArea,
+ );
+ guideWindow.setBounds(guideBounds, false);
+ guideWindow.setAlwaysOnTop(true, 'floating', 1);
+ if (backdropWindow && !backdropWindow.isDestroyed()) {
+ backdropWindow.setBounds(display.workArea, false);
+ }
+}
+
+function hasPermissionGuide(): boolean {
+ return Boolean(
+ nativeHost
+ || (guideWindow && !guideWindow.isDestroyed()),
+ );
+}
+
+function isGuideLifecycleActive(generation: number): boolean {
+ return generation === guideLifecycleGeneration && hasPermissionGuide();
+}
+
+function isOwnedNativeHost(
+ generation: number,
+ host: MacComputerPermissionGuideNativeHost,
+): boolean {
+ return isGuideLifecycleActive(generation) && nativeHost === host;
+}
+
+function cancelPendingObserverTrailingProbe(): void {
+ if (pendingObserverTrailingProbe) clearTimeout(pendingObserverTrailingProbe);
+ pendingObserverTrailingProbe = null;
+}
+
+function resetPermissionProbeBypassThrottle(): void {
+ cancelPendingObserverTrailingProbe();
+ lastPermissionProbeBypassAt = null;
+}
+
+function resetGuideLifecycleUpdates(): void {
+ guideLifecycleGeneration += 1;
+ permissionGuideUpdateQueue = Promise.resolve();
+ resetPermissionProbeBypassThrottle();
+}
+
+function beginGuideLifecycle(): void {
+ resetGuideLifecycleUpdates();
+ guideStatus = null;
+ lastSwitchObservation = '';
+ lastSwitchLocation = null;
+ // A drag is evidence only for the guide lifecycle where it happened. A
+ // historical flag must never authorize a locator probe in a later run,
+ // because starting that locator can itself re-register the Accessibility row.
+ writePermissionDragState({ accessibility: false, screenRecording: false });
+}
+
+function serializePermissionGuideUpdate(
+ label: string,
+ update: (generation: number) => Promise<void> | void,
+ generation = guideLifecycleGeneration,
+): Promise<void> {
+ const queuedUpdate = permissionGuideUpdateQueue.then(async () => {
+ if (!isGuideLifecycleActive(generation)) return;
+ try {
+ await update(generation);
+ } catch (error) {
+ log.debug(`${label} failed`, {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ });
+ permissionGuideUpdateQueue = queuedUpdate;
+ return queuedUpdate;
+}
+
+function scheduleObserverTrailingPermissionProbe(generation: number): void {
+ if (pendingObserverTrailingProbe) return;
+ const lastBypassAt = lastPermissionProbeBypassAt;
+ if (lastBypassAt === null) return;
+
+ const delay = Math.max(
+ 0,
+ lastBypassAt + PERMISSION_PROBE_BYPASS_MIN_INTERVAL_MS - Date.now(),
+ );
+ const pendingProbe = setTimeout(() => {
+ if (pendingObserverTrailingProbe !== pendingProbe) return;
+ void serializePermissionGuideUpdate(
+ 'Computer Use switch observer trailing permission probe',
+ async (currentGeneration) => {
+ if (pendingObserverTrailingProbe !== pendingProbe) return;
+ pendingObserverTrailingProbe = null;
+ await refreshElectronPermissionGuideStateSerialized({
+ bypassPermissionProbeCache: true,
+ }, currentGeneration);
+ },
+ generation,
+ );
+ }, delay);
+ pendingObserverTrailingProbe = pendingProbe;
+}
+
+function broadcastPermissionGuideStatus(status: ComputerStatus): void {
+ guideStatus = status;
+ sendPermissionGuideStatus(status);
+}
+
+function sendPermissionGuideStatus(
+ status: ComputerStatus,
+ guideOverride?: ComputerStatus | null,
+): void {
+ const guideWebContentsId = guideWindow && !guideWindow.isDestroyed()
+ ? guideWindow.webContents.id
+ : null;
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) {
+ const outboundStatus = (
+ guideOverride
+ && guideWebContentsId === win.webContents.id
+ )
+ ? guideOverride
+ : status;
+ win.webContents.send(
+ MAKER_PUSH.COMPUTER_PERMISSION_GUIDE_STATUS_CHANGED,
+ outboundStatus,
+ );
+ }
+ }
+}
+
+function broadcastPermissionGuideCancelled(): void {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) {
+ win.webContents.send(MAKER_PUSH.COMPUTER_PERMISSION_GUIDE_CANCELLED);
+ }
+ }
+}
+
+function clearNativeAttachTimeout(): void {
+ if (!nativeAttachTimeout) return;
+ clearTimeout(nativeAttachTimeout);
+ nativeAttachTimeout = null;
+}
+
+function armNativeAttachTimeout(
+ generation: number,
+ ownerHost: MacComputerPermissionGuideNativeHost,
+): void {
+ clearNativeAttachTimeout();
+ if (
+ !isOwnedNativeHost(generation, ownerHost)
+ || nativeGuideAttached
+ ) {
+ return;
+ }
+ const timeout = setTimeout(() => {
+ if (nativeAttachTimeout === timeout) nativeAttachTimeout = null;
+ if (
+ !isOwnedNativeHost(generation, ownerHost)
+ || nativeGuideAttached
+ ) {
+ return;
+ }
+ log.warn('native Computer Use permission coach did not attach to System Settings in time');
+ closeComputerPermissionGuideWindow();
+ broadcastPermissionGuideCancelled();
+ }, NATIVE_ATTACH_TIMEOUT_MS);
+ nativeAttachTimeout = timeout;
+}
+
+function rememberSwitchLocation(location: ComputerUseSwitchLocationResult): void {
+ if (location.status === 'unavailable' && lastSwitchLocation) {
+ if (location.systemWindowBounds) {
+ lastSwitchLocation = {
+ ...lastSwitchLocation,
+ systemWindowBounds: location.systemWindowBounds,
+ };
+ }
+ return;
+ }
+ lastSwitchLocation = location;
+}
+
+export function getComputerPermissionPaneUrl(status: ComputerStatus | null): string | null {
+ switch (missingPermission(status)) {
+ case 'accessibility':
+ return MAC_ACCESSIBILITY_SETTINGS_URL;
+ case 'screenRecording':
+ return MAC_SCREEN_RECORDING_SETTINGS_URL;
+ default:
+ return null;
+ }
+}
+
+export function seedOpenedPermissionPane(url: string): void {
+ if (isComputerPermissionPaneUrl(url)) {
+ lastOpenedPermissionPaneUrl = url;
+ }
+}
+
+export async function openComputerPermissionPaneForStatus(
+ status: ComputerStatus | null,
+): Promise<void> {
+ if (process.platform !== 'darwin') return;
+ const url = getComputerPermissionPaneUrl(status);
+ if (!url || lastOpenedPermissionPaneUrl === url) return;
+ lastOpenedPermissionPaneUrl = url;
+ try {
+ await shell.openExternal(url);
+ log.debug('opened Computer Use permission pane', { url });
+ } catch (error) {
+ if (lastOpenedPermissionPaneUrl === url) lastOpenedPermissionPaneUrl = null;
+ log.warn('failed to open Computer Use permission pane', {
+ url,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
+
+function missingPermission(status: ComputerStatus | null): PermissionKind | null {
+ if (status?.permissionState?.accessibility !== 'granted') return 'accessibility';
+ if (
+ status.permissionState.screenRecording !== 'granted'
+ || status.permissionState.screenRecordingCapturable !== 'granted'
+ ) {
+ return 'screenRecording';
+ }
+ return null;
+}
+
+function isPausedPermissionProbePlaceholder(status: ComputerStatus): boolean {
+ const permissionState = status.permissionState;
+ return (
+ isComputerDriverPermissionProbePaused()
+ && permissionState?.platform === 'macos'
+ && permissionState.accessibility === 'missing'
+ && permissionState.screenRecording === 'unknown'
+ && permissionState.screenRecordingCapturable === 'unknown'
+ );
+}
+
+function observationKey(location: ComputerUseSwitchLocationResult): string {
+ if (location.status !== 'found') return location.status;
+ return [
+ location.status,
+ location.target.permission ?? 'unknown',
+ location.target.enabled === null ? 'unknown' : String(location.target.enabled),
+ ].join(':');
+}
+
+async function refreshElectronPermissionGuideState(
+ options: PermissionGuideRefreshOptions = {},
+): Promise<void> {
+ if (options.bypassPermissionProbeCache && !options.knownStatus) {
+ cancelPendingObserverTrailingProbe();
+ }
+ return serializePermissionGuideUpdate(
+ 'Electron permission guide status refresh',
+ (generation) => {
+ if (options.bypassPermissionProbeCache && !options.knownStatus) {
+ cancelPendingObserverTrailingProbe();
+ }
+ return refreshElectronPermissionGuideStateSerialized(options, generation);
+ },
+ );
+}
+
+async function refreshElectronPermissionGuideStateSerialized(
+ options: PermissionGuideRefreshOptions,
+ generation: number,
+): Promise<void> {
+ if (options.knownStatus) guideStatus = options.knownStatus;
+ const statusSnapshot = options.knownStatus ?? guideStatus;
+ let observedLocation = options.observedLocation ?? null;
+ if (isComputerDriverPermissionProbePaused()) {
+ const dragState = readPermissionDragState();
+ const activePermission = missingPermission(statusSnapshot) ?? 'accessibility';
+ // Starting CuaDriver's MCP locator is not passive on macOS: the driver
+ // may appear in the Accessibility list as a side effect of the probe.
+ // Do not inspect the page until this flow has a confirmed drag result.
+ if (!dragState[activePermission]) {
+ nativeHost?.update(nativeStateFrom(
+ statusSnapshot,
+ {
+ ...dragState,
+ [activePermission]: false,
+ },
+ lastSwitchLocation,
+ ));
+ if (options.forceBroadcast && statusSnapshot) {
+ broadcastPermissionGuideStatus(statusSnapshot);
+ }
+ return;
+ }
+
+ if (!observedLocation) {
+ observedLocation = await locateComputerUseSwitchTarget();
+ if (!isGuideLifecycleActive(generation)) return;
+ rememberSwitchLocation(observedLocation);
+ if (observedLocation.systemWindowBounds) {
+ positionGuideAtSystemSettings(observedLocation.systemWindowBounds);
+ }
+ }
+ if (observedLocation.status === 'not-found') {
+ const permission = missingPermission(statusSnapshot) ?? 'accessibility';
+ // A persisted drag flag only records a past interaction. The live
+ // System Settings row is the source of truth; if the locator cannot
+ // find it, do not render the switch step from stale history.
+ clearPermissionDragState(permission);
+ nativeHost?.update(nativeStateFrom(
+ statusSnapshot,
+ readPermissionDragState(),
+ lastSwitchLocation,
+ ));
+ if (options.forceBroadcast && statusSnapshot) {
+ broadcastPermissionGuideStatus(statusSnapshot);
+ }
+ return;
+ }
+ if (observedLocation.status === 'unavailable') {
+ nativeHost?.update(nativeStateFrom(
+ statusSnapshot,
+ readPermissionDragState(),
+ lastSwitchLocation,
+ ));
+ if (options.forceBroadcast && statusSnapshot) {
+ broadcastPermissionGuideStatus(statusSnapshot);
+ }
+ return;
+ }
+
+ const state = readPermissionDragState();
+ const permission = observedLocation.target.permission
+ ?? missingPermission(statusSnapshot)
+ ?? 'accessibility';
+ state[permission] = true;
+ writePermissionDragState(state);
+ resumeComputerDriverPermissionProbe();
+ log.info('CuaDriver row appeared; resumed the live permission runtime', { permission });
+ }
+
+ let status = options.knownStatus;
+ if (!status) {
+ if (options.bypassPermissionProbeCache) {
+ lastPermissionProbeBypassAt = Date.now();
+ }
+ status = await getComputerDriverStatus({
+ forcePermissionProbe: true,
+ ...(options.bypassPermissionProbeCache
+ ? { bypassPermissionProbeCache: true }
+ : {}),
+ ...(options.freshPermissionProbe
+ ? { freshPermissionProbe: true }
+ : {}),
+ });
+ }
+ if (!isGuideLifecycleActive(generation)) return;
+ const state = readPermissionDragState();
+ nativeHost?.update(nativeStateFrom(status, state, lastSwitchLocation));
+ void openComputerPermissionPaneForStatus(status);
+ broadcastPermissionGuideStatus(status);
+}
+
+async function observePermissionSwitchSerialized(generation: number): Promise<void> {
+ const statusSnapshot = guideStatus;
+ const dragState = readPermissionDragState();
+ const activePermission = missingPermission(statusSnapshot) ?? 'accessibility';
+ // See refreshElectronPermissionGuideState: querying through CuaDriver
+ // before the drag is itself capable of creating the row. This ownership
+ // gate follows the active pane even after the global probe resumes.
+ if (!dragState[activePermission]) {
+ lastSwitchObservation = 'awaiting-drag';
+ return;
+ }
+ const location = await locateComputerUseSwitchTarget();
+ if (!isGuideLifecycleActive(generation)) return;
+ rememberSwitchLocation(location);
+ if (location.systemWindowBounds) {
+ positionGuideAtSystemSettings(location.systemWindowBounds);
+ }
+ const nextObservation = observationKey(location);
+ const changed = lastSwitchObservation !== nextObservation;
+ lastSwitchObservation = nextObservation;
+ if (location.status === 'found') {
+ const state = readPermissionDragState();
+ const permission = location.target.permission
+ ?? missingPermission(statusSnapshot)
+ ?? 'accessibility';
+ if (!state[permission]) {
+ state[permission] = true;
+ writePermissionDragState(state);
+ }
+ }
+ const needsFreshPermissionProbe = changed
+ || (location.status === 'found' && location.target.enabled === null);
+ if (needsFreshPermissionProbe) {
+ const bypassIntervalElapsed = lastPermissionProbeBypassAt === null
+ || Date.now() - lastPermissionProbeBypassAt
+ >= PERMISSION_PROBE_BYPASS_MIN_INTERVAL_MS;
+ if (bypassIntervalElapsed) {
+ await refreshElectronPermissionGuideStateSerialized({
+ // Restart daemon so it picks up newly granted permissions —
+ // macOS may kill it on Screen Recording changes, but the
+ // autostart throttle can block revival without fresh.
+ freshPermissionProbe: true,
+ bypassPermissionProbeCache: true,
+ observedLocation: location,
+ }, generation);
+ } else {
+ scheduleObserverTrailingPermissionProbe(generation);
+ await refreshElectronPermissionGuideStateSerialized({
+ observedLocation: location,
+ }, generation);
+ }
+ }
+}
+
+async function observePermissionSwitch(): Promise<void> {
+ const generation = guideLifecycleGeneration;
+ if (!hasPermissionGuide() || switchObserverPendingGeneration === generation) return;
+ switchObserverPendingGeneration = generation;
+ try {
+ await serializePermissionGuideUpdate(
+ 'Computer Use switch observer',
+ observePermissionSwitchSerialized,
+ );
+ } finally {
+ if (switchObserverPendingGeneration === generation) {
+ switchObserverPendingGeneration = null;
+ }
+ }
+}
+
+function startSwitchObserver(): void {
+ if (switchObserverTimer) return;
+ switchObserverTimer = setInterval(() => {
+ void observePermissionSwitch();
+ }, SWITCH_OBSERVER_INTERVAL_MS);
+ void observePermissionSwitch();
+}
+
+function stopSwitchObserver(): void {
+ if (switchObserverTimer) clearInterval(switchObserverTimer);
+ switchObserverTimer = null;
+ switchObserverPendingGeneration = null;
+ lastSwitchObservation = '';
+}
+
+function restoreGuideAfterDrag(): void {
+ if (dragRestoreTimer) clearTimeout(dragRestoreTimer);
+ dragRestoreTimer = null;
+ dragInProgress = false;
+ draggedPermission = null;
+ if (guideWindow && !guideWindow.isDestroyed()) {
+ guideWindow.setIgnoreMouseEvents(false);
+ guideWindow.setAlwaysOnTop(true, 'floating', 1);
+ guideWindow.showInactive();
+ }
+}
+
+async function completeElectronPermissionAppDrag(
+ permission: PermissionKind | null,
+): Promise<boolean> {
+ cancelPendingObserverTrailingProbe();
+ let accepted = false;
+ await serializePermissionGuideUpdate(
+ 'Electron permission guide drag completion refresh',
+ async (generation) => {
+ cancelPendingObserverTrailingProbe();
+ if (permission) {
+ const state = readPermissionDragState();
+ state[permission] = true;
+ writePermissionDragState(state);
+ }
+ try {
+ await refreshElectronPermissionGuideStateSerialized({
+ freshPermissionProbe: true,
+ bypassPermissionProbeCache: true,
+ }, generation);
+ accepted = Boolean(
+ permission
+ && isGuideLifecycleActive(generation)
+ && readPermissionDragState()[permission],
+ );
+ } finally {
+ if (
+ permission
+ && isGuideLifecycleActive(generation)
+ && !accepted
+ ) {
+ clearPermissionDragState(permission);
+ }
+ }
+ },
+ );
+ return accepted;
+}
+
+function armDragRestore(): void {
+ if (dragRestoreTimer) clearTimeout(dragRestoreTimer);
+ dragRestoreTimer = setTimeout(() => {
+ log.debug('restoring Electron permission guide after drag fallback');
+ restoreGuideAfterDrag();
+ // Chromium can omit dragend after startDrag returns. Without a positive
+ // copy dropEffect there is no safe evidence that System Settings accepted
+ // the app, so restore the coach without starting the locator.
+ }, DRAG_RESTORE_TIMEOUT_MS);
+}
+
+/** Refresh the visible Electron coach after an explicit status check. */
+export function refreshComputerPermissionGuideWindow(status?: ComputerStatus): void {
+ if (status) {
+ if (!hasPermissionGuide()) {
+ broadcastPermissionGuideStatus(status);
+ return;
+ }
+ const preserveGuideSnapshot = isPausedPermissionProbePlaceholder(status);
+ void serializePermissionGuideUpdate('explicit permission guide status refresh', async (generation) => {
+ if (preserveGuideSnapshot) {
+ // A status read while the probe is paused contains a synthetic
+ // Accessibility-missing placeholder. Other Settings windows still
+ // need that runtime status, but the coach must keep its authoritative
+ // preflight snapshot and pass through the existing drag ownership gate.
+ sendPermissionGuideStatus(status, guideStatus);
+ await refreshElectronPermissionGuideStateSerialized({}, generation);
+ return;
+ }
+ nativeHost?.update(nativeStateFrom(status, readPermissionDragState(), lastSwitchLocation));
+ broadcastPermissionGuideStatus(status);
+ });
+ return;
+ }
+ void refreshElectronPermissionGuideState();
+}
+
+function closeElectronPermissionGuideWindow(): void {
+ clearNativeAttachTimeout();
+ const currentGuide = guideWindow;
+ const currentBackdrop = backdropWindow;
+ guideWindow = null;
+ backdropWindow = null;
+ guideOwner = null;
+ // Attaching the native AppKit coach closes only the hidden Electron
+ // fallback. Keep the preflight snapshot alive for its observer; clearing it
+ // here would make the native flow fall back to Accessibility after attach.
+ if (!nativeHost) guideStatus = null;
+ // The native AppKit coach still relies on this read-only AX observer to
+ // notice each System Settings toggle. Stop it only when the whole guide is
+ // being closed, not when native takes over from the Electron fallback.
+ if (!nativeHost) {
+ stopSwitchObserver();
+ resetPermissionProbeBypassThrottle();
+ }
+ restoreGuideAfterDrag();
+ closeWindow(currentGuide);
+ closeWindow(currentBackdrop);
+ scheduleMainAppPresenceRestore('computer-permission-guide-closed');
+}
+
+/** Close both the native AppKit coach and the Electron fallback. */
+export function closeComputerPermissionGuideWindow(): void {
+ resetGuideLifecycleUpdates();
+ clearNativeAttachTimeout();
+ nativeGuideAttached = false;
+ lastOpenedPermissionPaneUrl = null;
+ resumeComputerDriverPermissionProbe();
+ nativeHost?.dismiss();
+ nativeHost = null;
+ lastSwitchLocation = null;
+ void closeComputerUseSwitchLocator();
+ closeElectronPermissionGuideWindow();
+}
+
+/** Return true only for IPC emitted by the independent guide renderer. */
+export function isComputerPermissionGuideWebContents(sender: WebContents): boolean {
+ return Boolean(
+ guideWindow
+ && !guideWindow.isDestroyed()
+ && guideWindow.webContents.id === sender.id,
+ );
+}
+
+/** Return the preflight snapshot only to the renderer owned by this guide. */
+export function getComputerPermissionGuideStatus(
+ sender: WebContents,
+): ComputerStatus | null {
+ if (!isComputerPermissionGuideWebContents(sender)) return null;
+ return guideStatus;
+}
+
+function isValidComputerPermissionDragIconDataUrl(value: unknown): value is string {
+ if (typeof value !== 'string' || !value.startsWith(DRAG_ICON_DATA_URL_PREFIX)) {
+ return false;
+ }
+ const encoded = value.slice(DRAG_ICON_DATA_URL_PREFIX.length);
+ return (
+ encoded.length > 0
+ && encoded.length <= MAX_DRAG_ICON_BASE64_LENGTH
+ && encoded.length % 4 === 0
+ && encoded.startsWith(PNG_SIGNATURE_BASE64_PREFIX)
+ && /^[A-Za-z0-9+/]+={0,2}$/.test(encoded)
+ );
+}
+
+/** Start a native file drag for the real Computer Use.app bundle. */
+export function startComputerPermissionAppDrag(
+ sender: WebContents,
+ iconDataUrl: unknown,
+): void {
+ if (!isComputerPermissionGuideWebContents(sender)) return;
+ const appBundlePath = getComputerDriverAppBundlePath();
+ const hasValidIcon = isValidComputerPermissionDragIconDataUrl(iconDataUrl);
+ if (!appBundlePath || !hasValidIcon) {
+ log.warn('Computer Use app drag is unavailable', {
+ hasAppBundle: Boolean(appBundlePath),
+ hasValidIcon,
+ });
+ return;
+ }
+ let icon: Electron.NativeImage;
+ try {
+ icon = nativeImage.createFromDataURL(iconDataUrl);
+ } catch (error) {
+ log.warn('Computer Use app drag icon could not be decoded', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return;
+ }
+ if (icon.isEmpty()) {
+ log.warn('Computer Use app drag icon is empty');
+ return;
+ }
+
+ dragInProgress = true;
+ draggedPermission = missingPermission(guideStatus) ?? 'accessibility';
+ guideWindow?.setIgnoreMouseEvents(true, { forward: true });
+ armDragRestore();
+ try {
+ sender.startDrag({ file: appBundlePath, icon });
+ } catch (error) {
+ log.warn('Computer Use Electron app drag failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ restoreGuideAfterDrag();
+ }
+}
+
+/** Finish the current drag and only inspect the row after a confirmed copy drop. */
+export function finishComputerPermissionAppDrag(
+ sender: WebContents,
+ didCopy: unknown,
+): Promise<boolean> {
+ if (!isComputerPermissionGuideWebContents(sender) || !dragInProgress) {
+ return Promise.resolve(false);
+ }
+ const permission = draggedPermission;
+ restoreGuideAfterDrag();
+ if (didCopy !== true) return Promise.resolve(false);
+ return completeElectronPermissionAppDrag(permission);
+}
+
+/** Show (or bring back) the independent Electron permission coach. */
+export async function showComputerPermissionGuideWindow(
+ owner: BrowserWindow | null,
+ initialStatus?: ComputerStatus,
+): Promise<void> {
+ if (process.platform !== 'darwin') return;
+ const existingGuide = hasPermissionGuide();
+ if (!existingGuide) beginGuideLifecycle();
+ const generation = guideLifecycleGeneration;
+ guideOwner = owner && !owner.isDestroyed() ? owner : null;
+ if (!existingGuide && initialStatus) guideStatus = initialStatus;
+ if (nativeHost || (guideWindow && !guideWindow.isDestroyed())) {
+ await refreshElectronPermissionGuideState({
+ bypassPermissionProbeCache: true,
+ ...(initialStatus ? { knownStatus: initialStatus } : {}),
+ });
+ if (isGuideLifecycleActive(generation)) startSwitchObserver();
+ return;
+ }
+ const display = currentDisplay();
+ const guideBounds = guideBoundsForWorkArea(display.workArea);
+ let fallbackRequested = false;
+ let backdropLoaded = false;
+ let guideLoaded = false;
+ const showElectronFallback = (): void => {
+ if (!fallbackRequested || !backdropLoaded || !guideLoaded) return;
+ if (
+ generation !== guideLifecycleGeneration
+ || backdropWindow !== backdrop
+ || guideWindow !== guide
+ ) {
+ return;
+ }
+ if (!backdrop.isDestroyed()) {
+ backdrop.setAlwaysOnTop(true, 'floating');
+ backdrop.setVisibleOnAllWorkspaces(true, {
+ visibleOnFullScreen: true,
+ skipTransformProcessType: true,
+ });
+ backdrop.showInactive();
+ }
+ if (!guide.isDestroyed()) {
+ guide.setAlwaysOnTop(true, 'floating', 1);
+ guide.setVisibleOnAllWorkspaces(true, {
+ visibleOnFullScreen: true,
+ skipTransformProcessType: true,
+ });
+ guide.showInactive();
+ startSwitchObserver();
+ scheduleMainAppPresenceRestore('computer-permission-guide-shown');
+ }
+ };
+
+ const backdrop = new BrowserWindow({
+ ...display.workArea,
+ frame: false,
+ transparent: true,
+ resizable: false,
+ movable: false,
+ minimizable: false,
+ maximizable: false,
+ fullscreenable: false,
+ focusable: false,
+ show: false,
+ skipTaskbar: false,
+ hiddenInMissionControl: true,
+ alwaysOnTop: true,
+ hasShadow: false,
+ backgroundColor: '#00000000',
+ webPreferences: {
+ preload: path.join(__dirname, 'preload.js'),
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ experimentalFeatures: false,
+ plugins: false,
+ navigateOnDragDrop: false,
+ backgroundThrottling: false,
+ spellcheck: false,
+ },
+ });
+ backdropWindow = backdrop;
+ backdrop.setIgnoreMouseEvents(true, { forward: true });
+ preventPermissionGuideNavigation(backdrop.webContents);
+ backdrop.webContents.once('did-finish-load', () => {
+ if (
+ generation !== guideLifecycleGeneration
+ || backdropWindow !== backdrop
+ || backdrop.isDestroyed()
+ ) {
+ return;
+ }
+ backdropLoaded = true;
+ showElectronFallback();
+ });
+ backdrop.once('closed', () => {
+ if (
+ generation === guideLifecycleGeneration
+ && backdropWindow === backdrop
+ ) {
+ backdropWindow = null;
+ }
+ });
+ void loadPermissionView(backdrop, 'computer-permission-backdrop').catch((error) => {
+ log.warn('computer permission guide backdrop failed to load', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ if (
+ !isGuideLifecycleActive(generation)
+ || backdropWindow !== backdrop
+ ) {
+ return;
+ }
+ closeComputerPermissionGuideWindow();
+ broadcastPermissionGuideCancelled();
+ });
+
+ const guide = new BrowserWindow({
+ ...guideBounds,
+ frame: false,
+ transparent: true,
+ resizable: false,
+ movable: true,
+ minimizable: false,
+ maximizable: false,
+ fullscreenable: false,
+ focusable: true,
+ acceptFirstMouse: true,
+ show: false,
+ skipTaskbar: false,
+ hiddenInMissionControl: true,
+ alwaysOnTop: true,
+ hasShadow: false,
+ backgroundColor: '#00000000',
+ webPreferences: {
+ preload: path.join(__dirname, 'preload.js'),
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ experimentalFeatures: false,
+ plugins: false,
+ navigateOnDragDrop: false,
+ backgroundThrottling: false,
+ spellcheck: false,
+ },
+ });
+ guideWindow = guide;
+ preventPermissionGuideNavigation(guide.webContents);
+ guide.webContents.once('did-finish-load', () => {
+ if (
+ !isGuideLifecycleActive(generation)
+ || guideWindow !== guide
+ || guide.isDestroyed()
+ ) {
+ return;
+ }
+ guideLoaded = true;
+ showElectronFallback();
+ });
+ guide.once('closed', () => {
+ if (
+ generation !== guideLifecycleGeneration
+ || guideWindow !== guide
+ ) {
+ return;
+ }
+ if (!nativeHost) {
+ const completed = missingPermission(guideStatus) === null;
+ if (!completed) cancelComputerDriverPermissionGrant();
+ closeComputerPermissionGuideWindow();
+ if (!completed) broadcastPermissionGuideCancelled();
+ return;
+ }
+ guideWindow = null;
+ restoreGuideAfterDrag();
+ if (backdropWindow === backdrop) {
+ backdropWindow = null;
+ closeWindow(backdrop);
+ }
+ scheduleMainAppPresenceRestore('computer-permission-guide-closed');
+ });
+ guide.webContents.on('render-process-gone', (_event, details) => {
+ log.warn('computer permission guide renderer exited', { reason: details.reason });
+ if (
+ !isGuideLifecycleActive(generation)
+ || guideWindow !== guide
+ ) {
+ return;
+ }
+ closeComputerPermissionGuideWindow();
+ broadcastPermissionGuideCancelled();
+ });
+ void loadPermissionView(guide, 'computer-permission-guide').catch((error) => {
+ log.warn('computer permission guide renderer failed to load', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ if (
+ !isGuideLifecycleActive(generation)
+ || guideWindow !== guide
+ ) {
+ return;
+ }
+ closeComputerPermissionGuideWindow();
+ broadcastPermissionGuideCancelled();
+ });
+
+ // Resolve a persisted drag hint against the live System Settings row before
+ // the native panel gets its first frame. Otherwise a removed CuaDriver can
+ // briefly render the switch coach and then fall back to the drag coach.
+ await refreshElectronPermissionGuideState({
+ bypassPermissionProbeCache: true,
+ ...(initialStatus ? { knownStatus: initialStatus } : {}),
+ });
+ if (!isGuideLifecycleActive(generation)) return;
+
+ // Keep the Electron coach loaded but hidden while the native AppKit guide
+ // starts. It is a failure fallback only; showing it eagerly creates a
+ // visible old-dialog -> native-dialog swap whenever helper startup is slow.
+ const appBundlePath = getComputerDriverAppBundlePath();
+ if (appBundlePath) {
+ nativeGuideAttached = false;
+ const ownsNativeHost = (): boolean => (
+ isOwnedNativeHost(generation, pendingNativeHost)
+ );
+ const pendingNativeHost = new MacComputerPermissionGuideNativeHost({
+ onAttached: () => {
+ if (!ownsNativeHost()) return;
+ nativeGuideAttached = true;
+ clearNativeAttachTimeout();
+ closeElectronPermissionGuideWindow();
+ log.info('native Computer Use permission coach attached to System Settings');
+ },
+ onCloseRequested: () => {
+ if (!ownsNativeHost()) return;
+ cancelComputerDriverPermissionGrant();
+ closeComputerPermissionGuideWindow();
+ broadcastPermissionGuideCancelled();
+ },
+ onCompleted: () => {
+ if (!ownsNativeHost()) return;
+ closeComputerPermissionGuideWindow();
+ },
+ onExited: () => {
+ if (!ownsNativeHost()) return;
+ if (!nativeGuideAttached) {
+ clearNativeAttachTimeout();
+ nativeHost = null;
+ fallbackRequested = true;
+ showElectronFallback();
+ log.warn(
+ 'native Computer Use permission coach exited before attaching; '
+ + 'showing Electron fallback',
+ );
+ return;
+ }
+ log.warn('native Computer Use permission coach exited unexpectedly');
+ closeComputerPermissionGuideWindow();
+ broadcastPermissionGuideCancelled();
+ },
+ onAuthSheetDismissed: () => {
+ if (!ownsNativeHost()) return;
+ log.info('auth sheet dismissed; rechecking permissions');
+ cancelPendingObserverTrailingProbe();
+ void serializePermissionGuideUpdate(
+ 'auth sheet dismissed permission recheck',
+ async (gen) => {
+ cancelPendingObserverTrailingProbe();
+ await refreshElectronPermissionGuideStateSerialized({
+ freshPermissionProbe: true,
+ bypassPermissionProbeCache: true,
+ forceBroadcast: true,
+ }, gen);
+ },
+ generation,
+ );
+ },
+ onDragBegan: (permission) => {
+ if (!ownsNativeHost()) return;
+ log.debug('native Computer Use permission drag began', { permission });
+ },
+ onDragEnded: (permission, operation) => {
+ if (!ownsNativeHost()) return;
+ log.debug('native Computer Use permission drag ended', { permission, operation });
+ cancelPendingObserverTrailingProbe();
+ void serializePermissionGuideUpdate(
+ 'native permission guide drag completion refresh',
+ async (generation) => {
+ cancelPendingObserverTrailingProbe();
+ if ((operation & 1) !== 0) {
+ const state = readPermissionDragState();
+ state[permission] = true;
+ writePermissionDragState(state);
+ }
+ // Restart the daemon to pick up newly granted permissions.
+ // macOS may kill it on Screen Recording changes, but the
+ // autostart throttle can block revival; fresh bypasses it.
+ await refreshElectronPermissionGuideStateSerialized({
+ freshPermissionProbe: true,
+ bypassPermissionProbeCache: true,
+ forceBroadcast: true,
+ }, generation);
+ },
+ generation,
+ );
+ },
+ });
+ nativeHost = pendingNativeHost;
+ void pendingNativeHost.show(
+ appBundlePath,
+ nativeStateFrom(guideStatus, readPermissionDragState(), lastSwitchLocation),
+ getResolvedMainLocale(),
+ ).then((started) => {
+ // 关闭可能发生在 helper 启动完成之前;旧实例不能重新挂超时或唤起 fallback。
+ if (!ownsNativeHost()) return;
+ if (started) {
+ armNativeAttachTimeout(generation, pendingNativeHost);
+ // Keep observing the real checkbox for the full two-step native flow.
+ // This is what advances Accessibility -> Screen Recording and closes
+ // the coach after the second toggle.
+ startSwitchObserver();
+ return;
+ }
+ nativeHost = null;
+ fallbackRequested = true;
+ showElectronFallback();
+ log.warn('native Computer Use permission coach unavailable; showing Electron fallback');
+ });
+ } else {
+ fallbackRequested = true;
+ showElectronFallback();
+ }
+}
+
+function nativeStateFrom(
+ status: ComputerStatus | null,
+ dragState: PermissionDragState,
+ location: ComputerUseSwitchLocationResult | null,
+): ComputerPermissionGuideNativeState {
+ const permissionState = status?.permissionState;
+ const target = location?.status === 'found' ? location.target : null;
+ return {
+ accessibilityGranted: permissionState?.accessibility === 'granted',
+ screenRecordingGranted: permissionState?.screenRecording === 'granted'
+ && permissionState.screenRecordingCapturable !== 'missing',
+ draggedAccessibility: dragState.accessibility,
+ draggedScreenRecording: dragState.screenRecording,
+ ...(target ? { switchTargetX: target.x, switchTargetY: target.y } : {}),
+ ...(location?.status === 'found' && location.systemWindowBounds
+ ? {
+ switchWindowWidth: location.systemWindowBounds.width,
+ switchWindowHeight: location.systemWindowBounds.height,
+ }
+ : {}),
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/computerPermissionGuideEligibility.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/computerPermissionGuideEligibility.test.ts
new file mode 100644
index 0000000000..989ab7afe2
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/computerPermissionGuideEligibility.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import { shouldUseComputerPermissionGuide } from '../computerPermissionGuideEligibility.js';
+
+describe('shouldUseComputerPermissionGuide', () => {
+ it('uses the guide when macOS has the CuaDriver app bundle', () => {
+ expect(shouldUseComputerPermissionGuide({
+ platform: 'darwin',
+ showGuide: true,
+ appBundlePath: '/Applications/CuaDriver.app',
+ })).toBe(true);
+ });
+
+ it('keeps CLI-only macOS installs on the legacy grant flow', () => {
+ expect(shouldUseComputerPermissionGuide({
+ platform: 'darwin',
+ showGuide: true,
+ appBundlePath: null,
+ })).toBe(false);
+ });
+
+ it('does not show the macOS guide on other platforms or without an explicit request', () => {
+ expect(shouldUseComputerPermissionGuide({
+ platform: 'win32',
+ showGuide: true,
+ appBundlePath: 'C:\\CuaDriver.app',
+ })).toBe(false);
+ expect(shouldUseComputerPermissionGuide({
+ platform: 'darwin',
+ showGuide: false,
+ appBundlePath: '/Applications/CuaDriver.app',
+ })).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 8c680a6ab9..548efb51e0 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -513,6 +513,10 @@ export const MAKER_INVOKE = {
COMPUTER_GRANT_PERMISSIONS: 'maker:computer:grant-permissions',
// macOS: CuaDriver.app 的真实安装图标(授权引导弹窗里给用户当识别参照)。
COMPUTER_DRIVER_ICON: 'maker:computer:driver-icon',
+ // macOS: 当前授权引导生命周期持有的预检快照(不触发新的权限探测)。
+ COMPUTER_PERMISSION_GUIDE_STATUS: 'maker:computer:permission-guide-status',
+ // macOS:结束原生 app 拖拽,并等待 Main 通过实时 System Settings 行确认结果。
+ COMPUTER_PERMISSION_APP_DRAG_END: 'maker:computer:permission-app-drag-end',
// macOS: 取消在途的 CuaDriver 授权流程(引导弹窗「取消」时收割 grant 子进程)。
COMPUTER_CANCEL_PERMISSION_GRANT: 'maker:computer:cancel-permission-grant',
/**
@@ -573,6 +577,13 @@ export const MAKER_INVOKE = {
* (typically localStorage 镜像) 推给 main, main 只更新内存缓存供后续工具调用读。
*/
export const MAKER_SEND = {
+ /**
+ * macOS permission coach: begin a native drag of the real Computer Use app
+ * bundle into System Settings. Main validates that the sender is the
+ * dedicated guide window before acting. Drag completion is an invoke above
+ * because the renderer must wait for Main's live-row confirmation.
+ */
+ COMPUTER_PERMISSION_APP_DRAG_START: 'maker:computer:permission-app-drag-start',
/**
* 把 renderer `newMakerDraft` 的关键子集 (lastByVendor / fastModeByModel /
* effortByModel) 同步给 main 缓存 (newMakerDefaultsCache)。collab mode spawn
@@ -608,6 +619,10 @@ export const MAKER_SEND = {
export const MAKER_PUSH = {
EVENT: 'maker:event',
STATUS_CHANGED: 'maker:status-changed',
+ /** 用户从独立 Computer Use 授权引导浮窗主动取消。 */
+ COMPUTER_PERMISSION_GUIDE_CANCELLED: 'maker:computer:permission-guide-cancelled',
+ /** Native Computer Use onboarding status changed while System Settings is open. */
+ COMPUTER_PERMISSION_GUIDE_STATUS_CHANGED: 'maker:computer:permission-guide-status-changed',
INPUT_PROJECTION: 'maker:input:projection',
/** New interaction request (permission / ask_user_question / plan_review) */
INTERACTION_REQUEST: 'maker:interaction-request',
diff --git a/apps/desktop/src/main/maker-ipc/computerPermissionGuideEligibility.ts b/apps/desktop/src/main/maker-ipc/computerPermissionGuideEligibility.ts
new file mode 100644
index 0000000000..a14159e68b
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/computerPermissionGuideEligibility.ts
@@ -0,0 +1,16 @@
+/**
+ * Keeps the native permission guide on the path where macOS can drag the
+ * installed CuaDriver app bundle. CLI-only installs must retain the legacy
+ * grant flow because pausing their permission probe would dead-end it.
+ */
+export function shouldUseComputerPermissionGuide(options: {
+ platform: NodeJS.Platform;
+ showGuide: boolean;
+ appBundlePath: string | null;
+}): boolean {
+ return (
+ options.platform === 'darwin'
+ && options.showGuide
+ && options.appBundlePath !== null
+ );
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 0af623fd75..ae78ac195b 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -60,12 +60,28 @@ import { shutdownCodexEnvironment } from '../mcp-integrations/codexEnvironment.j
import {
checkComputerDriverUpdate,
cancelComputerDriverPermissionGrant,
+ getComputerDriverAppBundlePath,
getComputerDriverAppIcon,
getComputerDriverStatus,
grantComputerDriverPermissions,
installComputerDriver,
+ pauseComputerDriverPermissionProbe,
updateComputerDriver,
} from '../mcp-integrations/computer.js';
+import {
+ closeComputerPermissionGuideWindow,
+ finishComputerPermissionAppDrag,
+ getComputerPermissionGuideStatus,
+ openComputerPermissionPaneForStatus,
+ isComputerPermissionGuideWebContents,
+ refreshComputerPermissionGuideWindow,
+ seedOpenedPermissionPane,
+ showComputerPermissionGuideWindow,
+ startComputerPermissionAppDrag,
+} from '../computer-permission-guide/window.js';
+import { parseComputerPermissionGrantRequest } from '../computer-permission-guide/request.js';
+import { shouldUseComputerPermissionGuide } from './computerPermissionGuideEligibility.js';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import * as imageCacheStore from '../imageCacheStore.js';
import { collectCindyMediaUrls, commitChatImageUrls } from '../cindy-media/chatAttachments.js';
import * as cindyChatAttachments from '../cindy-media/chatAttachments.js';
@@ -7038,15 +7054,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
});
// ── Local desktop computer-use (Settings →「电脑使用」) ─────────────────
- // Probe external driver availability. Read-only and side-effect-free.
+ // Probe the installed CuaDriver used by the phase-one Computer Use runtime.
ipcMain.handle(MAKER_INVOKE.COMPUTER_STATUS, async (_event, options?: {
includeDoctor?: boolean;
forcePermissionProbe?: boolean;
+ skipPermissionProbe?: boolean;
freshPermissionProbe?: boolean;
bypassPermissionProbeCache?: boolean;
+ passivePermissionProbeOnly?: boolean;
}) => {
try {
- return await getComputerDriverStatus(options);
+ const status = await getComputerDriverStatus(options);
+ if (
+ options?.forcePermissionProbe === true
+ || options?.freshPermissionProbe === true
+ ) {
+ refreshComputerPermissionGuideWindow(status);
+ }
+ return status;
} catch (err) {
throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
}
@@ -7060,23 +7085,92 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
}
});
- ipcMain.handle(MAKER_INVOKE.COMPUTER_GRANT_PERMISSIONS, async () => {
+ ipcMain.handle(MAKER_INVOKE.COMPUTER_GRANT_PERMISSIONS, async (_event, payload?: unknown) => {
+ assertTrustedAppRendererEvent(_event);
+ const options = parseComputerPermissionGrantRequest(payload);
+ if (!options) {
+ throwIpcError('INVALID_PARAMS', 'Invalid Computer Use permission request');
+ }
+ const shouldShowGuide = shouldUseComputerPermissionGuide({
+ platform: process.platform,
+ showGuide: options.showGuide,
+ appBundlePath: getComputerDriverAppBundlePath(),
+ });
try {
- return await grantComputerDriverPermissions();
+ // Permission snapshots are mutable TCC state and cannot be accepted from
+ // Renderer. Re-establish the state in Main immediately before guide side
+ // effects, bypassing both daemon and probe caches.
+ const initialStatus = shouldShowGuide
+ ? await getComputerDriverStatus({
+ forcePermissionProbe: true,
+ freshPermissionProbe: true,
+ bypassPermissionProbeCache: true,
+ })
+ : undefined;
+ if (shouldShowGuide) {
+ if (!initialStatus) throw new Error('Computer Use permission guide status unavailable');
+ if (options.openedPaneUrl) {
+ seedOpenedPermissionPane(options.openedPaneUrl);
+ }
+ await openComputerPermissionPaneForStatus(initialStatus);
+ // Phase one keeps CuaDriver as the real permission/runtime identity.
+ // The new guide wraps its existing grant flow without introducing a
+ // second Computer Use.app entry in macOS privacy settings.
+ await pauseComputerDriverPermissionProbe();
+ await showComputerPermissionGuideWindow(
+ BrowserWindow.fromWebContents(_event.sender),
+ initialStatus,
+ );
+ }
+ return await grantComputerDriverPermissions(
+ initialStatus,
+ );
} catch (err) {
+ if (shouldShowGuide) closeComputerPermissionGuideWindow();
throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
}
});
- // 查询型:授权引导弹窗的 CuaDriver 图标。取不到(未装 app bundle / 非 macOS /
- // 读图失败)返回 null,renderer 降级用通用图标继续渲染,不抛错。
+ // 查询型:授权引导弹窗的 CuaDriver 图标。取不到时 renderer 降级用通用图标。
ipcMain.handle(MAKER_INVOKE.COMPUTER_DRIVER_ICON, async () => {
return { iconDataUrl: await getComputerDriverAppIcon() };
});
+ ipcMain.handle(MAKER_INVOKE.COMPUTER_PERMISSION_GUIDE_STATUS, async (_event) => {
+ const status = getComputerPermissionGuideStatus(_event.sender);
+ if (!status) {
+ throwIpcError('PRECONDITION_FAILED', 'Computer Use permission guide is not active');
+ }
+ return status;
+ });
+
+ ipcMain.on(MAKER_SEND.COMPUTER_PERMISSION_APP_DRAG_START, (_event, payload?: {
+ iconDataUrl?: unknown;
+ }) => {
+ startComputerPermissionAppDrag(_event.sender, payload?.iconDataUrl);
+ });
+
+ ipcMain.handle(MAKER_INVOKE.COMPUTER_PERMISSION_APP_DRAG_END, async (_event, payload?: {
+ didCopy?: unknown;
+ }) => {
+ return finishComputerPermissionAppDrag(_event.sender, payload?.didCopy);
+ });
+
// 命令型:取消在途授权流程。幂等,无在途 grant 时 no-op。
- ipcMain.handle(MAKER_INVOKE.COMPUTER_CANCEL_PERMISSION_GRANT, async () => {
+ ipcMain.handle(MAKER_INVOKE.COMPUTER_CANCEL_PERMISSION_GRANT, async (_event) => {
+ const cancelledFromGuide = isComputerPermissionGuideWebContents(_event.sender);
+ if (!cancelledFromGuide) {
+ assertTrustedAppRendererEvent(_event);
+ }
cancelComputerDriverPermissionGrant();
+ closeComputerPermissionGuideWindow();
+ if (cancelledFromGuide) {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) {
+ win.webContents.send(MAKER_PUSH.COMPUTER_PERMISSION_GUIDE_CANCELLED);
+ }
+ }
+ }
return { cancelled: true };
});
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
index bfa5a6ebc3..44bb392241 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
@@ -88,6 +88,7 @@ import {
getComputerDriverStatus,
grantComputerDriverPermissions,
installComputerDriver,
+ pauseComputerDriverPermissionProbe,
pickLatestCuaDriverVersion,
resetComputerDriverPermissionProbeCacheForTests,
resetComputerDriverUpdateStateForTests,
@@ -351,6 +352,31 @@ describe('computer mcp integration', () => {
expect(spawnMock.mock.calls.some((call) => call[1]?.[0] === 'doctor')).toBe(false);
});
+ it('does not probe or autostart the permission daemon while waiting for the real app drag', async () => {
+ setPlatform('darwin');
+ await pauseComputerDriverPermissionProbe();
+ mockDriverSpawn({ stdout: 'cua-driver 0.7.1\n' });
+ mockDriverSpawn({ stdout: 'Cua Driver daemon is running\n pid: 4242\n' });
+
+ await expect(getComputerDriverStatus({
+ forcePermissionProbe: true,
+ freshPermissionProbe: true,
+ bypassPermissionProbeCache: true,
+ })).resolves.toMatchObject({
+ installed: true,
+ daemonRunning: true,
+ permissionState: {
+ platform: 'macos',
+ status: 'missing',
+ accessibility: 'missing',
+ reason: 'Waiting for CuaDriver to be added in System Settings.',
+ },
+ });
+
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ expect(driverStdinWrites).toEqual([]);
+ });
+
it('runs cua-driver doctor only for explicit deep status checks', async () => {
mockDriverSpawn({ stdout: 'cua-driver 0.1.0\n' });
mockDriverSpawn({ stdout: 'Cua Driver daemon is running\n' });
@@ -2329,14 +2355,83 @@ describe('computer mcp integration', () => {
it('checks current Computer Use opt-in before dispatching MCP tool calls', async () => {
const isComputerUseEnabled = vi.fn(() => false);
- const deps = getComputerMcpDeps({ isComputerUseEnabled });
+ const prepareRuntimeBeforeUse = vi.fn(async () => undefined);
+ const deps = getComputerMcpDeps({ isComputerUseEnabled, prepareRuntimeBeforeUse });
await expect(deps.callTool('list_windows', {}, { agentKind: 'codex' }))
.rejects.toThrow('Computer Use is disabled');
expect(isComputerUseEnabled).toHaveBeenCalledWith({ agentKind: 'codex' });
+ expect(prepareRuntimeBeforeUse).not.toHaveBeenCalled();
expect(spawnMock).not.toHaveBeenCalled();
});
+ it('closes active MCP sessions and blocks tool dispatch while permission onboarding is paused', async () => {
+ setPlatform('darwin');
+ mcpCallToolMock
+ .mockResolvedValueOnce({
+ content: [{ type: 'text', text: '{"ok":true,"windows":[]}' }],
+ })
+ .mockResolvedValueOnce({
+ content: [{ type: 'text', text: '{"ok":true}' }],
+ });
+
+ await callComputerDriverTool(
+ 'list_windows',
+ {},
+ { sessionId: 'session-permission-guide-pause' },
+ );
+ await pauseComputerDriverPermissionProbe();
+
+ expect(mcpCloseMock).toHaveBeenCalledOnce();
+ await expect(callComputerDriverTool(
+ 'list_windows',
+ {},
+ { sessionId: 'session-permission-guide-pause' },
+ )).rejects.toThrow('permission onboarding is active');
+ expect(mcpConnectMock).toHaveBeenCalledOnce();
+ });
+
+ it('prepares the runtime before dispatching the first enabled tool call', async () => {
+ const prepareRuntimeBeforeUse = vi.fn(async () => undefined);
+ mcpCallToolMock.mockResolvedValueOnce({
+ content: [{ type: 'text', text: '{"ok":true,"windows":[]}' }],
+ });
+ const deps = getComputerMcpDeps({
+ isComputerUseEnabled: () => true,
+ prepareRuntimeBeforeUse,
+ });
+
+ await expect(deps.callTool(
+ 'list_windows',
+ {},
+ { sessionId: 'session-runtime-gate' },
+ )).resolves.toEqual({ ok: true, windows: [] });
+ expect(prepareRuntimeBeforeUse).toHaveBeenCalledTimes(1);
+ expect(prepareRuntimeBeforeUse.mock.invocationCallOrder[0]).toBeLessThan(
+ mcpCallToolMock.mock.invocationCallOrder[0]!,
+ );
+ });
+
+ it('prepares the runtime only once for subsequent tool calls', async () => {
+ const prepareRuntimeBeforeUse = vi.fn(async () => undefined);
+ mcpCallToolMock
+ .mockResolvedValueOnce({
+ content: [{ type: 'text', text: '{"ok":true,"windows":[]}' }],
+ })
+ .mockResolvedValueOnce({
+ content: [{ type: 'text', text: '{"ok":true,"windows":[]}' }],
+ });
+ const deps = getComputerMcpDeps({
+ isComputerUseEnabled: () => true,
+ prepareRuntimeBeforeUse,
+ });
+
+ await deps.callTool('list_windows', {}, { sessionId: 'session-runtime-gate-once' });
+ await deps.callTool('list_windows', {}, { sessionId: 'session-runtime-gate-once' });
+
+ expect(prepareRuntimeBeforeUse).toHaveBeenCalledTimes(1);
+ });
+
it('runs the official installer and returns refreshed status', async () => {
mockDriverSpawn({ stdout: 'installed\n' });
mockDriverSpawn({ stdout: 'cua-driver 0.5.8\n' });
@@ -2378,6 +2473,73 @@ describe('computer mcp integration', () => {
expect(spawnMock.mock.calls.some((call) => call[1]?.[0] === 'permissions')).toBe(false);
});
+ it('can inspect a running macOS daemon without triggering the permission probe', async () => {
+ if (process.platform !== 'darwin') return;
+
+ mockDriverSpawn({ stdout: 'cua-driver 0.5.8\n' });
+ mockDriverSpawn({ stdout: 'Cua Driver daemon is running\n' });
+
+ await expect(getComputerDriverStatus({ skipPermissionProbe: true })).resolves.toMatchObject({
+ installed: true,
+ daemonRunning: true,
+ permissionState: {
+ platform: 'macos',
+ status: 'unknown',
+ },
+ });
+ expect(spawnMock.mock.calls.some((call) => call[1]?.[0] === 'permissions')).toBe(false);
+ });
+
+ it('keeps page-entry status checks passive on CuaDriver versions before 0.12.2', async () => {
+ if (process.platform !== 'darwin') return;
+
+ mockDriverSpawn({ stdout: 'cua-driver 0.12.1\n' });
+ mockDriverSpawn({ stdout: 'Cua Driver daemon is running\n pid: 4242\n' });
+
+ await expect(getComputerDriverStatus({
+ forcePermissionProbe: true,
+ bypassPermissionProbeCache: true,
+ passivePermissionProbeOnly: true,
+ })).resolves.toMatchObject({
+ installed: true,
+ daemonRunning: true,
+ permissionState: {
+ platform: 'macos',
+ status: 'unknown',
+ },
+ });
+ expect(spawnMock.mock.calls.some((call) => call[1]?.[0] === 'permissions')).toBe(false);
+ });
+
+ it('refreshes page-entry permissions through the read-only 0.12.2 status command', async () => {
+ if (process.platform !== 'darwin') return;
+
+ mockDriverSpawn({ stdout: 'cua-driver 0.12.2\n' });
+ mockDriverSpawn({ stdout: 'Cua Driver daemon is running\n pid: 4242\n' });
+ mockDriverSpawn({
+ stdout:
+ '{"accessibility":true,"screen_recording":true,"screen_recording_capturable":true,"source":{"attribution":"driver-daemon"}}\n',
+ });
+
+ await expect(getComputerDriverStatus({
+ forcePermissionProbe: true,
+ bypassPermissionProbeCache: true,
+ passivePermissionProbeOnly: true,
+ })).resolves.toMatchObject({
+ installed: true,
+ permissionState: {
+ accessibility: 'granted',
+ screenRecording: 'granted',
+ status: 'granted',
+ },
+ });
+ expect(spawnMock).toHaveBeenCalledWith(
+ 'cua-driver',
+ ['permissions', 'status', '--json'],
+ expect.objectContaining({ windowsHide: true }),
+ );
+ });
+
it('can force a macOS permission probe even when the daemon status is stopped', async () => {
if (process.platform !== 'darwin') return;
@@ -2818,6 +2980,62 @@ describe('computer mcp integration', () => {
});
});
+ it('leaves row creation to the phase-one guide while its drag step is active', async () => {
+ setPlatform('darwin');
+ await pauseComputerDriverPermissionProbe();
+ mockDriverSpawn({ stdout: 'cua-driver 0.12.2\n' });
+ mockDriverSpawn({ stdout: 'Cua Driver daemon is not running\n' });
+
+ await expect(grantComputerDriverPermissions()).resolves.toMatchObject({
+ ok: false,
+ status: {
+ permissionState: {
+ status: 'missing',
+ accessibility: 'missing',
+ reason: 'Waiting for CuaDriver to be added in System Settings.',
+ },
+ },
+ });
+ expect(
+ spawnMock.mock.calls.some(
+ (call) => call[1]?.[0] === 'permissions' && call[1]?.[1] === 'grant',
+ ),
+ ).toBe(false);
+ });
+
+ it('preserves the preflight permission snapshot while the phase-one guide is active', async () => {
+ setPlatform('darwin');
+ await pauseComputerDriverPermissionProbe();
+ const preflightStatus: ComputerDriverStatus = {
+ installed: true,
+ executablePath: '/Applications/CuaDriver.app/Contents/MacOS/cua-driver',
+ version: '0.12.2',
+ daemonRunning: true,
+ installCommand: 'test',
+ docsUrl: 'https://cua.ai/docs/cua-driver',
+ permissionState: {
+ platform: 'macos',
+ required: true,
+ status: 'missing',
+ accessibility: 'granted',
+ screenRecording: 'missing',
+ screenRecordingCapturable: 'missing',
+ canGrant: true,
+ },
+ };
+
+ await expect(grantComputerDriverPermissions(preflightStatus)).resolves.toMatchObject({
+ ok: false,
+ status: {
+ permissionState: {
+ accessibility: 'granted',
+ screenRecording: 'missing',
+ },
+ },
+ });
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
it('kills the in-flight grant child when the user cancels the permission guide', async () => {
if (process.platform !== 'darwin') return;
diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.ts
index c9424b93ad..92b5feaac7 100644
--- a/apps/desktop/src/main/mcp-integrations/computer.ts
+++ b/apps/desktop/src/main/mcp-integrations/computer.ts
@@ -72,6 +72,9 @@ const UPDATE_CHECK_TIMEOUT_MS = 10_000;
const LOG_OUTPUT_PREVIEW_CHARS = 2_000;
const TYPE_TEXT_CHUNK_CHARS = 400;
const CUA_DRIVER_SESSION_PROCESS_NONCE = randomUUID().replace(/-/g, '').slice(0, 12);
+// 0.12.2 changed `permissions status` into a strictly read-only daemon query.
+// Older builds may touch ScreenCaptureKit while checking capturability.
+const PASSIVE_PERMISSION_STATUS_MIN_VERSION = '0.12.2';
const SCREENSHOT_OUTPUT_TOOL_NAMES = new Set<ComputerMcpToolName>(['get_window_state']);
const DRIVER_SESSION_ARG_TOOL_NAMES = new Set<ComputerMcpToolName>([
'list_windows',
@@ -132,9 +135,22 @@ const PROCESS_SNAPSHOT_CACHE_MS = 2_000;
const LIST_WINDOWS_LOCAL_ARG_NAMES = new Set(['query', 'workspace_root', 'process_name']);
const WIN32_FALLBACK_SOURCE = 'xdmaker_win32_fallback';
const WINDOWS_WIN32_FALLBACK_TOOL_NAMES = new Set<ComputerMcpToolName>(['list_windows', 'list_apps']);
-// CuaDriver 的 macOS app bundle 安装位置(LaunchServices 拉起 daemon / 取图标共用)。
+// Phase one uses the upstream CuaDriver app as the real runtime and TCC
+// identity.
const CUA_DRIVER_APP_BUNDLE_PATH = '/Applications/CuaDriver.app';
+let computerDriverPermissionProbePaused = false;
+
+/**
+ * macOS permission panes accept application bundles as native file drags.
+ * Keep the technical bundle path in main; renderer only sees "Computer Use".
+ */
+export function getComputerDriverAppBundlePath(): string | null {
+ if (process.platform !== 'darwin') return null;
+ if (!existsSync(CUA_DRIVER_APP_BUNDLE_PATH)) return null;
+ return CUA_DRIVER_APP_BUNDLE_PATH;
+}
+
const WINDOWS_WIN32_WINDOW_SNAPSHOT_SCRIPT = String.raw`
$ErrorActionPreference = 'Stop'
Add-Type -TypeDefinition @'
@@ -326,11 +342,15 @@ export interface ComputerDriverPermissionGrantResult {
export interface ComputerMcpDepsOptions {
isComputerUseEnabled?: (context?: ComputerMcpCallContext) => boolean;
+ /** Optional provider gate before the first status/tool request. */
+ prepareRuntimeBeforeUse?: () => Promise<void>;
}
interface ComputerDriverStatusOptions {
includeDoctor?: boolean;
forcePermissionProbe?: boolean;
+ /** Passive surfaces must not trigger ScreenCaptureKit authorization prompts. */
+ skipPermissionProbe?: boolean;
/**
* 显式用户动作(重新检查 / 开启开关)专用:先重启 daemon 再实测。
* 背景:辅助功能(AX)被用户在系统设置里撤销后,**正在运行的 daemon 感知不到**
@@ -348,6 +368,8 @@ interface ComputerDriverStatusOptions {
* 弹授权对话框,实测可能再触发的弹窗与引导语义一致。
*/
bypassPermissionProbeCache?: boolean;
+ /** Never fall back to a status implementation that may open a macOS TCC prompt. */
+ passivePermissionProbeOnly?: boolean;
}
class ComputerDriverError extends Error {
@@ -392,6 +414,7 @@ export function resetComputerDriverPermissionProbeCacheForTests(): void {
cachedPermissionProbe = null;
lastDaemonAutostartAt = 0;
daemonAutostartInFlight = null;
+ computerDriverPermissionProbePaused = false;
}
// ── macOS daemon 自愈启动 ────────────────────────────────────────────────
@@ -531,12 +554,59 @@ function resolveDriverCommand(): string {
return DRIVER_COMMAND;
}
+function resolveDriverInvocation(args: readonly string[]): {
+ command: string;
+ args: string[];
+ env?: Record<string, string>;
+} {
+ return { command: resolveDriverCommand(), args: [...args] };
+}
+
+/** Whether permission onboarding is deliberately waiting for a real app drag. */
+export function isComputerDriverPermissionProbePaused(): boolean {
+ return computerDriverPermissionProbePaused;
+}
+
+function assertComputerDriverToolDispatchAvailable(): void {
+ if (computerDriverPermissionProbePaused) {
+ throw new ComputerDriverError(
+ 'Computer Use tool calls are paused while permission onboarding is active.',
+ );
+ }
+}
+
+/**
+ * Pause permission probes while the app is absent from the current macOS
+ * permission pane. Close active agent MCP sessions and reject new tool calls
+ * so they cannot re-register a deleted app row while the guide waits for a
+ * fresh drag.
+ */
+export async function pauseComputerDriverPermissionProbe(): Promise<void> {
+ computerDriverPermissionProbePaused = true;
+ cachedPermissionProbe = null;
+ lastDaemonAutostartAt = 0;
+ await cleanupActiveComputerDriverSessions();
+}
+
+/** Resume live permission checks after System Settings contains Computer Use. */
+export function resumeComputerDriverPermissionProbe(): void {
+ computerDriverPermissionProbePaused = false;
+ cachedPermissionProbe = null;
+ lastDaemonAutostartAt = 0;
+}
+
function runDriver(args: string[], timeoutMs: number, options: RunDriverOptions = {}): Promise<ExecResult> {
return new Promise((resolve, reject) => {
- const command = resolveDriverCommand();
- const child = spawn(command, args, {
+ const invocation = resolveDriverInvocation(args);
+ const child = spawn(invocation.command, invocation.args, {
stdio: [options.stdin === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
windowsHide: true,
+ env: invocation.env
+ ? {
+ ...process.env,
+ ...invocation.env,
+ }
+ : undefined,
});
options.onChild?.(child);
let stdout = '';
@@ -1913,10 +1983,14 @@ function logCuaMcpStderr(sessionId: string, stream: Stream): void {
}
function createCuaMcpSession(sessionId: string): CuaMcpSessionEntry {
+ const invocation = resolveDriverInvocation(['mcp']);
const transport = new StdioClientTransport({
- command: resolveDriverCommand(),
- args: ['mcp'],
- env: inheritedProcessEnv(),
+ command: invocation.command,
+ args: invocation.args,
+ env: {
+ ...inheritedProcessEnv(),
+ ...(invocation.env ?? {}),
+ },
stderr: 'pipe',
});
const stderr = transport.stderr;
@@ -1953,6 +2027,7 @@ function createCuaMcpSession(sessionId: string): CuaMcpSessionEntry {
}
async function getCuaMcpSession(sessionId: string): Promise<CuaMcpSessionEntry> {
+ assertComputerDriverToolDispatchAvailable();
const existing = cuaMcpSessions.get(sessionId);
if (existing) {
await existing.ready;
@@ -2175,7 +2250,8 @@ function normalizePermissionState(raw: unknown): ComputerDriverPermissionState {
};
}
- const source = objectValue(obj.source)?.attribution;
+ const sourceObject = objectValue(obj.source);
+ const source = sourceObject?.attribution;
const sourceAttribution = typeof source === 'string' ? source : undefined;
const accessibility = readBooleanGrant(obj.accessibility);
const screenRecording = readBooleanGrant(obj.screen_recording);
@@ -2219,6 +2295,13 @@ export async function getComputerDriverStatus(
): Promise<ComputerDriverStatus> {
try {
const version = await readDriverVersion();
+ const installedVersion = extractDriverSemver(version);
+ const passivePermissionProbeSupported =
+ options.passivePermissionProbeOnly !== true
+ || (
+ installedVersion !== null
+ && compareSemver(installedVersion, PASSIVE_PERMISSION_STATUS_MIN_VERSION) >= 0
+ );
let daemon: DaemonStatus = await readDaemonStatus().catch((err) => ({
running: false,
message: err instanceof Error ? err.message : String(err),
@@ -2234,13 +2317,15 @@ export async function getComputerDriverStatus(
// - stop 失败(daemon 仍在)→ 同上,静默回落不重启的现场实测。
if (
process.platform === 'darwin' &&
+ !computerDriverPermissionProbePaused &&
options.freshPermissionProbe === true &&
+ passivePermissionProbeSupported &&
daemon.running &&
cuaMcpSessions.size === 0 &&
// CLI-only 安装(无 app bundle)时自愈的 `open` 必然失败:停了就拉不回来,
// 宁可保留运行中的 daemon(此时读不到 AX 撤销)也不能让「重新检查」这种
// 看似只读的动作变成破坏性操作(review P2)。
- existsSync(CUA_DRIVER_APP_BUNDLE_PATH)
+ Boolean(getComputerDriverAppBundlePath())
) {
await runDriver(['stop'], STATUS_TIMEOUT_MS).catch((err: unknown) => {
logger.warn('failed to stop cua-driver daemon for fresh permission probe', {
@@ -2258,7 +2343,9 @@ export async function getComputerDriverStatus(
// fresh 探测刚主动停掉 daemon,豁免节流立即拉起)。
if (
process.platform === 'darwin' &&
+ !computerDriverPermissionProbePaused &&
!daemon.running &&
+ passivePermissionProbeSupported &&
(options.forcePermissionProbe === true || options.freshPermissionProbe === true)
) {
const revived = await tryAutostartCuaDaemon({
@@ -2278,6 +2365,9 @@ export async function getComputerDriverStatus(
const grantFlowAtProbeStart = permissionGrantInFlight;
const shouldProbePermissions =
process.platform === 'darwin' &&
+ !computerDriverPermissionProbePaused &&
+ options.skipPermissionProbe !== true &&
+ passivePermissionProbeSupported &&
(daemon.running || options.forcePermissionProbe === true || options.freshPermissionProbe === true);
let permissions: unknown = null;
let permissionProbe: 'run' | 'cached' | 'skipped' = 'skipped';
@@ -2317,7 +2407,18 @@ export async function getComputerDriverStatus(
}
}
} else {
- permissionState = normalizePermissionState(null);
+ permissionState = computerDriverPermissionProbePaused && process.platform === 'darwin'
+ ? {
+ platform: 'macos',
+ required: true,
+ status: 'missing',
+ accessibility: 'missing',
+ screenRecording: 'unknown',
+ screenRecordingCapturable: 'unknown',
+ reason: 'Waiting for CuaDriver to be added in System Settings.',
+ canGrant: true,
+ }
+ : normalizePermissionState(null);
}
// 权限已确认到位时,收割仍在傻等系统弹窗的 grant 子进程(用户可能是在系统
// 设置里手动授的权,上游 `permissions grant` 不会自己退出)。
@@ -3011,7 +3112,9 @@ export function cancelComputerDriverPermissionGrant(): void {
stopPermissionGrantFlow('user cancelled permission guide');
}
-export async function grantComputerDriverPermissions(): Promise<ComputerDriverPermissionGrantResult> {
+export async function grantComputerDriverPermissions(
+ knownStatus?: ComputerDriverStatus,
+): Promise<ComputerDriverPermissionGrantResult> {
if (process.platform !== 'darwin') {
const status = await getComputerDriverStatus();
return {
@@ -3022,6 +3125,22 @@ export async function grantComputerDriverPermissions(): Promise<ComputerDriverPe
};
}
+ // The phase-one macOS guide owns the drag/enable interaction. While it is
+ // waiting for the real CuaDriver.app row, do not run upstream
+ // `permissions grant`: that command would recreate the row and replace the
+ // designed drag step with its own legacy onboarding.
+ if (computerDriverPermissionProbePaused) {
+ const status = knownStatus
+ ?? await getComputerDriverStatus({ skipPermissionProbe: true });
+ return {
+ ok: false,
+ stdout: '',
+ stderr: '',
+ status,
+ };
+ }
+
+ // Legacy callers without the new guide retain upstream CuaDriver's grant.
const grantFlow = startPermissionGrantFlow();
await Promise.race([
grantFlow.catch(() => null),
@@ -3051,6 +3170,7 @@ export async function callComputerDriverTool(
args: Record<string, unknown>,
context?: ComputerMcpCallContext,
): Promise<unknown> {
+ assertComputerDriverToolDispatchAvailable();
const sessionId = readSessionIdFromContext(context);
if (!sessionId) {
throw new ComputerDriverError(`Computer Use tool calls require an active ${BRAND_NAME} session.`);
@@ -3060,6 +3180,7 @@ export async function callComputerDriverTool(
const driverInputArgs = stripLocalListWindowsArgs(name, rawArgs);
const normalizedArgs = normalizeToolArgsForDriver(name, driverInputArgs);
const entry = await getCuaMcpSession(sessionId);
+ assertComputerDriverToolDispatchAvailable();
const driverArgs = applyDriverSessionArgs(name, normalizedArgs, entry.driverSessionId);
await initializeDefaultCursorStyle(name, driverArgs, entry, entry.driverSessionId);
const timeoutMs = getCuaMcpToolTimeoutMs(name);
@@ -3093,6 +3214,7 @@ export async function callComputerDriverTool(
throw err;
}
const freshEntry = await getCuaMcpSession(sessionId);
+ assertComputerDriverToolDispatchAvailable();
if (getCuaMcpSessionCloseVersion(sessionId) !== sessionCloseVersion) {
await cleanupComputerDriverSessionInternal(sessionId, {
resetGeneration: false,
@@ -3214,23 +3336,37 @@ function cleanupComputerDriverSessionInternal(
return cleanup;
}
-export async function cleanupAllComputerDriverSessions(): Promise<void> {
- stopPermissionGrantFlow('cleanup');
- clearProcessSnapshotCache();
+async function cleanupActiveComputerDriverSessions(): Promise<void> {
const sessionIds = Array.from(cuaMcpSessions.keys());
await Promise.allSettled(sessionIds.map((sessionId) => cleanupComputerDriverSession(sessionId)));
await Promise.allSettled(Array.from(cuaMcpSessionCleanups.values()));
+}
+
+export async function cleanupAllComputerDriverSessions(): Promise<void> {
+ stopPermissionGrantFlow('cleanup');
+ clearProcessSnapshotCache();
+ await cleanupActiveComputerDriverSessions();
cuaDriverSessionGenerations.clear();
cuaMcpSessionCloseVersions.clear();
}
export function getComputerMcpDeps(options: ComputerMcpDepsOptions = {}): ComputerMcpDeps {
+ let runtimePreparation: Promise<void> | null = null;
+ const ensureRuntime = async (): Promise<void> => {
+ if (!options.prepareRuntimeBeforeUse) return;
+ runtimePreparation ??= Promise.resolve().then(options.prepareRuntimeBeforeUse);
+ await runtimePreparation;
+ };
return {
- getStatus: getComputerDriverStatus,
+ getStatus: async () => {
+ await ensureRuntime();
+ return getComputerDriverStatus();
+ },
callTool: async (name, args, context) => {
if (options.isComputerUseEnabled && !options.isComputerUseEnabled(context)) {
throw new ComputerDriverError('Computer Use is disabled in Settings.');
}
+ await ensureRuntime();
return callComputerDriverTool(name, args, context);
},
logger,
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 2015b3afa9..3d7255c578 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -259,6 +259,12 @@ const fanOutGhostPanelWindowStateChanged = createIpcFanOut('maker:ghost-panel-wi
const fanOutBinaryDownloadProgress = createIpcFanOut('binary-download-progress');
// Settings →「电脑使用」cua-driver 更新的下载进度(main 侧采样后广播)
const fanOutComputerDriverUpdateProgress = createIpcFanOut('computer-driver-update-progress');
+const fanOutComputerPermissionGuideCancelled = createIpcFanOut(
+ 'maker:computer:permission-guide-cancelled',
+);
+const fanOutComputerPermissionGuideStatusChanged = createIpcFanOut(
+ 'maker:computer:permission-guide-status-changed',
+);
const fanOutAppUpdateProgress = createIpcFanOut('app-update-progress');
const fanOutAuthStateChange = createIpcFanOut('auth:state-change');
const fanOutAuthSessionExpired = createIpcFanOut('auth:session-expired');
@@ -569,8 +575,10 @@ interface ComputerDriverStatus {
interface ComputerDriverStatusOptions {
includeDoctor?: boolean;
forcePermissionProbe?: boolean;
+ skipPermissionProbe?: boolean;
freshPermissionProbe?: boolean;
bypassPermissionProbeCache?: boolean;
+ passivePermissionProbeOnly?: boolean;
}
type ComputerDriverPermissionPlatform = 'macos' | 'windows' | 'linux' | 'unsupported';
@@ -4555,12 +4563,28 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('maker:computer:status', options),
installDriver: (): Promise<ComputerDriverInstallResult> =>
ipcRenderer.invoke('maker:computer:install-driver'),
- grantPermissions: (): Promise<ComputerDriverPermissionGrantResult> =>
- ipcRenderer.invoke('maker:computer:grant-permissions'),
+ grantPermissions: (options?: {
+ showGuide?: boolean;
+ openedPaneUrl?: string;
+ }): Promise<ComputerDriverPermissionGrantResult> =>
+ ipcRenderer.invoke('maker:computer:grant-permissions', options),
driverIcon: (): Promise<{ iconDataUrl: string | null }> =>
ipcRenderer.invoke('maker:computer:driver-icon'),
+ permissionGuideStatus: (): Promise<ComputerDriverStatus> =>
+ ipcRenderer.invoke('maker:computer:permission-guide-status'),
+ startPermissionAppDrag: (iconDataUrl: string): void =>
+ ipcRenderer.send('maker:computer:permission-app-drag-start', { iconDataUrl }),
+ finishPermissionAppDrag: (didCopy: boolean): Promise<boolean> =>
+ ipcRenderer.invoke('maker:computer:permission-app-drag-end', { didCopy }),
cancelPermissionGrant: (): Promise<{ cancelled: boolean }> =>
ipcRenderer.invoke('maker:computer:cancel-permission-grant'),
+ onPermissionGuideCancelled: (callback: () => void): (() => void) =>
+ fanOutComputerPermissionGuideCancelled(callback),
+ onPermissionGuideStatusChanged: (
+ callback: (status: ComputerDriverStatus) => void,
+ ): (() => void) => fanOutComputerPermissionGuideStatusChanged(
+ (data: unknown) => callback(data as ComputerDriverStatus),
+ ),
checkUpdate: (): Promise<ComputerDriverUpdateCheck> =>
ipcRenderer.invoke('maker:computer:check-update'),
updateDriver: (opts?: { joinOnly?: boolean }): Promise<ComputerDriverInstallResult> =>
diff --git a/apps/desktop/src/renderer/assets/system-settings/accessibility-icon.png b/apps/desktop/src/renderer/assets/system-settings/accessibility-icon.png
new file mode 100644
index 0000000000..c4bb948a5f
Binary files /dev/null and b/apps/desktop/src/renderer/assets/system-settings/accessibility-icon.png differ
diff --git a/apps/desktop/src/renderer/assets/system-settings/screen-recording-icon.png b/apps/desktop/src/renderer/assets/system-settings/screen-recording-icon.png
new file mode 100644
index 0000000000..e91c667793
Binary files /dev/null and b/apps/desktop/src/renderer/assets/system-settings/screen-recording-icon.png differ
diff --git a/apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx b/apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx
new file mode 100644
index 0000000000..34b4ebb1f8
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx
@@ -0,0 +1,345 @@
+/**
+ * Independent Computer Use permission coach attached to macOS System Settings.
+ *
+ * The visible card mirrors the web prototype, while its draggable app row
+ * starts a native Electron file drag for the actual app bundle that macOS must
+ * authorize. The larger transparent window lets the cursor guide animation
+ * travel beyond the card without being clipped.
+ */
+
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { ArrowRight, Check, MousePointer2, X } from 'lucide-react';
+
+import computerIcon from '../../../../../../appicon/computer.png';
+import { createLogger } from '@/lib/logger';
+
+const log = createLogger('ComputerPermissionGuideWindow');
+// Main restores the mouse-transparent guide after 12s. Prepare the follow-up
+// UI just before that restore when Chromium never emits dragend for startDrag.
+export const PERMISSION_APP_DRAG_UI_FALLBACK_MS = 11_750;
+export const PERMISSION_APP_DRAGGED_STORAGE_KEY = 'xdmaker.computer-permission-app-dragged';
+
+export type ComputerPermissionGuideStep = 'accessibility' | 'screen-recording' | 'complete';
+export type ComputerPermissionGuideInteraction = 'drag' | 'dragging' | 'turn-on';
+
+/** 把真实 macOS 权限快照映射成用户可理解的两步引导。 */
+export function resolveComputerPermissionGuideStep(
+ permissionState: ComputerDriverPermissionState | null | undefined,
+): ComputerPermissionGuideStep {
+ if (permissionState?.accessibility !== 'granted') return 'accessibility';
+ if (
+ permissionState.screenRecording !== 'granted'
+ || permissionState.screenRecordingCapturable !== 'granted'
+ ) {
+ return 'screen-recording';
+ }
+ return 'complete';
+}
+
+/** Keeps the instructional demo, native drag, and follow-up action unambiguous. */
+export function resolveComputerPermissionGuideInteraction(
+ dragging: boolean,
+ awaitingUser: boolean,
+): ComputerPermissionGuideInteraction {
+ if (dragging) return 'dragging';
+ if (awaitingUser) return 'turn-on';
+ return 'drag';
+}
+
+/** Restore the drag hint from this window lifecycle or an explicit query parameter. */
+export function resolveComputerPermissionGuideInitialAwaitingUser(
+ search: string,
+ storedValue?: string | null,
+): boolean {
+ return new URLSearchParams(search).get('dragged') === '1' || storedValue === '1';
+}
+
+function readPermissionAppDraggedState(): boolean {
+ try {
+ return resolveComputerPermissionGuideInitialAwaitingUser(
+ window.location.search,
+ window.sessionStorage.getItem(PERMISSION_APP_DRAGGED_STORAGE_KEY),
+ );
+ } catch {
+ return resolveComputerPermissionGuideInitialAwaitingUser(window.location.search);
+ }
+}
+
+function dragIconDataUrl(image: HTMLImageElement | null): string | null {
+ if (!image?.complete || image.naturalWidth <= 0 || image.naturalHeight <= 0) return null;
+ const canvas = document.createElement('canvas');
+ canvas.width = 96;
+ canvas.height = 96;
+ const context = canvas.getContext('2d');
+ if (!context) return null;
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
+ return canvas.toDataURL('image/png');
+}
+
+/** Mouse-through focus layer; System Settings remains the real drop target. */
+export function ComputerPermissionBackdrop() {
+ return (
+ <div
+ aria-hidden="true"
+ className="h-screen w-screen bg-transparent"
+ />
+ );
+}
+
+/** Floating cursor + Drag pill from the approved web interaction. */
+function DragCoach() {
+ const { t } = useTranslation();
+ return (
+ <span
+ aria-hidden="true"
+ className="computer-permission-drag-guide pointer-events-none absolute -top-3 right-8 z-10 inline-flex items-center gap-2 text-[var(--text-primary)]"
+ >
+ <span className="inline-flex size-10 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)]">
+ <MousePointer2 size={19} strokeWidth={1.8} aria-hidden="true" />
+ </span>
+ <span className="rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-1.5 text-13 font-medium leading-none">
+ {t('settings.computerUse.directControl.permissionGuide.dragHint')}
+ </span>
+ </span>
+ );
+}
+
+/** Real System Settings coach, with a native-draggable Computer Use app row. */
+export function ComputerPermissionGuideWindow() {
+ const { t } = useTranslation();
+ const [permissionState, setPermissionState] = useState<ComputerDriverPermissionState | null>(null);
+ const [driverIconDataUrl, setDriverIconDataUrl] = useState<string | null>(null);
+ const [awaitingUser, setAwaitingUser] = useState(readPermissionAppDraggedState);
+ const [dragging, setDragging] = useState(false);
+ const iconRef = useRef<HTMLImageElement>(null);
+ const dragUiFallbackTimerRef = useRef<number | null>(null);
+ const dragAttemptRef = useRef(0);
+ const previousStepRef = useRef<ComputerPermissionGuideStep>(resolveComputerPermissionGuideStep(null));
+ const step = resolveComputerPermissionGuideStep(permissionState);
+ const interaction = resolveComputerPermissionGuideInteraction(dragging, awaitingUser);
+
+ useEffect(() => {
+ let cancelled = false;
+ const driverIcon = window.electronAPI.maker.computer.driverIcon;
+ if (typeof driverIcon === 'function') {
+ void driverIcon().then(({ iconDataUrl }) => {
+ if (!cancelled) setDriverIconDataUrl(iconDataUrl);
+ }).catch((error) => {
+ log.debug('permission guide driver icon lookup failed', error);
+ });
+ }
+ void window.electronAPI.maker.computer.permissionGuideStatus().then((status) => {
+ if (!cancelled) setPermissionState(status.permissionState ?? null);
+ }).catch((error) => {
+ log.debug('permission guide initial status snapshot failed', error);
+ });
+ const onStatusChanged = window.electronAPI.maker.computer.onPermissionGuideStatusChanged;
+ const dispose = typeof onStatusChanged === 'function'
+ ? onStatusChanged((status) => {
+ if (!cancelled) setPermissionState(status.permissionState ?? null);
+ })
+ : () => undefined;
+ return () => {
+ cancelled = true;
+ dispose();
+ };
+ }, []);
+
+ useEffect(() => {
+ if (dragUiFallbackTimerRef.current !== null) {
+ window.clearTimeout(dragUiFallbackTimerRef.current);
+ dragUiFallbackTimerRef.current = null;
+ }
+ if (previousStepRef.current !== step) {
+ dragAttemptRef.current += 1;
+ setAwaitingUser(false);
+ setDragging(false);
+ try {
+ window.sessionStorage.removeItem(PERMISSION_APP_DRAGGED_STORAGE_KEY);
+ } catch {
+ // Restricted profiles do not expose sessionStorage; the main state wins.
+ }
+ previousStepRef.current = step;
+ }
+ }, [step]);
+
+ useEffect(() => {
+ if (step !== 'complete') return;
+ const timer = window.setTimeout(() => window.close(), 1200);
+ return () => window.clearTimeout(timer);
+ }, [step]);
+
+ useEffect(() => () => {
+ dragAttemptRef.current += 1;
+ if (dragUiFallbackTimerRef.current !== null) {
+ window.clearTimeout(dragUiFallbackTimerRef.current);
+ }
+ void window.electronAPI.maker.computer.finishPermissionAppDrag(false);
+ }, []);
+
+ const cancel = async () => {
+ try {
+ await window.electronAPI.maker.computer.cancelPermissionGrant();
+ } catch (error) {
+ log.debug('permission guide cancel failed', error);
+ window.close();
+ }
+ };
+
+ const isAccessibility = step === 'accessibility';
+ const label = isAccessibility
+ ? t('settings.computerUse.directControl.permissions.accessibilityLabel')
+ : t('settings.computerUse.directControl.permissions.screenRecordingLabel');
+
+ const handleDragStart = (event: React.DragEvent<HTMLButtonElement>) => {
+ const iconDataUrl = dragIconDataUrl(iconRef.current);
+ if (!iconDataUrl) {
+ event.preventDefault();
+ return;
+ }
+ event.preventDefault();
+ event.dataTransfer.effectAllowed = 'copy';
+ if (dragUiFallbackTimerRef.current !== null) {
+ window.clearTimeout(dragUiFallbackTimerRef.current);
+ }
+ dragAttemptRef.current += 1;
+ setAwaitingUser(false);
+ setDragging(true);
+ window.electronAPI.maker.computer.startPermissionAppDrag(iconDataUrl);
+ dragUiFallbackTimerRef.current = window.setTimeout(() => {
+ dragUiFallbackTimerRef.current = null;
+ setDragging(false);
+ setAwaitingUser(false);
+ }, PERMISSION_APP_DRAG_UI_FALLBACK_MS);
+ };
+
+ const handleDragEnd = async (event: React.DragEvent<HTMLButtonElement>) => {
+ if (dragUiFallbackTimerRef.current !== null) {
+ window.clearTimeout(dragUiFallbackTimerRef.current);
+ dragUiFallbackTimerRef.current = null;
+ }
+ const didCopy = event.dataTransfer.dropEffect === 'copy';
+ const attempt = dragAttemptRef.current;
+ setDragging(false);
+ let accepted = false;
+ try {
+ accepted = await window.electronAPI.maker.computer.finishPermissionAppDrag(didCopy);
+ } catch (error) {
+ log.debug('permission guide drag confirmation failed', error);
+ }
+ if (dragAttemptRef.current !== attempt) return;
+ setAwaitingUser(accepted);
+ try {
+ if (accepted) {
+ window.sessionStorage.setItem(PERMISSION_APP_DRAGGED_STORAGE_KEY, '1');
+ } else {
+ window.sessionStorage.removeItem(PERMISSION_APP_DRAGGED_STORAGE_KEY);
+ }
+ } catch {
+ // The main-process drag result remains authoritative in restricted profiles.
+ }
+ };
+
+ return (
+ <main className="relative h-screen w-screen select-none overflow-hidden bg-transparent">
+ <section className="pointer-events-none absolute inset-0 text-[var(--text-primary)]">
+ <div
+ className={`pointer-events-auto absolute bottom-3 right-4 flex min-h-[132px] w-[calc(100%_-_28px)] max-w-[432px] flex-col rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3 transition-[opacity,transform] duration-200 ease-out ${
+ dragging ? '!pointer-events-none scale-[0.96] opacity-0' : 'opacity-100'
+ }`}
+ >
+ {step !== 'complete' && interaction === 'drag' && <DragCoach />}
+
+ <header className="flex min-h-7 items-center justify-between text-[var(--text-tertiary)]">
+ <span className="font-mono text-11">
+ {step === 'complete'
+ ? t('settings.computerUse.directControl.permissionGuide.completeEyebrow')
+ : t('settings.computerUse.directControl.permissionGuide.step')}
+ </span>
+ <button
+ type="button"
+ onClick={() => void cancel()}
+ aria-label={t('commonUi.confirmDialog.cancel')}
+ className="inline-flex size-7 items-center justify-center rounded-full text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]"
+ >
+ <X size={17} strokeWidth={1.8} aria-hidden="true" />
+ </button>
+ </header>
+
+ {step === 'complete' ? (
+ <div key="complete" className="animate-confirm-content-in flex flex-1 flex-col justify-center">
+ <span className="inline-flex size-10 items-center justify-center rounded-full bg-[var(--surface-chip)]">
+ <Check size={19} strokeWidth={2.2} aria-hidden="true" />
+ </span>
+ <h1 className="mt-2 text-20 font-medium leading-tight">
+ {t('settings.computerUse.directControl.permissionGuide.readyTitle')}
+ </h1>
+ <p className="mt-1 text-12 leading-[1.45] text-[var(--text-secondary)]">
+ {t('settings.computerUse.directControl.permissionGuide.readyDescription')}
+ </p>
+ </div>
+ ) : (
+ <div key={step} className="animate-confirm-content-in flex flex-1 flex-col">
+ <h1 className="mt-1 text-20 font-medium leading-tight">
+ {t(
+ interaction === 'turn-on'
+ ? 'settings.computerUse.directControl.permissionGuide.turnOnAppTitle'
+ : 'settings.computerUse.directControl.permissionGuide.dragTitle',
+ { permission: label },
+ )}
+ </h1>
+ <button
+ type="button"
+ draggable
+ onDragStart={handleDragStart}
+ onDragEnd={handleDragEnd}
+ className="mt-3 flex min-h-[64px] w-full cursor-grab items-center gap-3 rounded-lg border border-[var(--border-default)] bg-[var(--surface-chip)] px-3 text-left transition-[transform,background-color] duration-200 ease-out hover:-translate-y-0.5 hover:bg-[var(--surface-hover)] active:cursor-grabbing active:scale-[0.99]"
+ >
+ <span className="inline-flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-[var(--surface-elevated)]">
+ <img
+ ref={iconRef}
+ className="size-full object-contain"
+ src={driverIconDataUrl ?? computerIcon}
+ alt=""
+ draggable={false}
+ />
+ </span>
+ <span className="min-w-0 flex-1 text-15 font-medium">
+ {t('settings.computerUse.directControl.permissionGuide.appName')}
+ </span>
+ {awaitingUser && (
+ <span className="inline-flex shrink-0 items-center gap-2 text-11 text-[var(--text-secondary)]">
+ <ArrowRight size={14} strokeWidth={1.8} aria-hidden="true" />
+ {t('settings.computerUse.directControl.permissionGuide.waiting')}
+ </span>
+ )}
+ </button>
+ </div>
+ )}
+ </div>
+
+ {dragging && (
+ <div
+ aria-live="polite"
+ className="computer-permission-drag-active pointer-events-none absolute bottom-3 right-4 inline-flex h-[52px] w-64 items-center gap-2.5 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 text-[var(--text-primary)]"
+ >
+ <span className="inline-flex size-8 shrink-0 items-center justify-center rounded-lg bg-[var(--surface-chip)]">
+ <MousePointer2 size={16} strokeWidth={1.8} aria-hidden="true" />
+ </span>
+ <span className="min-w-0">
+ <span className="block truncate text-12 font-medium">
+ {t('settings.computerUse.directControl.permissionGuide.draggingTitle')}
+ </span>
+ <span className="block truncate text-11 text-[var(--text-secondary)]">
+ {t('settings.computerUse.directControl.permissionGuide.draggingHint', {
+ permission: label,
+ })}
+ </span>
+ </span>
+ </div>
+ )}
+ </section>
+ </main>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
index b55d1135af..59261827a3 100644
--- a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
@@ -17,10 +17,21 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import * as AlertDialog from '@radix-ui/react-alert-dialog';
-import { Check, ChevronDown, Globe, MonitorCog, Download, LogIn, ExternalLink, RefreshCw, Smartphone } from 'lucide-react';
+import {
+ Check,
+ ChevronDown,
+ Globe,
+ MonitorCog,
+ Download,
+ LogIn,
+ ExternalLink,
+ RefreshCw,
+ Smartphone,
+} from 'lucide-react';
import { cn } from '@/lib/utils';
+import accessibilityPermissionIcon from '@/assets/system-settings/accessibility-icon.png';
+import screenRecordingPermissionIcon from '@/assets/system-settings/screen-recording-icon.png';
import { toast } from '@/lib/toast';
import { Switch } from '@/components/ui/switch';
import { Spinner } from '@/components/ui/spinner';
@@ -31,9 +42,14 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { createLogger } from '@/lib/logger';
-import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { BrowserBackendSubsection } from './BrowserBackendSubsection';
import { androidDeviceLabel, androidStatusFallback, describeAndroidDeviceStatus } from './androidStatusPresentation';
+import {
+ getComputerPermissionSwitchChecked,
+ isComputerPermissionPreflightInconclusive,
+ isComputerPermissionReady,
+ shouldStartComputerPermissionGuide,
+} from './computerPermissionFlow';
const log = createLogger('ComputerUseSection');
@@ -43,8 +59,6 @@ const ANDROID_PLUGIN_ID = 'android';
const BROWSER_PLUGIN_ID = 'browser';
const COMPUTER_PLUGIN_ID = 'computer';
const COMPUTER_PERMISSION_POLL_INTERVAL_MS = 1_500;
-// 手动开两个系统权限(找 App、看提示、来回切窗口)轻松超过 90s——超时会把引导
-// 弹窗收掉、开关弹回关闭,用户会以为流程失败(2026-07-03 实踩),给足 5 分钟。
const COMPUTER_PERMISSION_POLL_TIMEOUT_MS = 300_000;
const MAC_ACCESSIBILITY_SETTINGS_URL =
'x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility';
@@ -78,11 +92,6 @@ function androidSourceLabelKey(source: AndroidAdbPathSource | null | undefined):
}
}
-function isComputerPermissionReady(status: ComputerDriverStatus | null): boolean {
- const permissionState = status?.permissionState;
- return !permissionState?.required || permissionState.status === 'granted';
-}
-
function isComputerAccessibilityPermissionReady(status: ComputerDriverStatus | null): boolean {
return status?.permissionState?.accessibility === 'granted';
}
@@ -111,207 +120,66 @@ function getComputerPermissionLogSummary(status: ComputerDriverStatus | null) {
};
}
-function getMissingComputerPermissionSettingsUrl(status: ComputerDriverStatus | null): string | null {
- const permissionState = status?.permissionState;
- if (permissionState?.platform !== 'macos') return null;
- if (permissionState.status !== 'missing') return null;
- if (!isComputerAccessibilityPermissionReady(status)) return MAC_ACCESSIBILITY_SETTINGS_URL;
- if (!isComputerScreenRecordingPermissionReady(status)) return MAC_SCREEN_RECORDING_SETTINGS_URL;
- return null;
-}
-
-function getComputerAccessibilityPermissionLabel(status: ComputerDriverStatus | null, t: (key: string) => string): string {
- const permissionState = status?.permissionState;
- if (permissionState?.accessibility === 'unknown' || permissionState?.status === 'unknown') {
- return t('settings.computerUse.directControl.permissions.unknown');
- }
- return t('settings.computerUse.directControl.permissions.grant');
-}
-
-function getComputerScreenRecordingPermissionLabel(status: ComputerDriverStatus | null, t: (key: string) => string): string {
- const permissionState = status?.permissionState;
- if (
- permissionState?.screenRecording === 'unknown' ||
- permissionState?.screenRecordingCapturable === 'unknown' ||
- permissionState?.status === 'unknown'
- ) {
- return t('settings.computerUse.directControl.permissions.unknown');
- }
- return t('settings.computerUse.directControl.permissions.grant');
-}
-
interface ComputerUseSectionProps {
/** Active session working dir — the project whose .claude/settings.json the
* browser enable toggle reads/writes. */
workingDir?: string;
}
-interface ComputerPermissionBadgeProps {
- label: string;
- granted: boolean;
- onClick: () => void;
- grantLabel: string;
- grantedLabel: string;
-}
-
-function ComputerPermissionBadge({
+function ComputerPermissionRow({
label,
+ iconSrc,
granted,
- onClick,
- grantLabel,
- grantedLabel,
-}: ComputerPermissionBadgeProps) {
+ pending,
+ actionLabel,
+ onAction,
+}: {
+ label: string;
+ iconSrc: string;
+ granted: boolean;
+ pending: boolean;
+ actionLabel: string;
+ onAction: () => void;
+}) {
return (
<button
type="button"
- onClick={onClick}
- aria-label={`${label}: ${granted ? grantedLabel : grantLabel}`}
+ onClick={onAction}
+ disabled={pending}
className={cn(
- 'inline-flex min-h-7 items-center gap-2 rounded-full px-3 text-12 font-medium transition-colors',
- granted
- ? 'bg-transparent px-0 text-[var(--settings-section-sublabel)] hover:text-[var(--settings-section-title)]'
- : 'border border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)] text-[var(--settings-btn-secondary-text)] hover:bg-[var(--settings-btn-secondary-hover-bg)]',
+ 'flex min-h-[64px] w-full min-w-0 items-center gap-3 rounded-xl px-3.5 py-3 text-left',
+ 'border border-solid border-[var(--settings-input-border)] bg-[var(--settings-input-bg)]',
+ 'transition-colors hover:bg-[var(--settings-menu-bg-hover)]',
+ 'disabled:cursor-default disabled:hover:bg-[var(--settings-input-bg)]',
+ 'focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
)}
>
- <span>{label}</span>
- {granted ? (
- <span className="inline-flex items-center gap-1.5">
- <span className="inline-flex h-4 w-4 items-center justify-center rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] text-[var(--settings-section-title)]">
- <Check size={10} strokeWidth={2.4} className="text-[var(--settings-section-title)]" />
- </span>
- {grantedLabel}
- </span>
- ) : (
- <span>{grantLabel}</span>
- )}
+ <img className="size-8 shrink-0 object-contain grayscale opacity-70" src={iconSrc} alt="" aria-hidden="true" />
+ <span className="min-w-0 flex-1 truncate text-13 font-medium text-[var(--settings-section-title)]">
+ {label}
+ </span>
+ <span
+ className={cn(
+ 'inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-12 font-medium',
+ pending
+ ? 'border border-dashed border-[var(--settings-input-border)] bg-[var(--surface-chip)] text-[var(--settings-section-desc)]'
+ : granted
+ ? 'border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] text-[var(--settings-section-title)]'
+ : 'border border-[var(--surface-chip)] bg-[var(--surface-chip)] text-[var(--settings-section-title)]',
+ )}
+ >
+ {pending ? <Spinner size={12} /> : null}
+ <span>{actionLabel}</span>
+ {granted && !pending ? <Check size={13} strokeWidth={2.3} aria-hidden="true" /> : null}
+ </span>
</button>
);
}
-/** 引导弹窗里的单条权限行:实时勾选态,granted 后打勾。 */
-function GuidePermissionRow({ label, granted, waitingLabel, grantedLabel }: {
- label: string;
- granted: boolean;
- waitingLabel: string;
- grantedLabel: string;
-}) {
- return (
- <div className="flex items-center justify-between gap-3 rounded-lg bg-[var(--settings-input-bg)] px-3 py-2.5">
- <span className="text-13 font-medium text-[var(--confirm-title)]">{label}</span>
- {granted ? (
- <span className="inline-flex items-center gap-1.5 text-12 text-[var(--confirm-desc)]">
- <span className="inline-flex h-4 w-4 items-center justify-center rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)]">
- <Check size={10} strokeWidth={2.4} className="text-[var(--confirm-title)]" />
- </span>
- {grantedLabel}
- </span>
- ) : (
- <span className="inline-flex items-center gap-1.5 text-12 text-[var(--confirm-desc)]">
- <Spinner size={12} />
- {waitingLabel}
- </span>
- )}
- </div>
- );
-}
-
-/**
- * 授权引导常驻弹窗:轮询期间一直挂着,实时显示两项权限的授予状态,全部就位后由
- * 外层(pending=false)自动收掉;用户也可随时取消。带 CuaDriver 的真实安装图标,
- * 方便用户在系统设置的权限列表里认出要开的是哪一个 App。
- * 结构沿用 ConfirmDialog(docs/design-rules/cindy-design-system.md §Dialog);overlay 走 --overlay-modal token。
- */
-function ComputerPermissionGuideDialog({ open, status, iconDataUrl, onCancel }: {
- open: boolean;
- status: ComputerDriverStatus | null;
- iconDataUrl: string | null;
- onCancel: () => void;
-}) {
+export function ComputerUseSection({
+ workingDir,
+}: ComputerUseSectionProps) {
const { t } = useTranslation();
- return (
- <AlertDialog.Root open={open}>
- <AlertDialog.Portal>
- <AlertDialog.Overlay
- className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)] data-[state=open]:animate-confirm-overlay-in data-[state=closed]:animate-confirm-overlay-out"
- style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
- />
- <AlertDialog.Content
- className={cn(
- 'fixed left-1/2 top-1/2 z-[10000] -translate-x-1/2 -translate-y-1/2',
- 'w-full max-w-[400px] rounded-xl p-4',
- 'bg-[var(--confirm-bg)] shadow-[var(--confirm-shadow)]',
- 'data-[state=open]:animate-confirm-content-in',
- 'data-[state=closed]:animate-confirm-content-out',
- )}
- style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
- onEscapeKeyDown={(e) => e.preventDefault()}
- >
- <div className="flex items-start gap-3">
- {iconDataUrl ? (
- // CuaDriver 的 icns 画布不带 alpha,四角烤死了近黑色(系统设置里干净是
- // 因为 macOS 26 显示时自动套圆角遮罩)。实测其自带圆角 ≈24% 画布
- // (40px 下 ≈9.6px),裁剪半径必须**大于**它才能把暗角整圈裁掉——取
- // 11px(27.5%),连同边缘抗锯齿渐变一起裁进白色区域内。
- <img
- src={iconDataUrl}
- alt="CuaDriver"
- className="h-10 w-10 shrink-0 rounded-[11px] border border-[var(--settings-input-border)] object-cover"
- draggable={false}
- />
- ) : (
- <span className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-[10px] bg-[var(--settings-input-bg)]">
- <MonitorCog size={22} className="text-[var(--confirm-title)]" />
- </span>
- )}
- <div className="min-w-0">
- <AlertDialog.Title className="text-lg font-medium text-[var(--confirm-title)]">
- {t('settings.computerUse.directControl.permissionGuide.title')}
- </AlertDialog.Title>
- <AlertDialog.Description className="mt-1 text-13 leading-[1.5] text-[var(--confirm-desc)]">
- {t('settings.computerUse.directControl.permissionGuide.description')}
- </AlertDialog.Description>
- </div>
- </div>
- <div className="mt-4 flex flex-col gap-2">
- <GuidePermissionRow
- label={t('settings.computerUse.directControl.permissions.accessibilityLabel')}
- granted={isComputerAccessibilityPermissionReady(status)}
- waitingLabel={t('settings.computerUse.directControl.permissionGuide.waiting')}
- grantedLabel={t('settings.computerUse.directControl.permissions.granted')}
- />
- <GuidePermissionRow
- label={t('settings.computerUse.directControl.permissions.screenRecordingLabel')}
- granted={isComputerScreenRecordingPermissionReady(status)}
- waitingLabel={t('settings.computerUse.directControl.permissionGuide.waiting')}
- grantedLabel={t('settings.computerUse.directControl.permissions.granted')}
- />
- </div>
- <div className="mt-5 flex justify-end">
- <AlertDialog.Cancel asChild>
- <button
- onClick={onCancel}
- className={cn(
- 'inline-flex min-w-[96px] items-center justify-center rounded-full px-6 py-2.5 text-13 font-medium',
- 'transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2',
- 'active:scale-[0.98] border bg-transparent',
- 'border-[var(--confirm-btn-secondary-border)] text-[var(--confirm-btn-secondary-text)]',
- 'hover:bg-[var(--confirm-btn-secondary-hover)]',
- 'focus-visible:ring-[var(--confirm-btn-secondary-border)]',
- )}
- >
- {t('commonUi.confirmDialog.cancel')}
- </button>
- </AlertDialog.Cancel>
- </div>
- </AlertDialog.Content>
- </AlertDialog.Portal>
- </AlertDialog.Root>
- );
-}
-
-export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
- const { t } = useTranslation();
- const { confirm } = useConfirmDialog();
// null = not loaded yet (blank, no flash). After load, all resolve.
const [browserEnabled, setBrowserEnabled] = useState<boolean | null>(null);
const [androidEnabled, setAndroidEnabled] = useState<boolean | null>(null);
@@ -337,46 +205,66 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
const [computerTogglePending, setComputerTogglePending] = useState(false);
const [computerInstallPending, setComputerInstallPending] = useState(false);
const [computerPermissionPending, setComputerPermissionPending] = useState(false);
- // CuaDriver.app 真实图标(引导弹窗识别参照);null = 未取到,降级通用图标。
- const [driverIconDataUrl, setDriverIconDataUrl] = useState<string | null>(null);
- const driverIconFetchedRef = useRef(false);
+ const [computerPermissionRecheckPending, setComputerPermissionRecheckPending] = useState(false);
+ const [computerDetailsOpen, setComputerDetailsOpen] = useState(false);
+ const computerUseSectionMountedRef = useRef(true);
+ const computerTogglePendingRef = useRef(false);
+ const computerPermissionPendingRef = useRef(false);
const computerPermissionPollTimerRef = useRef<number | null>(null);
- // grant 子进程在途时轮询只等待、不再发 status(避免探测与授权流程互相打架)。
+ // Native grant remains cancellable while the user is moving between Settings panes.
const computerPermissionGrantInProgressRef = useRef(false);
const computerEnableIntentRef = useRef(false);
// 授权流程代际号:引导弹窗「取消」时 +1。grant/preflight 的 await 期间用户可能
// 已取消,continuation 必须校验代际,否则被取消的流程仍会打开系统设置抢焦点。
const computerPermissionFlowSeqRef = useRef(0);
- // 授权引导流程中最近一次自动打开的系统设置页 URL —— 同一个权限页只自动打开一次,
- // 权限逐个就位后再自动打开下一个缺失项的设置页(辅助功能 → 屏幕录制)。
- const lastOpenedComputerPermissionUrlRef = useRef<string | null>(null);
-
+ const computerPermissionCompletionInFlightRef = useRef(false);
const resetComputerPermissionFlow = useCallback(() => {
computerPermissionGrantInProgressRef.current = false;
}, []);
- // 引导弹窗打开时按需取一次 CuaDriver 图标(main 侧也有缓存,幂等)。
+ const cancelNativeComputerPermissionGrant = useCallback(() => {
+ void window.electronAPI.maker.computer.cancelPermissionGrant().catch((err) => {
+ log.debug('computer.cancelPermissionGrant failed (ignored)', err);
+ });
+ }, []);
+
useEffect(() => {
- if (!computerPermissionPending || driverIconFetchedRef.current) return;
- driverIconFetchedRef.current = true;
- void window.electronAPI.maker.computer.driverIcon()
- .then((r) => setDriverIconDataUrl(r.iconDataUrl))
- .catch((err) => log.debug('computer.driverIcon failed (generic icon fallback)', err));
+ computerPermissionPendingRef.current = computerPermissionPending;
}, [computerPermissionPending]);
- // 引导弹窗的取消:终止整个授权等待流程(轮询随 pending=false 自行停止)。
+ // Leaving Settings / Plugin detail invalidates the whole enable attempt,
+ // including install and fresh-preflight awaits before the guide is visible.
+ useEffect(() => {
+ computerUseSectionMountedRef.current = true;
+ return () => {
+ computerUseSectionMountedRef.current = false;
+ computerPermissionFlowSeqRef.current += 1;
+ computerEnableIntentRef.current = false;
+ computerPermissionCompletionInFlightRef.current = false;
+ const hadActivePermissionFlow = (
+ computerTogglePendingRef.current
+ || computerPermissionPendingRef.current
+ || computerPermissionGrantInProgressRef.current
+ );
+ resetComputerPermissionFlow();
+ if (hadActivePermissionFlow) {
+ cancelNativeComputerPermissionGrant();
+ }
+ computerTogglePendingRef.current = false;
+ };
+ }, [cancelNativeComputerPermissionGrant, resetComputerPermissionFlow]);
+
+ // 引导弹窗的取消:终止当前的一次性授权请求。
const handleCancelPermissionGuide = useCallback(() => {
computerPermissionFlowSeqRef.current += 1;
setComputerPermissionPending(false);
computerEnableIntentRef.current = false;
+ computerPermissionCompletionInFlightRef.current = false;
resetComputerPermissionFlow();
- lastOpenedComputerPermissionUrlRef.current = null;
// 收割 main 侧在途的 grant 子进程:取消必须让原生授权流程真正停下,
// 而不是只藏起引导弹窗(否则 15s 复用窗口内下次点击还会接上旧流程)。
- void window.electronAPI.maker.computer.cancelPermissionGrant().catch((err) => {
- log.debug('computer.cancelPermissionGrant failed (ignored)', err);
- });
- }, [resetComputerPermissionFlow]);
+ cancelNativeComputerPermissionGrant();
+ }, [cancelNativeComputerPermissionGrant, resetComputerPermissionFlow]);
const openComputerPermissionSettings = useCallback(
async (url: string, reason: string): Promise<boolean> => {
@@ -386,41 +274,92 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
toast.error(t('settings.computerUse.directControl.toast.openPermissionSettingsFailed'));
return false;
}
- lastOpenedComputerPermissionUrlRef.current = url;
return true;
},
[t],
);
+ // Native macOS onboarding observes the System Settings checkbox in main.
+ // Feed those changes back into this panel so the two permission steps can
+ // advance without asking the user to press Recheck.
+ useEffect(() => {
+ return window.electronAPI.maker.computer.onPermissionGuideStatusChanged((status) => {
+ setComputerStatus(status);
+ if (!computerPermissionPendingRef.current) return;
+ if (!status.installed || !isComputerPermissionReady(status)) {
+ return;
+ }
+
+ if (computerPermissionCompletionInFlightRef.current) return;
+ computerPermissionCompletionInFlightRef.current = true;
+ setComputerPermissionPending(false);
+ resetComputerPermissionFlow();
+ cancelNativeComputerPermissionGrant();
+ if (computerEnableIntentRef.current || computerEnabled) {
+ void window.electronAPI.maker.plugins.setEnabled(COMPUTER_PLUGIN_ID, true)
+ .then((result) => {
+ setComputerEnabled(true);
+ if (result.codexMcpRefreshed === false) {
+ toast.warning(t('settings.computerUse.codexRefreshDeferred'));
+ return;
+ }
+ toast.success(t('settings.computerUse.directControl.toast.enabled'));
+ })
+ .catch((err) => {
+ log.warn('plugins.setEnabled(computer) after native guide failed', err);
+ toast.error(t('settings.computerUse.directControl.toast.toggleFailed'));
+ })
+ .finally(() => {
+ computerPermissionCompletionInFlightRef.current = false;
+ });
+ } else {
+ computerPermissionCompletionInFlightRef.current = false;
+ }
+ });
+ }, [
+ cancelNativeComputerPermissionGrant,
+ computerEnabled,
+ resetComputerPermissionFlow,
+ t,
+ ]);
+
const refreshComputerPermissionStatus = useCallback(async (
reason: string,
- options?: { fresh?: boolean; live?: boolean },
+ options?: { fresh?: boolean; bypassCache?: boolean; passiveOnly?: boolean },
) => {
- // fresh:重启 daemon 后现场实测 —— 「辅助功能被撤销」只有重启 daemon 才读得到
- // (运行中的 daemon 对 AX 撤销无感知),仅用于用户显式动作(重新检查 / 开启开关)。
- // live:不重启但绕过弹窗抑制缓存现场实测 —— 授权引导轮询用,权限逐项授予的
- // 进度(授予方向 daemon 实时可见)不能被缓存冻住,否则第二个权限的设置页永远
- // 不会自动打开;引导期间系统本就在弹授权对话框,实测语义一致。
+ // fresh:重启 daemon 后现场实测 —— 「辅助功能被撤销」只有重启 daemon 才读得到。
+ // 仅在 driver 替换或已进入授权流程后使用;页面进入/Recheck 走 passiveOnly,
+ // 开启开关会重新验证可变的 macOS TCC 状态,不能消费可能已过期的页面快照。
const status = await window.electronAPI.maker.computer.status({
forcePermissionProbe: true,
...(options?.fresh ? { freshPermissionProbe: true } : {}),
- ...(options?.live ? { bypassPermissionProbeCache: true } : {}),
+ ...(options?.bypassCache ? { bypassPermissionProbeCache: true } : {}),
+ ...(options?.passiveOnly ? { passivePermissionProbeOnly: true } : {}),
});
log.debug('computer permission status refreshed', {
flowReason: reason,
fresh: options?.fresh === true,
- live: options?.live === true,
+ bypassCache: options?.bypassCache === true,
+ passiveOnly: options?.passiveOnly === true,
...getComputerPermissionLogSummary(status),
});
setComputerStatus(status);
return status;
}, []);
- const requestComputerPermissionGrant = useCallback(async (reason: string) => {
+ const requestComputerPermissionGrant = useCallback(async (
+ reason: string,
+ openedPaneUrl?: string,
+ ) => {
computerPermissionGrantInProgressRef.current = true;
log.debug('computer permission grant requested', { reason });
try {
- const result = await window.electronAPI.maker.computer.grantPermissions();
+ const result = await window.electronAPI.maker.computer.grantPermissions({
+ // The native coach presents the drag/enable steps beside System Settings.
+ // Permission status itself advances only after explicit user actions.
+ showGuide: window.electronAPI.platform === 'darwin',
+ ...(openedPaneUrl ? { openedPaneUrl } : {}),
+ });
log.debug('computer permission grant result', {
flowReason: reason,
ok: result.ok,
@@ -432,6 +371,13 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
computerPermissionGrantInProgressRef.current = false;
}
}, []);
+
+ // 独立引导浮窗里的关闭按钮由 main 广播回来。
+ useEffect(() => {
+ return window.electronAPI.maker.computer.onPermissionGuideCancelled(
+ handleCancelPermissionGuide,
+ );
+ }, [handleCancelPermissionGuide]);
// 更新检查每次打开面板只跑一次;status 对象在 install/授权流程里会反复刷新,
// 用 ref 防止重复触发网络请求。
const driverUpdateCheckedRef = useRef(false);
@@ -544,7 +490,15 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
log.warn('browser.status failed', err);
return { detected: false, browserKind: null, executablePath: null } as BrowserAvailability;
}),
- window.electronAPI.maker.computer.status({ forcePermissionProbe: true }).catch((err) => {
+ // Entering Automation is the shared refresh boundary for every card.
+ // CuaDriver 0.12.2+ reports its own TCC state without opening the legacy
+ // grant flow. Bypass our prior-result cache so reopening this page
+ // reflects the latest settings without requiring a manual Recheck.
+ window.electronAPI.maker.computer.status({
+ forcePermissionProbe: true,
+ bypassPermissionProbeCache: true,
+ passivePermissionProbeOnly: true,
+ }).catch((err) => {
log.warn('computer.status failed', err);
return {
installed: false,
@@ -628,9 +582,26 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
const result = await window.electronAPI.maker.computer.updateDriver(
joinOnly ? { joinOnly: true } : undefined,
);
- setComputerStatus(result.status);
+ let nextStatus = result.status;
+ if (nextStatus.installed && nextStatus.permissionState?.platform === 'macos') {
+ // A driver replacement may receive a new TCC identity. Re-probe the
+ // installed binary before allowing the capability to look usable.
+ nextStatus = await refreshComputerPermissionStatus('driver-update', { fresh: true });
+ }
+ setComputerStatus(nextStatus);
+ if (!isComputerPermissionReady(nextStatus)) {
+ setComputerPermissionPending(false);
+ setComputerEnabled(false);
+ if (computerEnabled) {
+ await window.electronAPI.maker.plugins.setEnabled(COMPUTER_PLUGIN_ID, false)
+ .catch((error) => log.warn('disabling computer after permission reset failed', error));
+ }
+ toast.warning(t('settings.computerUse.directControl.toast.permissionPending'));
+ }
setDriverUpdate(null);
- toast.success(t('settings.computerUse.directControl.update.toast.success'));
+ if (isComputerPermissionReady(nextStatus)) {
+ toast.success(t('settings.computerUse.directControl.update.toast.success'));
+ }
} catch (err) {
log.warn('computer driver update failed', err);
toast.error(t('settings.computerUse.directControl.update.toast.failed'));
@@ -645,7 +616,7 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
} finally {
setDriverUpdatePending(false);
}
- }, [t]);
+ }, [computerEnabled, refreshComputerPermissionStatus, t]);
useEffect(() => {
if (!computerStatus?.installed || driverUpdateCheckedRef.current) return;
@@ -692,15 +663,10 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
);
}, [t]);
- useEffect(() => {
- return () => {
- if (computerPermissionPollTimerRef.current !== null) {
- window.clearTimeout(computerPermissionPollTimerRef.current);
- computerPermissionPollTimerRef.current = null;
- }
- };
- }, []);
-
+ // CLI-only CuaDriver installs use the legacy `permissions grant` process and
+ // have no native-guide broadcasts. Keep checking that live permission state
+ // while the shared pending UI is visible. The completion ref also prevents a
+ // native broadcast and this fallback poll from enabling the plugin twice.
useEffect(() => {
if (!computerPermissionPending) {
if (computerPermissionPollTimerRef.current !== null) {
@@ -714,36 +680,26 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
const deadline = Date.now() + COMPUTER_PERMISSION_POLL_TIMEOUT_MS;
const poll = async () => {
try {
- if (computerPermissionGrantInProgressRef.current) {
- log.debug('computer permission poll waiting for grant to settle');
- computerPermissionPollTimerRef.current = window.setTimeout(poll, COMPUTER_PERMISSION_POLL_INTERVAL_MS);
- return;
- }
- const status = await refreshComputerPermissionStatus('poll', { live: true });
- if (cancelled) return;
- if (isComputerPermissionReady(status)) {
- // ⚠️ 完成态收尾必须「先启用、后收弹窗」,且不做 cancelled 早退:
- // setComputerPermissionPending(false) / setComputerEnabled(true) 都会让本
- // effect 立刻清理重建(cancelled=true),之前写在 await 后面的 cancelled
- // 早退会把「启用开关 + 成功提示」整段跳过 —— 表现为授权完成后弹窗消失、
- // 开关却回到关闭,而 main 侧插件已被启用,前后端状态错开(2026-07-03 实踩)。
- // 这里的 setState 即使撞上组件卸载也只是 React 18 的 no-op,无需早退。
- if (computerEnableIntentRef.current || computerEnabled) {
- await persistComputerEnabled(true);
+ if (!computerPermissionGrantInProgressRef.current) {
+ const status = await refreshComputerPermissionStatus('permission-poll', {
+ bypassCache: true,
+ });
+ if (cancelled) return;
+ if (isComputerPermissionReady(status)) {
+ if (computerPermissionCompletionInFlightRef.current) return;
+ computerPermissionCompletionInFlightRef.current = true;
+ setComputerPermissionPending(false);
+ resetComputerPermissionFlow();
+ cancelNativeComputerPermissionGrant();
+ try {
+ if (computerEnableIntentRef.current || computerEnabled) {
+ await persistComputerEnabled(true);
+ }
+ } finally {
+ computerPermissionCompletionInFlightRef.current = false;
+ }
+ return;
}
- setComputerPermissionPending(false);
- resetComputerPermissionFlow();
- lastOpenedComputerPermissionUrlRef.current = null;
- return;
- }
- // 授权是逐项完成的(辅助功能 → 屏幕录制):上一项就位后,自动把下一个
- // 缺失项的系统设置页带到用户面前;同一页只自动打开一次,避免反复抢焦点。
- const nextPermissionUrl = getMissingComputerPermissionSettingsUrl(status);
- if (
- nextPermissionUrl &&
- nextPermissionUrl !== lastOpenedComputerPermissionUrlRef.current
- ) {
- void openComputerPermissionSettings(nextPermissionUrl, 'poll-next-permission');
}
} catch (err) {
log.warn('computer permission poll failed', err);
@@ -753,14 +709,15 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
if (Date.now() >= deadline) {
setComputerPermissionPending(false);
resetComputerPermissionFlow();
- lastOpenedComputerPermissionUrlRef.current = null;
- if (!computerEnabled) {
- computerEnableIntentRef.current = false;
- }
+ cancelNativeComputerPermissionGrant();
+ if (!computerEnabled) computerEnableIntentRef.current = false;
toast.warning(t('settings.computerUse.directControl.toast.permissionPending'));
return;
}
- computerPermissionPollTimerRef.current = window.setTimeout(poll, COMPUTER_PERMISSION_POLL_INTERVAL_MS);
+ computerPermissionPollTimerRef.current = window.setTimeout(
+ poll,
+ COMPUTER_PERMISSION_POLL_INTERVAL_MS,
+ );
};
void poll();
@@ -772,9 +729,9 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
}
};
}, [
+ cancelNativeComputerPermissionGrant,
computerEnabled,
computerPermissionPending,
- openComputerPermissionSettings,
persistComputerEnabled,
refreshComputerPermissionStatus,
resetComputerPermissionFlow,
@@ -908,88 +865,80 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
const handleToggleComputer = useCallback(
async (next: boolean) => {
+ const flowSeq = computerPermissionFlowSeqRef.current;
+ const isCurrentFlow = () => (
+ computerUseSectionMountedRef.current
+ && computerPermissionFlowSeqRef.current === flowSeq
+ );
+ computerTogglePendingRef.current = true;
setComputerTogglePending(true);
computerEnableIntentRef.current = next;
+ if (next) computerPermissionCompletionInFlightRef.current = false;
let nextStatus = computerStatus;
try {
- if (next) {
- nextStatus = await refreshComputerPermissionStatus('toggle', { fresh: true });
- }
-
- if (next && (!nextStatus?.installed || !isComputerPermissionReady(nextStatus))) {
- const confirmed = await confirm({
- title: t('settings.computerUse.directControl.permissionIntro.title'),
- description: t(
- nextStatus?.permissionState?.platform === 'macos'
- ? 'settings.computerUse.directControl.permissionIntro.macosDescription'
- : 'settings.computerUse.directControl.permissionIntro.description',
- ),
- confirmText: t('settings.computerUse.directControl.permissionIntro.confirm'),
- cancelText: t('settings.computerUse.directControl.permissionIntro.cancel'),
- autoFocusConfirm: true,
- });
- if (!confirmed) {
- computerEnableIntentRef.current = false;
- lastOpenedComputerPermissionUrlRef.current = null;
- return;
- }
- }
-
if (next && !nextStatus?.installed) {
setComputerInstallPending(true);
const installResult = await window.electronAPI.maker.computer.installDriver();
+ if (!isCurrentFlow()) return;
nextStatus = installResult.status;
setComputerStatus(installResult.status);
if (!installResult.status.installed) {
throw new Error(installResult.status.error ?? 'cua-driver install did not produce an installed driver');
}
}
- if (next && !isComputerPermissionReady(nextStatus)) {
+ if (next && nextStatus?.permissionState?.platform === 'macos') {
+ nextStatus = await refreshComputerPermissionStatus('toggle-fresh-preflight', {
+ fresh: true,
+ bypassCache: true,
+ });
+ if (!isCurrentFlow()) return;
+ }
+ if (next && isComputerPermissionPreflightInconclusive(nextStatus)) {
+ computerEnableIntentRef.current = false;
+ setComputerPermissionPending(false);
+ resetComputerPermissionFlow();
+ toast.error(t('settings.computerUse.directControl.toast.permissionFailed'));
+ return;
+ }
+ if (shouldStartComputerPermissionGuide(next, nextStatus)) {
+ if (!isCurrentFlow()) return;
setComputerPermissionPending(true);
- const flowSeq = computerPermissionFlowSeqRef.current;
nextStatus = await requestComputerPermissionGrant('toggle');
// 用户在 grant 等待期间点了引导弹窗的「取消」:整个流程已终止,
// 不再打开系统设置/弹提示。
if (computerPermissionFlowSeqRef.current !== flowSeq) return;
if (!isComputerPermissionReady(nextStatus)) {
- const settingsUrl = getMissingComputerPermissionSettingsUrl(nextStatus);
- if (settingsUrl) {
- const opened = await openComputerPermissionSettings(settingsUrl, 'toggle');
- if (opened) {
- toast.warning(t('settings.computerUse.directControl.toast.permissionPending'));
- } else {
- computerEnableIntentRef.current = false;
- setComputerPermissionPending(false);
- resetComputerPermissionFlow();
- lastOpenedComputerPermissionUrlRef.current = null;
- toast.error(t('settings.computerUse.directControl.toast.permissionFailed'));
- }
- } else {
- toast.warning(t('settings.computerUse.directControl.toast.permissionPending'));
- }
+ toast.warning(t('settings.computerUse.directControl.toast.permissionPending'));
return;
}
setComputerPermissionPending(false);
resetComputerPermissionFlow();
- lastOpenedComputerPermissionUrlRef.current = null;
+ }
+ if (next && isComputerPermissionReady(nextStatus)) {
+ // The early status card may have been shown while a fresh check was
+ // in flight; close it when that check proves permissions are already
+ // complete.
+ setComputerPermissionPending(false);
+ resetComputerPermissionFlow();
}
+ if (!isCurrentFlow()) return;
await persistComputerEnabled(next);
if (!next) {
computerEnableIntentRef.current = false;
setComputerPermissionPending(false);
resetComputerPermissionFlow();
- lastOpenedComputerPermissionUrlRef.current = null;
}
if (nextStatus !== computerStatus) {
setComputerStatus(nextStatus);
}
} catch (err) {
+ if (!isCurrentFlow()) return;
log.warn('setProjectEnabled(computer) failed', err);
computerEnableIntentRef.current = false;
setComputerPermissionPending(false);
resetComputerPermissionFlow();
- lastOpenedComputerPermissionUrlRef.current = null;
+ cancelNativeComputerPermissionGrant();
toast.error(
next && !nextStatus?.installed
? t('settings.computerUse.directControl.toast.installFailed')
@@ -998,14 +947,16 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
: t('settings.computerUse.directControl.toast.toggleFailed'),
);
} finally {
- setComputerInstallPending(false);
- setComputerTogglePending(false);
+ computerTogglePendingRef.current = false;
+ if (computerUseSectionMountedRef.current) {
+ setComputerInstallPending(false);
+ setComputerTogglePending(false);
+ }
}
},
[
computerStatus,
- confirm,
- openComputerPermissionSettings,
+ cancelNativeComputerPermissionGrant,
persistComputerEnabled,
refreshComputerPermissionStatus,
requestComputerPermissionGrant,
@@ -1036,32 +987,46 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
const handleOpenComputerPermission = useCallback(
async (url: string, granted: boolean) => {
+ if (computerPermissionPending) return;
+ const flowSeq = computerPermissionFlowSeqRef.current;
+ // Open the exact System Settings pane before starting native onboarding.
+ // The old order waited for the paused grant flow first, so the user saw
+ // no feedback while the guide was preparing and the pane could open late.
+ const opened = await openComputerPermissionSettings(
+ url,
+ granted ? 'badge-granted' : 'badge-missing',
+ );
+ if (
+ !computerUseSectionMountedRef.current
+ || computerPermissionFlowSeqRef.current !== flowSeq
+ ) {
+ return;
+ }
+ if (!opened) return;
if (granted) {
- await openComputerPermissionSettings(url, 'badge-granted');
return;
}
setComputerPermissionPending(true);
- const flowSeq = computerPermissionFlowSeqRef.current;
+ const initialStatus = computerStatus;
try {
- const preflightStatus = await refreshComputerPermissionStatus('badge-preflight');
- if (computerPermissionFlowSeqRef.current !== flowSeq) return;
- if (isComputerPermissionReady(preflightStatus)) {
+ // Page entry/Recheck already supplied the source-of-truth snapshot.
+ // Pass it straight into the guide so its first frame chooses the
+ // current missing step without another probe or a driver restart.
+ if (isComputerPermissionReady(initialStatus)) {
setComputerPermissionPending(false);
resetComputerPermissionFlow();
- lastOpenedComputerPermissionUrlRef.current = null;
if (computerEnableIntentRef.current || computerEnabled) {
await persistComputerEnabled(true);
}
return;
}
- const status = await requestComputerPermissionGrant('badge');
+ const status = await requestComputerPermissionGrant('badge', url);
if (computerPermissionFlowSeqRef.current !== flowSeq) return;
if (isComputerPermissionReady(status)) {
setComputerPermissionPending(false);
resetComputerPermissionFlow();
- lastOpenedComputerPermissionUrlRef.current = null;
if (computerEnableIntentRef.current || computerEnabled) {
await persistComputerEnabled(true);
}
@@ -1069,71 +1034,91 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
}
log.debug('computer permission grant still pending after badge action', getComputerPermissionLogSummary(status));
- const settingsUrl = getMissingComputerPermissionSettingsUrl(status) ?? url;
- const opened = await openComputerPermissionSettings(settingsUrl, 'badge-missing');
- if (opened) {
- toast.warning(t('settings.computerUse.directControl.toast.permissionSettingsOpened'));
- }
- setComputerPermissionPending(false);
- resetComputerPermissionFlow();
- lastOpenedComputerPermissionUrlRef.current = null;
+ // The System Settings pane is already open. Keep the guide alive and
+ // let its native observer complete the remaining step.
+ toast.warning(t('settings.computerUse.directControl.toast.permissionPending'));
} catch (err) {
+ if (
+ !computerUseSectionMountedRef.current
+ || computerPermissionFlowSeqRef.current !== flowSeq
+ ) {
+ return;
+ }
log.warn('computer permission grant failed', err);
setComputerPermissionPending(false);
resetComputerPermissionFlow();
- lastOpenedComputerPermissionUrlRef.current = null;
+ cancelNativeComputerPermissionGrant();
toast.error(t('settings.computerUse.directControl.toast.permissionFailed'));
}
},
[
computerEnabled,
+ computerStatus,
+ computerPermissionPending,
+ cancelNativeComputerPermissionGrant,
openComputerPermissionSettings,
persistComputerEnabled,
- refreshComputerPermissionStatus,
requestComputerPermissionGrant,
resetComputerPermissionFlow,
t,
],
);
- const handleRefreshComputerStatus = useCallback(async () => {
+ // Recheck restarts the daemon so it picks up revoked permissions that a
+ // running daemon cannot detect (AX revoke is invisible to the live process;
+ // Screen Recording removal may not kill the daemon on all macOS versions).
+ // fresh=true is required: passiveOnly kept the old daemon alive and its
+ // stale TCC preflight kept reporting "granted" even after the user removed
+ // CuaDriver from Screen Recording.
+ const handleRecheckComputerStatus = useCallback(async () => {
+ setComputerPermissionRecheckPending(true);
try {
- const status = await refreshComputerPermissionStatus('recheck', { fresh: true });
- if (status.installed && isComputerPermissionReady(status)) {
- lastOpenedComputerPermissionUrlRef.current = null;
- if (computerEnableIntentRef.current || computerEnabled) {
- await persistComputerEnabled(true);
- }
- } else {
+ const status = await refreshComputerPermissionStatus('recheck', {
+ fresh: true,
+ bypassCache: true,
+ });
+ if (!status.installed || !isComputerPermissionReady(status)) {
log.debug('computer permission recheck found missing permissions', getComputerPermissionLogSummary(status));
}
- setComputerPermissionPending(false);
} catch (err) {
log.warn('computer.status refresh failed', err);
- setComputerPermissionPending(false);
- lastOpenedComputerPermissionUrlRef.current = null;
toast.error(t('settings.computerUse.directControl.toast.toggleFailed'));
+ } finally {
+ setComputerPermissionRecheckPending(false);
}
- }, [computerEnabled, persistComputerEnabled, refreshComputerPermissionStatus, t]);
+ }, [refreshComputerPermissionStatus, t]);
- // First render: blank until all reads land (no flash, rule 7).
- if (
+ const automationViewLoading =
browserEnabled === null
|| computerEnabled === null
|| availability === null
- || computerStatus === null
- ) {
+ || computerStatus === null;
+
+ // First render: blank until all reads land (no flash, rule 7).
+ if (automationViewLoading) {
return null;
}
- // 开关在「切换 / 安装 / 等待系统授权」的整个流程中置灰,视觉位置跟随用户意图
- // (开启中的等待期显示为开、避免"点了却弹回去"的错觉),流程结束才恢复可交互。
- const computerSwitchChecked = computerTogglePending
- ? computerEnableIntentRef.current
- : computerInstallPending || computerPermissionPending
- ? computerEnableIntentRef.current || computerEnabled
- : computerEnabled;
- const computerSwitchDisabled = computerTogglePending || computerInstallPending || computerPermissionPending;
+ const computerAccessibilityGranted = isComputerAccessibilityPermissionReady(computerStatus);
+ const computerScreenRecordingGranted = isComputerScreenRecordingPermissionReady(computerStatus);
+ const computerAccessibilityPending = computerPermissionPending && !computerAccessibilityGranted;
+ const computerScreenRecordingPending =
+ computerPermissionPending &&
+ computerAccessibilityGranted &&
+ !computerScreenRecordingGranted;
+ const computerReady =
+ computerStatus.installed && isComputerPermissionReady(computerStatus);
+ // Persisted opt-in and runtime readiness are separate states. Keeping an
+ // unavailable enabled configuration checked lets the user turn it off
+ // instead of forcing the only interaction back into onboarding.
+ const computerSwitchChecked = getComputerPermissionSwitchChecked(
+ computerEnabled,
+ computerTogglePending,
+ computerEnableIntentRef.current,
+ );
+ const computerSwitchDisabled =
+ computerTogglePending || computerInstallPending || computerPermissionPending;
+
const configuredDefaultAndroidDevice =
androidConfig?.value.defaultDeviceSerial
?? androidStatus?.configured_default_device_serial
@@ -1182,6 +1167,7 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
</div>
<div
+ id="automation-browser"
className={cn(
'flex flex-col overflow-hidden rounded-xl',
'bg-[var(--settings-theme-card-bg)]',
@@ -1269,6 +1255,7 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
<div aria-hidden="true" className="h-px bg-[var(--settings-theme-card-border)]" />
<div
+ id="automation-computer"
className={cn(
'flex flex-col overflow-hidden rounded-xl',
'bg-[var(--settings-theme-card-bg)]',
@@ -1301,154 +1288,210 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
aria-label={t('settings.computerUse.directControl.toggleAria')}
/>
</div>
- <div className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--settings-theme-card-border)] px-4 py-[14px]">
- <p className="min-w-0 text-12 leading-[1.5] text-[var(--settings-section-desc)]">
- {computerInstallPending
- ? t('settings.computerUse.directControl.installing')
- : computerPermissionPending
- ? t('settings.computerUse.directControl.authorizing')
- : computerStatus.installed
- ? t('settings.computerUse.directControl.detected', {
+ {/* Windows/Linux 没有 macOS TCC 权限,整块隐藏;安装进度改在下方状态行展示。 */}
+ {window.electronAPI.platform === 'darwin' ? (
+ <div className="border-t border-[var(--settings-theme-card-border)] px-4 py-4">
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-13 font-medium text-[var(--settings-section-title)]">
+ {t('settings.computerUse.directControl.permissions.title')}
+ </p>
+ {computerInstallPending || computerPermissionPending ? (
+ <span className="inline-flex items-center gap-1.5 text-12 text-[var(--settings-section-desc)]">
+ <Spinner size={12} />
+ {computerInstallPending
+ ? t('settings.computerUse.directControl.installing')
+ : t('settings.computerUse.directControl.authorizing')}
+ </span>
+ ) : (
+ <button
+ type="button"
+ onClick={() => void handleRecheckComputerStatus()}
+ disabled={computerPermissionRecheckPending}
+ className={cn(ACTION_BUTTON_CLASS, 'h-6 px-2.5')}
+ >
+ {computerPermissionRecheckPending ? (
+ <Spinner size={12} />
+ ) : (
+ <RefreshCw size={12} className="shrink-0" />
+ )}
+ {t('settings.computerUse.directControl.permissions.recheck')}
+ </button>
+ )}
+ </div>
+
+ <div className="mt-3 grid gap-2.5 sm:grid-cols-2">
+ <ComputerPermissionRow
+ label={t('settings.computerUse.directControl.permissions.accessibilityLabel')}
+ iconSrc={accessibilityPermissionIcon}
+ granted={computerAccessibilityGranted}
+ pending={computerAccessibilityPending}
+ actionLabel={
+ computerAccessibilityPending
+ ? t('settings.computerUse.directControl.permissionGuide.waiting')
+ : computerAccessibilityGranted
+ ? t('settings.computerUse.directControl.permissions.granted')
+ : t('settings.computerUse.directControl.permissions.grant')
+ }
+ onAction={() =>
+ void (
+ computerStatus.installed
+ ? handleOpenComputerPermission(
+ MAC_ACCESSIBILITY_SETTINGS_URL,
+ computerAccessibilityGranted,
+ )
+ : handleToggleComputer(true)
+ )
+ }
+ />
+ <ComputerPermissionRow
+ label={t('settings.computerUse.directControl.permissions.screenRecordingLabel')}
+ iconSrc={screenRecordingPermissionIcon}
+ granted={computerScreenRecordingGranted}
+ pending={computerScreenRecordingPending}
+ actionLabel={
+ computerScreenRecordingPending
+ ? t('settings.computerUse.directControl.permissionGuide.waiting')
+ : computerScreenRecordingGranted
+ ? t('settings.computerUse.directControl.permissions.granted')
+ : t('settings.computerUse.directControl.permissions.grant')
+ }
+ onAction={() =>
+ void (
+ computerStatus.installed
+ ? handleOpenComputerPermission(
+ MAC_SCREEN_RECORDING_SETTINGS_URL,
+ computerScreenRecordingGranted,
+ )
+ : handleToggleComputer(true)
+ )
+ }
+ />
+ </div>
+ </div>
+ ) : null}
+
+ <div className="relative border-t border-[var(--settings-theme-card-border)] px-4 py-2.5">
+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2">
+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="text-11 text-[var(--settings-section-desc)]">
+ {computerStatus.installed
+ ? t('settings.computerUse.directControl.status.version', {
version: computerStatus.version ?? 'cua-driver',
- path: computerStatus.executablePath ?? 'cua-driver',
- daemon: computerStatus.daemonRunning
- ? t('settings.computerUse.directControl.daemonRunning')
- : t('settings.computerUse.directControl.daemonStopped'),
})
: t('settings.computerUse.directControl.notDetected')}
- </p>
- <button type="button" onClick={handleOpenCuaProject} className={ACTION_BUTTON_CLASS}>
- <ExternalLink size={12} className="shrink-0" />
- {t('settings.computerUse.directControl.openSourceProject')}
- </button>
+ </span>
+ {window.electronAPI.platform !== 'darwin' && computerInstallPending ? (
+ <>
+ <span aria-hidden="true" className="text-11 text-[var(--settings-theme-card-border)]">
+ ·
+ </span>
+ <span className="inline-flex items-center gap-1.5 text-11 text-[var(--settings-section-desc)]">
+ <Spinner size={12} />
+ {t('settings.computerUse.directControl.installing')}
+ </span>
+ </>
+ ) : null}
+ {computerStatus.installed && driverUpdate?.latestVersion ? (
+ <>
+ <span aria-hidden="true" className="text-11 text-[var(--settings-theme-card-border)]">
+ ·
+ </span>
+ <span className="text-11 text-[var(--settings-section-desc)]">
+ {driverUpdatePending
+ ? driverUpdateProgress?.phase === 'installing'
+ ? t('settings.computerUse.directControl.update.installing')
+ : t('settings.computerUse.directControl.update.updating')
+ : t('settings.computerUse.directControl.update.available', {
+ version: driverUpdate.latestVersion,
+ })}
+ </span>
+ <button
+ type="button"
+ onClick={() => void handleUpdateDriver()}
+ disabled={driverUpdatePending || computerInstallPending}
+ className={cn(ACTION_BUTTON_CLASS, 'h-6 px-2.5')}
+ >
+ <Download size={12} className="shrink-0" />
+ {driverUpdatePending
+ ? t('settings.computerUse.directControl.update.updating')
+ : t('settings.computerUse.directControl.update.action')}
+ </button>
+ </>
+ ) : null}
+ </div>
+ <button
+ type="button"
+ onClick={() => setComputerDetailsOpen((open) => !open)}
+ aria-expanded={computerDetailsOpen}
+ className={cn(
+ 'inline-flex h-6 shrink-0 items-center gap-1 rounded-md px-1.5',
+ 'text-11 font-medium text-[var(--settings-section-desc)]',
+ 'transition-colors hover:bg-[var(--settings-input-bg)] hover:text-[var(--settings-section-title)]',
+ 'focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ {computerDetailsOpen
+ ? t('settings.computerUse.directControl.permissions.hideDetails')
+ : t('settings.computerUse.directControl.permissions.moreDetails')}
+ <ChevronDown
+ size={12}
+ className={cn(
+ 'transition-transform duration-200',
+ computerDetailsOpen && 'rotate-180',
+ )}
+ />
+ </button>
+ </div>
+ {driverUpdatePending &&
+ driverUpdateProgress?.phase === 'downloading' &&
+ driverUpdateProgress.downloadedBytes !== null &&
+ driverUpdateProgress.totalBytes ? (
+ <div className="absolute inset-x-0 bottom-0 h-[2px] bg-[var(--settings-input-bg)]">
+ <div
+ className="h-full bg-[var(--settings-section-title)] transition-[width] duration-500"
+ style={{
+ width: `${Math.min(
+ 100,
+ (driverUpdateProgress.downloadedBytes / driverUpdateProgress.totalBytes) * 100,
+ )}%`,
+ }}
+ />
+ </div>
+ ) : null}
</div>
- {/* 安静的更新入口:仅当检查到新版本时出现,一行小字 + 一个按钮,无任何主动提醒。
- 更新中把文案换成下载进度(main 侧采样广播),并在行底部铺一条 2px 进度条。 */}
- {computerStatus.installed && driverUpdate?.latestVersion ? (
- <div className="relative border-t border-[var(--settings-theme-card-border)]">
- <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-[14px]">
- <p className="min-w-0 text-12 leading-[1.5] text-[var(--settings-section-desc)]">
- {(() => {
- if (!driverUpdatePending) {
- return t('settings.computerUse.directControl.update.available', {
- version: driverUpdate.latestVersion,
- });
- }
- if (driverUpdateProgress?.phase === 'downloading' && driverUpdateProgress.downloadedBytes !== null) {
- const mb = (driverUpdateProgress.downloadedBytes / 1024 / 1024).toFixed(1);
- if (driverUpdateProgress.totalBytes) {
- const totalMb = (driverUpdateProgress.totalBytes / 1024 / 1024).toFixed(1);
- const percent = Math.min(
- 100,
- Math.round((driverUpdateProgress.downloadedBytes / driverUpdateProgress.totalBytes) * 100),
- );
- return t('settings.computerUse.directControl.update.downloadingPercent', {
- percent,
- downloaded: mb,
- total: totalMb,
- });
- }
- return t('settings.computerUse.directControl.update.downloadingBytes', { downloaded: mb });
- }
- if (driverUpdateProgress?.phase === 'installing') {
- return t('settings.computerUse.directControl.update.installing');
- }
- return t('settings.computerUse.directControl.update.updating');
- })()}
+
+ {computerDetailsOpen ? (
+ <div className="flex flex-col gap-3 border-t border-[var(--settings-theme-card-border)] px-4 py-3.5">
+ <div className="flex flex-col gap-2">
+ <p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
+ {t('settings.computerUse.directControl.driverInfo')}
</p>
+ {window.electronAPI.platform === 'darwin' ? (
+ <p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
+ {computerReady
+ ? t('settings.computerUse.directControl.permissions.runtimeConfirmations')
+ : t('settings.computerUse.directControl.permissions.macosHint')}
+ </p>
+ ) : null}
+ </div>
+ <div>
<button
type="button"
- onClick={() => void handleUpdateDriver()}
- disabled={driverUpdatePending || computerInstallPending}
+ onClick={handleOpenCuaProject}
className={ACTION_BUTTON_CLASS}
>
- <Download size={12} className="shrink-0" />
- {driverUpdatePending
- ? t('settings.computerUse.directControl.update.updating')
- : t('settings.computerUse.directControl.update.action')}
+ <ExternalLink size={12} className="shrink-0" />
+ {t('settings.computerUse.directControl.openSourceProject')}
</button>
</div>
- {driverUpdatePending &&
- driverUpdateProgress?.phase === 'downloading' &&
- driverUpdateProgress.downloadedBytes !== null &&
- driverUpdateProgress.totalBytes ? (
- <div className="absolute inset-x-0 bottom-0 h-[2px] bg-[var(--settings-input-bg)]">
- <div
- className="h-full bg-[var(--settings-section-title)] transition-[width] duration-500"
- style={{
- width: `${Math.min(
- 100,
- (driverUpdateProgress.downloadedBytes / driverUpdateProgress.totalBytes) * 100,
- )}%`,
- }}
- />
- </div>
- ) : null}
- </div>
- ) : null}
- {computerStatus.installed && computerStatus.permissionState?.platform === 'macos' ? (
- <div className="flex flex-wrap items-center gap-3 border-t border-[var(--settings-theme-card-border)] px-4 py-[14px]">
- <ComputerPermissionBadge
- label={t('settings.computerUse.directControl.permissions.accessibilityLabel')}
- granted={isComputerAccessibilityPermissionReady(computerStatus)}
- onClick={() =>
- void handleOpenComputerPermission(
- MAC_ACCESSIBILITY_SETTINGS_URL,
- isComputerAccessibilityPermissionReady(computerStatus),
- )
- }
- grantLabel={getComputerAccessibilityPermissionLabel(computerStatus, t)}
- grantedLabel={t('settings.computerUse.directControl.permissions.granted')}
- />
- <ComputerPermissionBadge
- label={t('settings.computerUse.directControl.permissions.screenRecordingLabel')}
- granted={isComputerScreenRecordingPermissionReady(computerStatus)}
- onClick={() =>
- void handleOpenComputerPermission(
- MAC_SCREEN_RECORDING_SETTINGS_URL,
- isComputerScreenRecordingPermissionReady(computerStatus),
- )
- }
- grantLabel={getComputerScreenRecordingPermissionLabel(computerStatus, t)}
- grantedLabel={t('settings.computerUse.directControl.permissions.granted')}
- />
- <button
- type="button"
- onClick={() => void handleRefreshComputerStatus()}
- className={ACTION_BUTTON_CLASS}
- >
- {t('settings.computerUse.directControl.permissions.recheck')}
- </button>
</div>
) : null}
</div>
- <p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
- {t('settings.computerUse.directControl.driverInfo')}
- </p>
- {computerStatus.installed && computerStatus.permissionState?.platform === 'macos' ? (
- <p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
- {isComputerPermissionReady(computerStatus)
- ? t('settings.computerUse.directControl.permissions.runtimeConfirmations')
- : t('settings.computerUse.directControl.permissions.macosHint')}
- </p>
- ) : null}
- {computerStatus.installed && computerStatus.permissionState?.platform === 'windows' ? (
- <p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
- {t('settings.computerUse.directControl.permissions.windowsHint')}
- </p>
- ) : null}
- {computerStatus.installed && computerStatus.permissionState?.platform === 'linux' ? (
- <p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
- {t('settings.computerUse.directControl.permissions.linuxHint')}
- </p>
- ) : null}
- <p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
- {t('settings.computerUse.directControl.toggleHint')}
- </p>
<div aria-hidden="true" className="h-px bg-[var(--settings-theme-card-border)]" />
<div
+ id="automation-android"
className={cn(
'flex flex-col overflow-hidden rounded-xl',
'bg-[var(--settings-theme-card-bg)]',
@@ -1643,13 +1686,6 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
<p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{t('settings.computerUse.android.toggleHint')}
</p>
-
- <ComputerPermissionGuideDialog
- open={computerPermissionPending}
- status={computerStatus}
- iconDataUrl={driverIconDataUrl}
- onCancel={handleCancelPermissionGuide}
- />
</div>
);
}
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/ComputerPermissionGuideWindow.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/ComputerPermissionGuideWindow.test.ts
new file mode 100644
index 0000000000..b5498b77aa
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/ComputerPermissionGuideWindow.test.ts
@@ -0,0 +1,257 @@
+// @vitest-environment jsdom
+
+import { createElement } from 'react';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ ComputerPermissionGuideWindow,
+ PERMISSION_APP_DRAG_UI_FALLBACK_MS,
+ PERMISSION_APP_DRAGGED_STORAGE_KEY,
+ resolveComputerPermissionGuideInitialAwaitingUser,
+ resolveComputerPermissionGuideInteraction,
+ resolveComputerPermissionGuideStep,
+} from '../ComputerPermissionGuideWindow';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, params?: { permission?: string; current?: number; total?: number }) =>
+ ({
+ 'settings.computerUse.directControl.permissions.accessibilityLabel': 'Accessibility',
+ 'settings.computerUse.directControl.permissions.screenRecordingLabel': 'Screen Recording',
+ 'settings.computerUse.directControl.permissionGuide.step': 'Open computer automation',
+ 'settings.computerUse.directControl.permissionGuide.dragTitle': `Drag Computer Use into ${params?.permission}`,
+ 'settings.computerUse.directControl.permissionGuide.turnOnAppTitle': `Turn on Computer Use in ${params?.permission}`,
+ 'settings.computerUse.directControl.permissionGuide.dragHint': 'Drag',
+ 'settings.computerUse.directControl.permissionGuide.draggingTitle': 'Dragging Computer Use',
+ 'settings.computerUse.directControl.permissionGuide.draggingHint': `Drop into ${params?.permission}`,
+ 'settings.computerUse.directControl.permissionGuide.appName': 'Computer Use',
+ 'settings.computerUse.directControl.permissionGuide.waiting': 'Waiting for you',
+ 'commonUi.confirmDialog.cancel': 'Cancel',
+ })[key] ?? key,
+ }),
+}));
+
+afterEach(() => {
+ cleanup();
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe('resolveComputerPermissionGuideInteraction', () => {
+ it('separates the idle demo, native drag, and user follow-up', () => {
+ expect(resolveComputerPermissionGuideInteraction(false, false)).toBe('drag');
+ expect(resolveComputerPermissionGuideInteraction(true, false)).toBe('dragging');
+ expect(resolveComputerPermissionGuideInteraction(false, true)).toBe('turn-on');
+ });
+
+ it('keeps the native drag state authoritative until dragend', () => {
+ expect(resolveComputerPermissionGuideInteraction(true, true)).toBe('dragging');
+ });
+});
+
+describe('resolveComputerPermissionGuideInitialAwaitingUser', () => {
+ it('resumes the turn-on flow after the app was already dragged', () => {
+ expect(resolveComputerPermissionGuideInitialAwaitingUser('?view=computer-permission-guide&dragged=1')).toBe(true);
+ expect(resolveComputerPermissionGuideInitialAwaitingUser('?view=computer-permission-guide')).toBe(false);
+ expect(resolveComputerPermissionGuideInitialAwaitingUser(
+ '?view=computer-permission-guide',
+ '1',
+ )).toBe(true);
+ expect(PERMISSION_APP_DRAGGED_STORAGE_KEY).toBe('xdmaker.computer-permission-app-dragged');
+ });
+});
+
+describe('ComputerPermissionGuideWindow native drag fallback', () => {
+ it('does not reuse a localStorage drag hint from an earlier guide lifecycle', async () => {
+ window.localStorage.setItem(PERMISSION_APP_DRAGGED_STORAGE_KEY, '1');
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ maker: {
+ computer: {
+ permissionGuideStatus: vi.fn().mockResolvedValue({
+ permissionState: {
+ platform: 'macos',
+ required: true,
+ status: 'missing',
+ accessibility: 'missing',
+ screenRecording: 'missing',
+ screenRecordingCapturable: 'missing',
+ canGrant: true,
+ },
+ }),
+ driverIcon: vi.fn().mockResolvedValue({ iconDataUrl: null }),
+ startPermissionAppDrag: vi.fn(),
+ finishPermissionAppDrag: vi.fn(),
+ cancelPermissionGrant: vi.fn().mockResolvedValue({ cancelled: true }),
+ onPermissionGuideStatusChanged: vi.fn(() => () => undefined),
+ },
+ },
+ },
+ });
+
+ render(createElement(ComputerPermissionGuideWindow));
+
+ expect(await screen.findByText('Drag Computer Use into Accessibility')).toBeTruthy();
+ expect(screen.queryByText('Turn on Computer Use in Accessibility')).toBeNull();
+ });
+
+ it('initializes from the guide preflight snapshot without probing permissions again', async () => {
+ const status = vi.fn();
+ const permissionGuideStatus = vi.fn().mockResolvedValue({
+ permissionState: {
+ platform: 'macos',
+ required: true,
+ status: 'missing',
+ accessibility: 'granted',
+ screenRecording: 'missing',
+ screenRecordingCapturable: 'missing',
+ canGrant: true,
+ },
+ });
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ maker: {
+ computer: {
+ status,
+ permissionGuideStatus,
+ driverIcon: vi.fn().mockResolvedValue({ iconDataUrl: null }),
+ startPermissionAppDrag: vi.fn(),
+ finishPermissionAppDrag: vi.fn(),
+ cancelPermissionGrant: vi.fn().mockResolvedValue({ cancelled: true }),
+ onPermissionGuideStatusChanged: vi.fn(() => () => undefined),
+ },
+ },
+ },
+ });
+
+ render(createElement(ComputerPermissionGuideWindow));
+
+ expect(await screen.findByText('Drag Computer Use into Screen Recording')).toBeTruthy();
+ expect(permissionGuideStatus).toHaveBeenCalledOnce();
+ expect(status).not.toHaveBeenCalled();
+ });
+
+ it('requires Main to confirm a copied app row before entering the turn-on state', async () => {
+ vi.useFakeTimers();
+ const startPermissionAppDrag = vi.fn();
+ const copiedDragResults = [false, true];
+ const finishPermissionAppDrag = vi.fn(async (didCopy: boolean) => (
+ didCopy ? copiedDragResults.shift() ?? false : false
+ ));
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ maker: {
+ computer: {
+ permissionGuideStatus: vi.fn(() => new Promise(() => undefined)),
+ startPermissionAppDrag,
+ finishPermissionAppDrag,
+ cancelPermissionGrant: vi.fn().mockResolvedValue({ cancelled: true }),
+ },
+ },
+ },
+ });
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
+ drawImage: vi.fn(),
+ } as unknown as CanvasRenderingContext2D);
+ vi.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockReturnValue('data:image/png;base64,test');
+
+ render(createElement(ComputerPermissionGuideWindow));
+ expect(screen.getByText('Open computer automation')).toBeTruthy();
+ const image = document.querySelector('img');
+ expect(image).not.toBeNull();
+ Object.defineProperties(image!, {
+ complete: { configurable: true, value: true },
+ naturalWidth: { configurable: true, value: 96 },
+ naturalHeight: { configurable: true, value: 96 },
+ });
+
+ fireEvent.dragStart(screen.getByRole('button', { name: 'Computer Use' }), {
+ dataTransfer: { effectAllowed: 'none' },
+ });
+ expect(startPermissionAppDrag).toHaveBeenCalledOnce();
+ expect(screen.getByText('Dragging Computer Use')).toBeTruthy();
+
+ act(() => vi.advanceTimersByTime(PERMISSION_APP_DRAG_UI_FALLBACK_MS));
+
+ expect(screen.queryByText('Dragging Computer Use')).toBeNull();
+ expect(screen.getByText('Drag Computer Use into Accessibility')).toBeTruthy();
+
+ const retryButton = screen.getByRole('button', { name: /Computer Use/ });
+ expect(retryButton).toHaveProperty('draggable', true);
+ fireEvent.dragStart(retryButton, {
+ dataTransfer: { effectAllowed: 'none' },
+ });
+
+ expect(startPermissionAppDrag).toHaveBeenCalledTimes(2);
+ expect(screen.getByText('Dragging Computer Use')).toBeTruthy();
+
+ fireEvent.dragEnd(retryButton, {
+ dataTransfer: { dropEffect: 'none' },
+ });
+ expect(finishPermissionAppDrag).toHaveBeenLastCalledWith(false);
+ expect(screen.getByText('Drag Computer Use into Accessibility')).toBeTruthy();
+
+ fireEvent.dragStart(retryButton, {
+ dataTransfer: { effectAllowed: 'none' },
+ });
+ fireEvent.dragEnd(retryButton, {
+ dataTransfer: { dropEffect: 'copy' },
+ });
+ expect(finishPermissionAppDrag).toHaveBeenLastCalledWith(true);
+ await act(async () => Promise.resolve());
+ expect(screen.getByText('Drag Computer Use into Accessibility')).toBeTruthy();
+
+ fireEvent.dragStart(retryButton, {
+ dataTransfer: { effectAllowed: 'none' },
+ });
+ fireEvent.dragEnd(retryButton, {
+ dataTransfer: { dropEffect: 'copy' },
+ });
+ await act(async () => Promise.resolve());
+ expect(screen.getByText('Turn on Computer Use in Accessibility')).toBeTruthy();
+ });
+});
+
+describe('resolveComputerPermissionGuideStep', () => {
+ it('starts with Accessibility', () => {
+ expect(resolveComputerPermissionGuideStep({
+ platform: 'macos',
+ required: true,
+ status: 'missing',
+ accessibility: 'missing',
+ screenRecording: 'missing',
+ screenRecordingCapturable: 'missing',
+ canGrant: true,
+ })).toBe('accessibility');
+ });
+
+ it('moves to Screen Recording after Accessibility is granted', () => {
+ expect(resolveComputerPermissionGuideStep({
+ platform: 'macos',
+ required: true,
+ status: 'missing',
+ accessibility: 'granted',
+ screenRecording: 'granted',
+ screenRecordingCapturable: 'missing',
+ canGrant: true,
+ })).toBe('screen-recording');
+ });
+
+ it('completes only after both permissions are usable', () => {
+ expect(resolveComputerPermissionGuideStep({
+ platform: 'macos',
+ required: true,
+ status: 'granted',
+ accessibility: 'granted',
+ screenRecording: 'granted',
+ screenRecordingCapturable: 'granted',
+ canGrant: true,
+ })).toBe('complete');
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/computerPermissionFlow.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/computerPermissionFlow.test.ts
new file mode 100644
index 0000000000..df8f8393d8
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/computerPermissionFlow.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getComputerPermissionSwitchChecked,
+ isComputerPermissionPreflightInconclusive,
+ isComputerPermissionReady,
+ shouldStartComputerPermissionGuide,
+} from '../computerPermissionFlow';
+
+function status(
+ accessibility: ComputerDriverPermissionState['accessibility'],
+ screenRecording: ComputerDriverPermissionState['screenRecording'],
+): ComputerDriverStatus {
+ const granted = accessibility === 'granted' && screenRecording === 'granted';
+ return {
+ installed: true,
+ executablePath: '/tmp/cua-driver',
+ version: 'test',
+ daemonRunning: true,
+ installCommand: 'test',
+ docsUrl: 'https://cua.ai/docs/cua-driver',
+ permissionState: {
+ platform: 'macos',
+ required: true,
+ status: granted ? 'granted' : 'missing',
+ accessibility,
+ screenRecording,
+ screenRecordingCapturable: screenRecording,
+ canGrant: true,
+ },
+ };
+}
+
+describe('computer permission flow', () => {
+ it('skips onboarding when the preflight snapshot is already ready', () => {
+ const ready = status('granted', 'granted');
+
+ expect(isComputerPermissionReady(ready)).toBe(true);
+ expect(shouldStartComputerPermissionGuide(true, ready)).toBe(false);
+ });
+
+ it('starts onboarding when either permission is still missing', () => {
+ expect(shouldStartComputerPermissionGuide(
+ true,
+ status('missing', 'missing'),
+ )).toBe(true);
+ expect(shouldStartComputerPermissionGuide(
+ true,
+ status('granted', 'missing'),
+ )).toBe(true);
+ });
+
+ it('does not start onboarding when passive preflight is inconclusive', () => {
+ const missing = status('missing', 'missing');
+ const unknown: ComputerDriverStatus = {
+ ...missing,
+ permissionState: {
+ ...missing.permissionState!,
+ status: 'unknown',
+ },
+ };
+
+ expect(isComputerPermissionReady(null)).toBe(false);
+ expect(isComputerPermissionReady(unknown)).toBe(false);
+ expect(isComputerPermissionPreflightInconclusive(unknown)).toBe(true);
+ expect(isComputerPermissionPreflightInconclusive(missing)).toBe(false);
+ expect(isComputerPermissionPreflightInconclusive(null)).toBe(false);
+ expect(shouldStartComputerPermissionGuide(true, unknown)).toBe(false);
+ expect(shouldStartComputerPermissionGuide(true, null)).toBe(false);
+ });
+
+ it('treats a loaded status without platform permissions as ready', () => {
+ const { permissionState: _permissionState, ...withoutPermissionState } =
+ status('granted', 'granted');
+
+ expect(isComputerPermissionReady(withoutPermissionState)).toBe(true);
+ });
+
+ it('never starts onboarding while disabling the feature', () => {
+ expect(shouldStartComputerPermissionGuide(
+ false,
+ status('missing', 'missing'),
+ )).toBe(false);
+ });
+
+ it('keeps persisted opt-in visible independently from runtime readiness', () => {
+ expect(getComputerPermissionSwitchChecked(true, false, false)).toBe(true);
+ expect(getComputerPermissionSwitchChecked(false, false, true)).toBe(false);
+ expect(getComputerPermissionSwitchChecked(false, true, true)).toBe(true);
+ expect(getComputerPermissionSwitchChecked(true, true, false)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts b/apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts
new file mode 100644
index 0000000000..eb3c568f89
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts
@@ -0,0 +1,31 @@
+/** Whether the current runtime permission snapshot is sufficient for use. */
+export function isComputerPermissionReady(status: ComputerDriverStatus | null): boolean {
+ if (status === null) return false;
+ const permissionState = status.permissionState;
+ return !permissionState?.required || permissionState.status === 'granted';
+}
+
+/** Whether passive preflight could not establish the current permission state. */
+export function isComputerPermissionPreflightInconclusive(
+ status: ComputerDriverStatus | null,
+): boolean {
+ return status?.permissionState?.required === true
+ && status.permissionState.status === 'unknown';
+}
+
+/** Start onboarding only after preflight proves at least one permission is missing. */
+export function shouldStartComputerPermissionGuide(
+ enabling: boolean,
+ status: ComputerDriverStatus | null,
+): boolean {
+ return enabling && status?.permissionState?.status === 'missing';
+}
+
+/** Keep persisted opt-in separate from whether the runtime is currently ready. */
+export function getComputerPermissionSwitchChecked(
+ enabled: boolean,
+ togglePending: boolean,
+ enableIntent: boolean,
+): boolean {
+ return togglePending ? enableIntent : enabled;
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 88cdc40be1..a1fd0e1e68 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1730,6 +1730,15 @@
"directControl": {
"title": "Computer automation",
"description": "Let agents inspect windows, read UI, click, and type",
+ "status": {
+ "ready": "Ready to use",
+ "needsPermission": "Needs system access",
+ "notInstalled": "Driver not installed",
+ "disabled": "Turned off",
+ "checking": "Checking access…",
+ "setup": "Set up access",
+ "version": "CUA Driver {{version}}"
+ },
"toggleAria": "Toggle direct computer control",
"driverInfo": "Computer automation is powered by the open-source CUA Driver. It runs locally to read the screen and perform actions such as clicking and typing.",
"openSourceProject": "View open-source project",
@@ -1747,14 +1756,25 @@
"cancel": "Not now"
},
"permissionGuide": {
- "title": "Waiting for system permissions",
- "description": "In System Settings, grant the permissions below to CuaDriver (look for the app matching the icon on the left). This will continue automatically once everything is granted.",
- "waiting": "Pending"
+ "waiting": "Waiting for you",
+ "step": "Open computer automation",
+ "completeEyebrow": "Permissions complete",
+ "dragTitle": "Drag CuaDriver into {{permission}}",
+ "turnOnAppTitle": "Turn on CuaDriver in {{permission}}",
+ "dragHint": "Drag",
+ "draggingTitle": "Dragging CuaDriver",
+ "draggingHint": "Drop into {{permission}}",
+ "appName": "CuaDriver",
+ "turnOnTitle": "Turn on {{permission}}",
+ "turnOnDescription": "Turn on this permission in System Settings. Cindy will continue automatically.",
+ "readyTitle": "Computer Use is ready",
+ "readyDescription": "Cindy can now operate this computer when you ask."
},
"permissions": {
- "macosHint": "macOS requires core Accessibility and Screen Recording permissions for Cua Driver. During actual use, the system may still show additional confirmations for a target app or a specific action.",
- "accessibilityLabel": "CuaDriver Accessibility",
- "screenRecordingLabel": "CuaDriver Screen Recording",
+ "title": "System access",
+ "macosHint": "Computer Use needs Accessibility and Screen Recording. During actual use, macOS may still show additional confirmations for a target app or action.",
+ "accessibilityLabel": "Accessibility",
+ "screenRecordingLabel": "Screen Recording",
"grant": "Grant",
"accessibility": "Accessibility: {{status}}",
"screenRecording": "Screen Recording: {{status}}",
@@ -1766,6 +1786,8 @@
"openAccessibility": "Open Accessibility settings",
"openScreenRecording": "Open Screen Recording settings",
"recheck": "Recheck",
+ "moreDetails": "More details",
+ "hideDetails": "Hide details",
"windowsHint": "Windows does not require extra system permissions. Keep the target app visible on the active desktop while the agent works.",
"linuxHint": "Linux does not use macOS TCC permissions; make sure the current desktop session allows window inspection and input automation."
},
@@ -1788,9 +1810,10 @@
"disabled": "Direct computer control disabled",
"toggleFailed": "Failed to toggle direct computer control",
"installFailed": "Failed to install cua-driver",
- "permissionFailed": "cua-driver permissions are not complete",
- "permissionPending": "Finish Cua Driver system permissions and this will enable automatically",
+ "permissionFailed": "Computer Use permissions are not complete",
+ "permissionPending": "Finish the two system permissions, then return here and click Recheck",
"permissionSettingsOpened": "System permission settings opened. After granting, come back and click \"Recheck\".",
+ "permissionSettingsMonitoring": "System permission settings opened. Finish the permissions and the status will update automatically.",
"openPermissionSettingsFailed": "Failed to open system permission settings"
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 66fa2d5e08..a5303a8f74 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1729,6 +1729,15 @@
"directControl": {
"title": "自動操作コンピュータ",
"description": "エージェントがウィンドウを調べ、UI を読み取り、クリックや入力を実行できます",
+ "status": {
+ "ready": "使用できます",
+ "needsPermission": "システム権限が必要です",
+ "notInstalled": "ドライバー未インストール",
+ "disabled": "オフ",
+ "checking": "権限を確認中…",
+ "setup": "権限を設定",
+ "version": "CUA Driver {{version}}"
+ },
"toggleAria": "コンピュータの直接操作を切り替える",
"driverInfo": "コンピュータ自動操作はオープンソースの CUA Driver で提供されます。ローカルで動作し、画面の読み取りやクリック、入力などを行います。",
"openSourceProject": "オープンソースプロジェクトを見る",
@@ -1746,14 +1755,25 @@
"cancel": "後で"
},
"permissionGuide": {
- "title": "システム権限の許可を待っています",
- "description": "システム設定で CuaDriver に以下の権限を許可してください(権限リストで左のアイコンのアプリを探してください)。すべて許可されると自動的に続行します。",
- "waiting": "許可待ち"
+ "waiting": "操作待ち",
+ "step": "コンピュータ操作を有効にする",
+ "completeEyebrow": "権限の設定完了",
+ "dragTitle": "CuaDriver を「{{permission}}」にドラッグ",
+ "turnOnAppTitle": "「{{permission}}」で CuaDriver をオンにする",
+ "dragHint": "ドラッグ",
+ "draggingTitle": "CuaDriver をドラッグ中",
+ "draggingHint": "「{{permission}}」の一覧にドロップ",
+ "appName": "CuaDriver",
+ "turnOnTitle": "「{{permission}}」をオンにする",
+ "turnOnDescription": "システム設定でこの権限をオンにしてください。Cindy が自動的に続行します。",
+ "readyTitle": "Computer Use の準備ができました",
+ "readyDescription": "必要なときに Cindy がこのコンピュータを操作できます。"
},
"permissions": {
- "macosHint": "macOS では Cua Driver に「アクセシビリティ」と「画面収録」の基本権限が必要です。実際の使用中には、対象アプリや具体的な操作ごとに追加の確認が表示されることがあります。",
- "accessibilityLabel": "CuaDriver アクセシビリティ",
- "screenRecordingLabel": "CuaDriver 画面収録",
+ "title": "システム権限",
+ "macosHint": "コンピュータ操作には「アクセシビリティ」と「画面収録」が必要です。実際の使用中には、対象アプリや操作ごとに追加確認が表示されることがあります。",
+ "accessibilityLabel": "アクセシビリティ",
+ "screenRecordingLabel": "画面収録",
"grant": "許可する",
"accessibility": "アクセシビリティ:{{status}}",
"screenRecording": "画面収録:{{status}}",
@@ -1765,6 +1785,8 @@
"openAccessibility": "アクセシビリティ設定を開く",
"openScreenRecording": "画面収録設定を開く",
"recheck": "再確認",
+ "moreDetails": "詳細情報",
+ "hideDetails": "詳細を閉じる",
"windowsHint": "Windows では追加のシステム権限は不要です。agent が作業している間は、対象アプリを現在のアクティブなデスクトップ上で表示したままにしてください。",
"linuxHint": "Linux では macOS の TCC 権限は使いません。現在のデスクトップセッションでウィンドウ取得と入力自動化が許可されていることを確認してください。"
},
@@ -1787,9 +1809,10 @@
"disabled": "コンピュータの直接操作を無効にしました",
"toggleFailed": "コンピュータの直接操作の切り替えに失敗しました",
"installFailed": "cua-driver のインストールに失敗しました",
- "permissionFailed": "cua-driver の権限付与が完了していません",
- "permissionPending": "Cua Driver のシステム権限を完了すると、ここが自動で有効になります",
+ "permissionFailed": "コンピュータ操作の権限が完了していません",
+ "permissionPending": "2つのシステム権限を許可したら、ここに戻って「再確認」を押してください",
"permissionSettingsOpened": "システム権限設定を開きました。許可が完了したら、ここに戻って「再チェック」を押してください。",
+ "permissionSettingsMonitoring": "システムの権限設定を開きました。権限を付与すると、状態は自動的に更新されます。",
"openPermissionSettingsFailed": "システム権限設定を開けませんでした"
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 6644848abd..e092085a9a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1729,6 +1729,15 @@
"directControl": {
"title": "자동 조작 컴퓨터",
"description": "에이전트가 창을 검사하고 UI를 읽고 클릭하거나 입력할 수 있습니다",
+ "status": {
+ "ready": "사용할 수 있음",
+ "needsPermission": "시스템 권한 필요",
+ "notInstalled": "드라이버가 설치되지 않음",
+ "disabled": "꺼짐",
+ "checking": "권한 확인 중…",
+ "setup": "권한 설정",
+ "version": "CUA Driver {{version}}"
+ },
"toggleAria": "컴퓨터 직접 제어 전환",
"driverInfo": "컴퓨터 자동 조작은 오픈 소스 CUA Driver로 제공됩니다. 로컬에서 실행되어 화면을 읽고 클릭, 입력 등의 작업을 수행합니다.",
"openSourceProject": "오픈 소스 프로젝트 보기",
@@ -1746,14 +1755,25 @@
"cancel": "나중에"
},
"permissionGuide": {
- "title": "시스템 권한 허용 대기 중",
- "description": "시스템 설정에서 CuaDriver에 아래 권한을 허용해 주세요(권한 목록에서 왼쪽 아이콘과 같은 앱을 찾으세요). 모두 허용되면 자동으로 계속됩니다.",
- "waiting": "허용 대기"
+ "waiting": "켜기 대기",
+ "step": "컴퓨터 자동화 켜기",
+ "completeEyebrow": "권한 설정 완료",
+ "dragTitle": "CuaDriver를 {{permission}}으로 드래그",
+ "turnOnAppTitle": "{{permission}}에서 CuaDriver 켜기",
+ "dragHint": "드래그",
+ "draggingTitle": "CuaDriver 드래그 중",
+ "draggingHint": "{{permission}} 목록에 놓으세요",
+ "appName": "CuaDriver",
+ "turnOnTitle": "{{permission}} 켜기",
+ "turnOnDescription": "시스템 설정에서 이 권한을 켜세요. Cindy가 자동으로 계속합니다.",
+ "readyTitle": "Computer Use 준비 완료",
+ "readyDescription": "이제 요청할 때 Cindy가 이 컴퓨터를 조작할 수 있습니다."
},
"permissions": {
- "macosHint": "macOS에서는 Cua Driver에 손쉬운 사용 및 화면 기록 기본 권한이 필요합니다. 실제 사용 중에는 대상 앱이나 특정 동작에 대해 추가 확인이 표시될 수 있습니다.",
- "accessibilityLabel": "CuaDriver 손쉬운 사용",
- "screenRecordingLabel": "CuaDriver 화면 기록",
+ "title": "시스템 권한",
+ "macosHint": "컴퓨터 사용에는 손쉬운 사용 및 화면 기록 권한이 필요합니다. 실제 사용 중에는 대상 앱이나 동작에 대한 추가 확인이 표시될 수 있습니다.",
+ "accessibilityLabel": "손쉬운 사용",
+ "screenRecordingLabel": "화면 기록",
"grant": "허용",
"accessibility": "손쉬운 사용: {{status}}",
"screenRecording": "화면 기록: {{status}}",
@@ -1765,6 +1785,8 @@
"openAccessibility": "손쉬운 사용 설정 열기",
"openScreenRecording": "화면 기록 설정 열기",
"recheck": "다시 확인",
+ "moreDetails": "자세한 설명",
+ "hideDetails": "설명 접기",
"windowsHint": "Windows에서는 추가 시스템 권한이 필요하지 않습니다. 에이전트가 작업하는 동안 대상 앱을 현재 활성 데스크톱에 보이도록 유지하세요.",
"linuxHint": "Linux에서는 macOS TCC 권한을 사용하지 않습니다. 현재 데스크톱 세션에서 창 검사와 입력 자동화가 허용되는지 확인하세요."
},
@@ -1787,9 +1809,10 @@
"disabled": "컴퓨터 직접 제어 비활성화됨",
"toggleFailed": "컴퓨터 직접 제어 전환 실패",
"installFailed": "cua-driver 설치 실패",
- "permissionFailed": "cua-driver 권한 부여가 완료되지 않았습니다",
- "permissionPending": "Cua Driver 시스템 권한을 완료하면 여기에서 자동으로 활성화됩니다",
+ "permissionFailed": "컴퓨터 사용 권한이 완료되지 않았습니다",
+ "permissionPending": "두 시스템 권한을 허용한 후 여기로 돌아와 다시 확인을 누르세요",
"permissionSettingsOpened": "시스템 권한 설정을 열었습니다. 권한 부여를 마친 뒤 여기로 돌아와 \"다시 확인\"을 눌러 주세요.",
+ "permissionSettingsMonitoring": "시스템 권한 설정을 열었습니다. 권한 부여를 마치면 상태가 자동으로 업데이트됩니다.",
"openPermissionSettingsFailed": "시스템 권한 설정을 열지 못했습니다"
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 35ad748fd8..f8d9a74b07 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1729,6 +1729,15 @@
"directControl": {
"title": "自动操作电脑",
"description": "让 agent 检查窗口、读取界面并点击或输入",
+ "status": {
+ "ready": "可以使用",
+ "needsPermission": "需要系统授权",
+ "notInstalled": "尚未安装驱动",
+ "disabled": "已关闭",
+ "checking": "正在检查权限…",
+ "setup": "设置权限",
+ "version": "CUA Driver {{version}}"
+ },
"toggleAria": "切换直接操作电脑",
"driverInfo": "自动操作电脑由开源 CUA Driver 提供,运行在本机,用于读取屏幕并执行点击、输入等操作。",
"openSourceProject": "查看开源项目",
@@ -1746,14 +1755,25 @@
"cancel": "稍后再说"
},
"permissionGuide": {
- "title": "等待系统授权",
- "description": "请在系统设置中为 CuaDriver 开启以下权限(在权限列表里找到左侧图标对应的 App)。全部开启后这里会自动继续。",
- "waiting": "待授权"
+ "waiting": "等待你开启",
+ "step": "打开自动操作电脑",
+ "completeEyebrow": "权限已完成",
+ "dragTitle": "将 CuaDriver 拖入「{{permission}}」",
+ "turnOnAppTitle": "在「{{permission}}」中打开 CuaDriver",
+ "dragHint": "拖拽",
+ "draggingTitle": "正在拖拽 CuaDriver",
+ "draggingHint": "放入「{{permission}}」列表",
+ "appName": "CuaDriver",
+ "turnOnTitle": "打开「{{permission}}」",
+ "turnOnDescription": "请在系统设置中打开这项权限。开启后,Cindy 会自动继续。",
+ "readyTitle": "Computer Use 已就绪",
+ "readyDescription": "现在可以让 Cindy 操作这台电脑。"
},
"permissions": {
- "macosHint": "macOS 需要为 Cua Driver 授予「辅助功能」和「屏幕录制」核心权限。实际使用时,系统还可能按目标 App 或具体动作弹出额外确认。",
- "accessibilityLabel": "CuaDriver 辅助功能",
- "screenRecordingLabel": "CuaDriver 屏幕录制",
+ "title": "系统授权",
+ "macosHint": "电脑使用需要「辅助功能」和「屏幕录制」。实际使用时,macOS 仍可能按目标 App 或具体动作弹出额外确认。",
+ "accessibilityLabel": "辅助功能",
+ "screenRecordingLabel": "屏幕录制",
"grant": "去授权",
"accessibility": "辅助功能:{{status}}",
"screenRecording": "屏幕录制:{{status}}",
@@ -1765,6 +1785,8 @@
"openAccessibility": "打开辅助功能设置",
"openScreenRecording": "打开屏幕录制设置",
"recheck": "重新检查",
+ "moreDetails": "更多说明",
+ "hideDetails": "收起说明",
"windowsHint": "Windows 不需要额外系统授权。使用时请保持目标应用在当前活动桌面中可见,agent 会接管前台操作。",
"linuxHint": "Linux 不需要 macOS 的 TCC 授权;请确保当前桌面会话允许窗口读取和输入自动化。"
},
@@ -1787,9 +1809,10 @@
"disabled": "已禁用直接电脑控制",
"toggleFailed": "切换直接电脑控制失败",
"installFailed": "cua-driver 安装失败",
- "permissionFailed": "cua-driver 授权未完成",
- "permissionPending": "请完成 Cua Driver 的系统授权,然后此处会自动启用",
+ "permissionFailed": "电脑使用权限未完成",
+ "permissionPending": "请完成这两项系统权限,然后回到这里点击“重新检查”",
"permissionSettingsOpened": "已打开系统权限设置。完成授权后,请回到这里点“重新检查”。",
+ "permissionSettingsMonitoring": "已打开系统权限设置。完成授权后,状态会自动更新。",
"openPermissionSettingsFailed": "无法打开系统权限设置"
}
}
diff --git a/apps/desktop/src/renderer/index.tsx b/apps/desktop/src/renderer/index.tsx
index c3c641e058..6951afca07 100644
--- a/apps/desktop/src/renderer/index.tsx
+++ b/apps/desktop/src/renderer/index.tsx
@@ -69,17 +69,23 @@ void bootstrapGitSafetySettingsFromMain();
const view = new URLSearchParams(window.location.search).get('view');
const isVoiceInputOverlay = view === 'voice-input-overlay';
const isVoiceInputDictionaryToast = view === 'voice-input-dictionary-toast';
+const isComputerPermissionGuide = view === 'computer-permission-guide';
+const isComputerPermissionBackdrop = view === 'computer-permission-backdrop';
+const isComputerPermissionView = isComputerPermissionGuide || isComputerPermissionBackdrop;
document.documentElement.dataset.platform = window.electronAPI.platform;
if (isVoiceInputOverlay || isVoiceInputDictionaryToast) {
document.documentElement.dataset.voiceInputOverlay = 'true';
}
+if (isComputerPermissionView) {
+ document.documentElement.dataset.computerPermissionOverlay = 'true';
+}
// Windows-only: emulate macOS `acceptFirstMouse: false` so a click that
// activates the window from background doesn't fall through to any in-page
// target. Skip on voice-input overlay windows — those are click-through
// popups (focusable:false, acceptFirstMouse:true by design).
const disposeSwallowActivationClick =
- !isVoiceInputOverlay && !isVoiceInputDictionaryToast
+ !isVoiceInputOverlay && !isVoiceInputDictionaryToast && !isComputerPermissionView
? installSwallowActivationClick({
window,
platform: window.electronAPI?.platform ?? '',
@@ -122,6 +128,32 @@ if (!rootElement) {
const root = createRoot(rootElement);
void (async () => {
+ if (isComputerPermissionBackdrop) {
+ const { ComputerPermissionBackdrop } = await import(
+ './components/settings/ComputerPermissionGuideWindow'
+ );
+ root.render(
+ <ThemeProvider>
+ <ComputerPermissionBackdrop />
+ </ThemeProvider>,
+ );
+ return;
+ }
+
+ if (isComputerPermissionGuide) {
+ const { ComputerPermissionGuideWindow } = await import(
+ './components/settings/ComputerPermissionGuideWindow'
+ );
+ root.render(
+ <ThemeProvider>
+ <LocaleProvider>
+ <ComputerPermissionGuideWindow />
+ </LocaleProvider>
+ </ThemeProvider>,
+ );
+ return;
+ }
+
if (isVoiceInputDictionaryToast) {
const { VoiceInputDictionaryToast } = await import('./voice-input/VoiceInputDictionaryToast');
root.render(
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index b0aa4c33ab..413071ffa7 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -187,6 +187,12 @@
[data-theme='cindy-dark'][data-splash-active] .bg-content-area {
background: transparent;
}
+
+ html[data-computer-permission-overlay='true'],
+ html[data-computer-permission-overlay='true'] body,
+ html[data-computer-permission-overlay='true'] #root {
+ background: transparent;
+ }
}
/* 按 <html lang> 切换 CJK 字体栈 —— 同一汉字在中/日/韩字体中字形不同
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index c8fa20375f..455bac683a 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -250,8 +250,10 @@ interface ComputerDriverStatus {
interface ComputerDriverStatusOptions {
includeDoctor?: boolean;
forcePermissionProbe?: boolean;
+ skipPermissionProbe?: boolean;
freshPermissionProbe?: boolean;
bypassPermissionProbeCache?: boolean;
+ passivePermissionProbeOnly?: boolean;
}
type ComputerDriverPermissionPlatform = 'macos' | 'windows' | 'linux' | 'unsupported';
@@ -4364,9 +4366,19 @@ interface ElectronAPI {
computer: {
status: (options?: ComputerDriverStatusOptions) => Promise<ComputerDriverStatus>;
installDriver: () => Promise<ComputerDriverInstallResult>;
- grantPermissions: () => Promise<ComputerDriverPermissionGrantResult>;
+ grantPermissions: (options?: {
+ showGuide?: boolean;
+ openedPaneUrl?: string;
+ }) => Promise<ComputerDriverPermissionGrantResult>;
driverIcon: () => Promise<{ iconDataUrl: string | null }>;
+ permissionGuideStatus: () => Promise<ComputerDriverStatus>;
+ startPermissionAppDrag: (iconDataUrl: string) => void;
+ finishPermissionAppDrag: (didCopy: boolean) => Promise<boolean>;
cancelPermissionGrant: () => Promise<{ cancelled: boolean }>;
+ onPermissionGuideCancelled: (callback: () => void) => () => void;
+ onPermissionGuideStatusChanged: (
+ callback: (status: ComputerDriverStatus) => void,
+ ) => () => void;
checkUpdate: () => Promise<ComputerDriverUpdateCheck>;
updateDriver: (opts?: { joinOnly?: boolean }) => Promise<ComputerDriverInstallResult>;
onUpdateProgress: (