Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): confirm unreadable source attachments before resuming remote send
elfcvfb29ca37bba0
diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.tsindex 4fd48a0408..9222641f9a 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts@@ -14,6 +14,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const h = vi.hoisted(() => ({handlers: new Map<string, (...args: unknown[]) => unknown>(),trusted: true,+ ownerGeneration: 1,+ senderDestroyed: false,+ selectFile: vi.fn(),canUseDeviceLink: true,diagnosticsInfo: vi.fn(),quitHandlers: new Map<string, { fn: () => void; phase: string }>(),@@ -37,6 +40,8 @@ const h = vi.hoisted(() => ({}));vi.mock('electron', () => ({+ BrowserWindow: { fromWebContents: () => ({ isDestroyed: () => false }) },+ dialog: { showOpenDialog: h.selectFile },ipcMain: {handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => {h.handlers.set(channel, handler);@@ -53,9 +58,12 @@ vi.mock('../../lifecycle', () => ({}));// 读路径要比对 owner 作用域路径(账号边界复核),这里给个稳定值即可。vi.mock('../../appSessionState', () => ({+ getActiveAppSession: () => ({ dataOwnerId: 'owner-x', generation: h.ownerGeneration, mode: 'cloud' }),+ isAppSessionBoundaryPending: () => false,activeOwnerScopeKey: (): string => 'cloud:owner-x:1',ownerScopedUserDataPath: (...parts: string[]): string => ['/data/owners/x', ...parts].join('/'),}));+vi.mock('../../i18n', () => ({ t: (key: string) => key }));// 读路径还会查 purge 队列是否有待清记录;边界测试只关心授权,给"干净"。vi.mock('../mirrorCachePurgeQueue', () => ({enqueuePurge: vi.fn(async () => undefined),@@ -158,6 +166,8 @@ vi.mock('../subscriptionRefcount', () => ({import { DEVICE_LINK_INVOKE } from '../../../shared/deviceLinkIpc';import { registerDeviceLinkIpc } from '../ipc';+import { readWithSourceFileAccessRecovery } from '../sourceFileAccessRecovery';+import { rewriteOutboundMedia } from '../outboundMedia';import { DeviceLinkError, REMOTE_INVOKE_ALLOWLIST } from '@cindy/device-link';import { DESKTOP_LOCAL } from '../../../shared/remoteDesktop';import {@@ -169,7 +179,11 @@ import {} from '../index';import { setDeviceControlEnabled } from '../settings-store';-const EVENT = { sender: { id: 42 } } as Electron.IpcMainInvokeEvent;+const FRAME = { detached: false };+const EVENT = {+ sender: { id: 42, isDestroyed: () => h.senderDestroyed, mainFrame: FRAME },+ senderFrame: FRAME,+} as unknown as Electron.IpcMainInvokeEvent;/** 五个 channel 与一份能过运行期校验的最小 payload。 */const MIRROR_CACHE_CALLS: Array<[string, unknown]> = [@@ -198,10 +212,68 @@ beforeEach(() => {h.handlers.clear();h.quitHandlers.clear();h.trusted = true;+ h.ownerGeneration = 1;+ h.senderDestroyed = false;h.canUseDeviceLink = true;registerDeviceLinkIpc();});+// #6530 native recovery is installed only by the trusted foreground send adapter.+// The real rewrite/read boundary is covered in outboundMedia.test.ts; here the+// observable contract is exactly one final message, or none on cancellation/staleness.+describe('attachment access confirmation IPC', () => {+ const source = '/private/wechat/test.pdf';+ const payload = { deviceId: 'receiver', channel: 'maker:send', args: ['session', { content: [] }] };+ const denied = () => Object.assign(new Error('source denied'), { code: 'EPERM', syscall: 'open', path: source });+ function installReadFailure() {+ const read = vi.fn().mockRejectedValueOnce(denied()).mockResolvedValue('uploaded-ref');+ vi.mocked(rewriteOutboundMedia).mockImplementationOnce(async (_channel, args) => {+ const ref = await readWithSourceFileAccessRecovery(source, read);+ return [args[0], { content: [{ type: 'file', path: ref }] }];+ });+ return read;+ }++ it('continues the original send exactly once after selecting its source', async () => {+ const read = installReadFailure();+ h.selectFile.mockResolvedValueOnce({ canceled: false, filePaths: [source] });+ vi.mocked(remoteInvoke).mockResolvedValueOnce({ ok: true, result: 'accepted' });+ await expect(call(DEVICE_LINK_INVOKE.INVOKE, payload)).resolves.toBe('accepted');+ expect(read).toHaveBeenCalledTimes(2);+ expect(h.selectFile).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ defaultPath: source, properties: ['openFile'] }));+ expect(remoteInvoke).toHaveBeenCalledOnce();+ expect(vi.mocked(remoteInvoke).mock.calls[0][2]).toEqual(['session', { content: [{ type: 'file', path: 'uploaded-ref' }] }]);+ });++ it.each(['cancel', 'wrong-file', 'owner-change', 'window-closed', 'page-changed'])('does not dispatch after %s', async outcome => {+ const read = installReadFailure();+ h.selectFile.mockImplementationOnce(async () => {+ if (outcome === 'owner-change') h.ownerGeneration++;+ if (outcome === 'window-closed') h.senderDestroyed = true;+ if (outcome === 'page-changed') h.trusted = false;+ return { canceled: outcome === 'cancel', filePaths: [outcome === 'wrong-file' ? '/private/other.pdf' : source] };+ });+ await expect(call(DEVICE_LINK_INVOKE.INVOKE, payload)).rejects.toThrow();+ expect(read).toHaveBeenCalledOnce();+ expect(remoteInvoke).not.toHaveBeenCalled();+ });++ it('rejects an untrusted sender before opening a picker or forwarding', async () => {+ h.trusted = false;+ await expect(call(DEVICE_LINK_INVOKE.INVOKE, payload)).rejects.toThrow('PERMISSION_DENIED');+ expect(h.selectFile).not.toHaveBeenCalled();+ expect(remoteInvoke).not.toHaveBeenCalled();+ });++ it('keeps background sends noninteractive', async () => {+ const read = installReadFailure();+ await expect(call(DEVICE_LINK_INVOKE.INVOKE, { ...payload, scheduling: { background: true } })).rejects.toThrow();+ expect(read).toHaveBeenCalledOnce();+ expect(h.selectFile).not.toHaveBeenCalled();+ expect(remoteInvoke).not.toHaveBeenCalled();+ });+});+it('rejects Renderer-supplied remote Skill approval before forwarding any request', async () => {await expect(call(DEVICE_LINK_INVOKE.INVOKE, {deviceId: 'private-peer', channel: 'maker:remote-resources:invoke',diff --git a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.tsindex 38632e3833..6c80522e9b 100644--- a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts@@ -18,6 +18,7 @@ vi.mock('../../logger', () => ({}));import { rewriteOutboundMedia, withPeerAttachmentUpload, __testing } from '../outboundMedia';+import { withSourceFileAccessRecovery } from '../sourceFileAccessRecovery';import { buildPeerAttachmentRef, parsePeerAttachmentRef } from '@cindy/device-link';import { buildUserMessageAttachmentPayload } from '../../../renderer/lib/messageAttachmentPayload';import { REVIEW_START_REQUEST_LIMITS } from '../../maker-ipc/reviewStartHandler';@@ -49,6 +50,78 @@ beforeEach(() => {});describe('rewriteOutboundMedia — channel gating', () => {+ // #6530: native confirmation resumes the same attachment rewrite, never a second message.+ // Unit tier; existing access-denial coverage stops before this recovery boundary.+ it('confirms the denied original and resumes its upload without changing the draft payload', async () => {+ const file = '/private/wechat/test.pdf';+ const args = ['session', { type: 'user', content: [{ type: 'file', path: file }] }];+ const denied = Object.assign(new Error('denied'), { code: 'EPERM', syscall: 'open', path: file });+ uploadLocalFile.mockRejectedValueOnce(denied);+ const selectFile = vi.fn(async () => file);+ const result = await withSourceFileAccessRecovery({ selectFile, assertCurrent: () => {} },+ () => rewriteOutboundMedia('maker:send', args));+ expect(isAttachmentOssRef((result[1] as any).content[0].path)).toBe(true);+ expect(selectFile).toHaveBeenCalledWith(file);+ expect(uploadLocalFile).toHaveBeenCalledTimes(2);+ expect((args[1] as any).content[0].path).toBe(file);+ });++ it.each([null, '/private/another.pdf'])('keeps the original unsent when confirmation returns %s', async selected => {+ const file = '/private/wechat/test.pdf';+ uploadLocalFile.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES', syscall: 'open', path: file }));+ await expect(withSourceFileAccessRecovery({ selectFile: async () => selected, assertCurrent: () => {} },+ () => rewriteOutboundMedia('maker:send', ['session', { type: 'user', content: [{ type: 'file', path: file }] }]))+ ).rejects.toMatchObject({ code: 'DEVICE_LINK_MEDIA_ACCESS_DENIED' });+ expect(uploadLocalFile).toHaveBeenCalledOnce();+ });++ it('does not read again after the confirmation owner changes', async () => {+ const file = '/private/wechat/test.pdf';+ let current = true;+ uploadLocalFile.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EPERM', syscall: 'open', path: file }));+ await expect(withSourceFileAccessRecovery({+ selectFile: async () => { current = false; return file; },+ assertCurrent: () => { if (!current) throw new Error('cancelled'); },+ }, () => rewriteOutboundMedia('maker:send', ['session', { type: 'user', content: [{ type: 'file', path: file }] }]))+ ).rejects.toThrow('cancelled');+ expect(uploadLocalFile).toHaveBeenCalledOnce();+ });++ it('asks once per denied file and does not confirm transport failures', async () => {+ const file = '/private/wechat/test.pdf';+ const selectFile = vi.fn(async () => file);+ const run = () => withSourceFileAccessRecovery({ selectFile, assertCurrent: () => {} },+ () => rewriteOutboundMedia('maker:send', ['session', { type: 'user', content: [{ type: 'file', path: file }] }]));+ uploadLocalFile.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EPERM', syscall: 'open', path: file }));+ await expect(run()).rejects.toMatchObject({ code: 'DEVICE_LINK_MEDIA_ACCESS_DENIED' });+ expect(selectFile).toHaveBeenCalledOnce();+ expect(uploadLocalFile).toHaveBeenCalledTimes(2);+ selectFile.mockClear();+ uploadLocalFile.mockRejectedValue(new Error('network'));+ await expect(run()).rejects.toThrow('network');+ expect(selectFile).not.toHaveBeenCalled();+ });++ it('isolates a cancelled confirmation from another controller send', async () => {+ const first = '/private/one.pdf';+ const second = '/private/two.pdf';+ const attempted = new Set<string>();+ uploadLocalFile.mockImplementation(async (file: string) => {+ if (!attempted.has(file)) {+ attempted.add(file);+ throw Object.assign(new Error('denied'), { code: 'EPERM', syscall: 'open', path: file });+ }+ return { key: 'cindy/device-link/u/ok.pdf', size: 10, contentType: 'application/pdf', sha256: SHA256 };+ });+ const send = (file: string, selected: string | null) => withSourceFileAccessRecovery({+ selectFile: async source => { expect(source).toBe(file); return selected; }, assertCurrent: () => {},+ }, () => rewriteOutboundMedia('maker:send', ['session', { type: 'user', content: [{ type: 'file', path: file }] }]));+ const [cancelled, completed] = await Promise.allSettled([send(first, null), send(second, second)]);+ expect(cancelled.status).toBe('rejected');+ expect(completed.status).toBe('fulfilled');+ if (completed.status === 'fulfilled') expect(isAttachmentOssRef((completed.value[1] as any).content[0].path)).toBe(true);+ expect(uploadLocalFile.mock.calls.map(([file]) => file)).toEqual([first, second, second]);+ });it.each([['count', () => Array.from({ length: 21 }, () => ({ name: 'a', path: '/controller/a' }))],['metadata', () => [{ name: 'a', path: '/controller/a' }, { name: 'x'.repeat(4097), path: '/controller/b' }]],diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex 725692c029..1cee157970 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -82,6 +82,7 @@ import { createSentImageRetainer } from './remoteMediaPersistentCache';import { withOutboundReviewConfirmation } from '../maker-ipc/reviewOutboundInput.js';import { confirmReviewArtifacts } from '../reviewer/confirmReviewArtifacts.js';import { tryUploadPeerAttachment } from './filePeer';+import { withSourceFileAccessRecovery } from './sourceFileAccessRecovery';import { parseSharedTaskPeer, scrubSharedProviderCatalog } from '@cindy/device-link';import { withSharedTaskMedia } from './sharedTaskMediaContext.js';import {@@ -1689,6 +1690,45 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):() => handleInvoke(diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.channel, p.args),);}+ const interactiveAttachmentSend = ['maker:send', 'maker:steer', 'maker:input:enqueue', 'maker:input:steer'].includes(String(p.channel))+ && !(p.scheduling && typeof p.scheduling === 'object' && 'background' in p.scheduling && p.scheduling.background === true);+ if (interactiveAttachmentSend) {+ assertTrustedAppRendererEvent(e);+ const owner = getActiveAppSession();+ const frame = e.senderFrame;+ const targetWindow = BrowserWindow.fromWebContents(e.sender);+ const assertCurrent = () => {+ const current = getActiveAppSession();+ if (isAppSessionBoundaryPending() || !owner.dataOwnerId+ || current.dataOwnerId !== owner.dataOwnerId || current.generation !== owner.generation+ || e.sender.isDestroyed() || !frame || frame.detached || e.sender.mainFrame !== frame+ || !targetWindow || targetWindow.isDestroyed()) {+ throwIpcError('PERMISSION_DENIED', 'Attachment confirmation is no longer current');+ }+ assertTrustedAppRendererEvent(e);+ };+ const scopedDeps = diagnostics.forWindow(deps, e.sender.id);+ // This guard also runs immediately before final message dispatch, after all file awaits.+ const guardedDeps: DeviceLinkIpcDeps = {+ ...scopedDeps,+ invoke: (...args) => { assertCurrent(); return scopedDeps.invoke(...args); },+ };+ return withSourceFileAccessRecovery({+ assertCurrent,+ selectFile: async (source) => {+ assertCurrent();+ const selected = await dialog.showOpenDialog(targetWindow!, {+ title: t('attachmentAccessConfirmation.title'),+ message: t('attachmentAccessConfirmation.message'),+ buttonLabel: t('attachmentAccessConfirmation.button'),+ defaultPath: source,+ properties: ['openFile'],+ });+ assertCurrent();+ return selected.canceled || selected.filePaths.length !== 1 ? null : selected.filePaths[0];+ },+ }, () => handleInvoke(guardedDeps, p.deviceId, p.channel, p.args, p.scheduling));+ }return handleInvoke(diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.channel, p.args, p.scheduling);});// 多窗口订阅引用计数:每个发起订阅的窗口(WebContents)挂一次 'destroyed' 清理,diff --git a/apps/desktop/src/main/device-link/outboundMedia.ts b/apps/desktop/src/main/device-link/outboundMedia.tsindex 34284a6fc8..c6ea1175f9 100644--- a/apps/desktop/src/main/device-link/outboundMedia.ts+++ b/apps/desktop/src/main/device-link/outboundMedia.ts@@ -36,6 +36,7 @@ import { buildLegacyAttachmentOssRef, parseAttachmentOssRef } from '../../sharedimport { readStartReviewRequest } from '../maker-ipc/reviewStartHandler.js';import { withPreparedOutboundReview } from '../maker-ipc/reviewOutboundInput.js';import { createSourceFileAccessError, isSourceFileAccessError } from './sourceFileError';+import { readWithSourceFileAccessRecovery } from './sourceFileAccessRecovery';const log = createLogger('device-link:outboundMedia');@@ -117,8 +118,8 @@ async function uploadAttachment(src: AttachmentSource): Promise<string> {await direct(bytes, options?.contentType) ?? buildUploadedAttachmentRef(await uploadBuffer(bytes, options), originalName));const fileRef = async (file: string, options: Parameters<typeof uploadLocalFile>[1]) => {try {- return await retain(file,- await direct(file, options?.contentType) ?? buildUploadedAttachmentRef(await uploadLocalFile(file, options), originalName));+ return await readWithSourceFileAccessRecovery(file, async () => retain(file,+ await direct(file, options?.contentType) ?? buildUploadedAttachmentRef(await uploadLocalFile(file, options), originalName)));} catch (error) {if (isSourceFileAccessError(error, file)) {// Do not send Node's private source path across IPC or persist it in chat history.diff --git a/apps/desktop/src/main/device-link/sourceFileAccessRecovery.ts b/apps/desktop/src/main/device-link/sourceFileAccessRecovery.tsnew file mode 100644index 0000000000..22c4165396--- /dev/null+++ b/apps/desktop/src/main/device-link/sourceFileAccessRecovery.ts@@ -0,0 +1,38 @@+import { AsyncLocalStorage } from 'node:async_hooks';+import path from 'node:path';+import { createSourceFileAccessError, isSourceFileAccessError } from './sourceFileError';++interface SourceFileAccessRecovery {+ /** A native single-file picker; the selected path stays inside Main. */+ selectFile(source: string): Promise<string | null>;+ assertCurrent(): void;+}+const recoveryContext = new AsyncLocalStorage<SourceFileAccessRecovery & { attempted: Set<string> }>();++/** Only the trusted foreground chat adapter installs this scope. Exports/background jobs do not prompt. */+export function withSourceFileAccessRecovery<T>(recovery: SourceFileAccessRecovery, operation: () => Promise<T>): Promise<T> {+ return recoveryContext.run({ ...recovery, attempted: new Set() }, operation);+}++export async function readWithSourceFileAccessRecovery<T>(source: string, read: () => Promise<T>): Promise<T> {+ const scope = recoveryContext.getStore();+ scope?.assertCurrent();+ try {+ const result = await read();+ scope?.assertCurrent();+ return result;+ } catch (error) {+ if (!scope || !isSourceFileAccessError(error, source)+ || !path.isAbsolute(source) || scope.attempted.has(source)) throw error;+ scope.assertCurrent();+ scope.attempted.add(source);+ const selected = await scope.selectFile(source);+ scope.assertCurrent();+ // Confirm only this original. A different file must never silently replace a draft attachment.+ if (!selected || selected !== source) throw createSourceFileAccessError();+ // No recursive retry: a second denial returns the normal error and restores the draft.+ const result = await read();+ scope.assertCurrent();+ return result;+ }+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex aba355602a..9c9802a3fa 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1,4 +1,9 @@{+ "attachmentAccessConfirmation": {+ "title": "Confirm Attachment Access",+ "message": "Cindy cannot read this attachment. Select the original file to continue sending this message. Cancelling keeps your draft.",+ "button": "Use Original File"+ },"mailReader": {"markReadFailed": "Could not sync read status. Check mailbox authorization and reopen this email.","title": "Mail",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 96cdf7e0ca..ad8dea86f5 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1,4 +1,9 @@{+ "attachmentAccessConfirmation": {+ "title": "添付ファイルへのアクセスを確認",+ "message": "Cindy がこの添付ファイルを読み取れません。元のファイルを選択すると、このメッセージの送信を続行します。キャンセルすると下書きが保持されます。",+ "button": "元のファイルを使用"+ },"mailReader": {"markReadFailed": "既読状態を同期できませんでした。メールボックスの認証を確認して開き直してください。","title": "メール",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 7e71b3792a..c8bd309ee9 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1,4 +1,9 @@{+ "attachmentAccessConfirmation": {+ "title": "첨부 파일 접근 확인",+ "message": "Cindy가 이 첨부 파일을 읽을 수 없습니다. 원본 파일을 선택하면 이 메시지 전송을 계속합니다. 취소하면 초안이 유지됩니다.",+ "button": "원본 파일 사용"+ },"mailReader": {"markReadFailed": "읽음 상태를 동기화하지 못했습니다. 메일함 인증을 확인하고 다시 여세요.","title": "메일",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 8016472641..69e4fb5980 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1,4 +1,9 @@{+ "attachmentAccessConfirmation": {+ "title": "确认附件访问",+ "message": "Cindy 无法读取这个附件。请选择原文件,确认后继续发送这条消息;取消会保留草稿。",+ "button": "使用原文件"+ },"mailReader": {"markReadFailed": "未能同步已读状态,请检查邮箱授权后重新打开。","title": "邮件",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 66747c4090..34a58e54a1 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1,4 +1,9 @@{+ "attachmentAccessConfirmation": {+ "title": "確認附件存取",+ "message": "Cindy 無法讀取這個附件。請選擇原始檔案,確認後繼續傳送這則訊息;取消會保留草稿。",+ "button": "使用原始檔案"+ },"mailReader": {"markReadFailed": "未能同步已讀狀態,請檢查信箱授權後重新開啟。","title": "郵件",