Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(remote-desktop): 修复首次辅助功能权限检测 (#4372)

Dash6c3c3fb9a1e7
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/inputPermission.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/inputPermission.test.ts
new file mode 100644
index 0000000000..b5ed5f385a
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/__tests__/inputPermission.test.ts
@@ -0,0 +1,107 @@
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { readDesktopInputPermission } from '../inputHost';
+
+const mocks = vi.hoisted(() => ({
+ exec: vi.fn(),
+ access: vi.fn(),
+ app: {
+ isPackaged: false,
+ getAppPath: () => '/fixture/desktop',
+ getPath: () => '/fixture/profile',
+ },
+}));
+vi.mock('electron', () => ({ app: mocks.app, screen: {} }));
+vi.mock('node:child_process', async (importOriginal) => {
+ const original = await importOriginal<typeof import('node:child_process')>();
+ const { promisify } = await import('node:util');
+ return {
+ ...original,
+ execFile: Object.assign(vi.fn(), { [promisify.custom]: mocks.exec }),
+ };
+});
+vi.mock('node:fs/promises', () => ({
+ default: {
+ readFile: vi.fn(async () => 'fixture source'),
+ access: mocks.access,
+ mkdir: vi.fn(),
+ mkdtemp: vi.fn(async () => '/fixture/compile'),
+ writeFile: vi.fn(),
+ rm: vi.fn(),
+ rename: vi.fn(),
+ },
+}));
+
+describe('desktop input permission detection', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');
+ mocks.app.isPackaged = false;
+ mocks.access.mockResolvedValue(undefined);
+ mocks.exec.mockResolvedValue({ stdout: 'ready\n' });
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('bounds a slow cold build and lets later polls reuse it without prompting', async () => {
+ vi.useFakeTimers();
+ mocks.access.mockRejectedValue(new Error('ENOENT'));
+ let finishBuild!: () => void;
+ mocks.exec.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finishBuild = resolve;
+ }),
+ );
+ const first = readDesktopInputPermission();
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(await first).toBe('unknown');
+ expect(mocks.exec).toHaveBeenCalledTimes(1);
+
+ const retry = readDesktopInputPermission();
+ finishBuild();
+ expect(await retry).toBe('granted');
+ expect(mocks.exec.mock.calls.map(([binary, args]) => [binary === 'swiftc', args[0]])).toEqual([
+ [true, '-D'],
+ [false, '--check'],
+ ]);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('detects an existing grant on a cold dev build without requesting authorization', async () => {
+ mocks.access.mockRejectedValue(new Error('ENOENT'));
+ expect(await readDesktopInputPermission()).toBe('granted');
+ expect(mocks.exec.mock.calls.map(([binary, args]) => [binary === 'swiftc', args[0]])).toEqual([
+ [true, '-D'],
+ [false, '--check'],
+ ]);
+ });
+
+ it.each([
+ ['ready\n', 'granted'],
+ ['permission\n', 'missing'],
+ ['unexpected\n', 'unknown'],
+ ])('maps helper output %j to %s without prompting', async (stdout, expected) => {
+ mocks.exec.mockResolvedValue({ stdout });
+ expect(await readDesktopInputPermission()).toBe(expected);
+ expect(mocks.exec).toHaveBeenCalledExactlyOnceWith(
+ expect.stringContaining(path.join('remote-desktop', 'native')),
+ ['--check'],
+ { timeout: 5000, maxBuffer: 1024 },
+ );
+ });
+
+ it('does not claim a grant when preparation fails', async () => {
+ mocks.access.mockRejectedValue(new Error('ENOENT'));
+ mocks.exec.mockRejectedValue(new Error('compiler unavailable'));
+ expect(await readDesktopInputPermission()).toBe('unknown');
+ });
+
+ it('does not probe Accessibility on Windows', async () => {
+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');
+ expect(await readDesktopInputPermission()).toBe('notRequired');
+ expect(mocks.exec).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/remote-desktop/inputHost.ts b/apps/desktop/src/main/remote-desktop/inputHost.ts
index a625ab1ea4..2f9281673d 100644
--- a/apps/desktop/src/main/remote-desktop/inputHost.ts
+++ b/apps/desktop/src/main/remote-desktop/inputHost.ts
@@ -20,10 +20,10 @@ const exec = promisify(execFile);
const binaryName =
process.platform === 'darwin' ? 'cindy-macos-desktop-input' : 'cindy-windows-desktop-input.exe';
let build: Promise<string> | null = null;
-async function resolveBinary(prepare = true): Promise<string> {
+async function resolveBinary(): Promise<string> {
if (app.isPackaged)
return path.join(process.resourcesPath, 'tools', 'remote-desktop', binaryName);
- if (build && prepare) return build;
+ if (build) return build;
const resolve = async () => {
const sourceRoot = path.join(app.getAppPath(), 'native', 'remote-desktop');
const source =
@@ -34,9 +34,16 @@ async function resolveBinary(prepare = true): Promise<string> {
.update(await fs.readFile(source))
.update(process.arch)
.update('v1-O');
- const callerSource = process.platform === 'darwin'
- ? await fs.readFile(path.resolve(app.getAppPath(), '../../packages/remote-credentials-native/Sources/DesktopNativeCaller/DesktopNativeCaller.swift'), 'utf8')
- : '';
+ const callerSource =
+ process.platform === 'darwin'
+ ? await fs.readFile(
+ path.resolve(
+ app.getAppPath(),
+ '../../packages/remote-credentials-native/Sources/DesktopNativeCaller/DesktopNativeCaller.swift',
+ ),
+ 'utf8',
+ )
+ : '';
digest.update(callerSource);
if (process.platform === 'darwin') digest.update(process.execPath).update('dev-caller-v1');
if (process.platform === 'win32') {
@@ -56,7 +63,6 @@ async function resolveBinary(prepare = true): Promise<string> {
} catch {
/* build this source version */
}
- if (!prepare) throw new Error('DESKTOP_INPUT_NOT_PREPARED');
await fs.mkdir(directory, { recursive: true });
const temporary = `${binary}.${process.pid}.tmp`;
if (process.platform === 'darwin') {
@@ -65,7 +71,7 @@ async function resolveBinary(prepare = true): Promise<string> {
const buildDirectory = await fs.mkdtemp(path.join(directory, 'compile-'));
try {
const main = path.join(buildDirectory, 'main.swift');
- const program = (callerSource + '\n' + await fs.readFile(source, 'utf8')).replace(
+ const program = (callerSource + '\n' + (await fs.readFile(source, 'utf8'))).replace(
'"DESKTOP_INPUT_DEVELOPMENT_EXECUTABLE"',
JSON.stringify(Buffer.from(process.execPath).toString('base64')),
);
@@ -96,7 +102,6 @@ async function resolveBinary(prepare = true): Promise<string> {
await fs.rename(temporary, binary);
return binary;
};
- if (!prepare) return resolve();
build = resolve().finally(() => {
build = null;
});
@@ -107,16 +112,32 @@ async function resolveBinary(prepare = true): Promise<string> {
export async function readDesktopLockState(): Promise<'locked' | 'unlocked' | 'unavailable'> {
if (process.platform !== 'darwin') return 'unavailable';
try {
- const { stdout } = await exec(await resolveBinary(), ['--lock-state'], { timeout: 5000, maxBuffer: 1024 });
+ const { stdout } = await exec(await resolveBinary(), ['--lock-state'], {
+ timeout: 5000,
+ maxBuffer: 1024,
+ });
const value = stdout.trim();
return value === 'locked' || value === 'unlocked' ? value : 'unavailable';
- } catch { return 'unavailable'; }
+ } catch {
+ return 'unavailable';
+ }
}
export async function readDesktopInputPermission(): Promise<DesktopPermissionStatus> {
if (process.platform !== 'darwin') return 'notRequired';
+ let timer: ReturnType<typeof setTimeout> | undefined;
try {
- const { stdout } = await exec(await resolveBinary(false), ['--check'], {
+ // A cold dev build must prepare the helper too; preparation does not prompt.
+ // Bound this caller's wait below the remote channel budget. A slow build
+ // stays shared in resolveBinary so later polls reuse it instead of restarting.
+ const binary = await Promise.race([
+ resolveBinary(),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('DESKTOP_INPUT_PREPARING')), 5000);
+ }),
+ ]);
+ // Only --request-permission may open the macOS authorization UI.
+ const { stdout } = await exec(binary, ['--check'], {
timeout: 5000,
maxBuffer: 1024,
});
@@ -127,17 +148,28 @@ export async function readDesktopInputPermission(): Promise<DesktopPermissionSta
: 'unknown';
} catch {
return 'unknown';
+ } finally {
+ if (timer) clearTimeout(timer);
}
}
-export async function lockDesktopScreen(isCurrent: () => boolean, signal: AbortSignal): Promise<void> {
+export async function lockDesktopScreen(
+ isCurrent: () => boolean,
+ signal: AbortSignal,
+): Promise<void> {
if (process.platform !== 'darwin') throw new Error('DESKTOP_LOCK_UNAVAILABLE');
const binary = await resolveBinary();
if (signal.aborted || !isCurrent()) throw new Error('DESKTOP_LEASE_EXPIRED');
try {
- const { stdout } = await exec(binary, ['--lock-screen'], { timeout: 5000, maxBuffer: 1024, signal });
+ const { stdout } = await exec(binary, ['--lock-screen'], {
+ timeout: 5000,
+ maxBuffer: 1024,
+ signal,
+ });
if (stdout.trim() !== 'locked') throw new Error('DESKTOP_LOCK_FAILED');
- } catch { throw new Error('DESKTOP_LOCK_FAILED'); }
+ } catch {
+ throw new Error('DESKTOP_LOCK_FAILED');
+ }
}
export async function requestDesktopInputPermission(