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(desktop): 修复分享图片在页面失焦后复制失败 (#4544)

Dash24a7f9167710
diff --git a/apps/desktop/src/main/__tests__/pngClipboard.test.ts b/apps/desktop/src/main/__tests__/pngClipboard.test.ts
new file mode 100644
index 0000000000..ca129e7d04
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/pngClipboard.test.ts
@@ -0,0 +1,115 @@
+import type { IpcMainInvokeEvent, NativeImage } from 'electron';
+import { describe, expect, it, vi } from 'vitest';
+import { copyPngToClipboard } from '../pngClipboard';
+import { MAX_CLIPBOARD_PNG_BYTES } from '../../shared/pngClipboard';
+import { throwIpcError } from '../utils/ipcValidate';
+
+// Real 1×1 PNG; dimension mutations exercise rejection before native decoding.
+const pngBytes = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=',
+ 'base64',
+);
+const png = () => Uint8Array.from(pngBytes).buffer;
+const event = {} as IpcMainInvokeEvent;
+
+function harness() {
+ const image = { isEmpty: () => false, getSize: () => ({ width: 1, height: 1 }) } as NativeImage;
+ return { image, assertTrustedSender: vi.fn(), decode: vi.fn(() => image), write: vi.fn() };
+}
+
+describe('copyPngToClipboard', () => {
+ it.each([undefined, 'graph TD; A-->B'])(
+ 'writes PNG and optional source text atomically: %s',
+ (plainText) => {
+ const deps = harness();
+ copyPngToClipboard(event, { png: png(), plainText }, deps);
+ expect(deps.assertTrustedSender).toHaveBeenCalledWith(event);
+ expect(deps.decode).toHaveBeenCalledWith(pngBytes);
+ expect(deps.write.mock.calls).toEqual([
+ [{ image: deps.image, ...(plainText ? { text: plainText } : {}) }],
+ ]);
+ },
+ );
+
+ it('rejects an untrusted sender before inspecting payload or decoding', () => {
+ const deps = harness();
+ deps.assertTrustedSender.mockImplementation(() => throwIpcError('PERMISSION_DENIED', 'Denied'));
+ expect(() => copyPngToClipboard(event, null, deps)).toThrow('[PERMISSION_DENIED]');
+ expect(deps.decode).not.toHaveBeenCalled();
+ expect(deps.write).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ null,
+ {},
+ { png: 'file:///tmp/image.png' },
+ { png: new ArrayBuffer(32) },
+ { png: new ArrayBuffer(33) },
+ { png: png(), plainText: 42 },
+ { png: png(), plainText: 'x'.repeat(4 * 1024 * 1024 + 1) },
+ ])('rejects malformed payload without touching clipboard', (input) => {
+ const deps = harness();
+ expect(() => copyPngToClipboard(event, input, deps)).toThrow('[INVALID_PARAMS]');
+ expect(deps.decode).not.toHaveBeenCalled();
+ expect(deps.write).not.toHaveBeenCalled();
+ });
+
+ it('rejects oversized encoded bytes before decoding', () => {
+ const deps = harness();
+ expect(() =>
+ copyPngToClipboard(event, { png: new ArrayBuffer(MAX_CLIPBOARD_PNG_BYTES + 1) }, deps),
+ ).toThrow('[INVALID_PARAMS]');
+ expect(deps.decode).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [0, 1],
+ [1, 16_385],
+ [16_385, 1],
+ [5000, 5000],
+ ])('rejects unsafe dimensions %s × %s before decoding', (width, height) => {
+ const data = png();
+ const view = new DataView(data);
+ view.setUint32(16, width);
+ view.setUint32(20, height);
+ const deps = harness();
+ expect(() => copyPngToClipboard(event, { png: data }, deps)).toThrow('[INVALID_PARAMS]');
+ expect(deps.decode).not.toHaveBeenCalled();
+ expect(deps.write).not.toHaveBeenCalled();
+ });
+
+ it('supports a bounded long conversation image', () => {
+ const data = png();
+ new DataView(data).setUint32(16, 800);
+ new DataView(data).setUint32(20, 16_384);
+ const deps = harness();
+ deps.image.getSize = () => ({ width: 800, height: 16_384 });
+ copyPngToClipboard(event, { png: data }, deps);
+ expect(deps.write).toHaveBeenCalledOnce();
+ });
+
+ it.each(['empty', 'throw', 'dimensions'])(
+ 'leaves clipboard untouched on decode failure: %s',
+ (failure) => {
+ const deps = harness();
+ if (failure === 'empty') deps.image.isEmpty = () => true;
+ if (failure === 'dimensions') deps.image.getSize = () => ({ width: 2, height: 2 });
+ if (failure === 'throw')
+ deps.decode.mockImplementation(() => {
+ throw new Error('decoder details');
+ });
+ expect(() => copyPngToClipboard(event, { png: png() }, deps)).toThrow('[INVALID_PARAMS]');
+ expect(deps.write).not.toHaveBeenCalled();
+ },
+ );
+
+ it('reports write failures without leaking native error details', () => {
+ const deps = harness();
+ deps.write.mockImplementation(() => {
+ throw new Error('private native details');
+ });
+ expect(() => copyPngToClipboard(event, { png: png() }, deps)).toThrow(
+ '[INTERNAL] Unable to write PNG to clipboard',
+ );
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index bba6b9daff..60fb3793f0 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -503,6 +503,8 @@ import { isMainShellWindowUrl } from './cindy-brain/scheduleSlot.js';
import { sanitizeGhostNoticeText } from './cindy-brain/notifySlot.js';
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 { initHeartbeatService } from './heartbeatService';
import { registerRemoteDesktopIpc } from './remote-desktop';
import { initAnalyticsSettingsService, noteAuthColdStartState } from './analyticsSettingsService';
@@ -7459,6 +7461,15 @@ const registerIpcHandlers = () => {
}
});
+ // Local export bytes stay in memory; never route this to a remote host.
+ ipcMain.handle(COPY_PNG_TO_CLIPBOARD_CHANNEL, (event, params) =>
+ copyPngToClipboard(event, params, {
+ assertTrustedSender: assertTrustedAppRendererEvent,
+ decode: (bytes) => nativeImage.createFromBuffer(bytes),
+ write: (data) => clipboard.write(data),
+ }),
+ );
+
// ── Native clipboard helpers (media:copy-to-clipboard) ──
//
// Electron's `clipboard.writeImage` writes raw bitmap data — pastable in
diff --git a/apps/desktop/src/main/pngClipboard.ts b/apps/desktop/src/main/pngClipboard.ts
new file mode 100644
index 0000000000..9424d694ea
--- /dev/null
+++ b/apps/desktop/src/main/pngClipboard.ts
@@ -0,0 +1,71 @@
+import type { IpcMainInvokeEvent, NativeImage } from 'electron';
+
+import { MAX_CLIPBOARD_PNG_BYTES } from '../shared/pngClipboard.js';
+import { requireObject, throwIpcError } from './utils/ipcValidate.js';
+
+/** Native clipboard dependencies keep validation testable without Electron. */
+interface PngClipboardDependencies {
+ assertTrustedSender: (event: IpcMainInvokeEvent) => void;
+ decode: (bytes: Buffer) => NativeImage;
+ write: (data: { image: NativeImage; text?: string }) => void;
+}
+
+/** Validate before decoding; a small PNG must not allocate an unbounded bitmap. */
+export function copyPngToClipboard(
+ event: IpcMainInvokeEvent,
+ input: unknown,
+ deps: PngClipboardDependencies,
+): void {
+ deps.assertTrustedSender(event);
+ const { png, plainText } = requireObject(input);
+ if (
+ !(png instanceof ArrayBuffer) ||
+ png.byteLength < 33 ||
+ png.byteLength > MAX_CLIPBOARD_PNG_BYTES
+ ) {
+ throwIpcError('INVALID_PARAMS', 'Invalid clipboard PNG size');
+ }
+ if (
+ plainText !== undefined &&
+ (typeof plainText !== 'string' || plainText.length > 4 * 1024 * 1024)
+ ) {
+ throwIpcError('INVALID_PARAMS', 'Invalid clipboard text');
+ }
+ const bytes = Buffer.from(png);
+ if (
+ bytes.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a' ||
+ bytes.readUInt32BE(8) !== 13 ||
+ bytes.toString('ascii', 12, 16) !== 'IHDR'
+ ) {
+ throwIpcError('INVALID_PARAMS', 'Invalid clipboard PNG');
+ }
+ const width = bytes.readUInt32BE(16);
+ const height = bytes.readUInt32BE(20);
+ // Export uses a 4096² pixel budget; leave room for integer canvas rounding.
+ if (
+ !width ||
+ !height ||
+ width > 16_384 ||
+ height > 16_384 ||
+ width * height > 4096 ** 2 + 16_384
+ ) {
+ throwIpcError('INVALID_PARAMS', 'Clipboard PNG dimensions exceed export limits');
+ }
+ let image: NativeImage;
+ try {
+ image = deps.decode(bytes);
+ } catch {
+ throwIpcError('INVALID_PARAMS', 'Invalid clipboard PNG data');
+ }
+ if (image.isEmpty()) throwIpcError('INVALID_PARAMS', 'Invalid clipboard PNG data');
+ const size = image.getSize();
+ if (size.width !== width || size.height !== height) {
+ throwIpcError('INVALID_PARAMS', 'Unexpected clipboard PNG dimensions');
+ }
+ try {
+ // One write preserves image + source text together, without a focus check.
+ deps.write({ image, ...(plainText ? { text: plainText } : {}) });
+ } catch {
+ throwIpcError('INTERNAL', 'Unable to write PNG to clipboard');
+ }
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index c606e8b85a..5f21c74f08 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1,4 +1,5 @@
import { invokeOpenPath } from './openPath';
+import { COPY_PNG_TO_CLIPBOARD_CHANNEL, type CopyPngToClipboardParams } from '../shared/pngClipboard';
import { REMOTE_VIEWER } from '../shared/remoteDesktopViewer';
import type { RoutineInput } from '@cindy/maker-scheduler';
import {
@@ -3920,6 +3921,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
}): Promise<{ success: boolean; error?: string }> =>
ipcRenderer.invoke('shell:show-item-in-folder', params),
+ // Copy an in-memory export without requiring renderer focus.
+ copyPngToClipboard: (params: CopyPngToClipboardParams): Promise<void> =>
+ ipcRenderer.invoke(COPY_PNG_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 can
diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.ts
index 5bf07ab725..75648cf842 100644
--- a/apps/desktop/src/preload/sidebarWindowPreload.ts
+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts
@@ -1,4 +1,5 @@
import { invokeOpenPath } from './openPath';
+import { COPY_PNG_TO_CLIPBOARD_CHANNEL, type CopyPngToClipboardParams } from '../shared/pngClipboard';
/**
* 鍙充晶鏍忓瓙绐楀彛涓撶敤 preload锛氬彧鏆撮湶 RSB 绐楀彛鎵€闇€鐨勬渶灏忚兘鍔涖€?
*
@@ -239,6 +240,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
openFileInBrowser: (pathOrUrl: string): Promise<unknown> => ipcRenderer.invoke('shell:open-file-in-browser', pathOrUrl),
openPath: (pathOrUrl: string) => invokeOpenPath(ipcRenderer.invoke.bind(ipcRenderer), pathOrUrl),
showItemInFolder: (params: unknown): Promise<unknown> => ipcRenderer.invoke('shell:show-item-in-folder', params),
+ copyPngToClipboard: (params: CopyPngToClipboardParams): Promise<void> =>
+ ipcRenderer.invoke(COPY_PNG_TO_CLIPBOARD_CHANNEL, params),
copyMediaToClipboard: (params: unknown): Promise<unknown> =>
ipcRenderer.invoke('media:copy-to-clipboard', params),
openMediaWithDefaultApp: (params: unknown): Promise<void> =>
diff --git a/apps/desktop/src/renderer/lib/__tests__/rasterizeToImage.test.ts b/apps/desktop/src/renderer/lib/__tests__/rasterizeToImage.test.ts
index 16d620cf2e..c5bae34c95 100644
--- a/apps/desktop/src/renderer/lib/__tests__/rasterizeToImage.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/rasterizeToImage.test.ts
@@ -7,16 +7,56 @@
* 由运行时验证覆盖。
*/
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
EXPORT_MAX_EDGE_PX,
EXPORT_MAX_OUTPUT_PIXELS,
EXPORT_PNG_SCALE,
computeExportScale,
+ copyPngBlobToClipboard,
parseSvgIntrinsicSize,
} from '@/lib/rasterizeToImage';
+describe('copyPngBlobToClipboard', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it('uses native copying after async export loses document focus, preserving source text', async () => {
+ const copy = vi.fn().mockResolvedValue(undefined);
+ vi.stubGlobal('electronAPI', { copyPngToClipboard: copy });
+ vi.spyOn(document, 'hasFocus').mockReturnValue(false);
+ const webWrite = vi.fn(() => {
+ throw new Error('Document is not focused.');
+ });
+ vi.stubGlobal('navigator', { clipboard: { write: webWrite } });
+ const bytes = new ArrayBuffer(8);
+ let finish!: (value: ArrayBuffer) => void;
+ const blob = {
+ arrayBuffer: () =>
+ new Promise<ArrayBuffer>((resolve) => {
+ finish = resolve;
+ }),
+ } as Blob;
+ const copying = copyPngBlobToClipboard(blob, 'source');
+ expect(copy).not.toHaveBeenCalled();
+ finish(bytes);
+ await copying;
+ expect(copy).toHaveBeenCalledWith({ png: bytes, plainText: 'source' });
+ expect(webWrite).not.toHaveBeenCalled();
+ });
+
+ it('propagates native copy rejection so callers cannot show false success', async () => {
+ vi.stubGlobal('electronAPI', {
+ copyPngToClipboard: vi.fn().mockRejectedValue(new Error('[INTERNAL] Copy failed')),
+ });
+ const blob = { arrayBuffer: async () => new ArrayBuffer(8) } as Blob;
+ await expect(copyPngBlobToClipboard(blob)).rejects.toThrow('Copy failed');
+ });
+});
+
describe('computeExportScale', () => {
it('普通尺寸用满目标倍率(默认 3x)', () => {
expect(computeExportScale(400, 300)).toBe(EXPORT_PNG_SCALE);
diff --git a/apps/desktop/src/renderer/lib/rasterizeToImage.ts b/apps/desktop/src/renderer/lib/rasterizeToImage.ts
index c162b026b5..48d051961e 100644
--- a/apps/desktop/src/renderer/lib/rasterizeToImage.ts
+++ b/apps/desktop/src/renderer/lib/rasterizeToImage.ts
@@ -10,8 +10,8 @@
* (foreignObject 序列化)光栅化;web font(KaTeX 字体等)必须内联,
* 否则 SVG-as-image 渲染时回退系统字体——首次收集后模块级缓存。
*
- * 剪贴板走 `copyPngBlobToClipboard`(纯内存 ClipboardItem,不落盘,不涉及
- * cindy-media 总仓;与 ImageLightbox.handleCopyImage 同一范式)。
+ * 剪贴板走 `copyPngBlobToClipboard`(原生剪贴板,纯内存,不落盘,
+ * 不涉及 cindy-media 总仓)。
*/
import { getFontEmbedCSS, toBlob as domNodeToBlob } from 'html-to-image';
@@ -200,18 +200,14 @@ export async function domToPngBlob(
}
/**
- * PNG Blob → 系统剪贴板。位图侧 ClipboardItem 仅接受 image/png(Chromium
- * 限制,与 ImageLightbox 同注);Electron/Chromium 跨平台统一实现,
- * macOS/Windows 无平台分叉。纯内存操作、不落盘。
+ * PNG Blob → 原生系统剪贴板。生成长图期间页面可能失焦,因此不能使用
+ * 要求 document focus 的 navigator.clipboard.write。macOS/Windows 共用
+ * Electron bridge,不抢焦点、不落盘。
*
- * `plainText`(可选)与图片写进**同一个** ClipboardItem 作为 text/plain 备选
+ * `plainText`(可选)与图片在同一次原生写入中作为 text/plain 备选
* 表示:粘贴目标按自己的偏好取格式——飞书/文档吃图片,代码编辑器/输入框吃
* 源码(mermaid 源码 / 表格 TSV / 公式 LaTeX),一次复制两头可用。
*/
export async function copyPngBlobToClipboard(blob: Blob, plainText?: string): Promise<void> {
- const representations: Record<string, Blob> = { 'image/png': blob };
- if (plainText) {
- representations['text/plain'] = new Blob([plainText], { type: 'text/plain' });
- }
- await navigator.clipboard.write([new ClipboardItem(representations)]);
+ await window.electronAPI.copyPngToClipboard({ png: await blob.arrayBuffer(), plainText });
}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 435eb2e075..1f8d3cf5e6 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3022,6 +3022,11 @@ interface ElectronAPI {
filePath?: string;
}) => Promise<{ success: boolean; error?: string }>;
+ /** Copy an in-memory PNG export to the local native clipboard. */
+ copyPngToClipboard: (
+ params: import('../shared/pngClipboard').CopyPngToClipboardParams,
+ ) => 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/pngClipboard.ts b/apps/desktop/src/shared/pngClipboard.ts
new file mode 100644
index 0000000000..b3203f4d23
--- /dev/null
+++ b/apps/desktop/src/shared/pngClipboard.ts
@@ -0,0 +1,8 @@
+/** Local bitmap export only: no file paths, URLs, or remote clipboard access. */
+export const COPY_PNG_TO_CLIPBOARD_CHANNEL = 'media:copy-png-to-clipboard';
+export const MAX_CLIPBOARD_PNG_BYTES = 72 * 1024 * 1024;
+
+export interface CopyPngToClipboardParams {
+ png: ArrayBuffer;
+ plainText?: string;
+}