Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): macOS TCC 文件夹权限声明缺失及 EPERM 静默拒绝无提示 (#302)
ganlingyao30faefba05fe
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 50ce3de66a..0bb6c5d924 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -1099,6 +1099,14 @@ const config: ForgeConfig = {// Windows / Linux 完全忽略此字段。extendInfo: {NSMicrophoneUsageDescription: 'This app needs access to the microphone for voice input.',+ // agent 会话中访问受 TCC 保护的目录(桌面/文稿/下载)时,macOS 需要这些声明才能向+ // 用户展示授权弹窗;缺失时系统直接静默拒绝,不弹窗。+ NSDesktopFolderUsageDescription:+ "Cindy's AI agent needs access to read and write files on your Desktop.",+ NSDocumentsFolderUsageDescription:+ "Cindy's AI agent needs access to read and write files in your Documents folder.",+ NSDownloadsFolderUsageDescription:+ "Cindy's AI agent needs access to read and write files in your Downloads folder.",// 智能通讯录导入: 经 osascript 向"通讯录"发 Apple Events(只读拉取)。// 缺这条声明 macOS 会不弹授权窗直接拒绝(-1743), 用户只看到静默失败。NSAppleEventsUsageDescription:@@ -1157,6 +1165,12 @@ const config: ForgeConfig = {// the packaged app correctly in Privacy & Security > Microphone.extendHelperInfo: {NSMicrophoneUsageDescription: 'This app needs access to the microphone for voice input.',+ NSDesktopFolderUsageDescription:+ "Cindy's AI agent needs access to read and write files on your Desktop.",+ NSDocumentsFolderUsageDescription:+ "Cindy's AI agent needs access to read and write files in your Documents folder.",+ NSDownloadsFolderUsageDescription:+ "Cindy's AI agent needs access to read and write files in your Downloads folder.",},// chat-data-localization F1:drizzle SQL migration 文件需要随包发出,// main 通过 process.resourcesPath/drizzle 读取。dev 模式 main 走源码路径,diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.tsindex 8b36791786..f9e50b3345 100644--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts@@ -55,6 +55,8 @@ const mocks = vi.hoisted(() => ({readLayoutPreferences: vi.fn<() => Map<number, AgentIslandLayoutPreference>>(() => new Map()),writeLayoutPreference: vi.fn(),tapWindowBroadcast: vi.fn(),+ showMessageBox: vi.fn(),+ openExternal: vi.fn(),}));vi.mock('electron', () => {@@ -67,7 +69,9 @@ vi.mock('electron', () => {fromWebContents: mocks.browserWindowFromWebContents,getAllWindows: mocks.browserWindowGetAllWindows,},+ dialog: { showMessageBox: mocks.showMessageBox },ipcMain: { handle: mocks.ipcHandle },+ shell: { openExternal: mocks.openExternal },screen: {getPrimaryDisplay: mocks.getPrimaryDisplay,getDisplayMatching: mocks.getDisplayMatching,@@ -89,6 +93,8 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({tapWindowBroadcast: mocks.tapWindowBroadcast,}));+import { resetEpermGuidanceForTest } from '../../file-access/permissions.js';+beforeEach(() => {mocks.getSessionRowSnapshot.mockReset();mocks.getSessionRowSnapshot.mockResolvedValue(null);@@ -117,6 +123,11 @@ beforeEach(() => {mocks.readLayoutPreferences.mockReturnValue(new Map());mocks.writeLayoutPreference.mockReset();mocks.tapWindowBroadcast.mockReset();+ mocks.showMessageBox.mockReset();+ mocks.showMessageBox.mockResolvedValue({ response: 1, checkboxChecked: false });+ mocks.openExternal.mockReset();+ mocks.openExternal.mockResolvedValue(undefined);+ resetEpermGuidanceForTest();});type NativePublishCall = [@@ -1433,6 +1444,138 @@ describe('AgentIslandService native publishing', () => {});});+ it('shows localized macOS protected-folder guidance once per folder kind', async () => {+ const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');+ try {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn(() => true);+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish },+ });+ const event: AgentEvent = {+ type: 'tool_result_full',+ source: 'claude-code',+ data: {+ toolUseId: 'tool-1',+ fullText: `EPERM: operation not permitted, open '${process.env.HOME}/Desktop/blocked.txt'`,+ },+ };++ service.handleAgentEvent({ sessionId: 's1', agentKind: 'claude-code' }, event);+ await vi.waitFor(() => expect(mocks.showMessageBox).toHaveBeenCalledTimes(1));+ service.handleAgentEvent({ sessionId: 's2', agentKind: 'claude-code' }, event);+ await Promise.resolve();++ expect(mocks.showMessageBox).toHaveBeenCalledTimes(1);+ expect(mocks.showMessageBox).toHaveBeenCalledWith(expect.objectContaining({+ type: 'warning',+ title: 'macOS folder access denied',+ message: 'Cindy cannot access your Desktop folder',+ buttons: ['Open System Settings', 'Cancel'],+ }));+ expect(mocks.openExternal).not.toHaveBeenCalled();+ } finally {+ platformSpy.mockRestore();+ }+ });++ it('opens macOS folder settings from a guidance dialog attached to the main window', async () => {+ const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');+ try {+ const { AgentIslandService } = await import('../service.js');+ const mainWindow = { isDestroyed: () => false } as unknown as BrowserWindow;+ mocks.showMessageBox.mockResolvedValue({ response: 0, checkboxChecked: false });+ const service = new AgentIslandService({+ getMainWindow: () => mainWindow,+ nativeHost: { failed: false, publish: vi.fn(() => true) },+ });++ service.handleAgentEvent(+ { sessionId: 's1', agentKind: 'claude-code' },+ {+ type: 'tool_result_full',+ source: 'claude-code',+ data: {+ toolUseId: 'tool-1',+ fullText: `EPERM: operation not permitted, open '${process.env.HOME}/Documents/blocked.txt'`,+ isError: true,+ },+ },+ );++ await vi.waitFor(() => expect(mocks.openExternal).toHaveBeenCalledWith(+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_DocumentsFolder',+ ));+ expect(mocks.showMessageBox).toHaveBeenCalledWith(+ mainWindow,+ expect.objectContaining({ message: 'Cindy cannot access your Documents folder' }),+ );+ } finally {+ platformSpy.mockRestore();+ }+ });++ it('does not show protected-folder guidance for an explicitly successful tool result', async () => {+ const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');+ try {+ const { AgentIslandService } = await import('../service.js');+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish: vi.fn(() => true) },+ });++ service.handleAgentEvent(+ { sessionId: 's1', agentKind: 'codex' },+ {+ type: 'tool_result_full',+ source: 'codex',+ data: {+ toolUseId: 'tool-1',+ fullText: `Log excerpt: EPERM under '${process.env.HOME}/Desktop/blocked.txt'`,+ isError: false,+ },+ },+ );+ await Promise.resolve();++ expect(mocks.showMessageBox).not.toHaveBeenCalled();+ expect(mocks.openExternal).not.toHaveBeenCalled();+ } finally {+ platformSpy.mockRestore();+ }+ });++ it('does not show macOS protected-folder guidance on other platforms', async () => {+ const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');+ try {+ const { AgentIslandService } = await import('../service.js');+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish: vi.fn(() => true) },+ });++ service.handleAgentEvent(+ { sessionId: 's1', agentKind: 'claude-code' },+ {+ type: 'tool_result_full',+ source: 'claude-code',+ data: {+ toolUseId: 'tool-1',+ fullText: `EPERM: operation not permitted, open '${process.env.HOME}/Desktop/blocked.txt'`,+ isError: true,+ },+ },+ );+ await Promise.resolve();++ expect(mocks.showMessageBox).not.toHaveBeenCalled();+ expect(mocks.openExternal).not.toHaveBeenCalled();+ } finally {+ platformSpy.mockRestore();+ }+ });+it('clears unread completion attention when focused windows report visible sessions', async () => {const { AgentIslandService } = await import('../service.js');const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex 12b6f17a3f..d23707a477 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -102,6 +102,13 @@ import {} from './layoutPreferenceStore.js';import { throwIpcError } from '../utils/ipcValidate.js';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';+import {+ detectProtectedFolderEperm,+ openFolderPrivacySettings,+ releaseEpermGuidance,+ shouldShowEpermGuidance,+ type ProtectedFolderKind,+} from '../file-access/permissions.js';import { SessionActivityRelay } from './sessionActivityRelay.js';const log = createLogger('agent-island');@@ -608,6 +615,20 @@ export class AgentIslandService {this.clearCompletedSilencedRunForNewActivity(hydrated.sessionId);this.deferredCompletions.delete(hydrated.sessionId);}+ if (process.platform === 'darwin' && event.type === 'tool_result_full') {+ const data = event.data as { fullText?: string; isError?: boolean } | undefined;+ // Codex marks successful results explicitly; Claude Code currently omits isError.+ // Skip only a known success so Claude Code EPERM output still receives guidance.+ const folderKind = data?.isError !== false && data?.fullText+ ? detectProtectedFolderEperm(data.fullText)+ : null;+ if (folderKind && shouldShowEpermGuidance(folderKind)) {+ void this.showFolderEpermGuidance(folderKind).catch((error: unknown) => {+ releaseEpermGuidance(folderKind);+ log.warn('failed to show folder access guidance', { kind: folderKind, error });+ });+ }+ }const suppressCompletionAttention = this.isCompletionEventSilenced(hydrated.sessionId, event);const changed = applyAgentIslandEvent(this.state, hydrated, event, now, {suppressCompletionAttention,@@ -883,6 +904,29 @@ export class AgentIslandService {};}+ private async showFolderEpermGuidance(kind: ProtectedFolderKind): Promise<void> {+ const folderName = t(`fileAccess.epermGuidance.folderNames.${kind.toLowerCase()}`);+ const options = {+ type: 'warning' as const,+ title: t('fileAccess.epermGuidance.title'),+ message: t('fileAccess.epermGuidance.message').replace('{{folder}}', folderName),+ detail: t('fileAccess.epermGuidance.detail'),+ buttons: [+ t('fileAccess.epermGuidance.openSystemSettings'),+ t('fileAccess.epermGuidance.cancel'),+ ],+ defaultId: 0,+ cancelId: 1,+ };+ const mainWindow = this.deps.getMainWindow();+ const result = mainWindow && !mainWindow.isDestroyed()+ ? await dialog.showMessageBox(mainWindow, options)+ : await dialog.showMessageBox(options);+ if (result.response === 0) {+ await openFolderPrivacySettings(kind);+ }+ }+private ensureMetadata(sessionId: string): void {const cached = this.metadataCache.get(sessionId);if (this.metadataLoading.has(sessionId) || (cached && !isPlaceholderSessionTitle(cached.title))) return;diff --git a/apps/desktop/src/main/file-access/__tests__/permissions.test.ts b/apps/desktop/src/main/file-access/__tests__/permissions.test.tsnew file mode 100644index 0000000000..1e24ccbe2a--- /dev/null+++ b/apps/desktop/src/main/file-access/__tests__/permissions.test.ts@@ -0,0 +1,102 @@+import { homedir } from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ openExternal: vi.fn<(...args: unknown[]) => Promise<void>>(() => Promise.resolve()),+}));++vi.mock('electron', () => ({+ shell: { openExternal: mocks.openExternal },+}));++import {+ detectProtectedFolderEperm,+ openFolderPrivacySettings,+ releaseEpermGuidance,+ resetEpermGuidanceForTest,+ shouldShowEpermGuidance,+} from '../permissions.js';++beforeEach(() => {+ mocks.openExternal.mockReset();+ mocks.openExternal.mockResolvedValue(undefined);+ resetEpermGuidanceForTest();+});++afterEach(() => {+ resetEpermGuidanceForTest();+});++describe('protected folder permission guidance', () => {+ it.each([+ ['Desktop', 'Desktop'],+ ['Documents', 'Documents'],+ ['Downloads', 'Downloads'],+ ] as const)('detects macOS EPERM for %s', (folderName, expected) => {+ expect(+ detectProtectedFolderEperm(+ `Error: EPERM: operation not permitted, open '${path.join(homedir(), folderName, 'blocked.txt')}'`,+ 'darwin',+ ),+ ).toBe(expected);+ });++ it('detects an exact protected folder path followed by a quote', () => {+ expect(+ detectProtectedFolderEperm(+ `Error: EPERM: operation not permitted, scandir '${path.join(homedir(), 'Desktop')}'`,+ 'darwin',+ ),+ ).toBe('Desktop');+ });++ it.each(['DesktopBackup', 'Documents (Archive)', 'Downloads-old'])(+ 'does not classify a similarly prefixed folder: %s',+ (folderName) => {+ expect(+ detectProtectedFolderEperm(+ `Error: EPERM: operation not permitted, open '${path.join(homedir(), folderName, 'blocked.txt')}'`,+ 'darwin',+ ),+ ).toBeNull();+ },+ );++ it('does not classify non-macOS or unrelated failures', () => {+ const failure = `Error: EPERM: operation not permitted, open '${path.join(homedir(), 'Desktop', 'blocked.txt')}'`;+ expect(detectProtectedFolderEperm(failure, 'linux')).toBeNull();+ expect(detectProtectedFolderEperm(failure, 'win32')).toBeNull();+ expect(+ detectProtectedFolderEperm(+ `ENOENT: '${path.join(homedir(), 'Desktop', 'missing.txt')}'`,+ 'darwin',+ ),+ ).toBeNull();+ expect(+ detectProtectedFolderEperm(+ `EPERM: '${path.join(homedir(), 'Pictures', 'blocked.txt')}'`,+ 'darwin',+ ),+ ).toBeNull();+ });++ it('deduplicates each folder for the app process and supports release', () => {+ expect(shouldShowEpermGuidance('Desktop')).toBe(true);+ expect(shouldShowEpermGuidance('Desktop')).toBe(false);+ expect(shouldShowEpermGuidance('Documents')).toBe(true);+ releaseEpermGuidance('Desktop');+ expect(shouldShowEpermGuidance('Desktop')).toBe(true);+ });++ it('opens the matching macOS privacy pane only on macOS', async () => {+ await openFolderPrivacySettings('Desktop', 'darwin');+ expect(mocks.openExternal).toHaveBeenCalledWith(+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_DesktopFolder',+ );++ mocks.openExternal.mockClear();+ await openFolderPrivacySettings('Desktop', 'linux');+ expect(mocks.openExternal).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/file-access/permissions.ts b/apps/desktop/src/main/file-access/permissions.tsnew file mode 100644index 0000000000..926b68d672--- /dev/null+++ b/apps/desktop/src/main/file-access/permissions.ts@@ -0,0 +1,86 @@+import { homedir } from 'node:os';+import path from 'node:path';+import { shell } from 'electron';++import { createLogger } from '../logger.js';++const log = createLogger('file-access-permissions');++export type ProtectedFolderKind = 'Desktop' | 'Documents' | 'Downloads';++const PROTECTED_PATHS: Record<ProtectedFolderKind, string> = {+ Desktop: path.join(homedir(), 'Desktop'),+ Documents: path.join(homedir(), 'Documents'),+ Downloads: path.join(homedir(), 'Downloads'),+};++const TCC_SETTINGS_URLS: Record<ProtectedFolderKind, string> = {+ Desktop:+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_DesktopFolder',+ Documents:+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_DocumentsFolder',+ Downloads:+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_DownloadsFolder',+};++const EPERM_PATTERNS = /operation not permitted|eperm/i;++function containsPathOrDescendant(text: string, folderPath: string): boolean {+ let index = text.indexOf(folderPath);+ while (index !== -1) {+ const nextCharacter = text[index + folderPath.length];+ if (+ nextCharacter === undefined ||+ nextCharacter === '/' ||+ nextCharacter === '\\' ||+ nextCharacter === "'" ||+ nextCharacter === '"'+ ) {+ return true;+ }+ index = text.indexOf(folderPath, index + folderPath.length);+ }+ return false;+}++/** Returns the folder kind if a macOS tool result contains EPERM + a protected path. */+export function detectProtectedFolderEperm(+ text: string,+ platform: NodeJS.Platform = process.platform,+): ProtectedFolderKind | null {+ if (platform !== 'darwin' || !EPERM_PATTERNS.test(text)) return null;+ for (const [kind, folderPath] of Object.entries(PROTECTED_PATHS) as [ProtectedFolderKind, string][]) {+ if (containsPathOrDescendant(text, folderPath)) return kind;+ }+ return null;+}++// Shared across agent sessions for this app process. Restarting the app resets it.+const guidanceShownFor = new Set<ProtectedFolderKind>();++/** Opens the matching macOS System Settings panel. Does nothing on other platforms. */+export async function openFolderPrivacySettings(+ kind: ProtectedFolderKind,+ platform: NodeJS.Platform = process.platform,+): Promise<void> {+ if (platform !== 'darwin') return;+ const url = TCC_SETTINGS_URLS[kind];+ log.info('opening folder privacy settings', { kind, url });+ await shell.openExternal(url);+}++/** Reserves the process-lifetime guidance slot for a folder kind. */+export function shouldShowEpermGuidance(kind: ProtectedFolderKind): boolean {+ if (guidanceShownFor.has(kind)) return false;+ guidanceShownFor.add(kind);+ return true;+}++/** Allows a retry when the native dialog failed before it could be shown. */+export function releaseEpermGuidance(kind: ProtectedFolderKind): void {+ guidanceShownFor.delete(kind);+}++export function resetEpermGuidanceForTest(): void {+ guidanceShownFor.clear();+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 57ff69fa77..9f28fc3e46 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6825,5 +6825,19 @@"codexStateSkipped": "Codex has not been initialized on this machine, so session state was not fully restored. Run any Codex session once, then continuing will work.","workdirKeyInexact": "The chosen directory path is too long to place transcripts; downgraded to chat history only."}+ },+ "fileAccess": {+ "epermGuidance": {+ "title": "macOS folder access denied",+ "message": "Cindy cannot access your {{folder}} folder",+ "detail": "macOS denied access. Open System Settings to grant permission, then run your agent command again.",+ "openSystemSettings": "Open System Settings",+ "cancel": "Cancel",+ "folderNames": {+ "desktop": "Desktop",+ "documents": "Documents",+ "downloads": "Downloads"+ }+ }}}diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex c0282f79c7..7d6154f931 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6814,5 +6814,19 @@"codexStateSkipped": "このマシンでは Codex がまだ初期化されていないため、セッション状態は完全には復元されていません。Codex セッションを一度実行すれば続行できるようになります。","workdirKeyInexact": "選択したディレクトリのパスが長すぎるためトランスクリプトを配置できず、チャット履歴のみに切り替えました。"}+ },+ "fileAccess": {+ "epermGuidance": {+ "title": "macOS のフォルダアクセスが拒否されました",+ "message": "Cindy は「{{folder}}」フォルダにアクセスできません",+ "detail": "macOS によりアクセスが拒否されました。「システム設定」を開いて権限を付与し、Agent のコマンドをもう一度実行してください。",+ "openSystemSettings": "システム設定を開く",+ "cancel": "キャンセル",+ "folderNames": {+ "desktop": "デスクトップ",+ "documents": "書類",+ "downloads": "ダウンロード"+ }+ }}}diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex a210a8f368..e8cf1b3c4c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6814,5 +6814,19 @@"codexStateSkipped": "이 컴퓨터에서 Codex가 아직 초기화되지 않아 세션 상태가 완전히 복원되지 않았습니다. Codex 세션을 한 번 실행하면 이어갈 수 있습니다.","workdirKeyInexact": "선택한 디렉터리 경로가 너무 길어 트랜스크립트를 배치할 수 없어 채팅 기록만 가져왔습니다."}+ },+ "fileAccess": {+ "epermGuidance": {+ "title": "macOS 폴더 접근이 거부되었습니다",+ "message": "Cindy가 {{folder}} 폴더에 접근할 수 없습니다",+ "detail": "macOS에서 접근을 거부했습니다. 시스템 설정을 열어 권한을 부여한 다음 Agent 명령을 다시 실행하세요.",+ "openSystemSettings": "시스템 설정 열기",+ "cancel": "취소",+ "folderNames": {+ "desktop": "데스크탑",+ "documents": "문서",+ "downloads": "다운로드"+ }+ }}}diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 4f01e3e04c..7574c2c686 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6814,5 +6814,19 @@"codexStateSkipped": "本机尚未初始化 Codex 环境,会话状态未完全恢复;先运行一次 Codex 会话后即可正常续聊。","workdirKeyInexact": "所选目录路径过长,无法放置历史转录,已降级为仅聊天记录。"}+ },+ "fileAccess": {+ "epermGuidance": {+ "title": "macOS 文件夹访问被拒绝",+ "message": "Cindy 无法访问你的“{{folder}}”文件夹",+ "detail": "macOS 拒绝了访问。请打开“系统设置”授予权限,然后重新运行 Agent 命令。",+ "openSystemSettings": "打开系统设置",+ "cancel": "取消",+ "folderNames": {+ "desktop": "桌面",+ "documents": "文稿",+ "downloads": "下载"+ }+ }}}