Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 分享链接复制改由主进程写入并读回核对 (#5886)
Praise03f01d1ec178
diff --git a/apps/desktop/src/main/__tests__/textClipboard.test.ts b/apps/desktop/src/main/__tests__/textClipboard.test.tsnew file mode 100644index 0000000000..a91753a539--- /dev/null+++ b/apps/desktop/src/main/__tests__/textClipboard.test.ts@@ -0,0 +1,103 @@+import type { IpcMainInvokeEvent } from 'electron';+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ clearIssuedClipboardText,+ copyTextToClipboard,+ rememberIssuedClipboardText,+} from '../textClipboard';+import { MAX_CLIPBOARD_TEXT_CHARS } from '../../shared/textClipboard';+import { throwIpcError } from '../utils/ipcValidate';++const event = {} as IpcMainInvokeEvent;+const link = 'https://device-link.cindy.com.cn/provider-share/abc';+const later = () => new Date(Date.now() + 60_000).toISOString();++function harness(readBack: (written: string) => string | undefined = (written) => written) {+ let written = '';+ return {+ assertTrustedSender: vi.fn(),+ assertFocusedSender: vi.fn(),+ write: vi.fn(async (text: string) => {+ written = text;+ }),+ read: vi.fn(async () => readBack(written)),+ };+}++describe('copyTextToClipboard', () => {+ afterEach(() => {+ clearIssuedClipboardText();+ });++ it('writes the text and confirms it by reading the clipboard back', async () => {+ rememberIssuedClipboardText(link, later());+ const deps = harness();+ await copyTextToClipboard(event, { text: link }, deps);+ expect(deps.assertTrustedSender).toHaveBeenCalledWith(event);+ expect(deps.assertFocusedSender).toHaveBeenCalledWith(event);+ expect(deps.write).toHaveBeenCalledWith(link);+ expect(deps.read).toHaveBeenCalledTimes(1);+ });++ it('rejects an unfocused sender before writing', async () => {+ rememberIssuedClipboardText(link, later());+ const deps = harness();+ deps.assertFocusedSender.mockImplementation(() => throwIpcError('PERMISSION_DENIED', 'Denied'));+ await expect(copyTextToClipboard(event, { text: link }, deps)).rejects.toThrow('[PERMISSION_DENIED]');+ expect(deps.write).not.toHaveBeenCalled();+ });++ it('rejects text that Main did not issue as a share link', async () => {+ const deps = harness();+ await expect(copyTextToClipboard(event, { text: link }, deps)).rejects.toThrow('[PERMISSION_DENIED]');+ expect(deps.write).not.toHaveBeenCalled();+ });++ it('rejects an expired issued share link', async () => {+ rememberIssuedClipboardText(link, new Date(Date.now() - 1).toISOString());+ const deps = harness();+ await expect(copyTextToClipboard(event, { text: link }, deps)).rejects.toThrow('[PERMISSION_DENIED]');+ expect(deps.write).not.toHaveBeenCalled();+ });++ it('fails when the write resolves but the clipboard stays empty', async () => {+ rememberIssuedClipboardText(link, later());+ const deps = harness(() => '');+ await expect(copyTextToClipboard(event, { text: link }, deps)).rejects.toThrow('[INTERNAL]');+ });++ it('fails when the clipboard holds different text after the write', async () => {+ rememberIssuedClipboardText(link, later());+ const deps = harness(() => 'older clipboard text');+ await expect(copyTextToClipboard(event, { text: link }, deps)).rejects.toThrow('[INTERNAL]');+ });++ it('maps a native write error to INTERNAL without leaking its message', async () => {+ rememberIssuedClipboardText(link, later());+ const deps = harness();+ deps.write.mockRejectedValueOnce(new Error(`stdout: ${link}`));+ const error = await copyTextToClipboard(event, { text: link }, deps).catch((e: Error) => e);+ expect(String(error)).toContain('[INTERNAL]');+ expect(String(error)).not.toContain(link);+ expect(deps.read).not.toHaveBeenCalled();+ });++ it('rejects an untrusted sender before inspecting payload or writing', async () => {+ const deps = harness();+ deps.assertTrustedSender.mockImplementation(() => throwIpcError('PERMISSION_DENIED', 'Denied'));+ await expect(copyTextToClipboard(event, null, deps)).rejects.toThrow('[PERMISSION_DENIED]');+ expect(deps.write).not.toHaveBeenCalled();+ });++ it.each([+ null,+ {},+ { text: 1 },+ { text: '' },+ { text: 'x'.repeat(MAX_CLIPBOARD_TEXT_CHARS + 1) },+ ])('rejects invalid payload %#', async (input) => {+ const deps = harness();+ await expect(copyTextToClipboard(event, input, deps)).rejects.toThrow('[INVALID_PARAMS]');+ expect(deps.write).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 05b0842c63..0fe4448459 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -566,6 +566,13 @@ import { isIpcError } from '../shared/ipc-errors';import { readFileBytesForPreview } from './fileReadBytes.js';import { copyPngToClipboard } from './pngClipboard.js';import { COPY_PNG_TO_CLIPBOARD_CHANNEL } from '../shared/pngClipboard.js';+import { copyTextToClipboard } from './textClipboard.js';+import { COPY_TEXT_TO_CLIPBOARD_CHANNEL } from '../shared/textClipboard.js';+import {+ readLinuxClipboardSnapshot,+ supportsLinuxClipboard,+ writeLinuxClipboard,+} from './remote-desktop/linuxClipboardNative';import { initHeartbeatService } from './heartbeatService';import { registerRemoteDesktopIpc } from './remote-desktop';import { initAnalyticsSettingsService, noteAuthColdStartState } from './analyticsSettingsService';@@ -7780,6 +7787,29 @@ const registerIpcHandlers = () => {}),);+ // Hyprland may drop Chromium clipboard writes; reuse the remote-desktop+ // data-control writer there. Local only; never route this to a remote host.+ // Focused app-content is the local-intent check; skip the remote lock probe.+ ipcMain.handle(COPY_TEXT_TO_CLIPBOARD_CHANNEL, (event, params) =>+ copyTextToClipboard(event, params, {+ assertTrustedSender: assertTrustedAppRendererEvent,+ assertFocusedSender: (senderEvent) => {+ const win = BrowserWindow.fromWebContents(senderEvent.sender);+ if (!isFocusedAppContentWindow(win)) {+ throwIpcError('PERMISSION_DENIED', '此操作只能在 Cindy 主窗口聚焦时发起');+ }+ },+ write: (text) =>+ supportsLinuxClipboard()+ ? writeLinuxClipboard({ text }, () => true, { checkLock: false })+ : clipboard.writeText(text),+ read: async () =>+ supportsLinuxClipboard()+ ? (await readLinuxClipboardSnapshot(false, { checkLock: false })).content.text+ : clipboard.readText(),+ }),+ );+// ── Native clipboard helpers (media:copy-to-clipboard) ──//// Electron's `clipboard.writeImage` writes raw bitmap data — pastable indiff --git a/apps/desktop/src/main/device-link/providerShareRuntime.ts b/apps/desktop/src/main/device-link/providerShareRuntime.tsindex 38e8ce4df8..16f1756914 100644--- a/apps/desktop/src/main/device-link/providerShareRuntime.ts+++ b/apps/desktop/src/main/device-link/providerShareRuntime.ts@@ -38,6 +38,7 @@ import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.jsimport { currentLedgerCurrency } from '../usage/ledgerCurrency.js';import { getGatewayModelPricing, getModelPriceQuote } from '../usage/modelPricing.js';import { computePriceQuoteTurnMoney, normalizeModelIdForPricing } from '../usage/turnCostCalculator.js';+import { rememberIssuedClipboardText } from '../textClipboard.js';import { throwIpcError } from '../utils/ipcValidate.js';import {getControllerDisplayName,@@ -369,7 +370,9 @@ async function createLink(providerId: string): Promise<ProviderShareLinkCreated>// 倒计时按本机收到响应的时刻计算:链接刚签发,服务端从签发起算 5 分钟。不拿服务端的绝对时间// 和本机时钟相减(两边时钟可能有偏差,偏快会一生成就显示已过期),并留出请求往返的余量。const expiresAt = new Date(Date.now() + PROVIDER_SHARE_LINK_TTL_MS - LINK_TTL_SAFETY_MS).toISOString();- return { link: providerShareLinkFor(created.invitation), expiresAt };+ const link = providerShareLinkFor(created.invitation);+ rememberIssuedClipboardText(link, expiresAt);+ return { link, expiresAt };}async function execute(command: ProviderShareCommand): Promise<unknown> {diff --git a/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.tsindex b23e86760f..00b42b2e90 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/linuxClipboardNative.test.ts@@ -42,6 +42,26 @@ it('kills the new clipboard owner if the compositor locks during its handshake',);expect(kill).toHaveBeenCalledOnce();});+it('lets a local copy write and read back without the remote lock probe', async () => {+ // Older Hyprland omits solitaryBlockedBy, so the probe reports locked forever.+ h.unlocked.mockResolvedValue(false);+ const stdout = new EventEmitter();+ const child = Object.assign(new EventEmitter(), {+ stdout,+ stderr: { resume: vi.fn() },+ stdin: { on: vi.fn(), write: vi.fn(() => stdout.emit('data', Buffer.from('ready\n'))) },+ kill: vi.fn(),+ });+ h.spawn.mockReturnValue(child);+ await writeLinuxClipboard({ text: 'link' }, () => true, { checkLock: false });+ h.exec.mockImplementation(async (_tool, args: string[]) => ({+ stdout: Buffer.from(args.includes('--list-types') ? 'text/plain\n' : 'link'),+ }));+ expect((await readLinuxClipboardSnapshot(false, { checkLock: false })).content).toEqual({+ text: 'link',+ });+ expect(h.unlocked).not.toHaveBeenCalled();+});afterEach(() => {vi.unstubAllEnvs();vi.unstubAllGlobals();diff --git a/apps/desktop/src/main/remote-desktop/linuxClipboardNative.ts b/apps/desktop/src/main/remote-desktop/linuxClipboardNative.tsindex e9c3bb5fda..30591a25ca 100644--- a/apps/desktop/src/main/remote-desktop/linuxClipboardNative.ts+++ b/apps/desktop/src/main/remote-desktop/linuxClipboardNative.ts@@ -18,15 +18,24 @@ export function supportsLinuxClipboard(): boolean {return false;}}-async function read(args: string[], maxBuffer: number): Promise<Buffer> {- if (!(await isLinuxDesktopUnlocked())) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');+/** Remote transfers require an unlocked compositor. A local in-app copy skips+ * the probe: it is user-initiated, and older Hyprland lacks `solitaryBlockedBy`. */+interface LockOptions {+ checkLock?: boolean;+}+async function assertUnlocked(checkLock: boolean): Promise<void> {+ if (checkLock && !(await isLinuxDesktopUnlocked()))+ throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');+}+async function read(args: string[], maxBuffer: number, checkLock = true): Promise<Buffer> {+ await assertUnlocked(checkLock);try {const result = await exec('/usr/bin/wl-paste', args, {timeout: 2000,maxBuffer,encoding: 'buffer',});- if (!(await isLinuxDesktopUnlocked())) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');+ await assertUnlocked(checkLock);return result.stdout;} catch (error) {// Empty selection is distinct from failed compositor access. Never propagate@@ -44,10 +53,11 @@ async function read(args: string[], maxBuffer: number): Promise<Buffer> {}export async function readLinuxClipboardSnapshot(primary = false,+ { checkLock = true }: LockOptions = {},): Promise<{ formats: string[]; content: RemoteClipboardContent }> {if (!supportsLinuxClipboard()) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');const selection = primary ? ['--primary'] : [];- const formats = (await read([...selection, '--list-types'], 16384))+ const formats = (await read([...selection, '--list-types'], 16384, checkLock)).toString().trim().split('\n')@@ -69,7 +79,7 @@ export async function readLinuxClipboardSnapshot(const mime = types.find((type) => formats.includes(type));if (mime) {const value = (- await read([...selection, '--no-newline', '--type', mime], 2 * 1024 * 1024)+ await read([...selection, '--no-newline', '--type', mime], 2 * 1024 * 1024, checkLock)).toString();if (value.length > 512000) throw new Error('CLIPBOARD_TOO_LONG');if (value) content[key] = value;@@ -77,7 +87,7 @@ export async function readLinuxClipboardSnapshot(}}if (!primary && formats.includes('image/png')) {- const png = await read(['--no-newline', '--type', 'image/png'], 8 * 1024 * 1024);+ const png = await read(['--no-newline', '--type', 'image/png'], 8 * 1024 * 1024, checkLock);if (png.length < 33 ||!png.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))@@ -137,9 +147,10 @@ export function stopLinuxClipboardWriter(): void {export async function writeLinuxClipboard(content: RemoteClipboardContent,current: () => boolean,+ { checkLock = true }: LockOptions = {},): Promise<void> {const executable = await binary();- if (!(await isLinuxDesktopUnlocked())) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');+ await assertUnlocked(checkLock);if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');const child = spawn(executable, [], { stdio: 'pipe' });child.stderr.resume();@@ -172,7 +183,7 @@ export async function writeLinuxClipboard(}) + '\n',);});- if (!(await isLinuxDesktopUnlocked())) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');+ await assertUnlocked(checkLock);if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');writer?.kill();writer = child;diff --git a/apps/desktop/src/main/textClipboard.ts b/apps/desktop/src/main/textClipboard.tsnew file mode 100644index 0000000000..84dc4022af--- /dev/null+++ b/apps/desktop/src/main/textClipboard.ts@@ -0,0 +1,64 @@+import type { IpcMainInvokeEvent } from 'electron';++import { MAX_CLIPBOARD_TEXT_CHARS } from '../shared/textClipboard.js';+import { requireObject, throwIpcError } from './utils/ipcValidate.js';++/** Native clipboard dependencies keep validation testable without Electron. */+interface TextClipboardDependencies {+ assertTrustedSender: (event: IpcMainInvokeEvent) => void;+ assertFocusedSender: (event: IpcMainInvokeEvent) => void;+ write: (text: string) => void | Promise<void>;+ read: () => string | undefined | Promise<string | undefined>;+}++const issuedClipboardText = new Map<string, number>();++/** Record a share link Main just created, so copy only accepts that payload. */+export function rememberIssuedClipboardText(text: string, expiresAt: string): void {+ const expiresAtMs = Date.parse(expiresAt);+ if (!text || !Number.isFinite(expiresAtMs)) return;+ issuedClipboardText.set(text, expiresAtMs);+}++export function clearIssuedClipboardText(): void {+ issuedClipboardText.clear();+}++function isLiveIssuedClipboardText(text: string): boolean {+ const expiresAtMs = issuedClipboardText.get(text);+ if (expiresAtMs == null) return false;+ if (expiresAtMs <= Date.now()) {+ issuedClipboardText.delete(text);+ return false;+ }+ return true;+}++/**+ * Report success only after the system clipboard reads back the exact text.+ * Wayland compositors can drop a write silently, so a resolved write alone is+ * not proof that other apps (or a remote desktop viewer) will see it.+ */+export async function copyTextToClipboard(+ event: IpcMainInvokeEvent,+ input: unknown,+ deps: TextClipboardDependencies,+): Promise<void> {+ deps.assertTrustedSender(event);+ deps.assertFocusedSender(event);+ const { text } = requireObject(input);+ if (typeof text !== 'string' || !text || text.length > MAX_CLIPBOARD_TEXT_CHARS) {+ throwIpcError('INVALID_PARAMS', 'Invalid clipboard text');+ }+ if (!isLiveIssuedClipboardText(text)) {+ throwIpcError('PERMISSION_DENIED', 'Clipboard text was not issued by Main');+ }+ let actual: string | undefined;+ try {+ await deps.write(text);+ actual = await deps.read();+ } catch {+ throwIpcError('INTERNAL', 'Unable to write text to clipboard');+ }+ if (actual !== text) throwIpcError('INTERNAL', 'Clipboard did not keep the copied text');+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 8c71639917..7cf8826cc6 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -14,6 +14,10 @@ import {COPY_PNG_TO_CLIPBOARD_CHANNEL,type CopyPngToClipboardParams,} from '../shared/pngClipboard';+import {+ COPY_TEXT_TO_CLIPBOARD_CHANNEL,+ type CopyTextToClipboardParams,+} from '../shared/textClipboard';import type { ByokStatus } from '../shared/modelAccess.js';import type { LocalPluginOauthRequest, LocalPluginSecretRequest } from '../shared/pluginOauth';import { REMOTE_VIEWER } from '../shared/remoteDesktopViewer';@@ -4151,6 +4155,10 @@ contextBridge.exposeInMainWorld('electronAPI', {copyPngToClipboard: (params: CopyPngToClipboardParams): Promise<void> =>ipcRenderer.invoke(COPY_PNG_TO_CLIPBOARD_CHANNEL, params),+ // Copy text through Main and confirm it by reading the clipboard back.+ copyTextToClipboard: (params: CopyTextToClipboardParams): Promise<void> =>+ ipcRenderer.invoke(COPY_TEXT_TO_CLIPBOARD_CHANNEL, params),+// Copy an image / video (resolved from xdt-image:// or xdt-video:// URL,// or absolute path) into the system clipboard as a FILE REFERENCE. Used// by the chat right-click "copy image / copy video" menus so users candiff --git a/apps/desktop/src/renderer/features/provider-share/ProviderShareLinkDialog.tsx b/apps/desktop/src/renderer/features/provider-share/ProviderShareLinkDialog.tsxindex 685c66aefa..80d1a52cec 100644--- a/apps/desktop/src/renderer/features/provider-share/ProviderShareLinkDialog.tsx+++ b/apps/desktop/src/renderer/features/provider-share/ProviderShareLinkDialog.tsx@@ -88,7 +88,9 @@ export function ProviderShareLinkDialog({const copy = useCallback(async () => {if (state.status !== 'ready' || expired) return;try {- await navigator.clipboard.writeText(state.link);+ // Main verifies the write; on Linux/Wayland navigator.clipboard can+ // resolve while the system clipboard stays empty.+ await window.electronAPI.copyTextToClipboard({ text: state.link });setCopied(true);if (copiedTimer.current !== null) window.clearTimeout(copiedTimer.current);copiedTimer.current = window.setTimeout(() => setCopied(false), 1600);diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex cbb1f15577..6631fc9702 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3143,6 +3143,11 @@ interface ElectronAPI {params: import('../shared/pngClipboard').CopyPngToClipboardParams,) => Promise<void>;+ /** Copy text to the local clipboard; rejects unless it reads back intact. */+ copyTextToClipboard: (+ params: import('../shared/textClipboard').CopyTextToClipboardParams,+ ) => Promise<void>;+/*** Copy an image or video (resolved from `xdt-image://` / `xdt-video://`* URL, or absolute path) into the system clipboard as a FILE REFERENCE.diff --git a/apps/desktop/src/shared/textClipboard.ts b/apps/desktop/src/shared/textClipboard.tsnew file mode 100644index 0000000000..28e4bcfc98--- /dev/null+++ b/apps/desktop/src/shared/textClipboard.ts@@ -0,0 +1,7 @@+/** Local text copy only: never routed to a remote host. */+export const COPY_TEXT_TO_CLIPBOARD_CHANNEL = 'clipboard:copy-text';+export const MAX_CLIPBOARD_TEXT_CHARS = 64 * 1024;++export interface CopyTextToClipboardParams {+ text: string;+}