import { execSync } from 'node:child_process'; /** * macOS 权限引导工具。 * * 设计参考:UI-TARS-desktop/apps/ui-tars/src/main/utils/systemPermissions.ts * * 核心原则: * 1. 实际调用系统 API(CGEventPost / CGDisplayCreateImage)的是 cu-helperd 守护进程, * 因此 macOS TCC 权限数据库中记录的是 cu-helperd 二进制的权限状态。 * 2. 系统原生权限弹窗(AXIsProcessTrustedWithOptions / CGRequestScreenCaptureAccess) * 由 cu-helperd 在首次需要时自动触发,但这种弹窗有局限性: * - 只在权限状态为 "not determined" 时弹出一次 * - 用户如果点了"拒绝",之后不会再弹,必须手动去系统设置 * - 从后台进程触发弹窗有时会被其他窗口遮挡 * 3. 因此本模块的核心策略是:**主动探测 + 自动打开设置 + 明确文字引导**, * 参考 UI-TARS 的 openSystemPreferences() 做法,不管什么状态,只要权限缺失 * 就直接打开系统设置页面,让用户一目了然该勾选什么。 */ /** * 打开 macOS 系统设置 → 隐私与安全性 → 辅助功能 页面。 */ export function openAccessibilitySettings(): void { if (process.platform !== 'darwin') return; try { execSync( 'open "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"', { stdio: 'ignore', timeout: 5000 }, ); } catch { // fallback:如果系统设置URL scheme失效,尝试直接打开系统设置应用 try { execSync('open "x-apple.systempreferences:"', { stdio: 'ignore', timeout: 5000 }); } catch {} } } /** * 打开 macOS 系统设置 → 隐私与安全性 → 屏幕录制 页面。 */ export function openScreenCaptureSettings(): void { if (process.platform !== 'darwin') return; try { execSync( 'open "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"', { stdio: 'ignore', timeout: 5000 }, ); } catch { try { execSync('open "x-apple.systempreferences:"', { stdio: 'ignore', timeout: 5000 }); } catch {} } } /** * 检测当前是否运行在一个 .app bundle 内部(即 Tauri/Electron 打包后的生产环境)。 */ export function isRunningInAppBundle(): boolean { if (process.platform !== 'darwin') return false; return process.execPath.includes('.app/Contents/MacOS/'); } /** * 获取权限引导信息中应该告诉用户查找哪个应用名。 * * **只有两种情况**,因为实际调用系统 API 的进程只有两种: * · 打包进 .app 时,TCC 记的是宿主 App → 让用户找 "KakadeAI" * · 其余(CLI / dev)由 cu-helperd 守护进程调用 → 让用户找 "cu-helperd" * * 这里曾有第三种「终端应用名(Terminal/iTerm/Warp…)」分支,服务于已移除的 * nut-js transport —— 它在主进程内直接调 CGEvent,于是 TCC 记的是终端。 * nut-js 移除后那条分支恒为误导(会让用户去给终端授权,而真正需要授权的是 * cu-helperd),所以一并删除。 */ export function getPermissionTargetName(): string { return isRunningInAppBundle() ? 'KakadeAI' : 'cu-helperd'; } /** * 权限状态(与 cu-helperd protocol 中的 PermissionState 对齐)。 */ export type MacPermissionState = 'granted' | 'not_determined' | 'denied'; export interface PermissionCheckResult { accessibility: MacPermissionState; screenCapture: MacPermissionState; /** 是否有缺失的权限需要用户授权 */ hasMissingPermissions: boolean; /** 缺失的权限列表描述 */ missingPermissions: Array<'accessibility' | 'screenCapture'>; /** * 这次**查询本身**失败了(守护进程报错、认证失败、响应形状不认识)。 * * 与「查到了、结果是没授权」是两件完全不同的事,必须分开:前者要修的是我们自己, * 后者才该去引导用户点系统设置。混为一谈的代价是真实发生过的 —— 见 * `parsePermissionResponse` 的注释。 */ queryFailed: boolean; } /** * 解析 cu-helperd 返回的 permissions 响应,生成标准化的检查结果。 * 支持多种响应格式: * - 原生 wire 格式:{ response: { Ok: { accessibility, screenCapture } } } * - 高层 service 格式:{ ok: true, data: { accessibility, screenCapture } } * - 纯数据格式:{ accessibility, screenCapture } */ const PERMISSION_STATES = new Set(['granted', 'denied', 'not_determined']); /** * ⚠️ **「查不到」绝不能当成「没授权」。** * * 这里以前从任意形状的响应里挖 `accessibility` / `screenCapture`,挖不到就默认 * `not_determined`,于是**错误信封被当成了权限答案**:守护进程返回 * `{response:{Err:{code:'authentication_failed'}}}`,两个字段自然都不存在,函数愉快地 * 报告「两个权限都缺失」,调用方打印一整屏「请去系统设置授权」。 * * 而它确实一直在返回这个错误 —— `probePermissions` 把 32 字节的二进制配对令牌按 * utf8 读,HMAC 必然对不上。也就是说这个自检**从未成功过一次**,却始终显得像是在工作。 * 真实代价:用户被反复引去检查根本没问题的系统设置,而真正的故障在完全不同的地方; * 排查中先后错怪了 cdhash、用户的授权配置和另一处改动。 * * 修法不是把那次读改对就完了 —— 那只堵住一个诱因。判据本身必须能表达「我不知道」。 */ export function parsePermissionResponse(permResp: any): PermissionCheckResult { const unknown = (): PermissionCheckResult => ({ accessibility: 'not_determined', screenCapture: 'not_determined', // 查询失败时**不**声称有权限缺失:那会把用户引向系统设置,而问题不在那儿。 hasMissingPermissions: false, missingPermissions: [], queryFailed: true, }); // 明确的错误信封:直接判定为「查询失败」,不去它身上找权限字段。 if (permResp?.response?.Err || permResp?.ok === false) return unknown(); let perms: any = permResp; if (permResp?.response?.Ok) { perms = permResp.response.Ok; // 原生 wire 格式 } else if (permResp?.ok && permResp?.data) { perms = permResp.data; // 高层 service 格式(diagnostics/request 返回) } // 两个字段**都**认不出来 = 这根本不是一份权限响应,而不是「两个权限都没授权」。 const knownAccessibility = PERMISSION_STATES.has(perms?.accessibility); const knownScreenCapture = PERMISSION_STATES.has(perms?.screenCapture); if (!knownAccessibility && !knownScreenCapture) return unknown(); const accessibility: MacPermissionState = knownAccessibility ? perms.accessibility : 'not_determined'; const screenCapture: MacPermissionState = knownScreenCapture ? perms.screenCapture : 'not_determined'; const missingPermissions: Array<'accessibility' | 'screenCapture'> = []; if (accessibility !== 'granted') missingPermissions.push('accessibility'); if (screenCapture !== 'granted') missingPermissions.push('screenCapture'); return { accessibility, screenCapture, hasMissingPermissions: missingPermissions.length > 0, missingPermissions, queryFailed: false, }; } /** * 打印醒目的权限缺失提示,并自动打开系统设置。 * 参考 UI-TARS 的 wrapWithWarning + openSystemPreferences 模式。 * * 引导文案遵循三层结构: * 1. 为什么需要这些权限(让用户理解价值,减少抵触) * 2. 具体要做什么(分步骤、目标明确) * 3. 遇到问题怎么办(找不到应用、已勾选仍不行等常见坑) */ export function showPermissionGuidance(result: PermissionCheckResult): void { if (process.platform !== 'darwin') return; if (!result.hasMissingPermissions) return; const targetName = getPermissionTargetName(); const lines: string[] = []; const inAppBundle = isRunningInAppBundle(); lines.push(''); lines.push('╔════════════════════════════════════════════════════════════════╗'); lines.push('║ ⚠️ 需要授予 macOS 系统权限才能使用「电脑操控」功能 ║'); lines.push('╚════════════════════════════════════════════════════════════════╝'); lines.push(''); // 第 1 层:需要什么权限、为什么需要 lines.push('—— 需要授予的权限 ——'); lines.push(''); if (result.missingPermissions.includes('accessibility')) { lines.push(' 🖱️ 辅助功能(Accessibility)'); lines.push(' 用途:控制鼠标移动/点击、模拟键盘输入、拖拽操作'); lines.push(' 没有它:AI 无法操作你的鼠标和键盘'); lines.push(''); } if (result.missingPermissions.includes('screenCapture')) { lines.push(' 📷 屏幕录制(Screen Recording)'); lines.push(' 用途:读取屏幕画面,让 AI "看到" 你当前的界面'); lines.push(' 没有它:AI 看不到屏幕,无法判断该点哪里、该做什么'); lines.push(''); } lines.push('👉 已为你自动打开「系统设置 → 隐私与安全性」对应页面'); lines.push(''); // 第 2 层:具体操作步骤 lines.push('—— 授权步骤(只需 4 步,约 30 秒)——'); lines.push(''); const permLabels: string[] = []; if (result.missingPermissions.includes('accessibility')) permLabels.push('辅助功能'); if (result.missingPermissions.includes('screenCapture')) permLabels.push('屏幕录制'); lines.push(` 1. 在系统设置中,依次点击「隐私与安全性」→「${permLabels[0]}」`); if (permLabels.length > 1) { lines.push(` (两个权限都需要授权,授权完一个再切换到另一个)`); } lines.push(' 2. 点击左下角 🔒 锁形图标,输入开机密码解锁'); lines.push(` 3. 在右侧应用列表中找到「${targetName}」,打开它的开关`); if (!inAppBundle) { lines.push(' ⓘ 这里要授权的是 cu-helperd(守护进程),不是你的终端 ——'); lines.push(' 真正调用系统 API 的是它,所以 macOS 记录的也是它的权限。'); } lines.push(' 4. 完成后回到这里,继续让 AI 操作即可'); lines.push(''); // 第 3 层:常见问题 / 排错 lines.push('—— 常见问题 ——'); lines.push(''); lines.push(' Q: 列表里找不到「' + targetName + '」怎么办?'); lines.push(' A: 点击列表下方的 ➕ 按钮,手动添加' + targetName); if (!inAppBundle) { lines.push(' (cu-helperd 随包位于 vendor/computer-use/-/ 目录下;'); lines.push(' 源码构建时在 computer-use-native/target/release/)'); lines.push(' 也可以先让 AI 执行一次操作,cu-helperd 会主动弹出系统授权请求。'); } lines.push(''); lines.push(' Q: 已经勾选了,但还是提示权限不足?'); lines.push(' A: 把开关先关掉再重新打开一次,macOS 有时需要重新确认。'); lines.push(' 如果仍然不行,重启应用后再试。'); lines.push(''); lines.push(' Q: 这些权限安全吗?会不会泄露隐私?'); lines.push(' A: 权限只在本地使用,屏幕画面和操作都不会上传到任何服务器。'); lines.push(' AI 模型只接收截图用于分析操作,不做存储。'); lines.push(''); // 输出到 stderr,确保在 TUI/CLI 中都能看到 for (const line of lines) { process.stderr.write(line + '\n'); } // 自动打开对应的设置页面(优先屏幕录制,因为最直观) if (result.missingPermissions.includes('screenCapture')) { try { openScreenCaptureSettings(); } catch { process.stderr.write(' ⚠️ 未能自动打开系统设置,请手动打开:系统设置 → 隐私与安全性 → 屏幕录制\n'); } } if (result.missingPermissions.includes('accessibility')) { try { openAccessibilitySettings(); } catch { process.stderr.write(' ⚠️ 未能自动打开系统设置,请手动打开:系统设置 → 隐私与安全性 → 辅助功能\n'); } } } /** * 一次性完成权限检查:解析响应、打印引导、打开设置。 * 返回 true 表示权限齐全可以继续,false 表示需要用户授权。 */ export function ensureMacPermissions(permResp: any): boolean { if (process.platform !== 'darwin') return true; const result = parsePermissionResponse(permResp); if (result.queryFailed) { // 查询本身失败:说一句,然后**闭嘴**。既不打印权限引导(问题不在用户的设置里), // 也不阻断(真正的动作走的是另一条通道,它自己会如实报错)。 process.stderr.write( '[computer-use] 权限自检未能取得结果(守护进程没有返回可识别的权限响应)。' + '这是自检本身的问题,不代表权限缺失;实际操作若受阻会单独报错。\n', ); return true; } if (result.hasMissingPermissions) { showPermissionGuidance(result); return false; } return true; }