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): 收敛截图枚举与图片剪贴板回退

Dashf830db2c391f
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureSource.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureSource.test.ts
index 2d74f5a937..f568087224 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/captureSource.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureSource.test.ts
@@ -1,5 +1,24 @@
-import { describe, expect, it } from 'vitest';
-import { desktopCaptureSource } from '../captureSource';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { desktopCaptureSource, enumerateDesktopSources } from '../captureSource';
+
+afterEach(() => vi.useRealTimers());
+it.each([2000, 5000])('bounds enumeration at %s ms and ignores late completion', async (timeout) => {
+ vi.useFakeTimers();
+ let resolve!: (value: string[]) => void;
+ const result = enumerateDesktopSources(() => new Promise<string[]>(yes => { resolve = yes; }), timeout);
+ const rejection = expect(result).rejects.toThrow('DESKTOP_VIDEO_TIMEOUT');
+ await vi.advanceTimersByTimeAsync(timeout);
+ await rejection;
+ resolve(['old']);
+ await expect(enumerateDesktopSources(async () => ['new'], timeout)).resolves.toEqual(['new']);
+ expect(vi.getTimerCount()).toBe(0);
+});
+it('cleans enumeration timers on success and rejection', async () => {
+ vi.useFakeTimers();
+ await expect(enumerateDesktopSources(async () => [], 5000)).resolves.toEqual([]);
+ await expect(enumerateDesktopSources(async () => { throw new Error('capture failed'); }, 5000)).rejects.toThrow('capture failed');
+ expect(vi.getTimerCount()).toBe(0);
+});
describe('desktop capture availability', () => {
it('waits for the same attached display when capture temporarily omits it', () => {
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/clipboard.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/clipboard.test.ts
new file mode 100644
index 0000000000..aececed79f
--- /dev/null
+++ b/apps/desktop/src/main/remote-desktop/__tests__/clipboard.test.ts
@@ -0,0 +1,56 @@
+import { beforeEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ clipboard: {
+ availableFormats: vi.fn(), readImage: vi.fn(), readText: vi.fn(),
+ readHTML: vi.fn(), readRTF: vi.fn(),
+ },
+ version: vi.fn(), selection: vi.fn(),
+}));
+vi.mock('electron', () => ({ clipboard: mocks.clipboard, nativeImage: {} }));
+vi.mock('../inputHost', () => ({
+ readDesktopClipboardVersion: mocks.version, readDesktopSelection: mocks.selection,
+}));
+import { transferDesktopClipboardContent } from '../clipboard';
+
+const png = Buffer.from('iVBORw0KGgo=', 'base64');
+const image = { isEmpty: () => false, getSize: () => ({ width: 1, height: 1 }), toPNG: () => png };
+const copy = () => transferDesktopClipboardContent('copy', undefined, () => true, vi.fn());
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.selection.mockResolvedValue('');
+ mocks.version.mockResolvedValue('1');
+ mocks.clipboard.availableFormats.mockReturnValue(['image/png']);
+ mocks.clipboard.readImage.mockReturnValue(image);
+ mocks.clipboard.readText.mockReturnValue('caption');
+ mocks.clipboard.readHTML.mockReturnValue('<p>caption</p>');
+ mocks.clipboard.readRTF.mockReturnValue('rtf caption');
+});
+it.each(['CF_HDROP', 'public.file-url', 'text/uri-list'])('copies inline image without %s metadata or paths', async (format) => {
+ mocks.clipboard.availableFormats.mockReturnValue([format, 'image/png', 'text/plain']);
+ mocks.clipboard.readText.mockReturnValue('/private/local-image.png');
+ await expect(copy()).resolves.toEqual({ png: png.toString('base64') });
+ expect(mocks.clipboard.readImage).toHaveBeenCalledTimes(1);
+ expect(mocks.clipboard.readText).not.toHaveBeenCalled();
+ expect(mocks.clipboard.readHTML).not.toHaveBeenCalled();
+ expect(mocks.clipboard.readRTF).not.toHaveBeenCalled();
+});
+it('still refuses file-only clipboard content', async () => {
+ mocks.clipboard.availableFormats.mockReturnValue(['CF_HDROP', 'text/plain']);
+ mocks.clipboard.readImage.mockReturnValue({ isEmpty: () => true });
+ await expect(copy()).rejects.toThrow('CLIPBOARD_UNSUPPORTED');
+ expect(mocks.clipboard.readText).not.toHaveBeenCalled();
+});
+it('retains ordinary portable alternatives without file formats', async () => {
+ await expect(copy()).resolves.toEqual({ text: 'caption', html: '<p>caption</p>', rtf: 'rtf caption', png: png.toString('base64') });
+});
+it('rejects an image if the clipboard changes during capture', async () => {
+ mocks.clipboard.availableFormats.mockReturnValue(['CF_HDROP', 'image/png']);
+ mocks.version.mockResolvedValueOnce('1').mockResolvedValueOnce('2');
+ await expect(copy()).rejects.toThrow('DESKTOP_CLIPBOARD_CHANGED');
+});
+it('retains pixel bounds on file-backed images', async () => {
+ mocks.clipboard.availableFormats.mockReturnValue(['CF_HDROP', 'image/png']);
+ mocks.clipboard.readImage.mockReturnValue({ ...image, getSize: () => ({ width: 10000, height: 10000 }) });
+ await expect(copy()).rejects.toThrow('CLIPBOARD_TOO_LONG');
+});
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
index c79b7b5cee..d2e3b13c8f 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import { RemoteDesktopController, type DesktopControllerDeps } from '../controller';
import { acquireHumanDesktopInput, withAgentDesktopInput } from '../inputOwnership';
+import { enumerateDesktopSources } from '../captureSource';
import type { RemoteDesktopIceReply, RemoteDesktopLease } from '@cindy/device-link';
function harness() {
@@ -39,6 +40,27 @@ function harness() {
};
}
describe('remote desktop authority and lifecycle', () => {
+ it('releases a stalled fallback frame for another peer without stopping its lease', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = harness(), first = await h.start();
+ let finish!: (value: string) => void;
+ h.deps.frame = () => enumerateDesktopSources(() => new Promise<string>(yes => { finish = yes; }), 5000);
+ const stalled = h.controller.request('phone', { op: 'frame', lease: first.lease });
+ const rejection = expect(stalled).rejects.toThrow('DESKTOP_VIDEO_TIMEOUT');
+ const next = await h.controller.request('other', { op: 'start', displayId: '1', takeover: true }) as RemoteDesktopLease;
+ await vi.advanceTimersByTimeAsync(5000);
+ await rejection;
+ const stops = vi.mocked(h.deps.stopVideo).mock.calls.length;
+ h.advance(350);
+ h.deps.frame = async () => 'new frame';
+ await expect(h.controller.request('other', { op: 'frame', lease: next.lease })).resolves.toEqual({ jpeg: 'new frame' });
+ finish('stale frame');
+ await Promise.resolve();
+ expect(h.controller.hasLease(next.lease)).toBe(true);
+ expect(h.deps.stopVideo).toHaveBeenCalledTimes(stops);
+ } finally { vi.useRealTimers(); }
+ });
it('keeps ICE and media retries inside their peer lease, including after takeover', async () => {
const h = harness(),
first = await h.start();
diff --git a/apps/desktop/src/main/remote-desktop/captureSource.ts b/apps/desktop/src/main/remote-desktop/captureSource.ts
index 45c8b2bc96..beb59e18e9 100644
--- a/apps/desktop/src/main/remote-desktop/captureSource.ts
+++ b/apps/desktop/src/main/remote-desktop/captureSource.ts
@@ -1,3 +1,21 @@
+/** Bound both offer and fallback enumeration; late results have no side effects. */
+export async function enumerateDesktopSources<T>(
+ enumerate: () => Promise<T>,
+ timeoutMs: number,
+): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ enumerate(),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('DESKTOP_VIDEO_TIMEOUT')), timeoutMs);
+ }),
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+}
+
/** A display can remain attached while its capture source is temporarily unavailable. */
export function desktopCaptureSource<T extends { display_id: string }>(
sources: readonly T[],
diff --git a/apps/desktop/src/main/remote-desktop/clipboard.ts b/apps/desktop/src/main/remote-desktop/clipboard.ts
index 02c70c1365..4c957e5b99 100644
--- a/apps/desktop/src/main/remote-desktop/clipboard.ts
+++ b/apps/desktop/src/main/remote-desktop/clipboard.ts
@@ -67,17 +67,20 @@ export async function transferDesktopClipboardContent(
const before = await readDesktopClipboardVersion(true);
check();
const formats = clipboard.availableFormats();
- // Paths represent files on this computer, not transferable content.
- if (formats.some((format) => /file-url|filenames|hdrop|filecontents|filegroupdescriptor|uri-list/i.test(format)))
+ // A file-backed image may also expose a portable bitmap. Never read the
+ // file flavor or dereference its path; a file alone remains unsupported.
+ const fileBacked = formats.some((format) => /file-url|filenames|hdrop|filecontents|filegroupdescriptor|uri-list/i.test(format));
+ const image = clipboard.readImage();
+ if (fileBacked && image.isEmpty())
throw new Error('CLIPBOARD_UNSUPPORTED');
const snapshot: RemoteClipboardContent = {};
- const text = clipboard.readText();
- const html = clipboard.readHTML();
- const rtf = clipboard.readRTF();
+ // File-manager text/HTML can be a local path rather than image content.
+ const text = fileBacked ? '' : clipboard.readText();
+ const html = fileBacked ? '' : clipboard.readHTML();
+ const rtf = fileBacked ? '' : clipboard.readRTF();
if (text) snapshot.text = text;
if (html) snapshot.html = html;
if (rtf) snapshot.rtf = rtf;
- const image = clipboard.readImage();
if (!image.isEmpty()) {
const size = image.getSize();
if (size.width * size.height > 64_000_000) throw new Error('CLIPBOARD_TOO_LONG');
diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.ts
index 499a672fc8..196c98b62d 100644
--- a/apps/desktop/src/main/remote-desktop/index.ts
+++ b/apps/desktop/src/main/remote-desktop/index.ts
@@ -33,7 +33,7 @@ import {
import { readDeviceLinkSettings, writeDeviceLinkSetting } from '../device-link/settings-store';
import { throwIpcError } from '../utils/ipcValidate';
import { RemoteDesktopController } from './controller';
-import { desktopCaptureSource } from './captureSource';
+import { desktopCaptureSource, enumerateDesktopSources } from './captureSource';
import { encodeDesktopFrame, encodeNativeRelayFrame } from './frame';
import { transferDesktopClipboard, transferDesktopClipboardContent } from './clipboard';
import { NativeDesktopCapture } from './nativeCapture';
@@ -140,17 +140,17 @@ function stopVideo(): void {
pending = null;
}
}
-async function sources(thumbnail = false) {
+async function sources(thumbnail = false, timeoutMs = 5000) {
if (
process.platform === 'darwin' &&
systemPreferences.getMediaAccessStatus('screen') !== 'granted'
)
throw new Error('DESKTOP_SCREEN_PERMISSION_REQUIRED');
- return desktopCapturer.getSources({
+ return enumerateDesktopSources(() => desktopCapturer.getSources({
types: ['screen'],
thumbnailSize: thumbnail ? { width: 1280, height: 1280 } : { width: 0, height: 0 },
fetchWindowIcons: false,
- });
+ }), timeoutMs);
}
async function offer(
lease: RemoteDesktopLease,
@@ -174,21 +174,12 @@ async function offer(
captureGrant = null;
const currentHost = host;
let source: DesktopCapturerSource | null = null;
- let enumerationTimer: ReturnType<typeof setTimeout> | undefined;
let nativeAvailable = process.platform === 'darwin';
try {
nativeAvailable ||=
process.platform === 'win32' && (await readWindowsDesktopSupport()) === 'ready';
try {
- const available = await Promise.race([
- sources(),
- new Promise<never>((_, reject) => {
- enumerationTimer = setTimeout(
- () => reject(new Error('DESKTOP_VIDEO_TIMEOUT')),
- nativeAvailable ? 2000 : 5000,
- );
- }),
- ]);
+ const available = await sources(false, nativeAvailable ? 2000 : 5000);
source = desktopCaptureSource(available, lease.display.id, screen.getAllDisplays());
} catch (error) {
// A locked macOS session can reject Chromium's source enumeration even
@@ -201,7 +192,6 @@ async function offer(
throw error;
}
} finally {
- if (enumerationTimer) clearTimeout(enumerationTimer);
preparingOffer = false;
}
if (!source && !nativeAvailable) throw new Error('DESKTOP_VIDEO_UNAVAILABLE');