🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(desktop): guide macOS privacy permissions with a drag panel inside System Settings (#20932)
Innei58151f622449
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 996efa8cfd4..42a9d12f826 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -77,6 +77,7 @@"@lobechat/device-sandbox": "workspace:*","@lobechat/electron-client-ipc": "workspace:*","@lobechat/electron-mac-notifications": "workspace:*",+ "@lobechat/electron-mac-permission-guide": "workspace:*","@lobechat/electron-server-ipc": "workspace:*","@lobechat/file-loaders": "workspace:*","@lobechat/heterogeneous-agents": "workspace:*",diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yamlindex 16b0ddc7935..aa0edf84c9c 100644--- a/apps/desktop/pnpm-lock.yaml+++ b/apps/desktop/pnpm-lock.yaml@@ -88,6 +88,9 @@ importers:'@lobechat/electron-mac-notifications':specifier: workspace:*version: link:../../packages/electron-mac-notifications+ '@lobechat/electron-mac-permission-guide':+ specifier: workspace:*+ version: link:../../packages/electron-mac-permission-guide'@lobechat/electron-server-ipc':specifier: workspace:*version: link:../../packages/electron-server-ipc@@ -430,6 +433,19 @@ importers:specifier: ^12.4.0version: 12.4.0+ ../../packages/electron-mac-permission-guide:+ dependencies:+ '@lobechat/napi-loader':+ specifier: workspace:*+ version: link:../napi-loader+ devDependencies:+ node-addon-api:+ specifier: ^8.5.0+ version: 8.9.2+ node-gyp:+ specifier: ^12.4.0+ version: 12.4.0+../../packages/electron-server-ipc:dependencies:debug:diff --git a/apps/desktop/pnpm-workspace.yaml b/apps/desktop/pnpm-workspace.yamlindex f32c98c2ad1..3247d3cc647 100644--- a/apps/desktop/pnpm-workspace.yaml+++ b/apps/desktop/pnpm-workspace.yaml@@ -10,6 +10,7 @@ packages:- '../../packages/electron-server-ipc'- '../../packages/electron-client-ipc'- '../../packages/electron-mac-notifications'+ - '../../packages/electron-mac-permission-guide'- '../../packages/napi-loader'- '../../packages/file-loaders'- '../../packages/html-artifact'diff --git a/apps/desktop/resources/locales/en/dialog.json b/apps/desktop/resources/locales/en/dialog.jsonindex 18829abb766..2d9ee6efa40 100644--- a/apps/desktop/resources/locales/en/dialog.json+++ b/apps/desktop/resources/locales/en/dialog.json@@ -15,6 +15,26 @@"fullDiskAccess.openSettings": "Open Settings","fullDiskAccess.skip": "Later","fullDiskAccess.title": "Full Disk Access Required",+ "permissionGuide.close": "Close",+ "permissionGuide.confirming.subtitle": "Use Touch ID or your password",+ "permissionGuide.confirming.title": "Confirm in the system dialog",+ "permissionGuide.granted.subtitle": "Returning to the app…",+ "permissionGuide.granted.title": "{{permission}} is on",+ "permissionGuide.missing.action": "Open Settings",+ "permissionGuide.missing.subtitle": "Reopen it to continue",+ "permissionGuide.missing.title": "Settings not found",+ "permissionGuide.offPane.action": "Go Back",+ "permissionGuide.offPane.subtitle": "Go back to {{permission}}",+ "permissionGuide.offPane.title": "You left this page",+ "permissionGuide.permission.accessibility": "Accessibility",+ "permissionGuide.permission.fullDisk": "Full Disk Access",+ "permissionGuide.permission.inputMonitoring": "Input Monitoring",+ "permissionGuide.permission.screen": "Screen Recording",+ "permissionGuide.relaunch.action": "Reopen",+ "permissionGuide.relaunch.subtitle": "Reopen the app to apply",+ "permissionGuide.retry.subtitle": "Cancelled · Drag again to retry",+ "permissionGuide.waiting.subtitle": "{{permission}} · Or turn on its switch",+ "permissionGuide.waiting.title": "Drag into the list above","screenCaptureAccess.cancel": "Later","screenCaptureAccess.detail": "Open System Settings, enable Screen Recording for LobeHub, then try Quick Composer again.","screenCaptureAccess.message": "Quick Composer needs Screen Recording permission before it can capture screenshots.",diff --git a/apps/desktop/resources/locales/zh-CN/dialog.json b/apps/desktop/resources/locales/zh-CN/dialog.jsonindex 51b8beb4df0..291ba32e229 100644--- a/apps/desktop/resources/locales/zh-CN/dialog.json+++ b/apps/desktop/resources/locales/zh-CN/dialog.json@@ -15,6 +15,26 @@"fullDiskAccess.openSettings": "打开设置","fullDiskAccess.skip": "稍后","fullDiskAccess.title": "需要完全磁盘访问权限",+ "permissionGuide.close": "关闭",+ "permissionGuide.confirming.subtitle": "使用触控 ID 或登录密码",+ "permissionGuide.confirming.title": "请在系统弹窗中确认",+ "permissionGuide.granted.subtitle": "正在回到应用…",+ "permissionGuide.granted.title": "{{permission}}已开启",+ "permissionGuide.missing.action": "打开设置",+ "permissionGuide.missing.subtitle": "重新打开后继续",+ "permissionGuide.missing.title": "未找到设置窗口",+ "permissionGuide.offPane.action": "返回",+ "permissionGuide.offPane.subtitle": "返回「{{permission}}」继续",+ "permissionGuide.offPane.title": "已离开授权页面",+ "permissionGuide.permission.accessibility": "辅助功能",+ "permissionGuide.permission.fullDisk": "完全磁盘访问权限",+ "permissionGuide.permission.inputMonitoring": "输入监控",+ "permissionGuide.permission.screen": "屏幕录制",+ "permissionGuide.relaunch.action": "重新打开",+ "permissionGuide.relaunch.subtitle": "重新打开应用后生效",+ "permissionGuide.retry.subtitle": "已取消 · 再拖一次即可",+ "permissionGuide.waiting.subtitle": "{{permission}} · 或打开已有开关",+ "permissionGuide.waiting.title": "拖到上方列表","screenCaptureAccess.cancel": "稍后","screenCaptureAccess.detail": "请打开系统设置,为 LobeHub 开启“屏幕录制”权限,然后再次尝试 Quick Composer。","screenCaptureAccess.message": "Quick Composer 需要“屏幕录制”权限后才能进行截图。",diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.tsindex 14241e29a49..b30388a145e 100644--- a/apps/desktop/src/main/controllers/SystemCtr.ts+++ b/apps/desktop/src/main/controllers/SystemCtr.ts@@ -94,7 +94,10 @@ export default class SystemController extends ControllerModule {}@IpcMethod()- requestAccessibilityAccess() {+ async requestAccessibilityAccess(): Promise<boolean> {+ if (await this.app.permissionGuide.open('accessibility')) {+ return getAccessibilityStatus() === 'granted';+ }return requestAccessibilityAccess();}@@ -136,6 +139,8 @@ export default class SystemController extends ControllerModule {return 'granted';}+ if (await this.app.permissionGuide.open('fullDisk')) return 'opened_settings';+const mainWindow = this.app.browserManager.getMainWindow()?.browserWindow;// Get localized strings@@ -181,11 +186,15 @@ export default class SystemController extends ControllerModule {@IpcMethod()async requestScreenAccess(): Promise<boolean> {+ if (await this.app.permissionGuide.open('screen')) {+ return getMediaAccessStatus('screen') === 'granted';+ }return requestScreenCaptureAccess();}@IpcMethod()async openFullDiskAccessSettings() {+ if (await this.app.permissionGuide.open('fullDisk')) return;return openFullDiskAccessSettings();}diff --git a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.tsindex 8d711053e6f..ddbb63784a5 100644--- a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts@@ -131,6 +131,10 @@ const mockGetDesktopBootstrapIdentity = vi.fn(() => ({userId: 'user_1',}));+const mockPermissionGuide = {+ open: vi.fn(async (_permission: string) => false),+};+const mockApp = {appStoragePath: '/mock/storage',browserManager: mockBrowserManager,@@ -138,6 +142,7 @@ const mockApp = {getDesktopBootstrapIdentity: mockGetDesktopBootstrapIdentity,})),i18n: mockI18n,+ permissionGuide: mockPermissionGuide,storeManager: mockStoreManager,} as unknown as App;@@ -153,6 +158,7 @@ describe('SystemController', () => {__resetMacPermissionsModuleCache();__setMacPermissionsModule(permissionsMock as any);fontListGetFonts2Mock.mockResolvedValue([]);+ mockPermissionGuide.open.mockResolvedValue(false);controller = new SystemController(mockApp);});@@ -258,6 +264,47 @@ describe('SystemController', () => {});});+ describe('permission drag guide', () => {+ it('should guide accessibility through the drag panel without pre-registering the app', async () => {+ mockPermissionGuide.open.mockResolvedValue(true);+ permissionsMock.getAuthStatus.mockReturnValue('denied');++ const result = await invokeIpc('system.requestAccessibilityAccess');++ expect(mockPermissionGuide.open).toHaveBeenCalledWith('accessibility');+ expect(permissionsMock.askForAccessibilityAccess).not.toHaveBeenCalled();+ expect(result).toBe(false);++ permissionsMock.getAuthStatus.mockReturnValue('authorized');+ });++ it('should guide screen recording without the system prompt', async () => {+ mockPermissionGuide.open.mockResolvedValue(true);+ permissionsMock.getAuthStatus.mockReturnValue('denied');++ await invokeIpc('system.requestScreenAccess');++ expect(mockPermissionGuide.open).toHaveBeenCalledWith('screen');+ expect(permissionsMock.askForScreenCaptureAccess).not.toHaveBeenCalled();++ permissionsMock.getAuthStatus.mockReturnValue('authorized');+ });++ it('should skip the Full Disk Access dialog when the guide opens', async () => {+ const { dialog } = await import('electron');+ mockPermissionGuide.open.mockResolvedValue(true);+ permissionsMock.getAuthStatus.mockReturnValue('denied');++ const result = await invokeIpc('system.promptFullDiskAccessIfNotGranted');++ expect(result).toBe('opened_settings');+ expect(mockPermissionGuide.open).toHaveBeenCalledWith('fullDisk');+ expect(dialog.showMessageBox).not.toHaveBeenCalled();++ permissionsMock.getAuthStatus.mockReturnValue('authorized');+ });+ });+describe('accessibility', () => {it('should request accessibility access on macOS', async () => {permissionsMock.getAuthStatus.mockReturnValue('authorized');diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.tsindex dabf64dae02..170561ece98 100644--- a/apps/desktop/src/main/core/App.ts+++ b/apps/desktop/src/main/core/App.ts@@ -25,6 +25,7 @@ import {runtimeEnvironmentBinaries,} from '@/modules/binaries';import { generateCliWrapper, getCliWrapperDir } from '@/modules/cliEmbedding';+import { PermissionGuide } from '@/modules/permissionGuide/PermissionGuide';import { ScreenCaptureManager } from '@/modules/screenCapture/ScreenCaptureManager';import { BUILD_CHANNEL, UPDATE_SERVER_URL } from '@/modules/updater/configs';import type { IServiceModule, ServiceLifecycle, ServiceModule } from '@/services';@@ -77,6 +78,7 @@ export class App {localFileProtocolManager: LocalFileProtocolManager;binaryManager: BinaryManager;screenCaptureManager: ScreenCaptureManager;+ permissionGuide: PermissionGuide;chromeFlags: string[] = ['OverlayScrollbar', 'FluentOverlayScrollbar', 'FluentScrollbar'];/**@@ -172,6 +174,7 @@ export class App {this.protocolManager = new ProtocolManager(this);this.binaryManager = new BinaryManager(this);this.screenCaptureManager = new ScreenCaptureManager(this);+ this.permissionGuide = new PermissionGuide(this);this.coreUpdateManager = new CoreUpdateManager(this);this.coreUpdateManager.initialize();diff --git a/apps/desktop/src/main/locales/default/dialog.ts b/apps/desktop/src/main/locales/default/dialog.tsindex f1d02a03d47..aa26a0f9f79 100644--- a/apps/desktop/src/main/locales/default/dialog.ts+++ b/apps/desktop/src/main/locales/default/dialog.ts@@ -16,6 +16,26 @@ const dialog = {'fullDiskAccess.openSettings': 'Open Settings','fullDiskAccess.skip': 'Later','fullDiskAccess.title': 'Full Disk Access Required',+ 'permissionGuide.close': 'Close',+ 'permissionGuide.confirming.subtitle': 'Use Touch ID or your password',+ 'permissionGuide.confirming.title': 'Confirm in the system dialog',+ 'permissionGuide.granted.subtitle': 'Returning to the app…',+ 'permissionGuide.granted.title': '{{permission}} is on',+ 'permissionGuide.missing.action': 'Open Settings',+ 'permissionGuide.missing.subtitle': 'Reopen it to continue',+ 'permissionGuide.missing.title': 'Settings not found',+ 'permissionGuide.offPane.action': 'Go Back',+ 'permissionGuide.offPane.subtitle': 'Go back to {{permission}}',+ 'permissionGuide.offPane.title': 'You left this page',+ 'permissionGuide.permission.accessibility': 'Accessibility',+ 'permissionGuide.permission.fullDisk': 'Full Disk Access',+ 'permissionGuide.permission.inputMonitoring': 'Input Monitoring',+ 'permissionGuide.permission.screen': 'Screen Recording',+ 'permissionGuide.relaunch.action': 'Reopen',+ 'permissionGuide.relaunch.subtitle': 'Reopen the app to apply',+ 'permissionGuide.retry.subtitle': 'Cancelled · Drag again to retry',+ 'permissionGuide.waiting.subtitle': '{{permission}} · Or turn on its switch',+ 'permissionGuide.waiting.title': 'Drag into the list above','screenCaptureAccess.cancel': 'Later','screenCaptureAccess.detail':'Open System Settings, enable Screen Recording for LobeHub, then try Quick Composer again.',diff --git a/apps/desktop/src/main/modules/permissionGuide/PermissionGuide.ts b/apps/desktop/src/main/modules/permissionGuide/PermissionGuide.tsnew file mode 100644index 00000000000..8eb194c68aa--- /dev/null+++ b/apps/desktop/src/main/modules/permissionGuide/PermissionGuide.ts@@ -0,0 +1,304 @@+import type { PermissionGuideStatus } from '@lobechat/electron-client-ipc';+import type * as GuideAddonModule from '@lobechat/electron-mac-permission-guide';+import type { PermissionGuideEvent } from '@lobechat/electron-mac-permission-guide';+import { app as electronApp, screen, shell } from 'electron';++import type { App } from '@/core/App';+import { createLogger } from '@/utils/logger';+import type { PermissionStatus } from '@/utils/permissions';+import {+ getAccessibilityStatus,+ getFullDiskAccessStatus,+ getInputMonitoringStatus,+ getScreenCaptureStatus,+} from '@/utils/permissions';+import * as electronIs from '@/utils/platform';++import type { GuidePhase } from './guideState';+import { buildGuideState } from './guideState';+import type { GuidedPermission } from './settingsPanes';+import { getAppBundlePath, getSettingsPaneUrl, getSettingsSidebarWidth } from './settingsPanes';++const logger = createLogger('modules:permissionGuide');++type GuideAddon = typeof GuideAddonModule;++export const POLL_INTERVAL_MS = 1000;+export const GRANTED_DISMISS_MS = 1200;+export const PROMPT_WAIT_MS = 4000;+export const PROMPT_SETTLE_MS = 1500;+export const TITLE_SETTLE_MS = 1000;++const STATUS_READERS: Record<GuidedPermission, () => PermissionStatus> = {+ accessibility: getAccessibilityStatus,+ fullDisk: getFullDiskAccessStatus,+ inputMonitoring: getInputMonitoringStatus,+ screen: getScreenCaptureStatus,+};++// Screen Recording only takes effect in a fresh process.+const RELAUNCH_REQUIRED = new Set<GuidedPermission>(['screen']);++const AWAITING_USER = new Set<GuidePhase>(['confirming', 'offPane', 'retry', 'waiting']);+const ACCEPTS_DROP = new Set<GuidePhase>(['retry', 'waiting']);++interface ActiveGuide {+ appPath: string;+ granted: boolean;+ lastTitle?: string;+ launchOrigin: { x: number; y: number };+ paneTitle?: string;+ permission: GuidedPermission;+ phase: GuidePhase;+ promptVisible: boolean;+ titleSettled: boolean;+}++export class PermissionGuide {+ private active?: ActiveGuide;+ private addon?: GuideAddon;+ private pollTimer?: ReturnType<typeof setInterval>;+ private phaseTimer?: ReturnType<typeof setTimeout>;+ private titleTimer?: ReturnType<typeof setTimeout>;+ private unsubscribe?: () => void;++ constructor(private readonly app: App) {}++ // `false` means the guide can't run here and the caller keeps its old flow.+ async open(permission: GuidedPermission): Promise<boolean> {+ if (!electronIs.macOS()) return false;+ if (this.isGranted(permission)) return true;++ const addon = await this.loadAddon();+ const appPath = getAppBundlePath(electronApp.getPath('exe'));+ if (!addon || !appPath) return false;++ this.close();+ this.active = {+ appPath,+ granted: false,+ launchOrigin: this.resolveLaunchOrigin(),+ permission,+ phase: 'waiting',+ promptVisible: false,+ titleSettled: false,+ };+ this.unsubscribe = addon.onGuideEvent((event) => this.handleEvent(event));+ this.pollTimer = setInterval(() => this.poll(), POLL_INTERVAL_MS);++ this.notify(permission, 'active');+ await this.openSettings(permission);+ this.render();+ logger.info(`[PermissionGuide] opened for ${permission}`);+ return true;+ }++ close() {+ clearInterval(this.pollTimer);+ clearTimeout(this.phaseTimer);+ clearTimeout(this.titleTimer);+ this.pollTimer = undefined;+ this.phaseTimer = undefined;+ this.titleTimer = undefined;+ this.unsubscribe?.();+ this.unsubscribe = undefined;+ const active = this.active;+ this.active = undefined;+ if (!active) return;+ this.addon?.hideGuide();+ if (!active.granted) this.notify(active.permission, 'dismissed');+ }++ private notify(permission: GuidedPermission, status: PermissionGuideStatus) {+ this.app.browserManager.broadcastToAllWindows('permissionGuideChanged', { permission, status });+ }++ // The panel flies out of the control the user just clicked; a request that+ // did not start from the main window flies out of the window's center.+ private resolveLaunchOrigin() {+ const cursor = screen.getCursorScreenPoint();+ const bounds = this.app.browserManager.getMainWindow()?.browserWindow?.getBounds();+ if (!bounds) return cursor;+ const insideWindow =+ cursor.x >= bounds.x &&+ cursor.x <= bounds.x + bounds.width &&+ cursor.y >= bounds.y &&+ cursor.y <= bounds.y + bounds.height;+ return insideWindow+ ? cursor+ : { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };+ }++ private isGranted(permission: GuidedPermission) {+ return STATUS_READERS[permission]() === 'granted';+ }++ private async openSettings(permission: GuidedPermission) {+ await shell.openExternal(getSettingsPaneUrl(permission));+ this.addon?.activateSettings();++ // The deep link needs a moment to switch panes; the title seen after that+ // is the one the user must stay on.+ clearTimeout(this.titleTimer);+ if (this.active) this.active.titleSettled = false;+ this.titleTimer = setTimeout(() => {+ if (!this.active) return;+ this.active.titleSettled = true;+ this.active.paneTitle = this.active.lastTitle;+ }, TITLE_SETTLE_MS);+ }++ private async loadAddon(): Promise<GuideAddon | undefined> {+ if (this.addon) return this.addon;+ try {+ const addon = await import('@lobechat/electron-mac-permission-guide');+ if (!addon.isSupported()) return undefined;+ this.addon = addon;+ return addon;+ } catch (error) {+ logger.warn('[PermissionGuide] native addon unavailable:', error);+ return undefined;+ }+ }++ private poll() {+ const active = this.active;+ if (!active || active.phase === 'granted' || active.phase === 'relaunch') return;+ if (!this.isGranted(active.permission)) return;++ clearInterval(this.pollTimer);+ this.pollTimer = undefined;+ active.granted = true;+ this.notify(active.permission, 'granted');+ logger.info(`[PermissionGuide] ${active.permission} granted`);++ if (RELAUNCH_REQUIRED.has(active.permission)) {+ this.setPhase('relaunch');+ return;+ }+ this.setPhase('granted');+ this.phaseTimer = setTimeout(() => {+ this.close();+ this.app.browserManager.showMainWindow();+ }, GRANTED_DISMISS_MS);+ }++ private settleConfirmation(fallback: GuidePhase) {+ const active = this.active;+ if (active?.phase !== 'confirming') return;+ if (this.isGranted(active.permission)) {+ this.poll();+ return;+ }+ this.setPhase(fallback);+ }++ private handleEvent(event: PermissionGuideEvent) {+ const active = this.active;+ if (!active) return;++ switch (event.type) {+ case 'close': {+ this.close();+ return;+ }+ case 'action': {+ this.handleAction(active);+ return;+ }+ case 'dragEnded': {+ if (!event.dropped || !ACCEPTS_DROP.has(active.phase)) return;+ this.setPhase('confirming');+ // Dropping an app that is already listed, or onto the wrong spot,+ // raises no prompt; return to the drag state instead of spinning.+ this.phaseTimer = setTimeout(() => {+ if (!this.active?.promptVisible) this.settleConfirmation('waiting');+ }, PROMPT_WAIT_MS);+ return;+ }+ case 'promptShown': {+ active.promptVisible = true;+ if (AWAITING_USER.has(active.phase)) this.setPhase('confirming');+ return;+ }+ case 'promptDismissed': {+ active.promptVisible = false;+ if (active.phase !== 'confirming') return;+ clearTimeout(this.phaseTimer);+ this.phaseTimer = setTimeout(() => this.settleConfirmation('retry'), PROMPT_SETTLE_MS);+ return;+ }+ case 'windowTitle': {+ active.lastTitle = event.title;+ if (!active.titleSettled) return;+ if (!active.paneTitle) {+ active.paneTitle = event.title;+ return;+ }+ if (event.title === active.paneTitle) {+ if (active.phase === 'offPane') this.setPhase('waiting');+ } else if (ACCEPTS_DROP.has(active.phase)) {+ this.setPhase('offPane');+ }+ return;+ }+ case 'navigationClicked': {+ if (active.lastTitle === undefined && ACCEPTS_DROP.has(active.phase)) {+ this.setPhase('offPane');+ }+ return;+ }+ case 'settingsLost': {+ if (AWAITING_USER.has(active.phase)) this.setPhase('missing');+ return;+ }+ case 'settingsFound': {+ if (active.phase === 'missing') this.setPhase('waiting');+ return;+ }+ }+ }++ private handleAction(active: ActiveGuide) {+ switch (active.phase) {+ case 'relaunch': {+ this.close();+ electronApp.relaunch();+ electronApp.exit(0);+ return;+ }+ case 'missing': {+ void this.openSettings(active.permission);+ return;+ }+ case 'offPane': {+ void this.openSettings(active.permission);+ this.setPhase('waiting');+ return;+ }+ }+ }++ private setPhase(phase: GuidePhase) {+ if (!this.active) return;+ clearTimeout(this.phaseTimer);+ this.phaseTimer = undefined;+ this.active.phase = phase;+ this.render();+ }++ private render() {+ if (!this.active || !this.addon) return;+ this.addon.showGuide(+ buildGuideState({+ appName: electronApp.getName(),+ appPath: this.active.appPath,+ launchOrigin: this.active.launchOrigin,+ permission: this.active.permission,+ phase: this.active.phase,+ sidebarWidth: getSettingsSidebarWidth(process.getSystemVersion()),+ t: this.app.i18n.ns('dialog'),+ }),+ );+ }+}diff --git a/apps/desktop/src/main/modules/permissionGuide/__tests__/PermissionGuide.test.ts b/apps/desktop/src/main/modules/permissionGuide/__tests__/PermissionGuide.test.tsnew file mode 100644index 00000000000..bd63570823d--- /dev/null+++ b/apps/desktop/src/main/modules/permissionGuide/__tests__/PermissionGuide.test.ts@@ -0,0 +1,312 @@+import type { PermissionGuideEvent } from '@lobechat/electron-mac-permission-guide';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import {+ GRANTED_DISMISS_MS,+ PermissionGuide,+ POLL_INTERVAL_MS,+ PROMPT_SETTLE_MS,+ PROMPT_WAIT_MS,+ TITLE_SETTLE_MS,+} from '../PermissionGuide';++const { addonMock, electronMock, emit, statusMock } = vi.hoisted(() => {+ const listeners = new Set<(event: any) => void>();+ return {+ addonMock: {+ activateSettings: vi.fn(),+ hideGuide: vi.fn(),+ isSupported: vi.fn(() => true),+ onGuideEvent: vi.fn((listener: (event: any) => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ }),+ showGuide: vi.fn((_state: Record<string, unknown>) => true),+ },+ electronMock: {+ app: {+ exit: vi.fn(),+ getName: vi.fn(() => 'LobeHub'),+ getPath: vi.fn(() => '/Applications/LobeHub.app/Contents/MacOS/LobeHub'),+ relaunch: vi.fn(),+ },+ screen: { getCursorScreenPoint: vi.fn(() => ({ x: 400, y: 300 })) },+ shell: { openExternal: vi.fn(async () => undefined) },+ },+ emit: (event: any) => listeners.forEach((listener) => listener(event)),+ statusMock: vi.fn(() => 'denied'),+ };+});++vi.mock('electron', () => electronMock);+vi.mock('@lobechat/electron-mac-permission-guide', () => addonMock);+vi.mock('@/utils/platform', () => ({ macOS: vi.fn(() => true) }));+vi.mock('@/utils/permissions', () => ({+ getAccessibilityStatus: statusMock,+ getFullDiskAccessStatus: statusMock,+ getInputMonitoringStatus: statusMock,+ getScreenCaptureStatus: statusMock,+}));++const showMainWindow = vi.fn();+const broadcastToAllWindows = vi.fn();+const mainWindowBounds = { height: 800, width: 1200, x: 100, y: 100 };+const mockApp = {+ browserManager: {+ broadcastToAllWindows,+ getMainWindow: () => ({ browserWindow: { getBounds: () => mainWindowBounds } }),+ showMainWindow,+ },+ i18n: {+ ns: () => (key: string, options?: Record<string, string>) =>+ options ? `${key}:${JSON.stringify(options)}` : key,+ },+} as unknown as App;++const lastState = () => addonMock.showGuide.mock.lastCall?.[0];+const fire = (event: PermissionGuideEvent) => emit(event);++describe('PermissionGuide', () => {+ let guide: PermissionGuide;++ beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ statusMock.mockReturnValue('denied');+ addonMock.isSupported.mockReturnValue(true);+ (process as any).getSystemVersion = vi.fn(() => '27.0.1');+ guide = new PermissionGuide(mockApp);+ });++ afterEach(() => {+ guide.close();+ vi.useRealTimers();+ });++ it('does nothing when the permission is already granted', async () => {+ statusMock.mockReturnValue('granted');++ await expect(guide.open('accessibility')).resolves.toBe(true);++ expect(electronMock.shell.openExternal).not.toHaveBeenCalled();+ expect(addonMock.showGuide).not.toHaveBeenCalled();+ });++ it('reports unavailable when the native addon is not supported', async () => {+ addonMock.isSupported.mockReturnValue(false);++ await expect(guide.open('accessibility')).resolves.toBe(false);+ expect(electronMock.shell.openExternal).not.toHaveBeenCalled();+ });++ it('opens the privacy pane and offers the app bundle as a drag source', async () => {+ await expect(guide.open('accessibility')).resolves.toBe(true);++ expect(electronMock.shell.openExternal).toHaveBeenCalledWith(+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility',+ );+ expect(addonMock.activateSettings).toHaveBeenCalled();+ expect(lastState()).toMatchObject({+ accessory: 'appIcon',+ appPath: '/Applications/LobeHub.app',+ draggable: true,+ sidebarWidth: 232,+ title: 'permissionGuide.waiting.title',+ });+ });++ it('flies out of the clicked control inside the main window', async () => {+ await guide.open('accessibility');+ expect(lastState()).toMatchObject({ launchOrigin: { x: 400, y: 300 } });+ });++ it('flies out of the main window center when the request came from elsewhere', async () => {+ electronMock.screen.getCursorScreenPoint.mockReturnValueOnce({ x: 2000, y: 10 });++ await guide.open('accessibility');++ expect(lastState()).toMatchObject({ launchOrigin: { x: 700, y: 500 } });+ });++ it('shows success, then dismisses and returns to the app once granted', async () => {+ await guide.open('accessibility');+ statusMock.mockReturnValue('granted');++ vi.advanceTimersByTime(POLL_INTERVAL_MS);+ expect(lastState()).toMatchObject({ accessory: 'success', draggable: false });++ vi.advanceTimersByTime(GRANTED_DISMISS_MS);+ expect(addonMock.hideGuide).toHaveBeenCalled();+ expect(showMainWindow).toHaveBeenCalled();+ });++ it('tells the renderer when the guide opens and when it is granted', async () => {+ await guide.open('screen');+ expect(broadcastToAllWindows).toHaveBeenCalledWith('permissionGuideChanged', {+ permission: 'screen',+ status: 'active',+ });++ statusMock.mockReturnValue('granted');+ vi.advanceTimersByTime(POLL_INTERVAL_MS);+ expect(broadcastToAllWindows).toHaveBeenLastCalledWith('permissionGuideChanged', {+ permission: 'screen',+ status: 'granted',+ });++ guide.close();+ expect(broadcastToAllWindows).not.toHaveBeenCalledWith('permissionGuideChanged', {+ permission: 'screen',+ status: 'dismissed',+ });+ });++ it('tells the renderer when the guide is closed before granting', async () => {+ await guide.open('accessibility');++ fire({ type: 'close' });++ expect(broadcastToAllWindows).toHaveBeenLastCalledWith('permissionGuideChanged', {+ permission: 'accessibility',+ status: 'dismissed',+ });+ });++ it('asks to relaunch after Screen Recording is granted', async () => {+ await guide.open('screen');+ statusMock.mockReturnValue('granted');++ vi.advanceTimersByTime(POLL_INTERVAL_MS);+ expect(lastState()).toMatchObject({ actionLabel: 'permissionGuide.relaunch.action' });++ fire({ type: 'action' });+ expect(electronMock.app.relaunch).toHaveBeenCalled();+ expect(electronMock.app.exit).toHaveBeenCalledWith(0);+ });++ it('returns to the drag state when a drop raises no system prompt', async () => {+ await guide.open('accessibility');++ fire({ dropped: true, type: 'dragEnded' });+ expect(lastState()).toMatchObject({ accessory: 'spinner' });++ vi.advanceTimersByTime(PROMPT_WAIT_MS);+ expect(lastState()).toMatchObject({ accessory: 'appIcon', draggable: true });+ });++ it('offers a retry when the password prompt is cancelled', async () => {+ await guide.open('fullDisk');++ fire({ dropped: true, type: 'dragEnded' });+ fire({ type: 'promptShown' });+ vi.advanceTimersByTime(PROMPT_WAIT_MS * 3);+ expect(lastState()).toMatchObject({ accessory: 'spinner' });++ fire({ type: 'promptDismissed' });+ vi.advanceTimersByTime(PROMPT_SETTLE_MS);+ expect(lastState()).toMatchObject({+ accessory: 'appIcon',+ draggable: true,+ subtitle: 'permissionGuide.retry.subtitle',+ });++ fire({ dropped: true, type: 'dragEnded' });+ expect(lastState()).toMatchObject({ accessory: 'spinner' });+ });++ it('treats a dismissed prompt as success when the permission is now granted', async () => {+ await guide.open('fullDisk');++ fire({ type: 'promptShown' });+ expect(lastState()).toMatchObject({ accessory: 'spinner' });++ statusMock.mockReturnValue('granted');+ fire({ type: 'promptDismissed' });+ vi.advanceTimersByTime(PROMPT_SETTLE_MS);+ expect(lastState()).toMatchObject({ accessory: 'success' });+ });++ it('notices leaving the privacy pane through its window title and returns to it', async () => {+ await guide.open('fullDisk');+ fire({ title: 'Full Disk Access', type: 'windowTitle' });+ vi.advanceTimersByTime(TITLE_SETTLE_MS);++ fire({ title: 'General', type: 'windowTitle' });+ expect(lastState()).toMatchObject({+ accessory: 'settingsIcon',+ actionLabel: 'permissionGuide.offPane.action',+ });++ electronMock.shell.openExternal.mockClear();+ fire({ type: 'action' });+ expect(electronMock.shell.openExternal).toHaveBeenCalledWith(+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles',+ );+ expect(lastState()).toMatchObject({ accessory: 'appIcon', draggable: true });++ fire({ title: 'Full Disk Access', type: 'windowTitle' });+ vi.advanceTimersByTime(TITLE_SETTLE_MS);+ fire({ title: 'Wi-Fi', type: 'windowTitle' });+ expect(lastState()).toMatchObject({ accessory: 'settingsIcon' });+ fire({ title: 'Full Disk Access', type: 'windowTitle' });+ expect(lastState()).toMatchObject({ accessory: 'appIcon', draggable: true });+ });++ it('falls back to sidebar clicks when window titles are unreadable', async () => {+ await guide.open('accessibility');+ vi.advanceTimersByTime(TITLE_SETTLE_MS);++ fire({ type: 'navigationClicked' });+ expect(lastState()).toMatchObject({ accessory: 'settingsIcon' });+ });++ it('ignores navigation clicks when window titles are readable', async () => {+ await guide.open('accessibility');+ fire({ title: 'Accessibility', type: 'windowTitle' });+ vi.advanceTimersByTime(TITLE_SETTLE_MS);+ addonMock.showGuide.mockClear();++ fire({ type: 'navigationClicked' });+ expect(addonMock.showGuide).not.toHaveBeenCalled();+ });++ it('ignores a cancelled drag', async () => {+ await guide.open('accessibility');+ addonMock.showGuide.mockClear();++ fire({ dropped: false, type: 'dragEnded' });++ expect(addonMock.showGuide).not.toHaveBeenCalled();+ });++ it('switches to the missing state and reopens Settings from it', async () => {+ await guide.open('fullDisk');+ electronMock.shell.openExternal.mockClear();++ fire({ type: 'settingsLost' });+ expect(lastState()).toMatchObject({ accessory: 'settingsIcon' });++ fire({ type: 'action' });+ expect(electronMock.shell.openExternal).toHaveBeenCalledWith(+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles',+ );++ fire({ type: 'settingsFound' });+ expect(lastState()).toMatchObject({ accessory: 'appIcon', draggable: true });+ });++ it('stops polling and hides when the user closes the panel', async () => {+ await guide.open('accessibility');++ fire({ type: 'close' });+ expect(addonMock.hideGuide).toHaveBeenCalledTimes(1);++ statusMock.mockReturnValue('granted');+ addonMock.showGuide.mockClear();+ vi.advanceTimersByTime(POLL_INTERVAL_MS * 3);+ expect(addonMock.showGuide).not.toHaveBeenCalled();+ expect(showMainWindow).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/modules/permissionGuide/__tests__/guideState.test.ts b/apps/desktop/src/main/modules/permissionGuide/__tests__/guideState.test.tsnew file mode 100644index 00000000000..6e3c139188c--- /dev/null+++ b/apps/desktop/src/main/modules/permissionGuide/__tests__/guideState.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';++import type { GuidePhase } from '../guideState';+import { buildGuideState } from '../guideState';++const t = (key: string) => key;+const build = (phase: GuidePhase) =>+ buildGuideState({+ appName: 'LobeHub',+ appPath: '/Applications/LobeHub.app',+ permission: 'accessibility',+ phase,+ sidebarWidth: 232,+ t,+ });++describe('buildGuideState', () => {+ it('only offers the app as a drag source while waiting for a drop', () => {+ const draggable = (+ ['confirming', 'granted', 'missing', 'offPane', 'relaunch', 'retry', 'waiting'] as const+ ).filter((phase) => build(phase).draggable);++ expect(draggable).toEqual(['retry', 'waiting']);+ });++ it('gives every recoverable phase an action', () => {+ expect(build('missing').actionLabel).toBe('permissionGuide.missing.action');+ expect(build('offPane').actionLabel).toBe('permissionGuide.offPane.action');+ expect(build('relaunch').actionLabel).toBe('permissionGuide.relaunch.action');+ });+});diff --git a/apps/desktop/src/main/modules/permissionGuide/__tests__/settingsPanes.test.ts b/apps/desktop/src/main/modules/permissionGuide/__tests__/settingsPanes.test.tsnew file mode 100644index 00000000000..b60a3e5b26b--- /dev/null+++ b/apps/desktop/src/main/modules/permissionGuide/__tests__/settingsPanes.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';++import { getAppBundlePath, getSettingsSidebarWidth } from '../settingsPanes';++describe('settingsPanes', () => {+ it('resolves the outermost app bundle from the executable path', () => {+ expect(getAppBundlePath('/Applications/LobeHub.app/Contents/MacOS/LobeHub')).toBe(+ '/Applications/LobeHub.app',+ );+ expect(+ getAppBundlePath(+ '/repo/node_modules/electron/dist/Electron.app/Contents/Frameworks/Helper.app/Contents/MacOS/Helper',+ ),+ ).toBe('/repo/node_modules/electron/dist/Electron.app');+ expect(getAppBundlePath('/usr/local/bin/node')).toBeUndefined();+ });++ it('falls back to window centering on unmeasured macOS versions', () => {+ expect(getSettingsSidebarWidth('27.0.1')).toBe(232);+ expect(getSettingsSidebarWidth('15.6')).toBe(0);+ });+});diff --git a/apps/desktop/src/main/modules/permissionGuide/guideState.ts b/apps/desktop/src/main/modules/permissionGuide/guideState.tsnew file mode 100644index 00000000000..bc6657cea81--- /dev/null+++ b/apps/desktop/src/main/modules/permissionGuide/guideState.ts@@ -0,0 +1,107 @@+import type { PermissionGuideState } from '@lobechat/electron-mac-permission-guide';++import type { GuidedPermission } from './settingsPanes';++export type GuidePhase =+ 'confirming' | 'granted' | 'missing' | 'offPane' | 'relaunch' | 'retry' | 'waiting';++const BOTTOM_INSET = 20;+const MISSING_TIMEOUT_MS = 3000;++interface BuildGuideStateParams {+ appName: string;+ appPath: string;+ launchOrigin?: { x: number; y: number };+ permission: GuidedPermission;+ phase: GuidePhase;+ sidebarWidth: number;+ t: (key: string, options?: Record<string, string>) => string;+}++export const buildGuideState = ({+ appName,+ appPath,+ launchOrigin,+ permission,+ phase,+ sidebarWidth,+ t,+}: BuildGuideStateParams): PermissionGuideState => {+ const permissionName = t(`permissionGuide.permission.${permission}`);+ const base = {+ appPath,+ bottomInset: BOTTOM_INSET,+ closeLabel: t('permissionGuide.close'),+ iconLabel: appName,+ launchOrigin,+ missingTimeoutMs: MISSING_TIMEOUT_MS,+ sidebarWidth,+ };++ switch (phase) {+ case 'waiting':+ case 'retry': {+ return {+ ...base,+ accessory: 'appIcon',+ draggable: true,+ subtitle:+ phase === 'retry'+ ? t('permissionGuide.retry.subtitle')+ : t('permissionGuide.waiting.subtitle', { permission: permissionName }),+ title: t('permissionGuide.waiting.title'),+ };+ }+ case 'confirming': {+ return {+ ...base,+ accessory: 'spinner',+ draggable: false,+ subtitle: t('permissionGuide.confirming.subtitle'),+ title: t('permissionGuide.confirming.title'),+ };+ }+ case 'granted': {+ return {+ ...base,+ accessory: 'success',+ draggable: false,+ subtitle: t('permissionGuide.granted.subtitle'),+ title: t('permissionGuide.granted.title', { permission: permissionName }),+ };+ }+ case 'relaunch': {+ return {+ ...base,+ accessory: 'appIcon',+ actionLabel: t('permissionGuide.relaunch.action'),+ actionStyle: 'primary',+ draggable: false,+ subtitle: t('permissionGuide.relaunch.subtitle'),+ title: t('permissionGuide.granted.title', { permission: permissionName }),+ };+ }+ case 'offPane': {+ return {+ ...base,+ accessory: 'settingsIcon',+ actionLabel: t('permissionGuide.offPane.action'),+ actionStyle: 'secondary',+ draggable: false,+ subtitle: t('permissionGuide.offPane.subtitle', { permission: permissionName }),+ title: t('permissionGuide.offPane.title'),+ };+ }+ case 'missing': {+ return {+ ...base,+ accessory: 'settingsIcon',+ actionLabel: t('permissionGuide.missing.action'),+ actionStyle: 'secondary',+ draggable: false,+ subtitle: t('permissionGuide.missing.subtitle'),+ title: t('permissionGuide.missing.title'),+ };+ }+ }+};diff --git a/apps/desktop/src/main/modules/permissionGuide/settingsPanes.ts b/apps/desktop/src/main/modules/permissionGuide/settingsPanes.tsnew file mode 100644index 00000000000..4dff30f528f--- /dev/null+++ b/apps/desktop/src/main/modules/permissionGuide/settingsPanes.ts@@ -0,0 +1,27 @@+import type { GuidedPermission } from '@lobechat/electron-client-ipc';++export type { GuidedPermission } from '@lobechat/electron-client-ipc';++const PANE_ANCHORS: Record<GuidedPermission, string> = {+ accessibility: 'Privacy_Accessibility',+ fullDisk: 'Privacy_AllFiles',+ inputMonitoring: 'Privacy_ListenEvent',+ screen: 'Privacy_ScreenCapture',+};++// Measured from the System Settings accessibility tree; versions not listed+// here center the guide on the whole window rather than guess.+const SIDEBAR_WIDTH_BY_MAJOR: Record<number, number> = {+ 27: 232,+};++export const getSettingsPaneUrl = (permission: GuidedPermission) =>+ `x-apple.systempreferences:com.apple.preference.security?${PANE_ANCHORS[permission]}`;++export const getSettingsSidebarWidth = (systemVersion: string) =>+ SIDEBAR_WIDTH_BY_MAJOR[Number(systemVersion.split('.')[0])] ?? 0;++export const getAppBundlePath = (executablePath: string) => {+ const index = executablePath.indexOf('.app/');+ return index === -1 ? undefined : executablePath.slice(0, index + 4);+};diff --git a/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.test.ts b/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.test.tsindex 331228af78d..156d7d916d8 100644--- a/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.test.ts+++ b/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.test.ts@@ -91,6 +91,8 @@ vi.mock('./CaptureService', () => ({}));describe('ScreenCaptureManager', () => {+ const mockPermissionGuideOpen = vi.fn();+const createApp = ({ mainWindowVisible = true }: { mainWindowVisible?: boolean } = {}) => {const mainWindow = {browserWindow: {@@ -110,6 +112,9 @@ describe('ScreenCaptureManager', () => {i18n: {ns: vi.fn(() => (key: string) => key),},+ permissionGuide: {+ open: mockPermissionGuideOpen,+ },} as any;};@@ -121,6 +126,7 @@ describe('ScreenCaptureManager', () => {mockGetScreenCaptureStatus.mockReturnValue('granted');mockIsMac.value = true;mockRequestScreenCaptureAccess.mockResolvedValue(false);+ mockPermissionGuideOpen.mockResolvedValue(false);});it('keeps the app in regular mode when showing overlay on macOS', async () => {@@ -260,6 +266,18 @@ describe('ScreenCaptureManager', () => {expect(mockEnumerateWindows).not.toHaveBeenCalled();});+ it('opens the drag guide instead of the system prompt when it is available', async () => {+ mockGetScreenCaptureStatus.mockReturnValue('denied');+ mockPermissionGuideOpen.mockResolvedValue(true);+ const manager = new ScreenCaptureManager(createApp());+ await manager.startSession();++ await manager.beginCapture();++ expect(mockPermissionGuideOpen).toHaveBeenCalledWith('screen');+ expect(mockRequestScreenCaptureAccess).not.toHaveBeenCalled();+ });+it('does not open settings when permission prompt is dismissed', async () => {mockGetScreenCaptureStatus.mockReturnValue('denied');mockDialogShowMessageBox.mockResolvedValue({ response: 1 });diff --git a/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.ts b/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.tsindex 3305b740769..4c9621ca7a4 100644--- a/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.ts+++ b/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.ts@@ -353,6 +353,7 @@ export class ScreenCaptureManager {}logger.info(`Opening screen capture permission settings; status=${status}`);+ if (await this.app.permissionGuide.open('screen')) return;await requestScreenCaptureAccess();}diff --git a/locales/en-US/desktop-onboarding.json b/locales/en-US/desktop-onboarding.jsonindex bfd857bd7a3..ac05f008e3f 100644--- a/locales/en-US/desktop-onboarding.json+++ b/locales/en-US/desktop-onboarding.json@@ -33,19 +33,25 @@"screen2.features.6.subtitle": "Multi AI Providers","screen2.features.6.title": "One Platform, All Models","screen2.title": "Everything You Need",+ "screen3.actions.continue": "Continue","screen3.actions.grantAccess": "Grant Access","screen3.actions.granted": "Access Granted",- "screen3.actions.openSettings": "Open Settings",+ "screen3.actions.waiting": "Waiting for access","screen3.badge": "Permissions","screen3.description": "Grant permissions to unlock the full potential of Agents and Groups. You can manage these anytime in settings.",+ "screen3.hint.guide": "Drag LobeHub into the list in System Settings",+ "screen3.hint.incomplete": "Not finished yet. You can try again.",+ "screen3.hint.prompt": "Choose Allow in the system dialog","screen3.permissions.1.description": "Receive notifications when tasks complete, Agents respond, or important updates arrive","screen3.permissions.1.title": "Notifications","screen3.permissions.2.description": "Access files and folders to enable document analysis, knowledge base creation, and file processing workflows","screen3.permissions.2.title": "File Access",- "screen3.permissions.3.description": "Capture screen content and audio for voice interactions, screen analysis, and multimodal assistance",- "screen3.permissions.3.title": "Screen & Audio","screen3.permissions.4.description": "Enable system-level automation for seamless workflow execution across applications","screen3.permissions.4.title": "Accessibility",+ "screen3.permissions.microphone.description": "Use voice input and voice conversations",+ "screen3.permissions.microphone.title": "Microphone",+ "screen3.permissions.screen.description": "Analyze your screen and ask about screenshots",+ "screen3.permissions.screen.title": "Screen Recording","screen3.title": "Grant Permissions","screen3.title2": "Enable access to unlock full features","screen3.title3": "You can manage these anytime in settings",diff --git a/locales/zh-CN/desktop-onboarding.json b/locales/zh-CN/desktop-onboarding.jsonindex a8832b15ac0..33aa90efb85 100644--- a/locales/zh-CN/desktop-onboarding.json+++ b/locales/zh-CN/desktop-onboarding.json@@ -33,19 +33,25 @@"screen2.features.6.subtitle": "多模型服务商","screen2.features.6.title": "一个平台,连接所有模型","screen2.title": "你需要的一切",+ "screen3.actions.continue": "继续授权","screen3.actions.grantAccess": "授权","screen3.actions.granted": "已授权",- "screen3.actions.openSettings": "打开设置",+ "screen3.actions.waiting": "等待授权","screen3.badge": "权限","screen3.description": "授予权限以解锁代理和群组的全部潜能。您可以随时在设置中进行管理。",+ "screen3.hint.guide": "在「系统设置」中把 LobeHub 拖进列表",+ "screen3.hint.incomplete": "还没有完成,可以再试一次",+ "screen3.hint.prompt": "在系统弹窗中选择允许","screen3.permissions.1.description": "在任务完成、代理响应或有重要更新时接收通知","screen3.permissions.1.title": "通知","screen3.permissions.2.description": "访问文件和文件夹,以启用文档分析、知识库创建和文件处理流程","screen3.permissions.2.title": "文件访问",- "screen3.permissions.3.description": "捕捉屏幕内容和音频,用于语音交互、屏幕分析和多模态辅助",- "screen3.permissions.3.title": "屏幕与音频","screen3.permissions.4.description": "启用系统级自动化,实现跨应用的无缝工作流执行","screen3.permissions.4.title": "辅助功能",+ "screen3.permissions.microphone.description": "用于语音输入和语音对话",+ "screen3.permissions.microphone.title": "麦克风",+ "screen3.permissions.screen.description": "用于屏幕分析和截屏提问",+ "screen3.permissions.screen.title": "屏幕录制","screen3.title": "授予权限","screen3.title2": "启用访问权限以解锁完整功能","screen3.title3": "您可以随时在设置中进行管理",diff --git a/packages/electron-client-ipc/src/events/system.ts b/packages/electron-client-ipc/src/events/system.tsindex ff879dc0fd4..229dbdaa35d 100644--- a/packages/electron-client-ipc/src/events/system.ts+++ b/packages/electron-client-ipc/src/events/system.ts@@ -1,4 +1,10 @@-import type { ElectronAppState, ThemeAppearance, ThemeMode } from '../types';+import type {+ ElectronAppState,+ GuidedPermission,+ PermissionGuideStatus,+ ThemeAppearance,+ ThemeMode,+} from '../types';export interface SystemBroadcastEvents {/**@@ -8,6 +14,10 @@ export interface SystemBroadcastEvents {*/appStateUpdated: (data: Partial<ElectronAppState>) => void;localeChanged: (data: { locale: string }) => void;+ permissionGuideChanged: (data: {+ permission: GuidedPermission;+ status: PermissionGuideStatus;+ }) => void;systemThemeChanged: (data: { themeMode: ThemeAppearance }) => void;themeChanged: (data: { themeMode: ThemeMode }) => void;windowFocused: () => void;diff --git a/packages/electron-client-ipc/src/types/system.ts b/packages/electron-client-ipc/src/types/system.tsindex 6694b59eff9..d77b9eb45eb 100644--- a/packages/electron-client-ipc/src/types/system.ts+++ b/packages/electron-client-ipc/src/types/system.ts@@ -29,3 +29,6 @@ export interface UserPathData {export type ThemeMode = 'system' | 'dark' | 'light';export type ThemeAppearance = 'dark' | 'light' | string;++export type GuidedPermission = 'accessibility' | 'fullDisk' | 'inputMonitoring' | 'screen';+export type PermissionGuideStatus = 'active' | 'dismissed' | 'granted';diff --git a/packages/electron-mac-permission-guide/.gitignore b/packages/electron-mac-permission-guide/.gitignorenew file mode 100644index 00000000000..567609b1234--- /dev/null+++ b/packages/electron-mac-permission-guide/.gitignore@@ -0,0 +1 @@+build/diff --git a/packages/electron-mac-permission-guide/README.md b/packages/electron-mac-permission-guide/README.mdnew file mode 100644index 00000000000..4c50d96888b--- /dev/null+++ b/packages/electron-mac-permission-guide/README.md@@ -0,0 +1,38 @@+# @lobechat/electron-mac-permission-guide++Native N-API addon that floats a compact, non-activating panel inside the+macOS System Settings window. The panel offers the app bundle as a file drag+source, so the user can drop it straight into a privacy list (Accessibility,+Screen Recording, Full Disk Access, Input Monitoring) instead of hunting for+the app with the `+` button.++## Build++```bash+pnpm --filter @lobechat/electron-mac-permission-guide build:native+```++No-op on non-darwin platforms. The desktop packaging pipeline runs this+automatically in `beforePack`.++## Behavior++- The panel tracks the Settings window through `CGWindowListCopyWindowInfo`+ (bounds only, so no Screen Recording permission is needed) on a 60 Hz timer+ in common run loop modes, and stays pinned while the window is dragged.+- It is shown only while System Settings (or the Touch ID / password agent it+ raises) is the frontmost app.+- When the Settings window is gone for `missingTimeoutMs`, the panel centers on+ the main screen and emits `settingsLost`; `settingsFound` follows once the+ window is back.+- The Touch ID / password prompt (and the file chooser) is another Settings+ window centered over the main one; its appearance and dismissal emit+ `promptShown` / `promptDismissed`, which is how a cancelled prompt is told+ apart from a granted one.+- The main window's title is emitted as `windowTitle` when it changes. Titles+ of other apps are only readable with Screen Recording; without it, clicks on+ the Settings sidebar or toolbar navigation emit `navigationClicked` instead.+- The sidebar width cannot be read without Accessibility permission, so the+ caller passes it per macOS version; `0` centers the panel on the window.+- The background is `NSGlassEffectView` on macOS 26+, resolved at runtime, and+ `NSVisualEffectView` elsewhere.diff --git a/packages/electron-mac-permission-guide/binding.gyp b/packages/electron-mac-permission-guide/binding.gypnew file mode 100644index 00000000000..35d34293451--- /dev/null+++ b/packages/electron-mac-permission-guide/binding.gyp@@ -0,0 +1,23 @@+{+ "targets": [+ {+ "target_name": "lobehub_mac_permission_guide",+ "sources": ["native/addon.mm"],+ "include_dirs": ["<!@(node -p \"require('node-addon-api').include\")"],+ "dependencies": ["<!(node -p \"require('node-addon-api').gyp\")"],+ "defines": ["NAPI_DISABLE_CPP_EXCEPTIONS"],+ "conditions": [+ [+ "OS=='mac'",+ {+ "xcode_settings": {+ "OTHER_CPLUSPLUSFLAGS": ["-fobjc-arc", "-std=c++17"],+ "OTHER_LDFLAGS": ["-framework AppKit", "-framework CoreGraphics", "-framework QuartzCore"],+ "MACOSX_DEPLOYMENT_TARGET": "12.0"+ }+ }+ ]+ ]+ }+ ]+}diff --git a/packages/electron-mac-permission-guide/index.d.ts b/packages/electron-mac-permission-guide/index.d.tsnew file mode 100644index 00000000000..cc0b3ec06d9--- /dev/null+++ b/packages/electron-mac-permission-guide/index.d.ts@@ -0,0 +1,37 @@+export type PermissionGuideAccessory = 'appIcon' | 'settingsIcon' | 'spinner' | 'success';++export interface PermissionGuideState {+ accessory: PermissionGuideAccessory;+ actionLabel?: string;+ actionStyle?: 'primary' | 'secondary';+ appPath: string;+ bottomInset?: number;+ closeLabel: string;+ draggable: boolean;+ iconLabel?: string;+ /** Screen point (top-left origin) the panel flies in from on first appearance. */+ launchOrigin?: { x: number; y: number };+ missingTimeoutMs?: number;+ /** Width of the Settings sidebar; 0 centers the panel on the whole window. */+ sidebarWidth?: number;+ subtitle?: string;+ title: string;+}++export type PermissionGuideEvent =+ | { type: 'action' }+ | { type: 'close' }+ | { type: 'dragStarted' }+ | { dropped: boolean; type: 'dragEnded' }+ | { type: 'navigationClicked' }+ | { type: 'promptDismissed' }+ | { type: 'promptShown' }+ | { type: 'settingsFound' }+ | { type: 'settingsLost' }+ | { title: string; type: 'windowTitle' };++export function isSupported(): boolean;+export function showGuide(state: PermissionGuideState): boolean;+export function hideGuide(): void;+export function activateSettings(): void;+export function onGuideEvent(listener: (event: PermissionGuideEvent) => void): () => void;diff --git a/packages/electron-mac-permission-guide/index.js b/packages/electron-mac-permission-guide/index.jsnew file mode 100644index 00000000000..37eb8f613f5--- /dev/null+++ b/packages/electron-mac-permission-guide/index.js@@ -0,0 +1,58 @@+/* eslint-disable @typescript-eslint/no-require-imports */+'use strict';++const { loadNativeBinding } = require('@lobechat/napi-loader');++const binding =+ process.platform === 'darwin' && process.type !== 'renderer'+ ? loadNativeBinding({ dirname: __dirname, packageName: require('./package.json').name })+ : null;++const listeners = new Set();+let setupDone = false;++const ensureSetup = () => {+ if (!binding) return false;+ if (setupDone) return true;+ setupDone = binding.setup((eventJson) => {+ let event;+ try {+ event = JSON.parse(eventJson);+ } catch (error) {+ console.error('[electron-mac-permission-guide] invalid event payload:', error);+ return;+ }+ for (const listener of listeners) {+ try {+ listener(event);+ } catch (error) {+ console.error('[electron-mac-permission-guide] event listener failed:', error);+ }+ }+ });+ return setupDone;+};++const isSupported = () => !!binding;++const onGuideEvent = (listener) => {+ ensureSetup();+ listeners.add(listener);+ return () => listeners.delete(listener);+};++const showGuide = (state) => {+ if (!ensureSetup()) return false;+ binding.show(JSON.stringify(state));+ return true;+};++const hideGuide = () => {+ if (binding) binding.hide();+};++const activateSettings = () => {+ if (binding) binding.activateSettings();+};++module.exports = { activateSettings, hideGuide, isSupported, onGuideEvent, showGuide };diff --git a/packages/electron-mac-permission-guide/native/addon.mm b/packages/electron-mac-permission-guide/native/addon.mmnew file mode 100644index 00000000000..48e114b261e--- /dev/null+++ b/packages/electron-mac-permission-guide/native/addon.mm@@ -0,0 +1,842 @@+#include <napi.h>++#import <AppKit/AppKit.h>+#import <CoreGraphics/CoreGraphics.h>+#import <QuartzCore/QuartzCore.h>++static NSString *const kSettingsBundleId = @"com.apple.systempreferences";+static const CGFloat kPanelWidth = 380;+static const CGFloat kPanelHeight = 56;+static const CGFloat kCornerRadius = 14;+static const CGFloat kAccessorySize = 32;+static const NSRect kAccessoryFrame = {{16, 12}, {kAccessorySize, kAccessorySize}};+static const NSRect kHintFrame = {{8, 2}, {52, 52}};+static const CGFloat kTextX = 64;++// Closed-form damped spring from 0 to 1 (unit mass), parameterized the way+// SwiftUI's spring(response:dampingFraction:) is, so values can be tuned+// against familiar system motion.+typedef struct {+ double omega;+ double zeta;+ double velocity;+} LobeSpring;++static LobeSpring SpringMake(double response, double dampingFraction, double velocity) {+ return (LobeSpring){2 * M_PI / response, dampingFraction, velocity};+}++static double SpringValue(LobeSpring spring, double t) {+ double decay = spring.zeta * spring.omega;+ if (spring.zeta < 1) {+ double damped = spring.omega * sqrt(1 - spring.zeta * spring.zeta);+ double sine = (spring.velocity - decay) / damped;+ return 1 + exp(-decay * t) * (-cos(damped * t) + sine * sin(damped * t));+ }+ return 1 + exp(-spring.omega * t) * (-1 + (spring.velocity - spring.omega) * t);+}++static double SpringSettleTime(LobeSpring spring, double tolerance) {+ return log(1 / tolerance) / (spring.zeta * spring.omega);+}++static Napi::ThreadSafeFunction gEventTsfn;+static bool gEventTsfnActive = false;++static void EmitEvent(NSDictionary *payload) {+ if (!gEventTsfnActive) return;+ NSError *error = nil;+ NSData *data = [NSJSONSerialization dataWithJSONObject:payload options:0 error:&error];+ if (!data) return;+ std::string json((const char *)data.bytes, data.length);+ gEventTsfn.NonBlockingCall(+ [json](Napi::Env env, Napi::Function cb) { cb.Call({Napi::String::New(env, json)}); });+}++static void RunOnMain(dispatch_block_t block) {+ if ([NSThread isMainThread]) {+ block();+ } else {+ dispatch_sync(dispatch_get_main_queue(), block);+ }+}++static NSString *StringValue(NSDictionary *state, NSString *key) {+ id value = state[key];+ return [value isKindOfClass:[NSString class]] ? value : @"";+}++static double NumberValue(NSDictionary *state, NSString *key, double fallback) {+ id value = state[key];+ return [value isKindOfClass:[NSNumber class]] ? [value doubleValue] : fallback;+}++@interface LobeSettingsWindow : NSObject+@property (nonatomic, assign) uint32_t number;+@property (nonatomic, assign) CGRect bounds;+@property (nonatomic, copy) NSString *title;+@end++@implementation LobeSettingsWindow+@end++static NSArray<LobeSettingsWindow *> *SettingsWindows() {+ NSArray<NSRunningApplication *> *apps =+ [NSRunningApplication runningApplicationsWithBundleIdentifier:kSettingsBundleId];+ if (apps.count == 0) return @[];+ NSMutableSet<NSNumber *> *pids = [NSMutableSet set];+ for (NSRunningApplication *app in apps) [pids addObject:@(app.processIdentifier)];++ CFArrayRef list = CGWindowListCopyWindowInfo(+ kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);+ if (!list) return @[];++ NSMutableArray<LobeSettingsWindow *> *windows = [NSMutableArray array];+ for (NSDictionary *info in (__bridge NSArray *)list) {+ if (![pids containsObject:info[(id)kCGWindowOwnerPID]]) continue;+ if ([info[(id)kCGWindowLayer] intValue] != 0) continue;+ CGRect bounds;+ if (!CGRectMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)info[(id)kCGWindowBounds],+ &bounds)) {+ continue;+ }+ LobeSettingsWindow *window = [LobeSettingsWindow new];+ window.number = [info[(id)kCGWindowNumber] unsignedIntValue];+ window.bounds = bounds;+ // Window titles of other apps are only readable with Screen Recording.+ id title = info[(id)kCGWindowName];+ window.title = [title isKindOfClass:[NSString class]] ? title : nil;+ [windows addObject:window];+ }+ CFRelease(list);+ return windows;+}++static BOOL IsMainWindowCandidate(LobeSettingsWindow *window) {+ return window.bounds.size.width >= 300 && window.bounds.size.height >= 200;+}++// The Touch ID / password prompt and the file chooser open as separate+// Settings windows centered over the main one; search popovers are not.+static BOOL IsPromptWindow(LobeSettingsWindow *window, LobeSettingsWindow *main) {+ return window.number != main.number && window.bounds.size.width >= 200 &&+ window.bounds.size.height >= 150 &&+ fabs(CGRectGetMidX(window.bounds) - CGRectGetMidX(main.bounds)) <= 24;+}++static NSRect CocoaRectFromWindowBounds(CGRect bounds) {+ CGFloat primaryHeight = NSScreen.screens.firstObject.frame.size.height;+ return NSMakeRect(bounds.origin.x, primaryHeight - CGRectGetMaxY(bounds), bounds.size.width,+ bounds.size.height);+}++static NSRect PanelFrameForSettingsWindow(CGRect bounds, CGFloat sidebarWidth, CGFloat bottomInset) {+ // CGWindowList bounds are top-left based on the primary display, while+ // NSWindow frames are bottom-left based on the same display. Flipping with+ // the window's own screen misplaces the panel on secondary displays.+ CGFloat primaryHeight = NSScreen.screens.firstObject.frame.size.height;+ CGFloat bottom = primaryHeight - CGRectGetMaxY(bounds);+ CGFloat contentWidth = bounds.size.width - sidebarWidth;+ CGFloat x = sidebarWidth > 0 && contentWidth >= kPanelWidth + 32+ ? bounds.origin.x + sidebarWidth + (contentWidth - kPanelWidth) / 2+ : bounds.origin.x + (bounds.size.width - kPanelWidth) / 2;+ return NSMakeRect(round(x), round(bottom + bottomInset), kPanelWidth, kPanelHeight);+}++static BOOL ShouldShowAlongside(NSRunningApplication *front) {+ NSString *bundleId = front.bundleIdentifier;+ if (!bundleId) return NO;+ // Adding an app to a privacy list raises Touch ID / password UI owned by+ // these agents; the panel must stay up to tell the user to confirm there.+ return [bundleId isEqualToString:kSettingsBundleId] ||+ [bundleId isEqualToString:@"com.apple.SecurityAgent"] ||+ [bundleId isEqualToString:@"com.apple.LocalAuthentication.UIAgent"];+}++@interface LobeGuidePanel : NSPanel+@end++@implementation LobeGuidePanel+- (BOOL)canBecomeKeyWindow {+ return NO;+}+- (BOOL)canBecomeMainWindow {+ return NO;+}+@end++@interface LobeGuideButton : NSButton+@end++@implementation LobeGuideButton+- (BOOL)acceptsFirstMouse:(NSEvent *)event {+ return YES;+}+@end++@interface LobeGuideIconView : NSView <NSDraggingSource>+@property (nonatomic, strong) NSImage *image;+@property (nonatomic, copy) NSString *dragPath;+@property (nonatomic, assign) BOOL dragging;+@end++@implementation LobeGuideIconView++- (BOOL)acceptsFirstMouse:(NSEvent *)event {+ return YES;+}++- (BOOL)mouseDownCanMoveWindow {+ return NO;+}++- (void)drawRect:(NSRect)dirtyRect {+ [self.image drawInRect:self.bounds+ fromRect:NSZeroRect+ operation:NSCompositingOperationSourceOver+ fraction:1+ respectFlipped:YES+ hints:nil];+}++- (void)resetCursorRects {+ if (self.dragPath.length > 0) [self addCursorRect:self.bounds cursor:NSCursor.openHandCursor];+}++- (void)mouseDown:(NSEvent *)event {+}++- (void)mouseDragged:(NSEvent *)event {+ if (self.dragPath.length == 0 || self.dragging) return;+ self.dragging = YES;+ NSURL *url = [NSURL fileURLWithPath:self.dragPath];+ NSDraggingItem *item = [[NSDraggingItem alloc] initWithPasteboardWriter:url];+ [item setDraggingFrame:self.bounds contents:self.image];+ NSDraggingSession *session = [self beginDraggingSessionWithItems:@[ item ]+ event:event+ source:self];+ session.animatesToStartingPositionsOnCancelOrFail = YES;+ EmitEvent(@{@"type" : @"dragStarted"});+}++- (NSDragOperation)draggingSession:(NSDraggingSession *)session+ sourceOperationMaskForDraggingContext:(NSDraggingContext)context {+ return NSDragOperationCopy | NSDragOperationLink | NSDragOperationGeneric;+}++- (void)draggingSession:(NSDraggingSession *)session+ endedAtPoint:(NSPoint)screenPoint+ operation:(NSDragOperation)operation {+ self.dragging = NO;+ EmitEvent(@{@"type" : @"dragEnded", @"dropped" : @(operation != NSDragOperationNone)});+}++@end++@interface LobeGuideDragHintView : NSView+@property (nonatomic, strong) CAShapeLayer *ring;+@property (nonatomic, strong) CALayer *badge;+@end++@implementation LobeGuideDragHintView++- (instancetype)initWithFrame:(NSRect)frame {+ self = [super initWithFrame:frame];+ if (!self) return nil;+ self.wantsLayer = YES;+ self.layer.masksToBounds = NO;++ _ring = [CAShapeLayer layer];+ _ring.fillColor = NSColor.clearColor.CGColor;+ _ring.lineWidth = 1.5;+ _ring.lineDashPattern = @[ @4, @3 ];+ CGPathRef path = CGPathCreateWithRoundedRect(CGRectMake(2.75, 4.75, 42.5, 42.5), 11, 11, NULL);+ _ring.path = path;+ CGPathRelease(path);+ [self.layer addSublayer:_ring];++ _badge = [CALayer layer];+ _badge.frame = CGRectMake(34, 36, 16, 16);+ _badge.cornerRadius = 8;+ _badge.contentsGravity = kCAGravityCenter;+ [self.layer addSublayer:_badge];+ return self;+}++- (NSView *)hitTest:(NSPoint)point {+ return nil;+}++- (void)viewDidChangeEffectiveAppearance {+ [super viewDidChangeEffectiveAppearance];+ [self refreshColors];+}++- (void)refreshColors {+ [self.effectiveAppearance performAsCurrentDrawingAppearance:^{+ self.ring.strokeColor = NSColor.controlAccentColor.CGColor;+ self.badge.backgroundColor = NSColor.controlAccentColor.CGColor;+ }];+ NSImageSymbolConfiguration *config = [[NSImageSymbolConfiguration+ configurationWithPointSize:9+ weight:NSFontWeightBold]+ configurationByApplyingConfiguration:[NSImageSymbolConfiguration+ configurationWithPaletteColors:@[ NSColor.whiteColor ]]];+ NSImage *arrow = [[NSImage imageWithSystemSymbolName:@"arrow.up" accessibilityDescription:nil]+ imageWithSymbolConfiguration:config];+ CGFloat scale = self.window.backingScaleFactor ?: NSScreen.mainScreen.backingScaleFactor;+ self.badge.contentsScale = scale;+ self.badge.contents = [arrow layerContentsForContentsScale:scale];+}++- (void)startAnimating {+ [self refreshColors];+ [self stopAnimating];+ if (NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion) return;++ CABasicAnimation *march = [CABasicAnimation animationWithKeyPath:@"lineDashPhase"];+ march.fromValue = @0;+ march.toValue = @(-7);+ march.duration = 0.6;+ march.repeatCount = HUGE_VALF;+ [self.ring addAnimation:march forKey:@"march"];++ CABasicAnimation *bob = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];+ bob.fromValue = @0;+ bob.toValue = @2.5;+ bob.duration = 0.6;+ bob.autoreverses = YES;+ bob.repeatCount = HUGE_VALF;+ bob.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];+ [self.badge addAnimation:bob forKey:@"bob"];+}++- (void)stopAnimating {+ [self.ring removeAllAnimations];+ [self.badge removeAllAnimations];+}++@end++@interface LobeGuideController : NSObject+@property (nonatomic, strong) LobeGuidePanel *panel;+@property (nonatomic, strong) LobeGuideDragHintView *hintView;+@property (nonatomic, strong) LobeGuideIconView *iconView;+@property (nonatomic, strong) NSImageView *symbolView;+@property (nonatomic, strong) NSProgressIndicator *spinner;+@property (nonatomic, strong) NSTextField *titleLabel;+@property (nonatomic, strong) NSTextField *subtitleLabel;+@property (nonatomic, strong) LobeGuideButton *actionButton;+@property (nonatomic, strong) LobeGuideButton *closeButton;+@property (nonatomic, strong) NSTimer *timer;+@property (nonatomic, strong) NSDate *missingSince;+@property (nonatomic, assign) BOOL settingsLost;+@property (nonatomic, assign) CGFloat sidebarWidth;+@property (nonatomic, assign) CGFloat bottomInset;+@property (nonatomic, assign) NSTimeInterval missingTimeout;+@property (nonatomic, assign) uint32_t mainWindowNumber;+@property (nonatomic, assign) NSRect mainWindowFrame;+@property (nonatomic, copy) NSString *lastTitle;+@property (nonatomic, assign) BOOL promptVisible;+@property (nonatomic, strong) id clickMonitor;+@property (nonatomic, assign) BOOL hasAppeared;+@property (nonatomic, assign) BOOL hasLaunchOrigin;+@property (nonatomic, assign) NSPoint launchOrigin;+@property (nonatomic, assign) NSRect targetFrame;+@property (nonatomic, strong) NSTimer *flightTimer;+@property (nonatomic, assign) CFTimeInterval flightStartedAt;+@property (nonatomic, assign) LobeSpring positionSpring;+@property (nonatomic, assign) LobeSpring scaleSpring;+@property (nonatomic, assign) CFTimeInterval flightSettleTime;+@end++@implementation LobeGuideController++- (instancetype)init {+ self = [super init];+ if (!self) return nil;++ NSRect frame = NSMakeRect(0, 0, kPanelWidth, kPanelHeight);+ _panel = [[LobeGuidePanel alloc]+ initWithContentRect:frame+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel+ backing:NSBackingStoreBuffered+ defer:NO];+ _panel.floatingPanel = YES;+ _panel.level = NSFloatingWindowLevel;+ _panel.hidesOnDeactivate = NO;+ _panel.becomesKeyOnlyIfNeeded = YES;+ _panel.releasedWhenClosed = NO;+ _panel.movable = NO;+ _panel.opaque = NO;+ _panel.hasShadow = YES;+ _panel.backgroundColor = NSColor.clearColor;+ _panel.animationBehavior = NSWindowAnimationBehaviorUtilityWindow;+ _panel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |+ NSWindowCollectionBehaviorFullScreenAuxiliary |+ NSWindowCollectionBehaviorIgnoresCycle;++ NSView *container = [[NSView alloc] initWithFrame:frame];+ container.wantsLayer = YES;+ _panel.contentView = container;+ NSView *content = [self installBackgroundInto:container];++ _hintView = [[LobeGuideDragHintView alloc] initWithFrame:kHintFrame];+ [content addSubview:_hintView];++ _iconView = [[LobeGuideIconView alloc] initWithFrame:NSZeroRect];+ [_iconView setAccessibilityRole:NSAccessibilityImageRole];+ [content addSubview:_iconView];++ _symbolView = [NSImageView imageViewWithImage:[NSImage new]];+ _symbolView.imageScaling = NSImageScaleProportionallyUpOrDown;+ [content addSubview:_symbolView];++ _spinner = [NSProgressIndicator new];+ _spinner.style = NSProgressIndicatorStyleSpinning;+ _spinner.controlSize = NSControlSizeSmall;+ _spinner.displayedWhenStopped = NO;+ [content addSubview:_spinner];++ _titleLabel = [self makeLabelWithFont:[NSFont systemFontOfSize:13 weight:NSFontWeightSemibold]+ color:NSColor.labelColor];+ _subtitleLabel = [self makeLabelWithFont:[NSFont systemFontOfSize:11]+ color:NSColor.secondaryLabelColor];+ [content addSubview:_titleLabel];+ [content addSubview:_subtitleLabel];++ _actionButton = [LobeGuideButton buttonWithTitle:@"" target:self action:@selector(onAction:)];+ _actionButton.bezelStyle = NSBezelStylePush;+ _actionButton.controlSize = NSControlSizeRegular;+ [content addSubview:_actionButton];++ NSImageSymbolConfiguration *closeConfig =+ [NSImageSymbolConfiguration configurationWithPointSize:15 weight:NSFontWeightRegular];+ NSImage *closeImage = [[NSImage imageWithSystemSymbolName:@"xmark.circle.fill"+ accessibilityDescription:nil]+ imageWithSymbolConfiguration:closeConfig];+ _closeButton = [LobeGuideButton buttonWithImage:closeImage target:self action:@selector(onClose:)];+ _closeButton.bordered = NO;+ _closeButton.contentTintColor = NSColor.tertiaryLabelColor;+ [content addSubview:_closeButton];++ _sidebarWidth = 0;+ _bottomInset = 20;+ _missingTimeout = 3;+ return self;+}++- (NSView *)installBackgroundInto:(NSView *)container {+ NSRect bounds = container.bounds;+ NSView *content = [[NSView alloc] initWithFrame:bounds];+ content.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;++ // NSGlassEffectView ships with macOS 26; resolve it at runtime so the addon+ // still builds against older SDKs and runs on older systems.+ Class glassClass = NSClassFromString(@"NSGlassEffectView");+ if (glassClass) {+ NSView *glass = [[glassClass alloc] initWithFrame:bounds];+ glass.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;+ [glass setValue:@(kCornerRadius) forKey:@"cornerRadius"];+ [glass setValue:content forKey:@"contentView"];+ [container addSubview:glass];+ return content;+ }++ NSVisualEffectView *effect = [[NSVisualEffectView alloc] initWithFrame:bounds];+ effect.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;+ effect.material = NSVisualEffectMaterialPopover;+ effect.blendingMode = NSVisualEffectBlendingModeBehindWindow;+ effect.state = NSVisualEffectStateActive;+ effect.maskImage = [NSImage imageWithSize:bounds.size+ flipped:NO+ drawingHandler:^BOOL(NSRect rect) {+ [[NSBezierPath bezierPathWithRoundedRect:rect+ xRadius:kCornerRadius+ yRadius:kCornerRadius] fill];+ return YES;+ }];+ [effect addSubview:content];+ [container addSubview:effect];+ return content;+}++- (NSTextField *)makeLabelWithFont:(NSFont *)font color:(NSColor *)color {+ NSTextField *label = [NSTextField labelWithString:@""];+ label.font = font;+ label.textColor = color;+ label.lineBreakMode = NSLineBreakByTruncatingTail;+ label.maximumNumberOfLines = 1;+ return label;+}++- (void)applyState:(NSDictionary *)state {+ NSString *accessory = StringValue(state, @"accessory");+ NSString *appPath = StringValue(state, @"appPath");+ BOOL draggable = [state[@"draggable"] boolValue] && appPath.length > 0;++ self.sidebarWidth = NumberValue(state, @"sidebarWidth", 0);+ self.bottomInset = NumberValue(state, @"bottomInset", 20);+ self.missingTimeout = NumberValue(state, @"missingTimeoutMs", 3000) / 1000.0;++ NSDictionary *origin = state[@"launchOrigin"];+ if (!self.hasAppeared && [origin isKindOfClass:[NSDictionary class]]) {+ CGFloat primaryHeight = NSScreen.screens.firstObject.frame.size.height;+ self.launchOrigin = NSMakePoint(NumberValue(origin, @"x", 0),+ primaryHeight - NumberValue(origin, @"y", 0));+ self.hasLaunchOrigin = YES;+ }++ BOOL showsIcon = [accessory isEqualToString:@"appIcon"] || [accessory isEqualToString:@"settingsIcon"];+ self.iconView.hidden = !showsIcon;+ if (showsIcon) {+ NSString *iconPath = appPath;+ if ([accessory isEqualToString:@"settingsIcon"]) {+ iconPath = [[NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:kSettingsBundleId] path];+ }+ self.iconView.image = iconPath.length > 0 ? [NSWorkspace.sharedWorkspace iconForFile:iconPath] : nil;+ [self.iconView setAccessibilityLabel:StringValue(state, @"iconLabel")];+ }+ self.iconView.dragPath = showsIcon && draggable ? appPath : nil;+ self.hintView.hidden = self.iconView.dragPath == nil;+ if (self.hintView.hidden) {+ [self.hintView stopAnimating];+ } else {+ [self.hintView startAnimating];+ }+ [self.panel invalidateCursorRectsForView:self.iconView];+ self.iconView.needsDisplay = YES;++ BOOL showsSuccess = [accessory isEqualToString:@"success"];+ self.symbolView.hidden = !showsSuccess;+ if (showsSuccess) {+ NSImageSymbolConfiguration *config =+ [NSImageSymbolConfiguration configurationWithPointSize:20 weight:NSFontWeightRegular];+ self.symbolView.image = [[NSImage imageWithSystemSymbolName:@"checkmark.circle.fill"+ accessibilityDescription:nil]+ imageWithSymbolConfiguration:config];+ self.symbolView.contentTintColor = NSColor.systemGreenColor;+ }++ if ([accessory isEqualToString:@"spinner"]) {+ [self.spinner startAnimation:nil];+ } else {+ [self.spinner stopAnimation:nil];+ }++ self.titleLabel.stringValue = StringValue(state, @"title");+ self.subtitleLabel.stringValue = StringValue(state, @"subtitle");+ self.subtitleLabel.hidden = self.subtitleLabel.stringValue.length == 0;++ NSString *actionLabel = StringValue(state, @"actionLabel");+ self.actionButton.hidden = actionLabel.length == 0;+ self.actionButton.title = actionLabel;+ self.actionButton.bezelColor = [StringValue(state, @"actionStyle") isEqualToString:@"primary"]+ ? NSColor.controlAccentColor+ : nil;+ [self.closeButton setAccessibilityLabel:StringValue(state, @"closeLabel")];+ self.closeButton.toolTip = StringValue(state, @"closeLabel");++ [self layoutContent];+}++- (void)layoutContent {+ CGFloat right = kPanelWidth - 10;+ self.closeButton.frame = NSMakeRect(right - 20, (kPanelHeight - 20) / 2, 20, 20);+ right -= 20 + 8;++ if (!self.actionButton.hidden) {+ [self.actionButton sizeToFit];+ NSSize size = self.actionButton.frame.size;+ CGFloat width = MAX(size.width, 64);+ self.actionButton.frame =+ NSMakeRect(right - width, round((kPanelHeight - size.height) / 2), width, size.height);+ right -= width + 8;+ }++ self.iconView.frame = kAccessoryFrame;+ self.symbolView.frame = NSInsetRect(kAccessoryFrame, 5, 5);+ self.spinner.frame = NSInsetRect(kAccessoryFrame, 8, 8);++ CGFloat textWidth = MAX(right - kTextX, 40);+ if (self.subtitleLabel.hidden) {+ self.titleLabel.frame = NSMakeRect(kTextX, (kPanelHeight - 16) / 2, textWidth, 16);+ } else {+ self.titleLabel.frame = NSMakeRect(kTextX, 28, textWidth, 16);+ self.subtitleLabel.frame = NSMakeRect(kTextX, 12, textWidth, 14);+ }+}++- (void)start {+ if (self.timer) return;+ __weak LobeGuideController *weakSelf = self;+ self.timer = [NSTimer timerWithTimeInterval:1.0 / 60.0+ repeats:YES+ block:^(NSTimer *timer) {+ [weakSelf tick];+ }];+ // Common modes keep the panel following while the user drags the Settings+ // window or our icon, both of which spin the run loop in tracking mode.+ [NSRunLoop.mainRunLoop addTimer:self.timer forMode:NSRunLoopCommonModes];+ self.clickMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:NSEventMaskLeftMouseDown+ handler:^(NSEvent *event) {+ [weakSelf handleGlobalClick];+ }];+ [self tick];+}++- (void)stop {+ [self.flightTimer invalidate];+ self.flightTimer = nil;+ [self.hintView stopAnimating];+ [self.timer invalidate];+ self.timer = nil;+ if (self.clickMonitor) [NSEvent removeMonitor:self.clickMonitor];+ self.clickMonitor = nil;+ [self.spinner stopAnimation:nil];+ [self.panel orderOut:nil];+}++- (LobeSettingsWindow *)resolveMainWindow:(NSArray<LobeSettingsWindow *> *)windows {+ for (LobeSettingsWindow *window in windows) {+ if (window.number == self.mainWindowNumber) return window;+ }+ LobeSettingsWindow *largest = nil;+ for (LobeSettingsWindow *window in windows) {+ if (!IsMainWindowCandidate(window)) continue;+ CGFloat area = window.bounds.size.width * window.bounds.size.height;+ if (!largest || area > largest.bounds.size.width * largest.bounds.size.height) largest = window;+ }+ self.mainWindowNumber = largest.number;+ return largest;+}++- (void)updatePromptVisible:(BOOL)visible {+ if (visible == self.promptVisible) return;+ self.promptVisible = visible;+ EmitEvent(@{@"type" : visible ? @"promptShown" : @"promptDismissed"});+}++- (void)tick {+ NSArray<LobeSettingsWindow *> *windows = SettingsWindows();+ LobeSettingsWindow *main = [self resolveMainWindow:windows];++ if (main) {+ self.missingSince = nil;+ self.mainWindowFrame = CocoaRectFromWindowBounds(main.bounds);+ if (self.settingsLost) {+ self.settingsLost = NO;+ EmitEvent(@{@"type" : @"settingsFound"});+ }+ if (main.title.length > 0 && ![main.title isEqualToString:self.lastTitle]) {+ self.lastTitle = main.title;+ EmitEvent(@{@"type" : @"windowTitle", @"title" : main.title});+ }+ BOOL prompt = NO;+ for (LobeSettingsWindow *window in windows) {+ if (IsPromptWindow(window, main)) prompt = YES;+ }+ [self updatePromptVisible:prompt];++ if (!ShouldShowAlongside(NSWorkspace.sharedWorkspace.frontmostApplication)) {+ if (self.panel.visible) [self.panel orderOut:nil];+ return;+ }+ [self placeAt:PanelFrameForSettingsWindow(main.bounds, self.sidebarWidth, self.bottomInset)];+ return;+ }++ self.mainWindowFrame = NSZeroRect;+ [self updatePromptVisible:NO];+ if (!self.missingSince) self.missingSince = [NSDate date];+ if (!self.settingsLost && -[self.missingSince timeIntervalSinceNow] >= self.missingTimeout) {+ self.settingsLost = YES;+ EmitEvent(@{@"type" : @"settingsLost"});+ }+ if (!self.settingsLost) {+ if (self.panel.visible) [self.panel orderOut:nil];+ return;+ }++ NSRect visible = NSScreen.mainScreen.visibleFrame;+ [self placeAt:NSMakeRect(round(NSMidX(visible) - kPanelWidth / 2), round(NSMidY(visible) - kPanelHeight / 2),+ kPanelWidth, kPanelHeight)];+}++// Without Screen Recording the pane title is unreadable, so a click on the+// sidebar or the toolbar back/forward buttons is the only hint that the user+// navigated away from the privacy list.+- (void)handleGlobalClick {+ NSRect frame = self.mainWindowFrame;+ if (NSIsEmptyRect(frame)) return;+ NSPoint point = NSEvent.mouseLocation;+ if (!NSPointInRect(point, frame)) return;++ CGFloat sidebar = self.sidebarWidth > 0 ? self.sidebarWidth : 220;+ CGFloat fromTop = NSMaxY(frame) - point.y;+ CGFloat fromLeft = point.x - NSMinX(frame);+ BOOL inSidebar = fromLeft <= sidebar && fromTop > 40;+ BOOL inNavigation = fromTop <= 52 && fromLeft > sidebar && fromLeft <= sidebar + 90;+ if (inSidebar || inNavigation) EmitEvent(@{@"type" : @"navigationClicked"});+}++static const CGFloat kFlightStartScale = 0.3;++- (void)applyFlightScale:(CGFloat)scale {+ CGFloat cx = kPanelWidth / 2, cy = kPanelHeight / 2;+ CATransform3D transform = CATransform3DMakeTranslation(cx, cy, 0);+ transform = CATransform3DScale(transform, scale, scale, 1);+ transform = CATransform3DTranslate(transform, -cx, -cy, 0);+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ self.panel.contentView.layer.sublayerTransform = transform;+ [CATransaction commit];+}++- (void)beginFlight {+ NSPoint end = NSMakePoint(NSMidX(self.targetFrame), NSMidY(self.targetFrame));+ CGFloat distance = hypot(end.x - self.launchOrigin.x, end.y - self.launchOrigin.y);++ // Position starts at rest and lands with a small overshoot; scale shares the+ // response but is bouncier, so its pop peaks right as the panel touches down.+ double response = MIN(MAX(0.5 + distance / 5000, 0.5), 0.68);+ self.positionSpring = SpringMake(response, 0.82, 0);+ self.scaleSpring = SpringMake(response, 0.6, 0);+ double tolerance = MAX(0.5 / MAX(distance, 1), 0.0005);+ self.flightSettleTime = MAX(SpringSettleTime(self.positionSpring, tolerance),+ SpringSettleTime(self.scaleSpring, 0.002));+ self.flightStartedAt = CACurrentMediaTime();++ self.panel.alphaValue = 0;+ [self applyFlightScale:kFlightStartScale];+ [self.panel setFrameOrigin:NSMakePoint(round(self.launchOrigin.x - kPanelWidth / 2),+ round(self.launchOrigin.y - kPanelHeight / 2))];+ [self.panel orderFrontRegardless];++ __weak LobeGuideController *weakSelf = self;+ self.flightTimer = [NSTimer timerWithTimeInterval:1.0 / 120.0+ repeats:YES+ block:^(NSTimer *timer) {+ [weakSelf stepFlight];+ }];+ [NSRunLoop.mainRunLoop addTimer:self.flightTimer forMode:NSRunLoopCommonModes];+}++- (void)stepFlight {+ double elapsed = CACurrentMediaTime() - self.flightStartedAt;+ if (elapsed >= self.flightSettleTime) {+ [self.flightTimer invalidate];+ self.flightTimer = nil;+ [self applyFlightScale:1];+ self.panel.alphaValue = 1;+ [self.panel setFrame:self.targetFrame display:YES];+ [self.panel invalidateShadow];+ return;+ }++ // A quadratic curve whose control point sits above both ends traces the+ // parabola of a thrown object; past 1 the spring overshoot continues along+ // the same arc before settling back. The end tracks Settings if it moves.+ CGFloat p = SpringValue(self.positionSpring, elapsed);+ NSPoint start = self.launchOrigin;+ NSPoint end = NSMakePoint(NSMidX(self.targetFrame), NSMidY(self.targetFrame));+ CGFloat distance = hypot(end.x - start.x, end.y - start.y);+ CGFloat lift = MIN(MAX(distance * 0.35, 80), 320);+ NSPoint control = NSMakePoint((start.x + end.x) / 2, MAX(start.y, end.y) + lift);+ CGFloat u = 1 - p;+ CGFloat x = u * u * start.x + 2 * u * p * control.x + p * p * end.x;+ CGFloat y = u * u * start.y + 2 * u * p * control.y + p * p * end.y;++ [self.panel setFrameOrigin:NSMakePoint(round(x - kPanelWidth / 2), round(y - kPanelHeight / 2))];+ CGFloat scale = kFlightStartScale + (1 - kFlightStartScale) * SpringValue(self.scaleSpring, elapsed);+ [self applyFlightScale:scale];+ self.panel.alphaValue = MIN(elapsed / 0.08, 1);+ [self.panel invalidateShadow];+}++- (void)placeAt:(NSRect)frame {+ self.targetFrame = frame;+ if (self.flightTimer) return;+ if (!self.hasAppeared) {+ self.hasAppeared = YES;+ if (self.hasLaunchOrigin && !NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion) {+ [self beginFlight];+ return;+ }+ }+ if (!NSEqualRects(self.panel.frame, frame)) [self.panel setFrame:frame display:YES];+ if (!self.panel.visible) {+ [self.panel orderFrontRegardless];+ [self.panel invalidateShadow];+ }+}++- (void)onAction:(id)sender {+ EmitEvent(@{@"type" : @"action"});+}++- (void)onClose:(id)sender {+ EmitEvent(@{@"type" : @"close"});+}++@end++static LobeGuideController *gController = nil;++static Napi::Value Setup(const Napi::CallbackInfo &info) {+ Napi::Env env = info.Env();+ if (gEventTsfnActive) return Napi::Boolean::New(env, true);+ Napi::Function cb = info[0].As<Napi::Function>();+ gEventTsfn = Napi::ThreadSafeFunction::New(env, cb, "lobehub-mac-permission-guide", 0, 1);+ gEventTsfn.Unref(env);+ gEventTsfnActive = true;+ return Napi::Boolean::New(env, true);+}++static Napi::Value Show(const Napi::CallbackInfo &info) {+ Napi::Env env = info.Env();+ std::string json = info[0].As<Napi::String>().Utf8Value();+ NSData *data = [NSData dataWithBytes:json.data() length:json.size()];+ NSDictionary *state = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];+ if (![state isKindOfClass:[NSDictionary class]]) {+ Napi::TypeError::New(env, "invalid guide state").ThrowAsJavaScriptException();+ return env.Undefined();+ }+ RunOnMain(^{+ if (!gController) gController = [LobeGuideController new];+ [gController applyState:state];+ [gController start];+ });+ return env.Undefined();+}++static Napi::Value Hide(const Napi::CallbackInfo &info) {+ RunOnMain(^{+ [gController stop];+ gController = nil;+ });+ return info.Env().Undefined();+}++static Napi::Value ActivateSettings(const Napi::CallbackInfo &info) {+ RunOnMain(^{+ NSRunningApplication *settings =+ [NSRunningApplication runningApplicationsWithBundleIdentifier:kSettingsBundleId].firstObject;+ if (!settings) return;+ // A deep link into an already running Settings switches panes without+ // raising it, and the panel only shows while Settings is frontmost.+ if (@available(macOS 14.0, *)) [NSApp yieldActivationToApplication:settings];+ [settings activateWithOptions:NSApplicationActivateAllWindows];+ });+ return info.Env().Undefined();+}++static Napi::Object Init(Napi::Env env, Napi::Object exports) {+ exports.Set("activateSettings", Napi::Function::New(env, ActivateSettings));+ exports.Set("setup", Napi::Function::New(env, Setup));+ exports.Set("show", Napi::Function::New(env, Show));+ exports.Set("hide", Napi::Function::New(env, Hide));+ return exports;+}++NODE_API_MODULE(lobehub_mac_permission_guide, Init)diff --git a/packages/electron-mac-permission-guide/package.json b/packages/electron-mac-permission-guide/package.jsonnew file mode 100644index 00000000000..35e25b56f71--- /dev/null+++ b/packages/electron-mac-permission-guide/package.json@@ -0,0 +1,23 @@+{+ "name": "@lobechat/electron-mac-permission-guide",+ "version": "1.0.0",+ "private": true,+ "main": "index.js",+ "types": "index.d.ts",+ "scripts": {+ "build:native": "node scripts/build-native.mjs",+ "install": "node scripts/build-native.mjs"+ },+ "dependencies": {+ "@lobechat/napi-loader": "workspace:*"+ },+ "devDependencies": {+ "node-addon-api": "^8.5.0",+ "node-gyp": "^11.4.2"+ },+ "lobechat": {+ "nativeAddonPlatforms": [+ "darwin"+ ]+ }+}diff --git a/packages/electron-mac-permission-guide/scripts/build-native.mjs b/packages/electron-mac-permission-guide/scripts/build-native.mjsnew file mode 100644index 00000000000..f7d5e2b0701--- /dev/null+++ b/packages/electron-mac-permission-guide/scripts/build-native.mjs@@ -0,0 +1,24 @@+import { execFile } from 'node:child_process';+import { createRequire } from 'node:module';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);++if (process.platform !== 'darwin') {+ console.info('[electron-mac-permission-guide] non-darwin platform, skipping native build');+ process.exit(0);+}++const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const require = createRequire(import.meta.url);+const nodeGyp = require.resolve('node-gyp/bin/node-gyp.js');++const { stdout, stderr } = await execFileAsync(process.execPath, [nodeGyp, 'rebuild'], {+ cwd: packageRoot,+ maxBuffer: 16 * 1024 * 1024,+});+if (stdout) console.info(stdout);+if (stderr) console.info(stderr);+console.info('[electron-mac-permission-guide] native build completed');diff --git a/packages/locales/src/default/desktop-onboarding.ts b/packages/locales/src/default/desktop-onboarding.tsindex e1820c923cf..678d6c27083 100644--- a/packages/locales/src/default/desktop-onboarding.ts+++ b/packages/locales/src/default/desktop-onboarding.ts@@ -43,7 +43,6 @@ export default {'screen3.actions.grantAccess': 'Grant Access','screen3.actions.granted': 'Access Granted',- 'screen3.actions.openSettings': 'Open Settings','screen3.badge': 'Permissions','screen3.description':'Grant permissions to unlock the full potential of Agents and Groups. You can manage these anytime in settings.',@@ -53,12 +52,18 @@ export default {'screen3.permissions.2.description':'Access files and folders to enable document analysis, knowledge base creation, and file processing workflows','screen3.permissions.2.title': 'File Access',- 'screen3.permissions.3.description':- 'Capture screen content and audio for voice interactions, screen analysis, and multimodal assistance',- 'screen3.permissions.3.title': 'Screen & Audio','screen3.permissions.4.description':'Enable system-level automation for seamless workflow execution across applications','screen3.permissions.4.title': 'Accessibility',+ 'screen3.actions.continue': 'Continue',+ 'screen3.actions.waiting': 'Waiting for access',+ 'screen3.hint.guide': 'Drag LobeHub into the list in System Settings',+ 'screen3.hint.incomplete': 'Not finished yet. You can try again.',+ 'screen3.hint.prompt': 'Choose Allow in the system dialog',+ 'screen3.permissions.microphone.description': 'Use voice input and voice conversations',+ 'screen3.permissions.microphone.title': 'Microphone',+ 'screen3.permissions.screen.description': 'Analyze your screen and ask about screenshots',+ 'screen3.permissions.screen.title': 'Screen Recording','screen3.title': 'Grant Permissions','screen3.title2': 'Enable access to unlock full features','screen3.title3': 'You can manage these anytime in settings',diff --git a/src/features/DesktopOnboarding/steps/PermissionsStep.tsx b/src/features/DesktopOnboarding/steps/PermissionsStep.tsxindex 6ea6d58e6ba..27fc47d271e 100644--- a/src/features/DesktopOnboarding/steps/PermissionsStep.tsx+++ b/src/features/DesktopOnboarding/steps/PermissionsStep.tsx@@ -1,70 +1,65 @@'use client';-import { useWatchBroadcast } from '@lobechat/electron-client-ipc';import { Block, Flexbox, Icon } from '@lobehub/ui';import { Button, Text } from '@lobehub/ui/base-ui';import { cssVar } from 'antd-style';+import type { LucideIcon } from 'lucide-react';import {Bell,Check,FolderOpen,+ Loader2Icon,Mic,+ Monitor,MonitorCog,- SquareArrowOutUpRight,Undo2Icon,} from 'lucide-react';-import { memo, useCallback, useEffect, useState } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { ensureElectronIpc } from '@/utils/electron/ipc';-import LobeMessage from '../components/LobeMessage';import OnboardingFooterActions from '../components/OnboardingFooterActions';--type PermissionMeta = {- descriptionKey: string;- icon: typeof Bell;- iconColor: string;- id: number;- titleKey: string;-};--type PermissionButtonKey = 'screen3.actions.grantAccess' | 'screen3.actions.openSettings';-type PermissionItem = PermissionMeta & {- buttonKey: PermissionButtonKey;- granted: boolean;-};--const permissionMetas: PermissionMeta[] = [- {- descriptionKey: 'screen3.permissions.1.description',- icon: Bell,- iconColor: '#FFCB47',- id: 1,- titleKey: 'screen3.permissions.1.title',+import type { PermissionId, PermissionStatus } from './usePermissionStatuses';+import { GUIDED_PERMISSIONS, PERMISSION_IDS, usePermissionStatuses } from './usePermissionStatuses';++const PERMISSION_META: Record<+ PermissionId,+ { descriptionKey: string; icon: LucideIcon; titleKey: string }+> = {+ accessibility: {+ descriptionKey: 'screen3.permissions.4.description',+ icon: MonitorCog,+ titleKey: 'screen3.permissions.4.title',},- {+ fullDisk: {descriptionKey: 'screen3.permissions.2.description',icon: FolderOpen,- iconColor: '#67AF3F',- id: 2,titleKey: 'screen3.permissions.2.title',},- {- descriptionKey: 'screen3.permissions.3.description',+ microphone: {+ descriptionKey: 'screen3.permissions.microphone.description',icon: Mic,- iconColor: '#4A77FF',- id: 3,- titleKey: 'screen3.permissions.3.title',+ titleKey: 'screen3.permissions.microphone.title',},- {- descriptionKey: 'screen3.permissions.4.description',- icon: MonitorCog,- iconColor: '#7A45D3',- id: 4,- titleKey: 'screen3.permissions.4.title',+ notification: {+ descriptionKey: 'screen3.permissions.1.description',+ icon: Bell,+ titleKey: 'screen3.permissions.1.title',+ },+ screen: {+ descriptionKey: 'screen3.permissions.screen.description',+ icon: Monitor,+ titleKey: 'screen3.permissions.screen.title',},-];+};++const resolveDescriptionKey = (id: PermissionId, status: PermissionStatus) => {+ if (status === 'pending') {+ return GUIDED_PERMISSIONS.has(id) ? 'screen3.hint.guide' : 'screen3.hint.prompt';+ }+ if (status === 'incomplete') return 'screen3.hint.incomplete';+ return PERMISSION_META[id].descriptionKey;+};interface PermissionsStepProps {onBack: () => void;@@ -73,87 +68,7 @@ interface PermissionsStepProps {const PermissionsStep = memo<PermissionsStepProps>(({ onBack, onNext }) => {const { t } = useTranslation('desktop-onboarding');- const [permissions, setPermissions] = useState<PermissionItem[]>(() =>- permissionMetas.map((p) => ({- ...p,- buttonKey: 'screen3.actions.grantAccess',- granted: false,- })),- );-- const checkAllPermissions = useCallback(async () => {- const ipc = ensureElectronIpc();- if (!ipc) return;- const state = await ipc.system.getAppState();- const isMac = state.platform === 'darwin';- if (!isMac) {- // If not on macOS, assume all permissions are granted- setPermissions((prev) => prev.map((p) => ({ ...p, granted: true })));- return;- }-- const notifStatus = await ipc.notification.getNotificationPermissionStatus();- const micStatus = await ipc.system.getMediaAccessStatus('microphone');- const screenStatus = await ipc.system.getMediaAccessStatus('screen');- const accessibilityStatus = await ipc.system.getAccessibilityStatus();- // Full Disk Access can now be checked by attempting to read protected directories- const fullDiskStatus = await ipc.system.getFullDiskAccessStatus();-- setPermissions((prev) =>- prev.map((p) => {- if (p.id === 1) return { ...p, granted: notifStatus === 'authorized' };- // Full Disk Access status is detected by reading protected directories- if (p.id === 2)- return { ...p, buttonKey: 'screen3.actions.openSettings', granted: fullDiskStatus };- if (p.id === 3)- return { ...p, granted: micStatus === 'granted' && screenStatus === 'granted' };- if (p.id === 4) return { ...p, granted: accessibilityStatus };- return p;- }),- );- }, []);-- useEffect(() => {- checkAllPermissions();- }, [checkAllPermissions]);-- // Listen for window focus event from Electron main process- // This is more reliable than browser focus events in Electron environment- useWatchBroadcast('windowFocused', () => {- checkAllPermissions();- });-- const handlePermissionRequest = async (permissionId: number) => {- const ipc = ensureElectronIpc();- if (!ipc) return;- switch (permissionId) {- case 1: {- await ipc.notification.requestNotificationPermission();- break;- }- case 2: {- // Use native prompt dialog for Full Disk Access- await ipc.system.promptFullDiskAccessIfNotGranted();- break;- }- case 3: {- await ipc.system.requestMicrophoneAccess();- await ipc.system.requestScreenAccess();- break;- }- case 4: {- await ipc.system.requestAccessibilityAccess();- break;- }- default: {- break;- }- }- // Re-check permissions after a short delay to allow system dialogs- setTimeout(() => {- void checkAllPermissions();- }, 1000);- };+ const { request, statuses } = usePermissionStatuses();return (<Flexbox gap={16} style={{ height: '100%', minHeight: '100%' }}>@@ -162,52 +77,82 @@ const PermissionsStep = memo<PermissionsStepProps>(({ onBack, onNext }) => {<Text as={'p'}>{t('screen3.description')}</Text></Flexbox><Block gap={12} padding={4} style={{ width: '100%' }} variant={'outlined'}>- {permissions.map((permission) => (- <Block- horizontal- align={'center'}- clickable={!permission.granted}- gap={16}- key={permission.id}- paddingBlock={8}- paddingInline={'12px 12px'}- variant={'borderless'}- style={{- background: permission.granted ? cssVar.colorFillSecondary : undefined,- borderColor: permission.granted ? cssVar.colorSuccess : undefined,- }}- onClick={() => !permission.granted && handlePermissionRequest(permission.id)}- >- <Block align={'center'} height={40} justify={'center'} variant={'outlined'} width={40}>- <Icon color={cssVar.colorTextDescription} icon={permission.icon} size={20} />- </Block>- <Flexbox gap={2} style={{ flex: 1 }}>- <Text weight={500}>{t(permission.titleKey as any)}</Text>- <Text color={cssVar.colorTextSecondary} fontSize={12}>- {t(permission.descriptionKey as any)}- </Text>- </Flexbox>- {permission.granted ? (- <Icon color={cssVar.colorSuccess} icon={Check} size={20} />- ) : (- <Button- icon={SquareArrowOutUpRight}- iconPosition={'end'}- size={'small'}- type={'text'}+ {PERMISSION_IDS.map((id) => {+ const status = statuses[id];+ const meta = PERMISSION_META[id];+ const actionable = status === 'idle' || status === 'incomplete';++ return (+ <Block+ horizontal+ align={'center'}+ clickable={actionable}+ gap={16}+ key={id}+ paddingBlock={8}+ paddingInline={'12px 12px'}+ variant={'borderless'}+ style={{+ background:+ status === 'granted'+ ? cssVar.colorFillSecondary+ : status === 'pending'+ ? cssVar.colorPrimaryBg+ : undefined,+ boxShadow:+ status === 'pending' ? `inset 0 0 0 1px ${cssVar.colorPrimaryBorder}` : undefined,+ }}+ onClick={actionable ? () => void request(id) : undefined}+ >+ <Block+ align={'center'}+ height={40}+ justify={'center'}+ variant={'outlined'}+ width={40}style={{- color: cssVar.colorTextSecondary,- }}- onClick={(e) => {- e.stopPropagation();- handlePermissionRequest(permission.id);+ background: status === 'pending' ? cssVar.colorBgContainer : undefined,}}>- {t(permission.buttonKey)}- </Button>- )}- </Block>- ))}+ <Icon color={cssVar.colorTextDescription} icon={meta.icon} size={20} />+ </Block>+ <Flexbox gap={2} style={{ flex: 1, minWidth: 0 }}>+ <Text weight={500}>{t(meta.titleKey as any)}</Text>+ <Text color={cssVar.colorTextSecondary} fontSize={12}>+ {t(resolveDescriptionKey(id, status) as any)}+ </Text>+ </Flexbox>+ {status === 'granted' && <Icon color={cssVar.colorSuccess} icon={Check} size={20} />}+ {status === 'pending' && (+ <Flexbox+ horizontal+ align={'center'}+ gap={6}+ style={{ color: cssVar.colorPrimaryText, flexShrink: 0, fontSize: 13 }}+ >+ <Icon spin icon={Loader2Icon} size={14} />+ {t('screen3.actions.waiting')}+ </Flexbox>+ )}+ {actionable && (+ <Button+ size={'small'}+ style={{ flexShrink: 0 }}+ onClick={(e) => {+ e.stopPropagation();+ void request(id);+ }}+ >+ {t(+ status === 'incomplete'+ ? 'screen3.actions.continue'+ : 'screen3.actions.grantAccess',+ )}+ </Button>+ )}+ </Block>+ );+ })}</Block><OnboardingFooterActionsleft={diff --git a/src/features/DesktopOnboarding/steps/usePermissionStatuses.test.ts b/src/features/DesktopOnboarding/steps/usePermissionStatuses.test.tsnew file mode 100644index 00000000000..65366f1c916--- /dev/null+++ b/src/features/DesktopOnboarding/steps/usePermissionStatuses.test.ts@@ -0,0 +1,111 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { usePermissionStatuses } from './usePermissionStatuses';++const { broadcastHandlers, ipc } = vi.hoisted(() => {+ const ipc = {+ notification: {+ getNotificationPermissionStatus: vi.fn(async () => 'denied'),+ requestNotificationPermission: vi.fn(async () => undefined),+ },+ system: {+ getAccessibilityStatus: vi.fn(async () => false),+ getAppState: vi.fn(async () => ({ platform: 'darwin' })),+ getFullDiskAccessStatus: vi.fn(async () => false),+ getMediaAccessStatus: vi.fn(async (_type: string) => 'denied'),+ promptFullDiskAccessIfNotGranted: vi.fn(async () => 'opened_settings'),+ requestAccessibilityAccess: vi.fn(async () => false),+ requestMicrophoneAccess: vi.fn(async () => false),+ requestScreenAccess: vi.fn(async () => false),+ },+ };+ return { broadcastHandlers: new Map<string, (data?: any) => void>(), ipc };+});++vi.mock('@lobechat/electron-client-ipc', () => ({+ useWatchBroadcast: (event: string, handler: (data?: any) => void) => {+ broadcastHandlers.set(event, handler);+ },+}));++vi.mock('@/utils/electron/ipc', () => ({ ensureElectronIpc: () => ipc }));++const broadcast = (event: string, data?: unknown) =>+ act(() => {+ broadcastHandlers.get(event)?.(data);+ });++describe('usePermissionStatuses', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ broadcastHandlers.clear();+ ipc.system.getAccessibilityStatus.mockResolvedValue(false);+ ipc.system.getMediaAccessStatus.mockResolvedValue('denied');+ });++ it('keeps a guided row actionable until the guide reports it opened', async () => {+ const { result } = renderHook(() => usePermissionStatuses());++ await act(() => result.current.request('accessibility'));+ expect(result.current.statuses.accessibility).toBe('idle');++ await broadcast('permissionGuideChanged', { permission: 'accessibility', status: 'active' });+ expect(result.current.statuses.accessibility).toBe('pending');+ });++ it('marks a guided row granted when the guide reports success', async () => {+ const { result } = renderHook(() => usePermissionStatuses());+ await broadcast('permissionGuideChanged', { permission: 'screen', status: 'active' });++ ipc.system.getMediaAccessStatus.mockImplementation(async (type: string) =>+ type === 'screen' ? 'granted' : 'denied',+ );+ await broadcast('permissionGuideChanged', { permission: 'screen', status: 'granted' });++ await waitFor(() => expect(result.current.statuses.screen).toBe('granted'));+ });++ it('offers to continue when the guide closes before granting', async () => {+ const { result } = renderHook(() => usePermissionStatuses());+ await broadcast('permissionGuideChanged', { permission: 'fullDisk', status: 'active' });++ await broadcast('permissionGuideChanged', { permission: 'fullDisk', status: 'dismissed' });++ expect(result.current.statuses.fullDisk).toBe('incomplete');+ });++ it('shows a prompt-based row as pending, then incomplete when access is refused', async () => {+ let resolveRequest!: () => void;+ ipc.system.requestMicrophoneAccess.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveRequest = () => resolve(false);+ }),+ );+ const { result } = renderHook(() => usePermissionStatuses());++ let pendingRequest!: Promise<void>;+ act(() => {+ pendingRequest = result.current.request('microphone');+ });+ expect(result.current.statuses.microphone).toBe('pending');++ await act(async () => {+ resolveRequest();+ await pendingRequest;+ });+ expect(result.current.statuses.microphone).toBe('incomplete');+ });++ it('keeps a pending row pending when the window regains focus before access is granted', async () => {+ const { result } = renderHook(() => usePermissionStatuses());+ await broadcast('permissionGuideChanged', { permission: 'accessibility', status: 'active' });++ await act(async () => {+ broadcastHandlers.get('windowFocused')?.();+ });++ expect(result.current.statuses.accessibility).toBe('pending');+ });+});diff --git a/src/features/DesktopOnboarding/steps/usePermissionStatuses.ts b/src/features/DesktopOnboarding/steps/usePermissionStatuses.tsnew file mode 100644index 00000000000..92e57da324d--- /dev/null+++ b/src/features/DesktopOnboarding/steps/usePermissionStatuses.ts@@ -0,0 +1,139 @@+import type { GuidedPermission } from '@lobechat/electron-client-ipc';+import { useWatchBroadcast } from '@lobechat/electron-client-ipc';+import { useCallback, useEffect, useState } from 'react';++import { ensureElectronIpc } from '@/utils/electron/ipc';++export type PermissionId = 'accessibility' | 'fullDisk' | 'microphone' | 'notification' | 'screen';+export type PermissionStatus = 'granted' | 'idle' | 'incomplete' | 'pending';++export const PERMISSION_IDS: PermissionId[] = [+ 'notification',+ 'fullDisk',+ 'microphone',+ 'screen',+ 'accessibility',+];++// These open the drag guide inside System Settings; the rest raise a system prompt.+export const GUIDED_PERMISSIONS = new Set<PermissionId>(['accessibility', 'fullDisk', 'screen']);++type PermissionStatuses = Record<PermissionId, PermissionStatus>;++const INITIAL_STATUSES = Object.fromEntries(+ PERMISSION_IDS.map((id) => [id, 'idle']),+) as PermissionStatuses;++const isPermissionId = (value: GuidedPermission): value is GuidedPermission & PermissionId =>+ (PERMISSION_IDS as string[]).includes(value);++const readGranted = async (): Promise<Record<PermissionId, boolean> | undefined> => {+ const ipc = ensureElectronIpc();+ if (!ipc) return undefined;++ const { platform } = await ipc.system.getAppState();+ if (platform !== 'darwin') {+ return Object.fromEntries(PERMISSION_IDS.map((id) => [id, true])) as Record<+ PermissionId,+ boolean+ >;+ }++ const [notification, microphone, screen, accessibility, fullDisk] = await Promise.all([+ ipc.notification.getNotificationPermissionStatus(),+ ipc.system.getMediaAccessStatus('microphone'),+ ipc.system.getMediaAccessStatus('screen'),+ ipc.system.getAccessibilityStatus(),+ ipc.system.getFullDiskAccessStatus(),+ ]);++ return {+ accessibility: !!accessibility,+ fullDisk: !!fullDisk,+ microphone: microphone === 'granted',+ notification: notification === 'authorized',+ screen: screen === 'granted',+ };+};++const requestPermission = async (id: PermissionId) => {+ const ipc = ensureElectronIpc();+ if (!ipc) return;++ switch (id) {+ case 'notification': {+ await ipc.notification.requestNotificationPermission();+ return;+ }+ case 'microphone': {+ await ipc.system.requestMicrophoneAccess();+ return;+ }+ case 'fullDisk': {+ await ipc.system.promptFullDiskAccessIfNotGranted();+ return;+ }+ case 'screen': {+ await ipc.system.requestScreenAccess();+ return;+ }+ case 'accessibility': {+ await ipc.system.requestAccessibilityAccess();+ return;+ }+ }+};++export const usePermissionStatuses = () => {+ const [statuses, setStatuses] = useState<PermissionStatuses>(INITIAL_STATUSES);++ const setStatus = useCallback((id: PermissionId, status: PermissionStatus) => {+ setStatuses((prev) => (prev[id] === status ? prev : { ...prev, [id]: status }));+ }, []);++ const refresh = useCallback(async () => {+ const granted = await readGranted();+ if (!granted) return;+ setStatuses((prev) => {+ const next = { ...prev };+ for (const id of PERMISSION_IDS) {+ if (granted[id]) next[id] = 'granted';+ else if (prev[id] === 'granted') next[id] = 'idle';+ }+ return next;+ });+ }, []);++ useEffect(() => {+ void refresh();+ }, [refresh]);++ useWatchBroadcast('windowFocused', () => {+ void refresh();+ });++ useWatchBroadcast('permissionGuideChanged', ({ permission, status }) => {+ if (!isPermissionId(permission)) return;+ if (status === 'active') setStatus(permission, 'pending');+ else if (status === 'dismissed') setStatus(permission, 'incomplete');+ else void refresh();+ });++ const request = useCallback(+ async (id: PermissionId) => {+ // Guided rows turn pending when the guide reports it opened, so a fallback+ // to the old Settings flow (no guide) leaves the row actionable.+ if (!GUIDED_PERMISSIONS.has(id)) setStatus(id, 'pending');+ await requestPermission(id);+ if (GUIDED_PERMISSIONS.has(id)) {+ await refresh();+ return;+ }+ const granted = await readGranted();+ setStatus(id, granted?.[id] ? 'granted' : 'incomplete');+ },+ [refresh, setStatus],+ );++ return { request, statuses };+};