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): 安全传输可执行附件并保留原始扩展名 (#1393)

DavidShenXDbbefa343af7b
diff --git a/apps/desktop/src/main/__tests__/chatAttachmentIpcOwnerBoundary.test.ts b/apps/desktop/src/main/__tests__/chatAttachmentIpcOwnerBoundary.test.ts
new file mode 100644
index 0000000000..424d9143e4
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/chatAttachmentIpcOwnerBoundary.test.ts
@@ -0,0 +1,28 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const bootstrapSource = readFileSync(
+ resolve(__dirname, '..', 'bootstrap-electron.ts'),
+ 'utf8',
+).replace(/\r\n?/g, '\n');
+const attachmentIpcSource = bootstrapSource.slice(
+ bootstrapSource.indexOf('const stageChatAttachment = createChatAttachmentStageHandler'),
+ bootstrapSource.indexOf('// Settings → About:'),
+);
+
+describe('chat attachment IPC owner boundary', () => {
+ it('stages against the active app data owner, including local mode', () => {
+ expect(attachmentIpcSource).toContain('const ownerId = getActiveAppSession().dataOwnerId;');
+ expect(attachmentIpcSource).not.toContain('authManager.getAuthState().user?.id');
+ });
+
+ it('protects persisted paths and rechecks owner scope before renderer cleanup', () => {
+ expect(attachmentIpcSource).toContain(
+ 'const protectedPaths = await listPersistedChatAttachmentPaths();',
+ );
+ expect(attachmentIpcSource).toContain('activeOwnerScopeKey() === ownerScopeKey');
+ expect(attachmentIpcSource).toContain('cleanupOwnedUnpersistedStagedChatAttachments({');
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/chatAttachmentStage.test.ts b/apps/desktop/src/main/__tests__/chatAttachmentStage.test.ts
new file mode 100644
index 0000000000..376edeebd8
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/chatAttachmentStage.test.ts
@@ -0,0 +1,120 @@
+import path from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ createChatAttachmentStageHandler,
+ type ChatAttachmentStageDeps,
+ type ChatAttachmentStageOpenedSource,
+ type ChatAttachmentStageSourceStat,
+} from '../chatAttachmentStage';
+
+function fileStat(dev = 1n, ino = 1n, size = 64n): ChatAttachmentStageSourceStat {
+ return { dev, ino, size, isFile: () => true };
+}
+
+function openedSource(
+ overrides: Partial<ChatAttachmentStageOpenedSource> = {},
+): ChatAttachmentStageOpenedSource {
+ return {
+ stat: vi.fn(async () => fileStat()),
+ copyTo: vi.fn(async () => {}),
+ close: vi.fn(async () => {}),
+ ...overrides,
+ };
+}
+
+function makeDeps(overrides: Partial<ChatAttachmentStageDeps> = {}): ChatAttachmentStageDeps {
+ return {
+ isPathAllowed: () => true,
+ realpath: vi.fn(async (filePath) => filePath),
+ stat: vi.fn(async () => fileStat()),
+ openSource: vi.fn(async () => openedSource()),
+ stageCopy: vi.fn(async ({ copyTo }) => {
+ const target = path.resolve('cache', 'staged-setup.exe.bin');
+ await copyTo(`${target}.part`);
+ return target;
+ }),
+ ...overrides,
+ };
+}
+
+describe('createChatAttachmentStageHandler', () => {
+ it('copies a dangerous local file from the validated handle to an inert .bin path', async () => {
+ const source = openedSource();
+ const deps = makeDeps({ openSource: vi.fn(async () => source) });
+ const sourcePath = path.resolve('downloads', 'setup.exe');
+
+ await expect(
+ createChatAttachmentStageHandler(deps)({ sourcePath, suggestedName: 'setup.exe' }),
+ ).resolves.toEqual({ success: true, path: path.resolve('cache', 'staged-setup.exe.bin') });
+
+ expect(deps.stat).toHaveBeenCalledWith(sourcePath);
+ expect(deps.openSource).toHaveBeenCalledWith(sourcePath);
+ expect(source.copyTo).toHaveBeenCalledWith(
+ `${path.resolve('cache', 'staged-setup.exe.bin')}.part`,
+ );
+ expect(source.close).toHaveBeenCalledOnce();
+ });
+
+ it('stages a dangerous physical path even when the display name has no executable suffix', async () => {
+ const source = openedSource();
+ const deps = makeDeps({ openSource: vi.fn(async () => source) });
+ const sourcePath = path.resolve('downloads', 'setup.exe');
+
+ await expect(
+ createChatAttachmentStageHandler(deps)({ sourcePath, suggestedName: 'attachment' }),
+ ).resolves.toEqual({ success: true, path: path.resolve('cache', 'staged-setup.exe.bin') });
+ });
+
+ it('rejects safe extensions and forbidden or relative source paths before copying', async () => {
+ const deps = makeDeps();
+ await expect(
+ createChatAttachmentStageHandler(deps)({
+ sourcePath: path.resolve('downloads', 'archive.zip'),
+ suggestedName: 'archive.zip',
+ }),
+ ).resolves.toEqual({ success: false, code: 'unsupported_type' });
+ await expect(
+ createChatAttachmentStageHandler(deps)({
+ sourcePath: 'setup.exe',
+ suggestedName: 'setup.exe',
+ }),
+ ).resolves.toEqual({ success: false, code: 'invalid_source' });
+
+ const forbidden = makeDeps({ isPathAllowed: () => false });
+ await expect(
+ createChatAttachmentStageHandler(forbidden)({
+ sourcePath: path.resolve('downloads', 'setup.exe'),
+ suggestedName: 'setup.exe',
+ }),
+ ).resolves.toEqual({ success: false, code: 'forbidden' });
+ expect(deps.stageCopy).not.toHaveBeenCalled();
+ expect(forbidden.stageCopy).not.toHaveBeenCalled();
+ });
+
+ it('rejects a source object replaced after validation and closes the handle', async () => {
+ const replacement = openedSource({ stat: vi.fn(async () => fileStat(1n, 2n)) });
+ const deps = makeDeps({ openSource: vi.fn(async () => replacement) });
+
+ await expect(
+ createChatAttachmentStageHandler(deps)({
+ sourcePath: path.resolve('downloads', 'setup.exe'),
+ suggestedName: 'setup.exe',
+ }),
+ ).resolves.toEqual({ success: false, code: 'forbidden' });
+ expect(deps.stageCopy).not.toHaveBeenCalled();
+ expect(replacement.close).toHaveBeenCalledOnce();
+ });
+
+ it('fails closed when the cache writer returns an executable destination', async () => {
+ const deps = makeDeps({
+ stageCopy: vi.fn(async () => path.resolve('cache', 'setup.exe')),
+ });
+ await expect(
+ createChatAttachmentStageHandler(deps)({
+ sourcePath: path.resolve('downloads', 'setup.exe'),
+ suggestedName: 'setup.exe',
+ }),
+ ).resolves.toEqual({ success: false, code: 'copy_failed' });
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/imageCacheStoreExt.test.ts b/apps/desktop/src/main/__tests__/imageCacheStoreExt.test.ts
index 81318a08f2..1e62f4850e 100644
--- a/apps/desktop/src/main/__tests__/imageCacheStoreExt.test.ts
+++ b/apps/desktop/src/main/__tests__/imageCacheStoreExt.test.ts
@@ -51,6 +51,10 @@ describe('imageCacheStore.copyFromPath — extension preservation', () => {
expect(await copiedExt('sheet.xlsx')).toBe('.xlsx');
expect(await copiedExt('notes.txt')).toBe('.txt');
expect(await copiedExt('readme.MD')).toBe('.md'); // lowercased
+ expect(await copiedExt('archive.zip')).toBe('.zip');
+ expect(await copiedExt('model.blend')).toBe('.blend');
+ expect(await copiedExt('design.psd')).toBe('.psd');
+ expect(await copiedExt('archive.tar.gz')).toBe('.gz');
});
it('still preserves image extensions (unchanged behavior)', async () => {
@@ -61,7 +65,7 @@ describe('imageCacheStore.copyFromPath — extension preservation', () => {
it('falls back to .bin when there is no usable extension', async () => {
expect(await copiedExt('no-extension')).toBe('.bin');
expect(await copiedExt('trailing.')).toBe('.bin'); // dot with nothing after
- expect(await copiedExt('archive.tar.gz')).toBe('.bin'); // .gz is not a supported attachment type
+ expect(await copiedExt(`name.${'a'.repeat(25)}`)).toBe('.bin');
});
it('does NOT preserve executable/installer extensions (→ .bin, so the chip can not openPath-exec)', async () => {
@@ -70,6 +74,11 @@ describe('imageCacheStore.copyFromPath — extension preservation', () => {
expect(await copiedExt('image.dmg')).toBe('.bin');
expect(await copiedExt('tool.app')).toBe('.bin');
expect(await copiedExt('lib.jar')).toBe('.bin');
+ expect(await copiedExt('script.cmd')).toBe('.bin');
+ expect(await copiedExt('script.ps1')).toBe('.bin');
+ expect(await copiedExt('script.js')).toBe('.bin');
+ expect(await copiedExt('script.py')).toBe('.bin');
+ expect(await copiedExt('update.msu')).toBe('.bin');
});
it('round-trips setup.exe → .bin cache → Save As setup.exe without opening it', async () => {
@@ -131,4 +140,15 @@ describe('imageCacheStore.writeBuffer — trusted mimeType wins over suggestedNa
});
expect(path.extname(filename).toLowerCase()).toBe('.png');
});
+
+ it('keeps a dangerous suggested name inert even when the MIME claims it is an image', async () => {
+ const { filename } = await imageCacheStore.writeBuffer({
+ sessionId: 'sess-ext',
+ buffer: new Uint8Array([1, 2, 3]),
+ mimeType: 'image/png',
+ suggestedName: 'setup.exe',
+ lifecycle: 'committed',
+ });
+ expect(path.extname(filename).toLowerCase()).toBe('.bin');
+ });
});
diff --git a/apps/desktop/src/main/__tests__/imageCacheStoreLifecycle.test.ts b/apps/desktop/src/main/__tests__/imageCacheStoreLifecycle.test.ts
index 4edc9dc3bd..bf49321d67 100644
--- a/apps/desktop/src/main/__tests__/imageCacheStoreLifecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/imageCacheStoreLifecycle.test.ts
@@ -107,6 +107,21 @@ describe('imageCacheStore lifecycle metadata', () => {
expect(await exists(absPath)).toBe(true);
});
+ it('removeFile removes the image and its lifecycle metadata', async () => {
+ const cached = await imageCacheStore.writeBuffer({
+ sessionId: 'session-a',
+ buffer: new Uint8Array([1, 2, 3]),
+ mimeType: 'image/png',
+ lifecycle: 'committed',
+ });
+ const { absPath } = imageCacheStore.resolveSafe(cached.url);
+
+ await imageCacheStore.removeFile(cached.url);
+
+ expect(await exists(absPath)).toBe(false);
+ expect(await exists(`${absPath}.xdt-meta.json`)).toBe(false);
+ });
+
it('markFilesCommitted turns a draft image into a sweep-safe history image', async () => {
const cached = await imageCacheStore.writeBuffer({
sessionId: 'session-a',
diff --git a/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts b/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts
index 3cd1c3fc05..49407f02f1 100644
--- a/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts
+++ b/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts
@@ -2,6 +2,8 @@
* normalizeAttachmentsOss.test.ts — 被控端入方向物化:device-link 出方向 OSS 引用 →
* presign-get 下载 → 写临时文件 → block.path 变本地路径 → 用后删 OSS。失败丢该附件。
*/
+import assert from 'node:assert/strict';
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('electron', () => ({ app: { getPath: () => '/tmp/test-attach' } }));
@@ -18,9 +20,11 @@ vi.mock('node:fs/promises', () => ({
}));
const copyFromPath = vi.hoisted(() => vi.fn());
+const removeFile = vi.hoisted(() => vi.fn(async () => {}));
const resolveSafe = vi.hoisted(() => vi.fn());
vi.mock('../imageCacheStore.js', () => ({
copyFromPath,
+ removeFile,
resolveSafe,
collectSessionImageUrls: vi.fn(() => []),
}));
@@ -30,8 +34,13 @@ const BLOB_HASH = 'a'.repeat(64);
const BLOB_URL = `cindy-media://blobs/${BLOB_HASH}.png`;
const ingestMedia = vi.hoisted(() => vi.fn());
vi.mock('../cindy-media/ingest.js', () => ({ ingestMedia }));
+const removeRefById = vi.hoisted(() => vi.fn(async () => 1));
+const deleteZeroRefBlobRecord = vi.hoisted(() => vi.fn(async () => false));
+vi.mock('../cindy-media/ledger.js', () => ({ removeRefById, deleteZeroRefBlobRecord }));
const blobResolveSafe = vi.hoisted(() => vi.fn());
+const deleteBlobFile = vi.hoisted(() => vi.fn(async () => {}));
vi.mock('../cindy-media/blobStore.js', () => ({
+ deleteBlobFile,
resolveSafe: blobResolveSafe,
mimeForExt: (ext: string) =>
(
@@ -56,6 +65,7 @@ vi.mock('../logger.js', () => ({
}));
import {
+ materializeDirectSendOssAttachments,
normalizeUserMessage,
materializeQueuedOssAttachments,
} from '../maker-ipc/normalizeAttachments';
@@ -101,6 +111,8 @@ beforeEach(() => {
deduplicated: false,
refIds: ['ref-1'],
});
+ removeRefById.mockResolvedValue(1);
+ deleteZeroRefBlobRecord.mockResolvedValue(false);
blobResolveSafe.mockImplementation((url: string) => ({
absPath: `/blobs/${url.slice('cindy-media://blobs/'.length)}`,
mimeType: 'image/png',
@@ -373,3 +385,202 @@ describe('materializeQueuedOssAttachments — 出方向 files[] + persistedConte
).rejects.toThrow(/完整性校验失败/);
});
});
+
+describe('materializeDirectSendOssAttachments — message + persistUserMessage 一次性物化', () => {
+ it('同一危险文件只下载一次,agent path 与持久路径同时落到 .bin,发送 accepted 后才删 OSS', async () => {
+ const ref = buildAttachmentOssRef({
+ ossKey: 'oss/setup.bin',
+ mimeType: 'application/octet-stream',
+ originalName: 'setup.exe',
+ size: 15,
+ sha256: ATTACHMENT_SHA256,
+ });
+ copyFromPath.mockImplementation(async ({ originalName }: { originalName: string }) => ({
+ url: `xdt-image://sess-1/cached-${originalName}.bin`,
+ filename: `cached-${originalName}.bin`,
+ }));
+ resolveSafe.mockImplementation((url: string) => ({
+ absPath: `/cache/${url.replace('xdt-image://', '')}`,
+ mimeType: 'application/octet-stream',
+ }));
+ const persistedContent = JSON.stringify({
+ text: 'run check',
+ images: [],
+ files: [{
+ name: 'setup.exe',
+ path: ref,
+ size: 15,
+ sha256: ATTACHMENT_SHA256,
+ }],
+ });
+
+ const out = await materializeDirectSendOssAttachments(
+ 'sess-1',
+ {
+ type: 'user',
+ content: [
+ { type: 'text', text: 'run check' },
+ {
+ type: 'file',
+ path: ref,
+ mimeType: 'application/octet-stream',
+ originalName: 'setup.exe',
+ },
+ ],
+ },
+ { persistUserMessage: { clientId: 'c1', content: persistedContent } },
+ );
+
+ assert.equal(downloadToFile.mock.calls.length, 1);
+ const copyArgs = copyFromPath.mock.calls[0]?.[0] as { originalName?: unknown } | undefined;
+ assert.equal(copyArgs?.originalName, 'setup.exe');
+ assert.equal(removeRemote.mock.calls.length, 0);
+ assert.equal(typeof out.cleanupAfterAcceptance, 'function');
+ assert.equal(typeof out.cleanupBeforeAcceptance, 'function');
+ await out.cleanupBeforeAcceptance?.();
+ expect(removeRemote).not.toHaveBeenCalled();
+ expect(removeFile).toHaveBeenCalledWith('xdt-image://sess-1/cached-setup.exe.bin');
+ out.cleanupAfterAcceptance?.();
+ const removeCalls = removeRemote.mock.calls as unknown[][];
+ assert.equal(removeCalls.length, 1);
+ assert.equal(removeCalls[0]?.[0], 'oss/setup.bin');
+
+ const block = (out.message as { content: Array<{ path?: string }> }).content[1];
+ assert.equal(block.path, '/cache/sess-1/cached-setup.exe.bin');
+ const pc = JSON.parse(
+ (out.sendOpts as { persistUserMessage: { content: string } }).persistUserMessage.content,
+ ) as { files: Array<{ name: string; path: string }> };
+ assert.deepEqual(pc.files[0], {
+ name: 'setup.exe',
+ path: '/cache/sess-1/cached-setup.exe.bin',
+ size: 15,
+ sha256: ATTACHMENT_SHA256,
+ });
+ });
+
+ it('cleans a cindy-media materialization and its ref before an unaccepted send', async () => {
+ const ref = buildAttachmentOssRef({
+ ossKey: 'oss/photo.png',
+ mimeType: 'image/png',
+ originalName: 'photo.png',
+ });
+ deleteZeroRefBlobRecord.mockResolvedValue(true);
+
+ const out = await materializeDirectSendOssAttachments(
+ 'sess-1',
+ { type: 'user', content: [{ type: 'file', path: ref, mimeType: 'image/png' }] },
+ undefined,
+ );
+
+ await out.cleanupBeforeAcceptance?.();
+
+ expect(removeRefById).toHaveBeenCalledWith('ref-1');
+ expect(deleteZeroRefBlobRecord).toHaveBeenCalledWith(BLOB_HASH, expect.any(Number));
+ expect(deleteBlobFile).toHaveBeenCalledWith(BLOB_HASH, '.png');
+ expect(removeRemote).not.toHaveBeenCalled();
+
+ out.cleanupAfterAcceptance?.();
+ expect(removeRemote).toHaveBeenCalledWith('oss/photo.png');
+ });
+
+ it('没有 OSS 引用时保持原对象,不产生文件 IO', async () => {
+ const message = {
+ type: 'user',
+ content: [{ type: 'file', path: 'C:\\cache\\local.pdf', mimeType: 'application/pdf' }],
+ };
+ const sendOpts = {
+ persistUserMessage: {
+ content: JSON.stringify({
+ text: '',
+ images: [],
+ files: [{ name: 'local.pdf', path: 'C:\\cache\\local.pdf' }],
+ }),
+ },
+ };
+ const out = await materializeDirectSendOssAttachments('sess-1', message, sendOpts);
+ assert.deepEqual(out, { message, sendOpts });
+ assert.equal(downloadToFile.mock.calls.length, 0);
+ });
+
+ it('materializing another OSS file does not strip an unrelated base64 image', async () => {
+ const fileRef = buildAttachmentOssRef({
+ ossKey: 'oss/doc.pdf',
+ mimeType: 'application/pdf',
+ originalName: 'doc.pdf',
+ });
+ copyFromPath.mockResolvedValue({
+ url: 'xdt-image://sess-1/cached-doc.pdf',
+ filename: 'cached-doc.pdf',
+ });
+ resolveSafe.mockReturnValue({
+ absPath: '/cache/sess-1/cached-doc.pdf',
+ mimeType: 'application/pdf',
+ });
+ const message = {
+ type: 'user',
+ content: [
+ { type: 'image', base64: 'inline-image', mimeType: 'image/png' },
+ { type: 'file', path: fileRef, mimeType: 'application/pdf' },
+ ],
+ };
+ const out = await materializeDirectSendOssAttachments(
+ 'sess-1',
+ message,
+ {
+ persistUserMessage: {
+ content: JSON.stringify({
+ text: '',
+ images: [],
+ files: [{ name: 'doc.pdf', path: fileRef }],
+ }),
+ },
+ },
+ );
+ assert.deepEqual((out.message as typeof message).content[0], {
+ type: 'image',
+ base64: 'inline-image',
+ mimeType: 'image/png',
+ });
+ });
+
+ it('dangerous original names stay .bin even when a remote MIME claims image/png', async () => {
+ const ref = buildAttachmentOssRef({
+ ossKey: 'oss/spoofed.png',
+ mimeType: 'image/png',
+ originalName: 'setup.exe',
+ size: 3,
+ sha256: ATTACHMENT_SHA256,
+ });
+ copyFromPath.mockResolvedValue({
+ url: 'xdt-image://sess-1/cached-setup.bin',
+ filename: 'cached-setup.bin',
+ });
+ resolveSafe.mockReturnValue({
+ absPath: '/cache/sess-1/cached-setup.bin',
+ mimeType: 'application/octet-stream',
+ });
+ const out = await materializeDirectSendOssAttachments(
+ 'sess-1',
+ {
+ type: 'user',
+ content: [{ type: 'file', path: ref, mimeType: 'image/png', originalName: 'setup.exe' }],
+ },
+ {
+ persistUserMessage: {
+ content: JSON.stringify({
+ text: '',
+ images: [],
+ files: [{ name: 'setup.exe', path: ref, size: 3, sha256: ATTACHMENT_SHA256 }],
+ }),
+ },
+ },
+ );
+ assert.equal(ingestMedia.mock.calls.length, 0);
+ const copyArgs = copyFromPath.mock.calls[0]?.[0] as { originalName?: unknown } | undefined;
+ assert.equal(copyArgs?.originalName, 'setup.exe');
+ assert.equal(
+ (out.message as { content: Array<{ path: string }> }).content[0].path,
+ '/cache/sess-1/cached-setup.bin',
+ );
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 2c3b3a6863..5c54bb5f87 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -199,6 +199,14 @@ import {
REMOTE_IMAGE_MAX_BYTES,
} from './lightboxMediaActions';
import { createChatAttachmentSaveHandler } from './chatAttachmentSave';
+import { createChatAttachmentStageHandler } from './chatAttachmentStage';
+import {
+ cleanupOwnedUnpersistedStagedChatAttachments,
+ getChatAttachmentCacheRoot,
+ getRemoteFileCacheRoot,
+ stageLocalFileToCache,
+ sweepStagedChatAttachmentsOnStartup,
+} from './file-browser/remote-file-cache';
import { sweepStartupDraftImages } from './imageCacheOrphanSweep';
import { sweepLegacyDialogueWorkingDirs } from './localDb/dialogueWorkdirSelfHeal';
import { BRAND_IDENTITY } from '@cindy/maker-shared/brand-identity';
@@ -236,6 +244,7 @@ import { cindyGhostSchemePrivilege } from './cindy-brain/runtime/electronSandbox
import { fetchReleaseNotes, fetchReleaseNotesIndex } from './releaseNotesService';
import { resolveWorkspacePathCached, resolveWorkspacePathBatchCached } from './pathResolver';
import { registerLocalDbIpc } from './localDb/ipc/registerAll';
+import { listPersistedChatAttachmentPaths } from './localDb/ipc/messages';
import {
registerLegacyMigrationIpc,
runLegacyUserDataMigrationForUser,
@@ -5055,13 +5064,67 @@ const registerIpcHandlers = () => {
getDownloadsDir: () => app.getPath('downloads'),
getAllowedSourceRoots: () => [
imageCacheStore.getCacheRoot(),
- path.join(app.getPath('userData'), 'remote-file-cache'),
+ getChatAttachmentCacheRoot(),
+ getRemoteFileCacheRoot(),
],
});
+ const stageChatAttachment = createChatAttachmentStageHandler({
+ isPathAllowed,
+ realpath: (filePath) => fs.promises.realpath(filePath),
+ stat: (filePath) => fs.promises.stat(filePath, { bigint: true }),
+ openSource: async (filePath) => {
+ const noFollow = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
+ const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY | noFollow);
+ return {
+ stat: () => handle.stat({ bigint: true }),
+ copyTo: async (targetPath) => {
+ await pipeline(
+ handle.createReadStream({ autoClose: false, start: 0 }),
+ fs.createWriteStream(targetPath, { flags: 'wx' }),
+ );
+ },
+ close: () => handle.close(),
+ };
+ },
+ stageCopy: (params) => {
+ const ownerId = getActiveAppSession().dataOwnerId;
+ if (!ownerId) throw new Error('Cannot stage an attachment without an active data owner');
+ return stageLocalFileToCache({ ...params, ownerId });
+ },
+ });
+ ipcMain.handle(
+ 'chat-attachment:stage',
+ (event, params: { sourcePath?: unknown; suggestedName?: unknown }) => {
+ assertTrustedAppRendererEvent(event);
+ return stageChatAttachment(params);
+ },
+ );
+ ipcMain.handle(
+ 'chat-attachment:cleanup',
+ async (event, filePaths: readonly string[]) => {
+ assertTrustedAppRendererEvent(event);
+ if (!Array.isArray(filePaths)) return;
+ const ownerScopeKey = activeOwnerScopeKey();
+ const ownerId = getActiveAppSession().dataOwnerId;
+ if (!ownerId || isAppSessionBoundaryPending()) return;
+ const protectedPaths = await listPersistedChatAttachmentPaths();
+ const isCurrentOwner = () =>
+ activeOwnerScopeKey() === ownerScopeKey && !isAppSessionBoundaryPending();
+ if (!isCurrentOwner()) return;
+ await cleanupOwnedUnpersistedStagedChatAttachments({
+ ownerId,
+ filePaths,
+ protectedPaths,
+ canRemove: isCurrentOwner,
+ });
+ },
+ );
ipcMain.handle(
'chat-attachment:save-as',
- (_event, params: { sourcePath?: unknown; suggestedName?: unknown }) =>
- saveChatAttachment(params),
+ (event, params: { sourcePath?: unknown; suggestedName?: unknown }) => {
+ assertTrustedAppRendererEvent(event);
+ return saveChatAttachment(params);
+ },
);
// Settings → About: 打开 <userData>/logs 在系统文件管理器。
@@ -5862,6 +5925,26 @@ app.on('ready', async () => {
// Phase 1.1: file worker 接管 DB 连接后,释放 main 端的 _db + optimize 定时器。
// 如果 worker takeover 失败并进入 inproc fallback,main _db 必须继续保留,
// 否则 fallback 会拿到已关闭的连接。
+ try {
+ const protectedPaths = await listPersistedChatAttachmentPaths();
+ const result = await sweepStagedChatAttachmentsOnStartup({
+ ownerId: userId,
+ protectedPaths,
+ createdBeforeMs: PROCESS_STARTED_AT_MS,
+ });
+ if (result.removed > 0 || result.protected > 0) {
+ dbClientLog.info('[ChatAttachment] startup staged attachment sweep completed', {
+ ...result,
+ ownerId: userId,
+ });
+ }
+ } catch (err) {
+ dbClientLog.warn('[ChatAttachment] startup staged attachment sweep failed (non-fatal)', {
+ ownerId: userId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ logStartupPhase('chat-attachment-sweep');
if (dbClientTakeover.shouldReleaseMainDb && process.env.XDT_DB_INPROC !== 'true') {
// 只把连接交给 worker,不能释放 shared-passive schema reader lease:worker
// 还会长期持有同一 DB;lease 必须留到真正 logout / app quit 才释放。
diff --git a/apps/desktop/src/main/chatAttachmentStage.ts b/apps/desktop/src/main/chatAttachmentStage.ts
new file mode 100644
index 0000000000..2eef014d38
--- /dev/null
+++ b/apps/desktop/src/main/chatAttachmentStage.ts
@@ -0,0 +1,123 @@
+/**
+ * Copies a dangerous local attachment into a controlled cache under an inert
+ * `.bin` filename before the renderer stores or sends the attachment record.
+ *
+ * The caller validates the selected path, resolves symlinks, then copies from
+ * the same already-opened file object that was checked. This keeps the source
+ * path from being swapped between validation and copy.
+ */
+import path from 'node:path';
+
+import { isDangerousAttachmentName } from '../shared/attachmentSafety.js';
+
+export type ChatAttachmentStageErrorCode =
+ | 'invalid_source'
+ | 'forbidden'
+ | 'not_found'
+ | 'not_file'
+ | 'unsupported_type'
+ | 'copy_failed';
+
+export type ChatAttachmentStageResult =
+ | { success: true; path: string }
+ | { success: false; code: ChatAttachmentStageErrorCode };
+
+export interface ChatAttachmentStageSourceStat {
+ dev: bigint;
+ ino: bigint;
+ size: bigint;
+ isFile(): boolean;
+}
+
+export interface ChatAttachmentStageOpenedSource {
+ stat(): Promise<ChatAttachmentStageSourceStat>;
+ copyTo(targetPath: string): Promise<void>;
+ close(): Promise<void>;
+}
+
+export interface ChatAttachmentStageDeps {
+ isPathAllowed(filePath: string): boolean;
+ realpath(filePath: string): Promise<string>;
+ stat(filePath: string): Promise<ChatAttachmentStageSourceStat>;
+ openSource(filePath: string): Promise<ChatAttachmentStageOpenedSource>;
+ stageCopy(params: {
+ suggestedName: string;
+ expectedSize: bigint;
+ copyTo(targetPath: string): Promise<void>;
+ }): Promise<string>;
+}
+
+function isSameFileObject(
+ expected: ChatAttachmentStageSourceStat,
+ actual: ChatAttachmentStageSourceStat,
+): boolean {
+ return expected.ino !== 0n && expected.dev === actual.dev && expected.ino === actual.ino;
+}
+
+export function createChatAttachmentStageHandler(deps: ChatAttachmentStageDeps) {
+ return async function stageChatAttachment(params: {
+ sourcePath?: unknown;
+ suggestedName?: unknown;
+ }): Promise<ChatAttachmentStageResult> {
+ const sourcePath = typeof params?.sourcePath === 'string' ? params.sourcePath : '';
+ const suggestedName = typeof params?.suggestedName === 'string' ? params.suggestedName : '';
+ if (!sourcePath || !path.isAbsolute(sourcePath)) {
+ return { success: false, code: 'invalid_source' };
+ }
+ if (
+ !suggestedName ||
+ (!isDangerousAttachmentName(suggestedName) && !isDangerousAttachmentName(sourcePath))
+ ) {
+ return { success: false, code: 'unsupported_type' };
+ }
+ if (!deps.isPathAllowed(sourcePath)) {
+ return { success: false, code: 'forbidden' };
+ }
+
+ let resolvedSourcePath: string;
+ try {
+ resolvedSourcePath = await deps.realpath(sourcePath);
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ return { success: false, code: code === 'ENOENT' ? 'not_found' : 'forbidden' };
+ }
+ if (!deps.isPathAllowed(resolvedSourcePath)) {
+ return { success: false, code: 'forbidden' };
+ }
+
+ let validatedSourceStat: ChatAttachmentStageSourceStat;
+ try {
+ validatedSourceStat = await deps.stat(resolvedSourcePath);
+ if (!validatedSourceStat.isFile()) return { success: false, code: 'not_file' };
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ return { success: false, code: code === 'ENOENT' ? 'not_found' : 'not_file' };
+ }
+
+ let openedSource: ChatAttachmentStageOpenedSource | null = null;
+ try {
+ openedSource = await deps.openSource(resolvedSourcePath);
+ const openedStat = await openedSource.stat();
+ if (!openedStat.isFile()) return { success: false, code: 'not_file' };
+ if (!isSameFileObject(validatedSourceStat, openedStat)) {
+ return { success: false, code: 'forbidden' };
+ }
+ const stagedPath = await deps.stageCopy({
+ suggestedName,
+ expectedSize: openedStat.size,
+ copyTo: (targetPath) => openedSource!.copyTo(targetPath),
+ });
+ if (!path.isAbsolute(stagedPath) || path.extname(stagedPath).toLowerCase() !== '.bin') {
+ return { success: false, code: 'copy_failed' };
+ }
+ return { success: true, path: stagedPath };
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ if (code === 'ENOENT') return { success: false, code: 'not_found' };
+ if (code === 'ELOOP') return { success: false, code: 'forbidden' };
+ return { success: false, code: 'copy_failed' };
+ } finally {
+ if (openedSource) await openedSource.close().catch(() => undefined);
+ }
+ };
+}
diff --git a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
index 6a422c8637..994733339f 100644
--- a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
@@ -136,6 +136,63 @@ describe('rewriteQueued — persistedContent 同批改写 + 去重单上传', ()
});
describe('rewriteOutboundMedia — send/steer content-block 形态', () => {
+ it('maker:send 同批改写 message 与持久内容,同一附件只上传一次并传播原名', async () => {
+ uploadLocalFile.mockResolvedValue({
+ key: 'cindy/device-link/u/setup.bin',
+ size: 42,
+ contentType: 'application/octet-stream',
+ sha256: SHA256,
+ });
+ const persistedContent = JSON.stringify({
+ text: 'check it',
+ images: [],
+ files: [{ name: 'setup.exe', path: 'C:\\cache\\setup.exe.bin' }],
+ });
+
+ const out = await rewriteOutboundMedia('maker:send', [
+ 'sess',
+ {
+ type: 'user',
+ content: [
+ {
+ type: 'file',
+ path: 'C:\\cache\\setup.exe.bin',
+ mimeType: 'application/octet-stream',
+ originalName: 'setup.exe',
+ },
+ ],
+ },
+ undefined,
+ { persistUserMessage: { clientId: 'c1', content: persistedContent } },
+ ]);
+
+ expect(uploadLocalFile).toHaveBeenCalledTimes(1);
+ const block = (out[1] as { content: Array<{ path: string; originalName: string }> }).content[0];
+ const pc = JSON.parse(
+ ((out[3] as { persistUserMessage: { content: string } }).persistUserMessage.content),
+ ) as { files: Array<{ path: string }> };
+ expect(pc.files[0].path).toBe(block.path);
+ expect(block.originalName).toBe('setup.exe');
+ expect(parseAttachmentOssRef(block.path)?.originalName).toBe('setup.exe');
+ });
+
+ it('uses queued file.name when originalName is absent', async () => {
+ const out = await rewriteOutboundMedia('maker:input:enqueue', [
+ 'sess',
+ {
+ files: [
+ {
+ name: 'archive.zip',
+ path: '/abs/archive.zip',
+ mimeType: 'application/zip',
+ },
+ ],
+ },
+ ]);
+ const ref = (out[1] as { files: Array<{ path: string }> }).files[0].path;
+ expect(parseAttachmentOssRef(ref)?.originalName).toBe('archive.zip');
+ });
+
it('xdt-image:// 块 → resolveSafe → uploadLocalFile → block.path 变 OSS 引用,base64 清掉', async () => {
resolveSafe.mockReturnValue({ absPath: '/cache/a.png', mimeType: 'image/png' });
const out = await rewriteOutboundMedia('maker:send', [
diff --git a/apps/desktop/src/main/device-link/outboundMedia.ts b/apps/desktop/src/main/device-link/outboundMedia.ts
index f6608ce7ad..be6c9e9d76 100644
--- a/apps/desktop/src/main/device-link/outboundMedia.ts
+++ b/apps/desktop/src/main/device-link/outboundMedia.ts
@@ -44,6 +44,7 @@ const EXT_BY_MIME: Record<string, string> = {
};
interface AttachmentSource {
+ name?: unknown;
url?: unknown;
path?: unknown;
base64?: unknown;
@@ -77,7 +78,12 @@ function persistedIntegrityFields(
/** 把一个附件源上传 OSS,返回 OSS 引用串。无可用来源 / 上传失败 → 抛错。 */
async function uploadAttachment(src: AttachmentSource): Promise<string> {
const mimeType = typeof src.mimeType === 'string' ? src.mimeType : undefined;
- const originalName = typeof src.originalName === 'string' ? src.originalName : undefined;
+ const originalName =
+ typeof src.originalName === 'string' && src.originalName
+ ? src.originalName
+ : typeof src.name === 'string' && src.name
+ ? src.name
+ : undefined;
// 1) 内存 base64(剪贴板/截图,视觉上下文语义)→ 压缩 → uploadBuffer(不把字节内联进 relay)
if (typeof src.base64 === 'string' && src.base64) {
@@ -198,20 +204,49 @@ function isAttachmentBlock(b: unknown): b is AttachmentSource & { type: string }
);
}
+function sourceRefKey(src: AttachmentSource): string {
+ return typeof src.url === 'string' && src.url
+ ? src.url
+ : typeof src.path === 'string' && src.path
+ ? src.path
+ : '';
+}
+
+async function uploadAttachmentOnce(
+ src: AttachmentSource,
+ refMap: Map<string, string>,
+): Promise<string> {
+ const key = sourceRefKey(src);
+ const cached = key ? refMap.get(key) : undefined;
+ if (cached) return cached;
+ const ref = await uploadAttachment(src);
+ if (key) refMap.set(key, ref);
+ return ref;
+}
+
/** 改写 send/steer 的 message(content-block 形态)。无附件 → 原样。 */
-async function rewriteMessage(message: unknown): Promise<unknown> {
+async function rewriteMessage(
+ message: unknown,
+ refMap: Map<string, string> = new Map(),
+): Promise<unknown> {
if (!message || typeof message !== 'object') return message; // string / null:无附件
const m = message as { type?: unknown; content?: unknown };
if (m.type !== 'user' || !Array.isArray(m.content)) return message;
const content: unknown[] = [];
for (const raw of m.content) {
if (isAttachmentBlock(raw)) {
- const ref = await uploadAttachment(raw);
+ const ref = await uploadAttachmentOnce(raw, refMap);
+ const originalName =
+ typeof raw.originalName === 'string' && raw.originalName
+ ? raw.originalName
+ : typeof raw.name === 'string' && raw.name
+ ? raw.name
+ : undefined;
content.push({
type: raw.type,
path: ref,
mimeType: raw.mimeType,
- originalName: raw.originalName,
+ ...(originalName ? { originalName } : {}),
});
} else {
content.push(raw);
@@ -278,19 +313,6 @@ async function rewriteQueued(item: unknown): Promise<unknown> {
// 原始 ref(url 或 path 字符串)→ OSS 引用;同一附件只传一次,供 files[] + persistedContent 复用。
const refMap = new Map<string, string>();
- const uploadOnce = async (src: AttachmentSource): Promise<string> => {
- const key =
- typeof src.url === 'string' && src.url
- ? src.url
- : typeof src.path === 'string' && src.path
- ? src.path
- : '';
- const cached = key ? refMap.get(key) : undefined;
- if (cached) return cached;
- const ref = await uploadAttachment(src);
- if (key) refMap.set(key, ref);
- return ref;
- };
const files: unknown[] = [];
for (const f of it.files) {
@@ -301,7 +323,7 @@ async function rewriteQueued(item: unknown): Promise<unknown> {
(f as AttachmentSource).path ||
(f as AttachmentSource).base64)
) {
- const ref = await uploadOnce(f as AttachmentSource);
+ const ref = await uploadAttachmentOnce(f as AttachmentSource, refMap);
// url 优先被 buildMakerUserMessage 取用;清掉 base64 避免把字节内联进 relay。
files.push({
...(f as object),
@@ -334,7 +356,33 @@ export async function rewriteOutboundMedia(channel: string, args: unknown[]): Pr
if (!isQueued && !isMessage) return args;
const next = [...args];
if (next[1] === undefined) return next;
- next[1] = isQueued ? await rewriteQueued(next[1]) : await rewriteMessage(next[1]);
+ if (isQueued) {
+ next[1] = await rewriteQueued(next[1]);
+ } else {
+ // Direct maker:send carries the same attachment twice: once in the agent
+ // message and once in sendOpts.persistUserMessage.content for DB history.
+ // Rewrite both with one ref map so every file uploads exactly once.
+ const refMap = new Map<string, string>();
+ next[1] = await rewriteMessage(next[1], refMap);
+ if (channel === 'maker:send') {
+ const sendOpts = next[3];
+ if (sendOpts && typeof sendOpts === 'object' && !Array.isArray(sendOpts)) {
+ const persist = (sendOpts as { persistUserMessage?: unknown }).persistUserMessage;
+ if (persist && typeof persist === 'object' && !Array.isArray(persist)) {
+ const content = (persist as { content?: unknown }).content;
+ if (typeof content === 'string') {
+ const rewrittenContent = rewritePersistedContent(content, refMap);
+ if (rewrittenContent !== content) {
+ next[3] = {
+ ...(sendOpts as object),
+ persistUserMessage: { ...(persist as object), content: rewrittenContent },
+ };
+ }
+ }
+ }
+ }
+ }
+ }
log.debug(`outbound media rewritten for ${channel}`);
return next;
}
@@ -344,6 +392,7 @@ export const __testing = {
rewriteMessage,
rewriteQueued,
rewritePersistedContent,
+ uploadAttachmentOnce,
MESSAGE_SHAPE_CHANNELS,
QUEUED_SHAPE_CHANNELS,
};
diff --git a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts
new file mode 100644
index 0000000000..2daf3f7756
--- /dev/null
+++ b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts
@@ -0,0 +1,191 @@
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const userDataDir = path.join(os.tmpdir(), `chat-attachment-cache-${randomUUID()}`);
+
+vi.mock('electron', () => ({
+ app: { getPath: () => userDataDir },
+}));
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+const {
+ cleanupOwnedUnpersistedStagedChatAttachments,
+ cleanupStagedChatAttachments,
+ getChatAttachmentCacheRoot,
+ getChatAttachmentOwnerCacheRoot,
+ getRemoteFileCacheRoot,
+ removeStagedChatAttachment,
+ stageLocalFileToCache,
+ sweepCacheOnStartup,
+ sweepStagedChatAttachmentsOnStartup,
+} = await import('../remote-file-cache');
+
+afterEach(async () => {
+ await fs.rm(userDataDir, { recursive: true, force: true });
+});
+
+describe('chat attachment staging cache', () => {
+ it('stores persisted chat attachments outside the disposable remote-file LRU', async () => {
+ const payload = Buffer.from('installer-bytes');
+ const stagedPath = await stageLocalFileToCache({
+ ownerId: 'owner-a',
+ suggestedName: 'setup.exe',
+ expectedSize: BigInt(payload.byteLength),
+ copyTo: (targetPath) => fs.writeFile(targetPath, payload),
+ });
+
+ expect(path.dirname(stagedPath)).toBe(getChatAttachmentOwnerCacheRoot('owner-a'));
+ expect(path.dirname(stagedPath)).not.toBe(getChatAttachmentCacheRoot());
+ expect(stagedPath.endsWith('.bin')).toBe(true);
+ expect(stagedPath.startsWith(`${getRemoteFileCacheRoot()}${path.sep}`)).toBe(false);
+
+ await fs.mkdir(getRemoteFileCacheRoot(), { recursive: true });
+ const disposablePart = path.join(getRemoteFileCacheRoot(), 'orphan.part');
+ await fs.writeFile(disposablePart, 'partial');
+ await sweepCacheOnStartup();
+
+ await expect(fs.stat(stagedPath)).resolves.toMatchObject({ size: payload.byteLength });
+ await expect(fs.stat(disposablePart)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('supports the reserved owner used by account-free local mode', async () => {
+ const payload = Buffer.from('local-installer');
+ const stagedPath = await stageLocalFileToCache({
+ ownerId: 'local-v1',
+ suggestedName: 'setup.exe',
+ expectedSize: BigInt(payload.byteLength),
+ copyTo: (targetPath) => fs.writeFile(targetPath, payload),
+ });
+
+ expect(path.dirname(stagedPath)).toBe(getChatAttachmentOwnerCacheRoot('local-v1'));
+ await expect(fs.readFile(stagedPath)).resolves.toEqual(payload);
+ });
+
+ it('sweeps only old, unreferenced files for the current owner', async () => {
+ const ownerId = 'owner-a';
+ const otherOwnerId = 'owner-b';
+ const ownerRoot = getChatAttachmentOwnerCacheRoot(ownerId);
+ const otherOwnerRoot = getChatAttachmentOwnerCacheRoot(otherOwnerId);
+ await fs.mkdir(ownerRoot, { recursive: true });
+ await fs.mkdir(otherOwnerRoot, { recursive: true });
+
+ const orphanPath = path.join(ownerRoot, 'orphan.bin');
+ const protectedPath = path.join(ownerRoot, 'protected.bin');
+ const partialPath = path.join(ownerRoot, 'partial.bin.part');
+ const freshPath = path.join(ownerRoot, 'fresh.bin');
+ const otherOwnerPath = path.join(otherOwnerRoot, 'other.bin');
+ await Promise.all([
+ fs.writeFile(orphanPath, 'orphan'),
+ fs.writeFile(protectedPath, 'protected'),
+ fs.writeFile(partialPath, 'partial'),
+ fs.writeFile(freshPath, 'fresh'),
+ fs.writeFile(otherOwnerPath, 'other'),
+ ]);
+ const oldTime = new Date(Date.now() - 60_000);
+ await Promise.all([
+ fs.utimes(orphanPath, oldTime, oldTime),
+ fs.utimes(protectedPath, oldTime, oldTime),
+ fs.utimes(partialPath, oldTime, oldTime),
+ fs.utimes(otherOwnerPath, oldTime, oldTime),
+ ]);
+
+ await expect(
+ sweepStagedChatAttachmentsOnStartup({
+ ownerId,
+ protectedPaths: [protectedPath],
+ createdBeforeMs: Date.now() - 1_000,
+ }),
+ ).resolves.toMatchObject({ inspected: 4, removed: 2, protected: 1 });
+
+ await expect(fs.stat(orphanPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(fs.stat(partialPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(fs.stat(protectedPath)).resolves.toBeDefined();
+ await expect(fs.stat(freshPath)).resolves.toBeDefined();
+ await expect(fs.stat(otherOwnerPath)).resolves.toBeDefined();
+ });
+
+ it('removes only controlled .bin files', async () => {
+ const root = getChatAttachmentCacheRoot();
+ await fs.mkdir(root, { recursive: true });
+ const stagedPath = path.join(root, 'staged.bin');
+ const safeNamePath = path.join(root, 'staged.exe');
+ const directoryPath = path.join(root, 'directory.bin');
+ const outsidePath = path.join(userDataDir, 'outside.bin');
+ await fs.writeFile(stagedPath, 'staged');
+ await fs.writeFile(safeNamePath, 'safe');
+ await fs.mkdir(directoryPath);
+ await fs.writeFile(outsidePath, 'outside');
+
+ await cleanupStagedChatAttachments([stagedPath, safeNamePath, directoryPath, outsidePath]);
+
+ await expect(fs.stat(stagedPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(fs.stat(safeNamePath)).resolves.toBeDefined();
+ await expect(fs.stat(directoryPath)).resolves.toBeDefined();
+ await expect(fs.stat(outsidePath)).resolves.toBeDefined();
+ });
+
+ it('renderer cleanup removes only current-owner files not retained by messages', async () => {
+ const ownerId = 'owner-a';
+ const ownerRoot = getChatAttachmentOwnerCacheRoot(ownerId);
+ const otherOwnerRoot = getChatAttachmentOwnerCacheRoot('owner-b');
+ await fs.mkdir(ownerRoot, { recursive: true });
+ await fs.mkdir(otherOwnerRoot, { recursive: true });
+ const draftPath = path.join(ownerRoot, 'draft.bin');
+ const persistedPath = path.join(ownerRoot, 'persisted.bin');
+ const otherOwnerPath = path.join(otherOwnerRoot, 'other.bin');
+ const nestedPath = path.join(ownerRoot, 'nested', 'nested.bin');
+ await fs.mkdir(path.dirname(nestedPath), { recursive: true });
+ await Promise.all([
+ fs.writeFile(draftPath, 'draft'),
+ fs.writeFile(persistedPath, 'persisted'),
+ fs.writeFile(otherOwnerPath, 'other'),
+ fs.writeFile(nestedPath, 'nested'),
+ ]);
+
+ await cleanupOwnedUnpersistedStagedChatAttachments({
+ ownerId,
+ filePaths: [draftPath, persistedPath, otherOwnerPath, nestedPath],
+ protectedPaths: [persistedPath],
+ });
+
+ await expect(fs.stat(draftPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(fs.stat(persistedPath)).resolves.toBeDefined();
+ await expect(fs.stat(otherOwnerPath)).resolves.toBeDefined();
+ await expect(fs.stat(nestedPath)).resolves.toBeDefined();
+ });
+
+ it('renderer cleanup rechecks the active owner before unlinking', async () => {
+ const ownerId = 'owner-a';
+ const ownerRoot = getChatAttachmentOwnerCacheRoot(ownerId);
+ const draftPath = path.join(ownerRoot, 'draft.bin');
+ await fs.mkdir(ownerRoot, { recursive: true });
+ await fs.writeFile(draftPath, 'draft');
+
+ await cleanupOwnedUnpersistedStagedChatAttachments({
+ ownerId,
+ filePaths: [draftPath],
+ protectedPaths: [],
+ canRemove: () => false,
+ });
+
+ await expect(fs.stat(draftPath)).resolves.toBeDefined();
+ });
+
+ it('is idempotent when the staged file is already gone', async () => {
+ await expect(removeStagedChatAttachment(path.join(getChatAttachmentCacheRoot(), 'gone.bin'))).resolves.toBe(
+ false,
+ );
+ });
+});
diff --git a/apps/desktop/src/main/file-browser/remote-file-cache.ts b/apps/desktop/src/main/file-browser/remote-file-cache.ts
index 1b9f73cbc2..8ea8e5272f 100644
--- a/apps/desktop/src/main/file-browser/remote-file-cache.ts
+++ b/apps/desktop/src/main/file-browser/remote-file-cache.ts
@@ -16,16 +16,18 @@
* caller 侧完成(这里每片/每 chunk 都回调)。
*/
-import { createHash } from 'node:crypto';
+import { createHash, randomUUID } from 'node:crypto';
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { app } from 'electron';
+import { dataOwnerStorageKey } from '../appSessionState.js';
import { createLogger } from '../logger.js';
const log = createLogger('file-browser/remote-cache');
const CACHE_DIR_NAME = 'remote-file-cache';
+const CHAT_ATTACHMENT_CACHE_DIR_NAME = 'chat-attachment-cache';
/** LRU 字节上限:4GB——够放两个 2GB 文件,超出按最旧访问逐出。 */
const MAX_CACHE_BYTES = 4 * 1024 * 1024 * 1024;
@@ -48,6 +50,190 @@ function cacheDir(): string {
return path.join(app.getPath('userData'), CACHE_DIR_NAME);
}
+export function getRemoteFileCacheRoot(): string {
+ return cacheDir();
+}
+
+function chatAttachmentCacheDir(): string {
+ return path.join(app.getPath('userData'), CHAT_ATTACHMENT_CACHE_DIR_NAME);
+}
+
+function chatAttachmentOwnerCacheDir(ownerId: string): string {
+ return path.join(chatAttachmentCacheDir(), dataOwnerStorageKey(ownerId));
+}
+
+export function getChatAttachmentOwnerCacheRoot(ownerId: string): string {
+ return chatAttachmentOwnerCacheDir(ownerId);
+}
+
+/**
+ * Chat history persists staged attachment paths, so this root must not share the
+ * bounded remote-file LRU whose entries are disposable fetch copies.
+ */
+export function getChatAttachmentCacheRoot(): string {
+ return chatAttachmentCacheDir();
+}
+
+function isInsideChatAttachmentCache(p: string): boolean {
+ return path.resolve(p).startsWith(`${chatAttachmentCacheDir()}${path.sep}`);
+}
+
+/**
+ * Extract persisted file paths from a user-message content JSON document.
+ * This is deliberately format-tolerant: malformed/legacy content contributes
+ * no paths, and the actual deletion function still applies its cache-root and
+ * `.bin` guards before touching anything on disk.
+ */
+export function extractChatAttachmentPathsFromPersistedContent(content: string): string[] {
+ try {
+ const parsed = JSON.parse(content) as { files?: unknown };
+ if (!Array.isArray(parsed.files)) return [];
+ return parsed.files.flatMap((entry) => {
+ if (!entry || typeof entry !== 'object') return [];
+ const candidate = (entry as { path?: unknown }).path;
+ return typeof candidate === 'string' ? [candidate] : [];
+ });
+ } catch {
+ return [];
+ }
+}
+
+/** Remove one staged attachment if it is a safe, controlled cache file. */
+export async function removeStagedChatAttachment(filePath: string): Promise<boolean> {
+ if (
+ typeof filePath !== 'string' ||
+ !path.isAbsolute(filePath) ||
+ !isInsideChatAttachmentCache(filePath) ||
+ path.extname(filePath).toLowerCase() !== '.bin'
+ ) {
+ return false;
+ }
+ try {
+ const stat = await fs.lstat(filePath);
+ if (!stat.isFile() && !stat.isSymbolicLink()) return false;
+ await fs.unlink(filePath);
+ return true;
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ if (code !== 'ENOENT') {
+ log.warn('staged chat attachment cleanup failed', {
+ filePath,
+ error: String(err),
+ });
+ }
+ return false;
+ }
+}
+
+/** Best-effort batch cleanup used by draft/message/session lifecycle hooks. */
+export async function cleanupStagedChatAttachments(
+ filePaths: readonly string[],
+): Promise<void> {
+ await Promise.all(filePaths.map((filePath) => removeStagedChatAttachment(filePath)));
+}
+
+function normalizePathForComparison(filePath: string): string {
+ const resolved = path.resolve(filePath);
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
+}
+
+/**
+ * Remove renderer-owned draft copies without crossing owner or persisted-message
+ * boundaries. The optional guard is checked immediately before unlink so an
+ * account switch that happens while filesystem metadata is being read cancels
+ * the destructive step.
+ */
+export async function cleanupOwnedUnpersistedStagedChatAttachments(params: {
+ ownerId: string;
+ filePaths: readonly string[];
+ protectedPaths: readonly string[];
+ canRemove?: () => boolean;
+}): Promise<void> {
+ const ownerDir = normalizePathForComparison(chatAttachmentOwnerCacheDir(params.ownerId));
+ const protectedPaths = new Set(params.protectedPaths.map(normalizePathForComparison));
+ await Promise.all(
+ params.filePaths.map(async (filePath) => {
+ if (
+ typeof filePath !== 'string' ||
+ !path.isAbsolute(filePath) ||
+ path.extname(filePath).toLowerCase() !== '.bin' ||
+ normalizePathForComparison(path.dirname(filePath)) !== ownerDir ||
+ protectedPaths.has(normalizePathForComparison(filePath))
+ ) {
+ return;
+ }
+ try {
+ const stat = await fs.lstat(filePath);
+ if (!stat.isFile() && !stat.isSymbolicLink()) return;
+ if (params.canRemove && !params.canRemove()) return;
+ await fs.unlink(filePath);
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ if (code !== 'ENOENT') {
+ log.warn('owned staged chat attachment cleanup failed', {
+ filePath,
+ error: String(err),
+ });
+ }
+ }
+ }),
+ );
+}
+
+export interface StartupStagedChatAttachmentSweepResult {
+ inspected: number;
+ removed: number;
+ protected: number;
+}
+
+/**
+ * Remove abandoned dangerous-attachment staging files from the current
+ * account. Renderer drafts are intentionally in-memory only, so anything
+ * created by an earlier process and not referenced by persisted messages is
+ * unreachable after restart. Files created by this process are left alone to
+ * avoid racing a draft that is still being assembled.
+ */
+export async function sweepStagedChatAttachmentsOnStartup(params: {
+ ownerId: string;
+ protectedPaths: readonly string[];
+ createdBeforeMs: number;
+}): Promise<StartupStagedChatAttachmentSweepResult> {
+ const result: StartupStagedChatAttachmentSweepResult = {
+ inspected: 0,
+ removed: 0,
+ protected: 0,
+ };
+ const protectedPaths = new Set(params.protectedPaths.map(normalizePathForComparison));
+ const ownerDir = chatAttachmentOwnerCacheDir(params.ownerId);
+ const entries = await fs.readdir(ownerDir, { withFileTypes: true }).catch(() => []);
+ for (const entry of entries) {
+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;
+ if (!entry.name.endsWith('.bin') && !entry.name.endsWith('.bin.part')) continue;
+
+ const filePath = path.join(ownerDir, entry.name);
+ result.inspected += 1;
+ try {
+ const stat = await fs.lstat(filePath);
+ if (stat.mtimeMs >= params.createdBeforeMs) continue;
+ if (protectedPaths.has(normalizePathForComparison(filePath))) {
+ result.protected += 1;
+ continue;
+ }
+ await fs.unlink(filePath);
+ result.removed += 1;
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ if (code !== 'ENOENT') {
+ log.warn('startup staged chat attachment sweep failed for file', {
+ filePath,
+ error: String(err),
+ });
+ }
+ }
+ }
+ return result;
+}
+
/** 路径身份前缀(不含 size/mtime):断线兜底按它捞最近副本。 */
function prefixHashFor(id: Pick<RemoteFileIdentity, 'transport' | 'endpointId' | 'workdir' | 'relPath'>): string {
return createHash('sha1')
@@ -207,6 +393,40 @@ export async function fetchRemoteFileToCache(
}
}
+/**
+ * Dangerous local chat attachments are copied here before entering renderer
+ * state. The display name is retained separately, while the physical cache
+ * filename always ends in `.bin` so a stale/open-by-path path cannot execute it.
+ */
+export async function stageLocalFileToCache(params: {
+ ownerId: string;
+ suggestedName: string;
+ expectedSize: bigint;
+ copyTo(targetPath: string): Promise<void>;
+}): Promise<string> {
+ const ownerDir = chatAttachmentOwnerCacheDir(params.ownerId);
+ await fs.mkdir(ownerDir, { recursive: true });
+ const base = shortenKeepExt(
+ sanitizeBaseName(path.basename(params.suggestedName)) || 'attachment',
+ 80,
+ );
+ const dest = path.join(ownerDir, `${randomUUID()}-${base}.bin`);
+ const tmp = `${dest}.part`;
+ try {
+ await params.copyTo(tmp);
+ const got = await fs.stat(tmp, { bigint: true });
+ if (!got.isFile() || got.size !== params.expectedSize) {
+ throw new Error(
+ `staged size mismatch: got ${got.size.toString()}, expect ${params.expectedSize.toString()}`,
+ );
+ }
+ await fs.rename(tmp, dest);
+ return dest;
+ } finally {
+ await fs.rm(tmp, { force: true }).catch(() => undefined);
+ }
+}
+
/**
* 按 mtime(≈最近使用)逐出,直到总字节 ≤ 上限。
* @param protectPath 本轮刚取回落地的文件:即便超上限也不逐出(mtime 最新
diff --git a/apps/desktop/src/main/imageCacheStore.ts b/apps/desktop/src/main/imageCacheStore.ts
index 2e8d6bca77..d1a470fe45 100644
--- a/apps/desktop/src/main/imageCacheStore.ts
+++ b/apps/desktop/src/main/imageCacheStore.ts
@@ -42,7 +42,10 @@ import path from 'node:path';
import fs from 'node:fs/promises';
import { existsSync, readdirSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
-import { SUPPORTED_TEXT_EXTS } from '../shared/textFileExts';
+import {
+ attachmentExtension,
+ isDangerousAttachmentName,
+} from '../shared/attachmentSafety';
const SCHEME = 'xdt-image';
const META_SUFFIX = '.xdt-meta.json';
@@ -99,21 +102,12 @@ const EXT_BY_MIME: Record<string, string> = {
'image/jpeg': '.jpg',
'image/gif': '.gif',
'image/webp': '.webp',
+ 'application/pdf': '.pdf',
+ 'text/plain': '.txt',
};
-// Document extensions (beyond images + text) whose original type we preserve when
-// materializing device-link attachments, so a phone-uploaded PDF/Office file isn't stored
-// as `.bin`. Deliberately an ALLOWLIST of the attachment categories the product supports —
-// it excludes OS-executable/installer extensions (.exe/.msi/.dmg/.app/.pkg/.jar/...), which
-// must NOT be preserved: a preserved executable extension would make the materialized file
-// chip open via `openPath` (OS default handler) and run. Anything outside image/text/doc
-// falls back to `.bin` (no auto-exec handler).
-const SUPPORTED_DOC_EXTS = new Set<string>(['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx']);
-
-/** True for extensions we preserve on materialization: images, readable-text/code, and docs. */
-function isPreservableAttachmentExt(ext: string): boolean {
- return Boolean(MIME_BY_EXT[ext]) || SUPPORTED_TEXT_EXTS.has(ext) || SUPPORTED_DOC_EXTS.has(ext);
-}
+/** A bounded portable suffix; dangerous executable types are filtered separately. */
+const SAFE_ATTACHMENT_EXT_RE = /^\.[a-z0-9][a-z0-9+_-]{0,23}$/;
// ---------------------------------------------------------------------------
// Path helpers
@@ -158,18 +152,22 @@ function assertSafeCacheFilename(filename: string): void {
}
function inferExt(originalName?: string, mimeType?: string): string {
- // A trusted image mimeType wins over the name's extension: `writeBuffer` passes the real
- // content type, so a suggestedName like `clipboard.pdf` must not mislabel a PNG buffer.
+ // A dangerous display name always wins over MIME hints. Device-link refs are remote input;
+ // a spoofed image MIME must not restore an executable extension or make it image-openable.
+ if (originalName && isDangerousAttachmentName(originalName)) return '.bin';
+ // Otherwise a trusted image mimeType wins over the name's extension: `writeBuffer` passes
+ // the real content type, so a suggestedName like `clipboard.pdf` must not mislabel a PNG.
if (mimeType && EXT_BY_MIME[mimeType]) return EXT_BY_MIME[mimeType];
if (originalName) {
- const dotIdx = originalName.lastIndexOf('.');
- if (dotIdx > 0) {
- const candidate = originalName.slice(dotIdx).toLowerCase();
- // Preserve the original type for supported attachment categories (image / text / doc) —
- // a phone-uploaded PDF/Office file keeps its extension instead of becoming `.bin`.
- // Executable/installer extensions are intentionally NOT preserved (→ `.bin`) so the
- // materialized file chip can't open via the OS default handler and run.
- if (isPreservableAttachmentExt(candidate)) return candidate;
+ const candidate = attachmentExtension(originalName);
+ // Preserve every syntactically safe non-executable extension. A narrow format allowlist
+ // previously changed valid files such as .zip/.blend/.psd into .bin on the receiving side.
+ if (
+ candidate &&
+ SAFE_ATTACHMENT_EXT_RE.test(candidate) &&
+ !isDangerousAttachmentName(originalName)
+ ) {
+ return candidate;
}
}
return '.bin';
@@ -703,8 +701,10 @@ export async function removeFile(url: string): Promise<void> {
return; // invalid url → nothing to delete
}
// `force: true` already silently ignores ENOENT — no extra catch needed for
- // missing files. Other I/O errors propagate naturally.
+ // missing files. Remove the sidecar too; otherwise a direct-send rejection
+ // would leave an unreferenced committed cache entry behind.
await fs.rm(absPath, { force: true });
+ await fs.rm(metaPathFor(absPath), { force: true });
}
export async function removeSession(sessionId: string): Promise<void> {
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
index eb3f3daff5..6aef131eb4 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
@@ -6,7 +6,38 @@ import { messages, sessions } from '../../schema';
const h = vi.hoisted(() => ({
db: null as ReturnType<typeof drizzle> | null,
+ sqlite: null as Database.Database | null,
handlers: new Map<string, (...args: unknown[]) => unknown>(),
+ cleanupStagedChatAttachments: vi.fn(async (_filePaths: readonly string[]) => undefined),
+ query: vi.fn(async (query: string): Promise<Array<{ content: string }>> => {
+ if (!h.sqlite) throw new Error('test sqlite not initialized');
+ return h.sqlite.prepare(query).all() as Array<{ content: string }>;
+ }),
+ tx: vi.fn(
+ async (
+ _name: string,
+ input: { sessionId: string; clientIds: string[] },
+ ): Promise<{ messages: Array<{ messageId: string; clientId: string }> }> => {
+ if (!h.sqlite) throw new Error('test sqlite not initialized');
+ const placeholders = input.clientIds.map(() => '?').join(', ');
+ const rows = h.sqlite
+ .prepare(
+ `SELECT id, client_id FROM messages WHERE session_id = ? AND client_id IN (${placeholders})`,
+ )
+ .all(input.sessionId, ...input.clientIds) as Array<{
+ id: string;
+ client_id: string;
+ }>;
+ h.sqlite
+ .prepare(
+ `DELETE FROM messages WHERE session_id = ? AND client_id IN (${placeholders})`,
+ )
+ .run(input.sessionId, ...input.clientIds);
+ return {
+ messages: rows.map((row) => ({ messageId: row.id, clientId: row.client_id })),
+ };
+ },
+ ),
}));
vi.mock('electron', () => ({
@@ -36,8 +67,30 @@ vi.mock('../../../git-context/prRefsStore', () => ({
recomputePrRefsForSession: vi.fn(async () => undefined),
recordPrRefsForMessage: vi.fn(async () => undefined),
}));
+vi.mock('../../../cindy-media/ledger', () => ({
+ removeRefs: vi.fn(async () => undefined),
+}));
+vi.mock('../../../cindy-media/chatAttachments', () => ({
+ commitMessageMediaRefs: vi.fn(async () => undefined),
+}));
+vi.mock('../../../file-browser/remote-file-cache', () => ({
+ cleanupStagedChatAttachments: h.cleanupStagedChatAttachments,
+ extractChatAttachmentPathsFromPersistedContent: (content: string): string[] => {
+ try {
+ const parsed = JSON.parse(content) as { files?: unknown };
+ if (!Array.isArray(parsed.files)) return [];
+ return parsed.files.flatMap((entry) => {
+ if (!entry || typeof entry !== 'object') return [];
+ const candidate = (entry as { path?: unknown }).path;
+ return typeof candidate === 'string' ? [candidate] : [];
+ });
+ } catch {
+ return [];
+ }
+ },
+}));
vi.mock('../../client/current', () => ({
- getDbClient: () => ({ drizzle: h.db }),
+ getDbClient: () => ({ drizzle: h.db, query: h.query, tx: h.tx }),
}));
import {
@@ -46,6 +99,9 @@ import {
findForkParentSessionId,
findPendingForkOrigin,
getMessageDeletionTarget,
+ commitMessageDeletion,
+ listDeletableSessionPersistedChatAttachmentPaths,
+ listPersistedChatAttachmentPaths,
markLatestAgentHandoffConsumed,
readPriorUserRoundCost,
registerMessageIpc,
@@ -58,6 +114,7 @@ function createDb(): Database.Database {
id TEXT PRIMARY KEY,
cleared_at INTEGER,
parent_session_id TEXT,
+ status TEXT NOT NULL DEFAULT 'active',
created_at INTEGER NOT NULL DEFAULT 0,
total_token_usage INTEGER NOT NULL DEFAULT 0
);
@@ -75,6 +132,7 @@ function createDb(): Database.Database {
);
`);
h.db = drizzle(sqlite, { schema: { messages, sessions } });
+ h.sqlite = sqlite;
return sqlite;
}
@@ -127,6 +185,125 @@ function insertCostMessage(
});
}
+describe('staged chat attachment retention', () => {
+ it('keeps a shared staged path until the last non-deleted fork is deleted', async () => {
+ const sqlite = createDb();
+ sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('parent', 'deleted');
+ sqlite
+ .prepare('INSERT INTO sessions (id, parent_session_id, status) VALUES (?, ?, ?)')
+ .run('fork', 'parent', 'active');
+
+ const sharedPath = 'C:\\chat-attachment-cache\\owner\\shared.bin';
+ const parentOnlyPath = 'C:\\chat-attachment-cache\\owner\\parent-only.bin';
+ const insert = sqlite.prepare(`
+ INSERT INTO messages (
+ id, client_id, session_id, role, content, created_at
+ ) VALUES (
+ @id, @id, @sessionId, 'user', @content, @createdAt
+ )
+ `);
+ insert.run({
+ id: 'parent-message',
+ sessionId: 'parent',
+ content: JSON.stringify({
+ files: [{ path: sharedPath }, { path: parentOnlyPath }],
+ }),
+ createdAt: 1,
+ });
+ insert.run({
+ id: 'fork-message',
+ sessionId: 'fork',
+ content: JSON.stringify({ files: [{ path: sharedPath }] }),
+ createdAt: 2,
+ });
+
+ await expect(listDeletableSessionPersistedChatAttachmentPaths('parent')).resolves.toEqual([
+ parentOnlyPath,
+ ]);
+
+ sqlite.prepare("UPDATE sessions SET status = 'deleted' WHERE id = 'fork'").run();
+ await expect(listDeletableSessionPersistedChatAttachmentPaths('parent')).resolves.toEqual([
+ sharedPath,
+ parentOnlyPath,
+ ]);
+ });
+
+ it('keeps a fork-referenced path when deleting a message from the parent session', async () => {
+ const sqlite = createDb();
+ sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('parent', 'active');
+ sqlite
+ .prepare('INSERT INTO sessions (id, parent_session_id, status) VALUES (?, ?, ?)')
+ .run('fork', 'parent', 'active');
+
+ const sharedPath = 'C:\\chat-attachment-cache\\owner\\shared.bin';
+ const parentOnlyPath = 'C:\\chat-attachment-cache\\owner\\parent-only.bin';
+ const insert = sqlite.prepare(`
+ INSERT INTO messages (
+ id, client_id, session_id, role, content, created_at
+ ) VALUES (
+ @id, @clientId, @sessionId, 'user', @content, @createdAt
+ )
+ `);
+ insert.run({
+ id: 'parent-message',
+ clientId: 'parent-client',
+ sessionId: 'parent',
+ content: JSON.stringify({ files: [{ path: sharedPath }, { path: parentOnlyPath }] }),
+ createdAt: 1,
+ });
+ insert.run({
+ id: 'fork-message',
+ clientId: 'fork-client',
+ sessionId: 'fork',
+ content: JSON.stringify({ files: [{ path: sharedPath }] }),
+ createdAt: 2,
+ });
+
+ h.cleanupStagedChatAttachments.mockClear();
+ await commitMessageDeletion('parent', ['parent-client'], 'handoff');
+
+ expect(h.cleanupStagedChatAttachments).toHaveBeenCalledWith([parentOnlyPath]);
+ });
+
+ it('does not protect staged paths referenced only by deleted sessions', async () => {
+ const sqlite = createDb();
+ sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('active', 'active');
+ sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('deleted', 'deleted');
+ sqlite.prepare('INSERT INTO sessions (id, status) VALUES (?, ?)').run('archived', 'archived');
+
+ const insert = sqlite.prepare(`
+ INSERT INTO messages (
+ id, client_id, session_id, role, content, created_at
+ ) VALUES (
+ @id, @id, @sessionId, 'user', @content, @createdAt
+ )
+ `);
+ insert.run({
+ id: 'active-message',
+ sessionId: 'active',
+ content: JSON.stringify({ files: [{ path: 'C:\\chat-attachment-cache\\active.bin' }] }),
+ createdAt: 1,
+ });
+ insert.run({
+ id: 'deleted-message',
+ sessionId: 'deleted',
+ content: JSON.stringify({ files: [{ path: 'C:\\chat-attachment-cache\\deleted.bin' }] }),
+ createdAt: 2,
+ });
+ insert.run({
+ id: 'archived-message',
+ sessionId: 'archived',
+ content: JSON.stringify({ files: [{ path: 'C:\\chat-attachment-cache\\archived.bin' }] }),
+ createdAt: 3,
+ });
+
+ await expect(listPersistedChatAttachmentPaths()).resolves.toEqual([
+ 'C:\\chat-attachment-cache\\active.bin',
+ 'C:\\chat-attachment-cache\\archived.bin',
+ ]);
+ });
+});
+
describe('local-db:messages:list cursor', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index c46bb6616e..c6117885ae 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -7,7 +7,7 @@
*/
import { ipcMain, BrowserWindow } from 'electron';
-import { and, asc, eq, inArray, lt, gt, gte, desc, isNull, or, sql, type SQL } from 'drizzle-orm';
+import { and, asc, eq, inArray, lt, gt, gte, desc, isNull, ne, or, sql, type SQL } from 'drizzle-orm';
import { createId } from '@paralleldrive/cuid2';
import { getDbClient } from '../client/current';
@@ -28,6 +28,10 @@ import { importExternalClaudeCodeMessagesForSession } from '../../maker-host/cla
import { isDeviceLinkInvoke } from '../../device-link/invoke-context';
import { onMessageCreated as onChatMessageCreatedForEmbedding } from '../../embedders/chat-history-embedder';
import { recomputePrRefsForSession, recordPrRefsForMessage } from '../../git-context/prRefsStore';
+import {
+ cleanupStagedChatAttachments,
+ extractChatAttachmentPathsFromPersistedContent,
+} from '../../file-browser/remote-file-cache';
import {
isSyntheticTriggerText,
mergeDismissedIntoErrorContent,
@@ -54,6 +58,12 @@ const messageRowid = sql<number>`rowid`;
type MessageRow = typeof messages.$inferSelect;
type MessageRowWithRowid = MessageRow & { rowid: number };
+const PERSISTED_CHAT_ATTACHMENT_ROWS_SQL = `SELECT m.content
+ FROM messages AS m
+ JOIN sessions AS s ON s.id = m.session_id
+ WHERE s.status != 'deleted'
+ AND m.content LIKE '%chat-attachment-cache%'`;
+
export interface EstimatedSessionValueEntry {
clientId: string;
money: RegionalMoney;
@@ -81,6 +91,66 @@ const VALID_ROLES: ReadonlySet<MessageRole> = new Set([
'thinking',
] as const);
+function uniqueStrings(values: readonly string[]): string[] {
+ return [...new Set(values)];
+}
+
+/** Return staged attachment paths persisted by a session's messages. */
+export async function listSessionPersistedChatAttachmentPaths(
+ sessionId: string,
+): Promise<string[]> {
+ const rows = await getDbClient().drizzle
+ .select({ content: messages.content })
+ .from(messages)
+ .where(eq(messages.sessionId, sessionId));
+ return uniqueStrings(
+ rows.flatMap((row) => extractChatAttachmentPathsFromPersistedContent(row.content)),
+ );
+}
+
+/**
+ * Return the staged attachment paths that may be removed after deleting one
+ * session. Forked sessions copy persisted message content, so a path remains
+ * protected while any other non-deleted session still references it.
+ */
+export async function listDeletableSessionPersistedChatAttachmentPaths(
+ sessionId: string,
+): Promise<string[]> {
+ const [sessionPaths, retainedPaths] = await Promise.all([
+ listSessionPersistedChatAttachmentPaths(sessionId),
+ listPersistedChatAttachmentPathsForOtherSessions(sessionId),
+ ]);
+ return sessionPaths.filter((filePath) => !retainedPaths.includes(filePath));
+}
+
+/** Return staged attachment paths referenced by other non-deleted sessions. */
+export async function listPersistedChatAttachmentPathsForOtherSessions(
+ sessionId: string,
+): Promise<string[]> {
+ const rows = await getDbClient().drizzle
+ .select({ content: messages.content })
+ .from(messages)
+ .innerJoin(sessions, eq(messages.sessionId, sessions.id))
+ .where(and(ne(messages.sessionId, sessionId), ne(sessions.status, 'deleted')));
+ return uniqueStrings(
+ rows.flatMap((row) => extractChatAttachmentPathsFromPersistedContent(row.content)),
+ );
+}
+
+/** Return all staged attachment paths retained by the current owner's message DB. */
+export async function listPersistedChatAttachmentPaths(): Promise<string[]> {
+ const rows = await getDbClient().query<{ content: unknown }>(
+ PERSISTED_CHAT_ATTACHMENT_ROWS_SQL,
+ );
+ return uniqueStrings(
+ rows.flatMap((row) =>
+ typeof row.content === 'string'
+ ? extractChatAttachmentPathsFromPersistedContent(row.content)
+ : [],
+ ),
+ );
+}
+
export function registerMessageIpc(): void {
ipcMain.handle('local-db:messages:list', async (_e, sessionId: unknown, opts: unknown) => {
const sid = requireString(sessionId, 'sessionId');
@@ -735,6 +805,15 @@ export async function commitMessageDeletion(
preview: string | null;
}> {
const now = Date.now();
+ const db = getDbClient().drizzle;
+ const deletedAttachmentPaths = uniqueStrings(
+ (
+ await db
+ .select({ content: messages.content })
+ .from(messages)
+ .where(and(eq(messages.sessionId, sessionId), inArray(messages.clientId, clientIds)))
+ ).flatMap((row) => extractChatAttachmentPathsFromPersistedContent(row.content)),
+ );
const result = await getDbClient().tx('message.delete', {
sessionId,
clientIds,
@@ -747,6 +826,29 @@ export async function commitMessageDeletion(
updatedAt: now,
});
+ if (deletedAttachmentPaths.length > 0) {
+ try {
+ const remainingAttachmentPaths = new Set(
+ await listSessionPersistedChatAttachmentPaths(sessionId),
+ );
+ const retainedByOtherSessions = new Set(
+ await listPersistedChatAttachmentPathsForOtherSessions(sessionId),
+ );
+ await cleanupStagedChatAttachments(
+ deletedAttachmentPaths.filter(
+ (filePath) =>
+ !retainedByOtherSessions.has(filePath) && !remainingAttachmentPaths.has(filePath),
+ ),
+ );
+ } catch (error) {
+ log.warn('message staged attachment cleanup failed', {
+ sessionId,
+ deletedClientIds: clientIds,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
// 当前生产聊天附件主要是 session-attachment 粗粒度引用,不能因删除一轮
// 误删同 session 其它气泡仍在用的 blob。这里只释放明确以消息 id/clientId
// 登记的 message refs;零引用 blob 由 recycler 统一回收。
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 7d20805844..14858e3a7f 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -53,7 +53,12 @@ import {
listInterruptedPendingSessionIds,
setOnSessionTurnEndedPersisted,
} from '../sessionActiveTurn';
-import { dismissErrorMessage, rebroadcastAgentSwitchBoundary } from './messages';
+import {
+ dismissErrorMessage,
+ listDeletableSessionPersistedChatAttachmentPaths,
+ rebroadcastAgentSwitchBoundary,
+} from './messages';
+import { cleanupStagedChatAttachments } from '../../file-browser/remote-file-cache';
import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer.js';
const log = createLogger('sessions');
@@ -1302,6 +1307,14 @@ export async function patchSessionMetaInDb(
err: err instanceof Error ? err.message : String(err),
});
});
+ void listDeletableSessionPersistedChatAttachmentPaths(sessionId)
+ .then((filePaths) => cleanupStagedChatAttachments(filePaths))
+ .catch((err) => {
+ log.warn('staged chat attachment cleanup failed', {
+ sessionId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ });
}
removeHookAttachmentDir(sessionId, patch.status);
scheduleWorktreeRecycleForStatusChange(sessionId, patch.status);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index 2b15e2c2b0..4c64e0bb09 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -310,6 +310,148 @@ describe('maker SEND transaction', () => {
expect(beforeDispatchDirectUserTurn).toHaveBeenCalledWith('session-1');
});
+ it('materializes direct OSS attachments after session/workdir preflight', async () => {
+ const events: string[] = [];
+ const materializeDirectSendOssAttachments = vi.fn(async (
+ _sessionId: string,
+ message: unknown,
+ sendOpts: unknown,
+ ) => {
+ events.push('materialize');
+ return {
+ message: { ...(message as object), materialized: true },
+ sendOpts: { ...(sendOpts as object), materialized: true },
+ };
+ });
+ const session = createSession({
+ send: vi.fn(async (message) => {
+ events.push('send');
+ expect(message).toMatchObject({ materialized: true });
+ return { accepted: true } satisfies SessionSendResult;
+ }),
+ });
+ const { deps } = createDeps({
+ getSession: vi.fn(() => session),
+ materializeDirectSendOssAttachments,
+ });
+ deps.prepareSendUserMessage = vi.fn(async (_sessionId, message) => {
+ events.push('normalize');
+ return message as UserMessage;
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await expect(
+ transaction.sendToAgentAccepted('session-1', { type: 'user', content: 'hello' }, undefined, { marker: true }),
+ ).resolves.toMatchObject({ accepted: true });
+
+ expect(events).toEqual(['materialize', 'normalize', 'send']);
+ expect(materializeDirectSendOssAttachments).toHaveBeenCalledWith(
+ 'session-1',
+ { type: 'user', content: 'hello' },
+ { marker: true },
+ );
+ });
+
+ it('cleans direct OSS materializations when normalization rejects before acceptance', async () => {
+ const cleanupBeforeAcceptance = vi.fn(async () => {});
+ const materializeDirectSendOssAttachments = vi.fn(async () => ({
+ message: { type: 'user', content: 'materialized' },
+ sendOpts: undefined,
+ cleanupBeforeAcceptance,
+ }));
+ const { deps } = createDeps({ materializeDirectSendOssAttachments });
+ deps.prepareSendUserMessage = vi.fn(async () => {
+ throw new Error('normalize failed');
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await expect(transaction.sendToAgentAccepted('session-1', 'hello')).rejects.toThrow('normalize failed');
+ expect(cleanupBeforeAcceptance).toHaveBeenCalledTimes(1);
+ });
+
+ it('cleans direct OSS materializations when vendor send is rejected before dispatch', async () => {
+ const cleanupBeforeAcceptance = vi.fn(async () => {});
+ const materializeDirectSendOssAttachments = vi.fn(async () => ({
+ message: { type: 'user', content: 'materialized' },
+ sendOpts: undefined,
+ cleanupBeforeAcceptance,
+ }));
+ const session = createSession({
+ send: vi.fn(async () => ({
+ accepted: false,
+ reason: 'cancelled-before-dispatch',
+ } satisfies SessionSendResult)),
+ });
+ const { deps } = createDeps({
+ getSession: vi.fn(() => session),
+ materializeDirectSendOssAttachments,
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await expect(transaction.sendToAgentAccepted('session-1', 'hello')).resolves.toMatchObject({
+ accepted: false,
+ });
+ expect(cleanupBeforeAcceptance).toHaveBeenCalledTimes(1);
+ });
+
+ it('cleans direct OSS materializations when vendor send throws before dispatch', async () => {
+ const cleanupBeforeAcceptance = vi.fn(async () => {});
+ const materializeDirectSendOssAttachments = vi.fn(async () => ({
+ message: { type: 'user', content: 'materialized' },
+ sendOpts: undefined,
+ cleanupBeforeAcceptance,
+ }));
+ const session = createSession({
+ send: vi.fn(async () => {
+ throw new Error('vendor send failed');
+ }),
+ });
+ const { deps } = createDeps({
+ getSession: vi.fn(() => session),
+ materializeDirectSendOssAttachments,
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await expect(transaction.sendToAgentAccepted('session-1', 'hello')).rejects.toThrow(
+ 'vendor send failed',
+ );
+ expect(cleanupBeforeAcceptance).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps local OSS materializations after accepted vendor dispatch', async () => {
+ const cleanupAfterAcceptance = vi.fn();
+ const cleanupBeforeAcceptance = vi.fn(async () => {});
+ const materializeDirectSendOssAttachments = vi.fn(async () => ({
+ message: { type: 'user', content: 'materialized' },
+ sendOpts: undefined,
+ cleanupAfterAcceptance,
+ cleanupBeforeAcceptance,
+ }));
+ const { deps } = createDeps({ materializeDirectSendOssAttachments });
+ const transaction = createMakerSendTransaction(deps);
+
+ await expect(transaction.sendToAgentAccepted('session-1', 'hello')).resolves.toMatchObject({
+ accepted: true,
+ });
+ expect(cleanupAfterAcceptance).toHaveBeenCalledTimes(1);
+ expect(cleanupBeforeAcceptance).not.toHaveBeenCalled();
+ });
+
+ it('does not materialize direct OSS attachments when workdir preflight rejects', async () => {
+ const materializeDirectSendOssAttachments = vi.fn();
+ const { deps } = createDeps({
+ checkWorkDirExists: vi.fn(async () => false),
+ materializeDirectSendOssAttachments,
+ });
+ const transaction = createMakerSendTransaction(deps);
+
+ await expect(
+ transaction.sendToAgentAccepted('session-1', { type: 'user', content: 'hello' }),
+ ).resolves.toMatchObject({ accepted: false });
+
+ expect(materializeDirectSendOssAttachments).not.toHaveBeenCalled();
+ });
+
it('consumes the direct-send baseline when vendor dispatch is not accepted', async () => {
const beforeDispatchDirectUserTurn = vi.fn(async () => {});
const onUndispatchedDirectUserTurn = vi.fn();
@@ -432,7 +574,8 @@ describe('maker SEND transaction', () => {
});
it('rejects a non-boolean interrupted-turn dispatch ack option before vendor dispatch', async () => {
- const { deps, session } = createDeps();
+ const materializeDirectSendOssAttachments = vi.fn();
+ const { deps, session } = createDeps({ materializeDirectSendOssAttachments });
const transaction = createMakerSendTransaction(deps);
await expect(
@@ -442,6 +585,7 @@ describe('maker SEND transaction', () => {
).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
expect(session.send).not.toHaveBeenCalled();
+ expect(materializeDirectSendOssAttachments).not.toHaveBeenCalled();
});
it('rolls back the prompt preview if accepted persistence fails before dispatch', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index 0ab5827874..f2fd3d36c8 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -112,6 +112,21 @@ export interface MakerSendTransactionDeps {
sessionId: string,
message: unknown,
): Promise<IpcUserMessage>;
+ /**
+ * Direct device-link sends may carry OSS attachment references that need to
+ * become local paths before normalization. Keep this after the transaction's
+ * session/workdir preflight so rejected sends do not materialize local copies.
+ */
+ materializeDirectSendOssAttachments?: (
+ sessionId: string,
+ message: unknown,
+ sendOpts: unknown,
+ ) => Promise<{
+ message: unknown;
+ sendOpts: unknown;
+ cleanupAfterAcceptance?: () => void;
+ cleanupBeforeAcceptance?: () => void | Promise<void>;
+ }>;
createDbMessage(
sessionId: string,
message: {
@@ -462,7 +477,47 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
if (sess.isTurnRunning()) {
throwIpcError('SESSION_RUNNING', `Session ${sessionId} is already running a turn`);
}
- const normalized = await deps.prepareSendUserMessage(sessionId, message);
+ const requestedSendOpts = (sendOpts ?? {}) as MakerSendOptions;
+ if (
+ requestedSendOpts.ackInterruptedTurnOnDispatch !== undefined &&
+ typeof requestedSendOpts.ackInterruptedTurnOnDispatch !== 'boolean'
+ ) {
+ throwIpcError('INVALID_PARAMS', 'ackInterruptedTurnOnDispatch must be a boolean');
+ }
+ let outgoingMessage = message;
+ let outgoingSendOpts = sendOpts;
+ let cleanupAfterAcceptance: (() => void) | undefined;
+ let cleanupBeforeAcceptance: (() => void | Promise<void>) | undefined;
+ let sendAccepted = false;
+ if (deps.materializeDirectSendOssAttachments) {
+ const materialized = await deps.materializeDirectSendOssAttachments(
+ sessionId,
+ outgoingMessage,
+ outgoingSendOpts,
+ );
+ outgoingMessage = materialized.message;
+ outgoingSendOpts = materialized.sendOpts;
+ cleanupAfterAcceptance = materialized.cleanupAfterAcceptance;
+ cleanupBeforeAcceptance = materialized.cleanupBeforeAcceptance;
+ }
+ const cleanupBeforeAcceptanceIfNeeded = async (): Promise<void> => {
+ if (!cleanupBeforeAcceptance) return;
+ try {
+ await cleanupBeforeAcceptance();
+ } catch (err) {
+ deps.log.warn('send: direct OSS materialization cleanup failed', {
+ sessionId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ }
+ };
+ let normalized: IpcUserMessage;
+ try {
+ normalized = await deps.prepareSendUserMessage(sessionId, outgoingMessage);
+ } catch (err) {
+ await cleanupBeforeAcceptanceIfNeeded();
+ throw err;
+ }
// session-agent-switch:切换后的首条消息把交接前缀拼进 wire payload。
// 落库/显示内容(persistUserMessage.content)不含交接段——display 与 sent 分离。
const pendingHandoff = (await deps.peekPendingHandoff?.(sessionId)) ?? null;
@@ -470,13 +525,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
? prependHandoffToUserMessage(normalized as HandoffWireMessage, pendingHandoff)
: normalized;
const meta = await deps.getSessionMeta(sessionId).catch(() => null);
- const so = (sendOpts ?? {}) as MakerSendOptions;
- if (
- so.ackInterruptedTurnOnDispatch !== undefined &&
- typeof so.ackInterruptedTurnOnDispatch !== 'boolean'
- ) {
- throwIpcError('INVALID_PARAMS', 'ackInterruptedTurnOnDispatch must be a boolean');
- }
+ const so = (outgoingSendOpts ?? {}) as MakerSendOptions;
const persistUserMessage = readPersistUserMessageOption(so);
const directPreDispatchHook = persistUserMessage ? null : deps.beforeDispatchDirectUserTurn;
let directPreDispatchHookStarted = false;
@@ -581,6 +630,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
}
},
});
+ sendAccepted = sendResult.accepted;
+ if (sendAccepted) cleanupAfterAcceptance?.();
+ else await cleanupBeforeAcceptanceIfNeeded();
if (sendResult.accepted && interruptedAckAt !== null) {
try {
await deps.ackInterruptedTurnDispatched?.(sessionId, interruptedAckAt);
@@ -618,6 +670,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
}),
);
} catch (err) {
+ if (!sendAccepted) await cleanupBeforeAcceptanceIfNeeded();
if (userPromptPreviewSessionId && userPromptPreviewClientId) {
deps.rollbackUserPromptPreview?.(
userPromptPreviewSessionId,
diff --git a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
index ba112ba60e..46d1f808c8 100644
--- a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
+++ b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
@@ -24,12 +24,14 @@ import { randomUUID } from 'node:crypto';
import * as imageCacheStore from '../imageCacheStore.js';
import * as cindyMediaBlobStore from '../cindy-media/blobStore.js';
+import * as cindyMediaLedger from '../cindy-media/ledger.js';
import { ingestMedia } from '../cindy-media/ingest.js';
import { createLogger } from '../logger.js';
import { isAttachmentOssRef, parseAttachmentOssRef } from '../../shared/attachmentOssRef.js';
import type { AttachmentIntegrity, AttachmentOssRef } from '../../shared/attachmentOssRef.js';
import { downloadToFile, removeRemote } from '../device-link/mediaTransfer.js';
import { throwIpcError } from '../utils/ipcValidate.js';
+import { isDangerousAttachmentName } from '../../shared/attachmentSafety.js';
const log = createLogger('maker-ipc/normalize');
@@ -262,6 +264,7 @@ function persistedContentNeedsMaterialize(json: string): boolean {
/** 物化结果:被控端 image cache 里的 `xdt-image://` url(渲染用)+ 其绝对路径(file chip / agent 用)。 */
type MaterializedRef = { url: string; absPath: string };
+type MaterializedCleanup = () => void | Promise<void>;
/**
* 用 materialize(OSS 引用串 → image cache 物化结果)改写 persistedContent JSON 串。
@@ -325,11 +328,16 @@ async function materializePersistedContent(
* 无 OSS 引用(本机会话)→ 原样返回,零额外 IO。旧引用物化失败维持历史降级;新引用失败直接阻止入队。
* OSS 删除放在 files[] + persistedContent 都物化之后,避免删早了另一副身取不到。
*/
-export async function materializeQueuedOssAttachments(
+async function materializeQueuedOssAttachmentsInternal(
sessionId: string,
item: unknown,
-): Promise<unknown> {
- if (!item || typeof item !== 'object') return item;
+ deferCleanup: boolean,
+): Promise<{
+ item: unknown;
+ cleanupAfterAcceptance?: () => void;
+ cleanupBeforeAcceptance?: () => Promise<void>;
+}> {
+ if (!item || typeof item !== 'object') return { item };
const it = item as { files?: unknown; persistedContent?: unknown };
const files = Array.isArray(it.files) ? it.files : null;
const pcStr = typeof it.persistedContent === 'string' ? it.persistedContent : null;
@@ -342,10 +350,34 @@ export async function materializeQueuedOssAttachments(
(isOssRefField((f as SerializedFileLike).url) ||
isOssRefField((f as SerializedFileLike).path)),
) ?? false;
- if (!filesHaveOss && !(pcStr && persistedContentNeedsMaterialize(pcStr))) return item; // 无需物化 → 原样
+ if (!filesHaveOss && !(pcStr && persistedContentNeedsMaterialize(pcStr))) return { item }; // 无需物化 → 原样
const byRef = new Map<string, MaterializedRef>(); // 引用串 → 物化结果(同串只下载/拷贝+入库一次)
const ossKeys = new Set<string>();
+ let cleanedUp = false;
+ const cleanupOss = () => {
+ if (cleanedUp) return;
+ cleanedUp = true;
+ for (const key of ossKeys) void removeRemote(key);
+ };
+ const localCleanupCallbacks: MaterializedCleanup[] = [];
+ let localCleanedUp = false;
+ const cleanupLocalMaterializations = async (): Promise<void> => {
+ if (localCleanedUp) return;
+ localCleanedUp = true;
+ for (const cleanup of localCleanupCallbacks) {
+ try {
+ await cleanup();
+ } catch (e) {
+ log.warn('local OSS materialization cleanup failed', { error: String(e) });
+ }
+ }
+ };
+ const cleanupBeforeAcceptance = async (): Promise<void> => {
+ // Keep the remote OSS object retryable until the direct send is accepted.
+ // Only the local materialization belongs to this rejection cleanup path.
+ await cleanupLocalMaterializations();
+ };
// 可入总仓的媒体(图片等白名单 mime)→ ingest 进 cindy-media 并直接挂
// session-attachment 引用(入队消息没有草稿期,等价老 lifecycle committed);
// 媒体附件统一走总仓 ingest(规则 25)。
@@ -366,6 +398,14 @@ export async function materializeQueuedOssAttachments(
},
],
});
+ const refId = written.refIds[0];
+ if (refId) {
+ localCleanupCallbacks.push(async () => {
+ await cindyMediaLedger.removeRefById(refId);
+ const removed = await cindyMediaLedger.deleteZeroRefBlobRecord(written.hash, Date.now() + 1);
+ if (removed) await cindyMediaBlobStore.deleteBlobFile(written.hash, written.ext);
+ });
+ }
return { url: written.url, absPath: cindyMediaBlobStore.resolveSafe(written.url).absPath };
};
// 物化:被控端本机绝对路径图片(手机文件浏览器发送)读字节入总仓;OSS 引用走
@@ -404,7 +444,12 @@ export async function materializeQueuedOssAttachments(
// 只收图片进总仓:ingestIntoBlobStore 是整读内存(readFile + sha256),
// 手机传的大视频/音频若走这条会让 main 进程内存翻倍(review P1);
// 等 blobStore 流式入口落地再放开非图片媒体,现阶段维持老文件级拷贝。
- if (mime && mime.startsWith('image/') && cindyMediaBlobStore.supportedMime(mime)) {
+ if (
+ mime &&
+ mime.startsWith('image/') &&
+ cindyMediaBlobStore.supportedMime(mime) &&
+ !isDangerousAttachmentName(ref.originalName ?? '')
+ ) {
entry = await ingestIntoBlobStore(tmp, mime);
} else {
// 非媒体附件维持历史兼容路径落地;规则 25 明确非媒体不进字节仓。
@@ -416,6 +461,7 @@ export async function materializeQueuedOssAttachments(
originalName,
lifecycle: 'committed',
});
+ localCleanupCallbacks.push(() => imageCacheStore.removeFile(url));
entry = { url, absPath: imageCacheStore.resolveSafe(url).absPath };
}
byRef.set(refStr, entry);
@@ -466,10 +512,162 @@ export async function materializeQueuedOssAttachments(
: it.persistedContent;
// files[] 与 persistedContent 都物化完才删 OSS(每个 key 删一次,best-effort 不阻塞)。
- return { ...(it as object), ...(files ? { files: nextFiles } : {}), persistedContent: nextPc };
+ const materializedItem = {
+ ...(it as object),
+ ...(files ? { files: nextFiles } : {}),
+ persistedContent: nextPc,
+ };
+ return {
+ item: materializedItem,
+ ...(deferCleanup && (ossKeys.size > 0 || localCleanupCallbacks.length > 0)
+ ? {
+ cleanupAfterAcceptance: cleanupOss,
+ cleanupBeforeAcceptance,
+ }
+ : {}),
+ };
+ } catch (err) {
+ await cleanupBeforeAcceptance();
+ throw err;
} finally {
- for (const k of ossKeys) void removeRemote(k);
+ if (!deferCleanup) cleanupOss();
+ }
+}
+
+export async function materializeQueuedOssAttachments(
+ sessionId: string,
+ item: unknown,
+): Promise<unknown> {
+ return (await materializeQueuedOssAttachmentsInternal(sessionId, item, false)).item;
+}
+
+/**
+ * Direct maker:send carries attachment references in two parallel shapes:
+ * the user-message blocks consumed by the agent and
+ * sendOpts.persistUserMessage.content stored in the local transcript.
+ *
+ * Reuse the queued materializer through a temporary files[] projection so both
+ * shapes share one download per OSS reference. Cleanup is returned to the
+ * caller and must run only after maker:send reports accepted=true, so a
+ * pre-accept rejection can retry the original OSS references.
+ */
+export async function materializeDirectSendOssAttachments(
+ sessionId: string,
+ message: unknown,
+ sendOpts: unknown,
+): Promise<{
+ message: unknown;
+ sendOpts: unknown;
+ cleanupAfterAcceptance?: () => void;
+ cleanupBeforeAcceptance?: () => Promise<void>;
+}> {
+ if (!message || typeof message !== 'object' || Array.isArray(message)) {
+ return { message, sendOpts };
+ }
+ const msg = message as { type?: unknown; content?: unknown };
+ if (msg.type !== 'user' || !Array.isArray(msg.content)) {
+ return { message, sendOpts };
+ }
+
+ const attachmentIndexes: number[] = [];
+ const projectedFiles: Array<Record<string, unknown>> = [];
+ for (let index = 0; index < msg.content.length; index += 1) {
+ const raw = msg.content[index];
+ if (
+ raw &&
+ typeof raw === 'object' &&
+ !Array.isArray(raw) &&
+ (((raw as { type?: unknown }).type === 'image') ||
+ (raw as { type?: unknown }).type === 'file')
+ ) {
+ attachmentIndexes.push(index);
+ const block = raw as Record<string, unknown>;
+ projectedFiles.push({
+ ...block,
+ ...(typeof block.path === 'string' ? { url: block.path } : {}),
+ });
+ }
+ }
+
+ const persist =
+ sendOpts && typeof sendOpts === 'object' && !Array.isArray(sendOpts)
+ ? (sendOpts as { persistUserMessage?: unknown }).persistUserMessage
+ : undefined;
+ const persistedContent =
+ persist && typeof persist === 'object' && !Array.isArray(persist)
+ ? (persist as { content?: unknown }).content
+ : undefined;
+ const hasProjectedOss = projectedFiles.some(
+ (file) => isOssRefField(file.url) || isOssRefField(file.path),
+ );
+ const persistedNeedsMaterialize =
+ typeof persistedContent === 'string' && persistedContentNeedsMaterialize(persistedContent);
+ if (!hasProjectedOss && !persistedNeedsMaterialize) {
+ return { message, sendOpts };
}
+
+ const materialized = await materializeQueuedOssAttachmentsInternal(
+ sessionId,
+ {
+ files: projectedFiles,
+ ...(typeof persistedContent === 'string' ? { persistedContent } : {}),
+ },
+ true,
+ );
+ const projected = materialized.item as { files?: unknown; persistedContent?: unknown };
+ const materializedFiles = Array.isArray(projected.files) ? projected.files : projectedFiles;
+ const nextContent = [...msg.content];
+ for (let index = 0; index < attachmentIndexes.length; index += 1) {
+ const original = msg.content[attachmentIndexes[index]];
+ const materialized = materializedFiles[index];
+ if (!original || typeof original !== 'object' || !materialized || typeof materialized !== 'object') {
+ continue;
+ }
+ const originalPath = (original as { path?: unknown }).path;
+ const pathValue = (materialized as { path?: unknown }).path;
+ if (
+ isOssRefField(originalPath) &&
+ typeof pathValue === 'string' &&
+ pathValue !== originalPath
+ ) {
+ nextContent[attachmentIndexes[index]] = {
+ ...(original as object),
+ path: pathValue,
+ base64: undefined,
+ };
+ }
+ }
+
+ let nextSendOpts = sendOpts;
+ if (
+ typeof projected.persistedContent === 'string' &&
+ projected.persistedContent !== persistedContent &&
+ sendOpts &&
+ typeof sendOpts === 'object' &&
+ !Array.isArray(sendOpts) &&
+ persist &&
+ typeof persist === 'object' &&
+ !Array.isArray(persist)
+ ) {
+ nextSendOpts = {
+ ...(sendOpts as object),
+ persistUserMessage: {
+ ...(persist as object),
+ content: projected.persistedContent,
+ },
+ };
+ }
+
+ return {
+ message: { ...msg, content: nextContent },
+ sendOpts: nextSendOpts,
+ ...(materialized.cleanupAfterAcceptance
+ ? { cleanupAfterAcceptance: materialized.cleanupAfterAcceptance }
+ : {}),
+ ...(materialized.cleanupBeforeAcceptance
+ ? { cleanupBeforeAcceptance: materialized.cleanupBeforeAcceptance }
+ : {}),
+ };
}
export async function cleanupSessionTempAttachments(sessionId: string): Promise<void> {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 4ba6b24251..df1ca22abe 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -382,7 +382,11 @@ import {
installInteractionLifecycleObserver,
} from './interactionRouter.js';
import { registerMakerMessageDeleteHandler } from './messageDeleteHandler.js';
-import { normalizeUserMessage, materializeQueuedOssAttachments } from './normalizeAttachments.js';
+import {
+ normalizeUserMessage,
+ materializeDirectSendOssAttachments,
+ materializeQueuedOssAttachments,
+} from './normalizeAttachments.js';
import { AGENT_ISLAND_DISPLAY_CONFIG } from '../agent-island/displayConfig.js';
import {
shouldClearAgentIslandSessionForOrcaWorker,
@@ -7667,6 +7671,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
broadcastSessionCreated,
prepareSendUserMessage: (sessionId, message) =>
prepareUserMessageForAgent(sessionId, message, 'send'),
+ materializeDirectSendOssAttachments,
createDbMessage: async (sessionId, message, opts) => {
// 真实用户消息(renderer 发送事务)→ 给两个自动续跑守卫充值额度。
//
@@ -7746,12 +7751,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
applyPendingAgentSwitch: (sessionId) => applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId),
log,
});
- const sendToAgentAccepted: typeof sendToAgentAcceptedUnlocked = (...args) => {
+
+ const sendToAgentAccepted: typeof sendToAgentAcceptedUnlocked = async (...args) => {
const [sessionId] = args;
- if (typeof sessionId !== 'string') return sendToAgentAcceptedUnlocked(...args);
- return withSendToSessionLock(sessionId, () => sendToAgentAcceptedUnlocked(...args));
+ if (typeof sessionId !== 'string') return await sendToAgentAcceptedUnlocked(...args);
+ return await withSendToSessionLock(sessionId, () => sendToAgentAcceptedUnlocked(...args));
};
-
/**
* Same-turn steer contract: resolved STEER means maker-core accepted the
* inserted message into the active turn (Claude: streaming input push;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 6e92ac37be..d478bec3e9 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2828,6 +2828,29 @@ contextBridge.exposeInMainWorld('electronAPI', {
openPath: (filePathOrUrl: string): Promise<{ success: boolean; error?: string }> =>
ipcRenderer.invoke('shell:open-path', filePathOrUrl),
+ // 危险本地附件入托盘前先复制成受控缓存里的 `.bin` 副本。显示名仍由
+ // renderer 单独保留,后续只能经“另存为”恢复原始扩展名。
+ stageChatAttachment: (params: {
+ sourcePath: string;
+ suggestedName: string;
+ }): Promise<
+ | { success: true; path: string }
+ | {
+ success: false;
+ code:
+ | 'invalid_source'
+ | 'forbidden'
+ | 'not_found'
+ | 'not_file'
+ | 'unsupported_type'
+ | 'copy_failed';
+ }
+ > => ipcRenderer.invoke('chat-attachment:stage', params),
+
+ /** Remove staged dangerous attachment copies from the controlled cache. */
+ cleanupStagedChatAttachments: (filePaths: readonly string[]): Promise<void> =>
+ ipcRenderer.invoke('chat-attachment:cleanup', filePaths),
+
// 安全降级聊天附件另存为。main 校验源路径并清洗 suggestedName;保存后
// 只返回结果,不自动打开或执行目标文件。
saveChatAttachmentAs: (params: {
diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
index 84a6acd563..43a038ad0e 100644
--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
@@ -1034,7 +1034,7 @@ describe('automation-generated sessions', () => {
expect(deleteHookSource).toContain("sessionService.update(sessionId, { status: 'deleted' })");
expect(deleteHookSource).toContain('window.electronAPI.cleanupSessionImages(sessionId)');
expect(deleteHookSource).toContain('makerChatStore.closeSessionQuery(sessionId)');
- expect(deleteHookSource).toContain('clearComposerDraft(sessionId)');
+ expect(deleteHookSource).toContain('discardComposerDraft(sessionId)');
expect(deleteHookSource).toContain('scheduler.deleteDialog.option.keep.title');
expect(deleteHookSource).toContain('scheduler.deleteDialog.option.archive.title');
expect(deleteHookSource).toContain('scheduler.deleteDialog.option.delete.title');
diff --git a/apps/desktop/src/renderer/__tests__/chatAttachmentSave.test.ts b/apps/desktop/src/renderer/__tests__/chatAttachmentSave.test.ts
index 7f4bbc8590..b9fabe0344 100644
--- a/apps/desktop/src/renderer/__tests__/chatAttachmentSave.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatAttachmentSave.test.ts
@@ -12,6 +12,10 @@ import {
function makeDeps(overrides: Partial<ChatAttachmentSaveDeps> = {}): ChatAttachmentSaveDeps {
return {
platform: 'win32',
+ stageDangerous: vi.fn(async () => ({
+ success: true as const,
+ path: 'C:\\cache\\staged-setup.exe.bin',
+ })),
fetchRemoteFile: vi.fn(async () => 'C:\\cache\\remote.bin'),
saveAs: vi.fn(async () => ({
status: 'saved' as const,
@@ -25,7 +29,13 @@ function makeDeps(overrides: Partial<ChatAttachmentSaveDeps> = {}): ChatAttachme
}
describe('safe attachment routing', () => {
- it('only treats a mismatched .bin materialization as safety-downgraded', () => {
+ it('treats dangerous names and historical mismatched .bin materializations as download-only', () => {
+ expect(isSafetyDowngradedAttachment({ name: 'setup.exe', path: 'C:\\Downloads\\setup.exe' })).toBe(
+ true,
+ );
+ expect(isSafetyDowngradedAttachment({ name: 'attachment', path: 'C:\\Downloads\\setup.exe' })).toBe(
+ true,
+ );
expect(isSafetyDowngradedAttachment({ name: 'setup.exe', path: 'C:\\cache\\random.bin' })).toBe(
true,
);
@@ -70,6 +80,7 @@ describe('saveChatAttachmentWithToasts', () => {
deps,
);
expect(deps.fetchRemoteFile).not.toHaveBeenCalled();
+ expect(deps.stageDangerous).not.toHaveBeenCalled();
expect(deps.saveAs).toHaveBeenCalledWith({
sourcePath: 'C:\\cache\\random.bin',
suggestedName: 'setup.exe',
@@ -79,6 +90,67 @@ describe('saveChatAttachmentWithToasts', () => {
expect(result).toBe('saved');
});
+ it('stages a legacy local executable path before Save As', async () => {
+ const deps = makeDeps();
+ const result = await saveChatAttachmentWithToasts(
+ { origin: { kind: 'local' }, workingDir: 'C:\\work' },
+ { name: 'setup.exe', path: 'C:\\Downloads\\setup.exe' },
+ deps,
+ );
+ expect(deps.stageDangerous).toHaveBeenCalledWith({
+ sourcePath: 'C:\\Downloads\\setup.exe',
+ suggestedName: 'setup.exe',
+ });
+ expect(deps.saveAs).toHaveBeenCalledWith({
+ sourcePath: 'C:\\cache\\staged-setup.exe.bin',
+ suggestedName: 'setup.exe',
+ });
+ expect(result).toBe('saved');
+ });
+
+ it('stages a dangerous legacy source path even when its persisted display name is safe', async () => {
+ const deps = makeDeps();
+ const result = await saveChatAttachmentWithToasts(
+ { origin: { kind: 'local' }, workingDir: 'C:\\work' },
+ { name: 'attachment', path: 'C:\\Downloads\\setup.exe' },
+ deps,
+ );
+ expect(deps.stageDangerous).toHaveBeenCalledWith({
+ sourcePath: 'C:\\Downloads\\setup.exe',
+ suggestedName: 'attachment',
+ });
+ expect(deps.saveAs).toHaveBeenCalledWith({
+ sourcePath: 'C:\\cache\\staged-setup.exe.bin',
+ suggestedName: 'attachment',
+ });
+ expect(result).toBe('saved');
+ });
+
+ it('cleans the temporary legacy staging copy after Save As completes', async () => {
+ const cleanupStaged = vi.fn(async () => {});
+ const deps = makeDeps({ cleanupStaged });
+ await saveChatAttachmentWithToasts(
+ { origin: { kind: 'local' }, workingDir: 'C:\\work' },
+ { name: 'setup.exe', path: 'C:\\Downloads\\setup.exe' },
+ deps,
+ );
+ expect(cleanupStaged).toHaveBeenCalledWith(['C:\\cache\\staged-setup.exe.bin']);
+ });
+
+ it('cleans the temporary legacy staging copy when Save As fails', async () => {
+ const cleanupStaged = vi.fn(async () => {});
+ const deps = makeDeps({
+ cleanupStaged,
+ saveAs: vi.fn(async () => ({ status: 'error' as const, code: 'copy_failed' as const })),
+ });
+ await saveChatAttachmentWithToasts(
+ { origin: { kind: 'local' }, workingDir: 'C:\\work' },
+ { name: 'setup.exe', path: 'C:\\Downloads\\setup.exe' },
+ deps,
+ );
+ expect(cleanupStaged).toHaveBeenCalledWith(['C:\\cache\\staged-setup.exe.bin']);
+ });
+
it('fetches a remote copy first and warns when the type is unsupported locally', async () => {
const deps = makeDeps({ platform: 'darwin' });
const origin = { kind: 'device' as const, deviceId: 'device-1' };
diff --git a/apps/desktop/src/renderer/__tests__/messageAttachmentPayload.test.ts b/apps/desktop/src/renderer/__tests__/messageAttachmentPayload.test.ts
index 1fdd8f011d..66f0125efc 100644
--- a/apps/desktop/src/renderer/__tests__/messageAttachmentPayload.test.ts
+++ b/apps/desktop/src/renderer/__tests__/messageAttachmentPayload.test.ts
@@ -65,6 +65,7 @@ describe('messageAttachmentPayload', () => {
type: 'image',
path: 'xdt-image://session/shot.png',
mimeType: 'image/png',
+ originalName: 'original.png',
},
]);
});
@@ -94,6 +95,7 @@ describe('messageAttachmentPayload', () => {
type: 'image',
base64: 'inline-image',
mimeType: 'image/png',
+ originalName: 'fallback.png',
},
]);
});
@@ -116,7 +118,7 @@ describe('messageAttachmentPayload', () => {
type: 'user',
content: [
{ type: 'text', text: 'read it' },
- { type: 'file', path: pdfPath, mimeType: 'application/pdf' },
+ { type: 'file', path: pdfPath, mimeType: 'application/pdf', originalName: 'doc.pdf' },
],
});
});
@@ -147,7 +149,13 @@ describe('messageAttachmentPayload', () => {
type: 'user',
content: [
{ type: 'text', text: 'inspect gif' },
- { type: 'file', path: 'xdt-image://session/clip.gif', mimeType: 'image/gif', originalPath: gifPath },
+ {
+ type: 'file',
+ path: 'xdt-image://session/clip.gif',
+ mimeType: 'image/gif',
+ originalName: 'clip.gif',
+ originalPath: gifPath,
+ },
],
});
});
@@ -170,7 +178,12 @@ describe('messageAttachmentPayload', () => {
type: 'user',
content: [
{ type: 'text', text: 'summarize video' },
- { type: 'file', path: videoPath, mimeType: 'video/mp4' },
+ {
+ type: 'file',
+ path: videoPath,
+ mimeType: 'video/mp4',
+ originalName: 'recording.mp4',
+ },
],
});
});
diff --git a/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts b/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts
index c1a2ec4275..5470ecb80c 100644
--- a/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts
+++ b/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts
@@ -65,7 +65,8 @@ describe('Attachment thumbnail — click opens lightbox (attachment-thumb-click)
// The preview button carries the hand cursor; the outer wrapper owns the
// hover boundary so moving onto the remove button does not hide the preview.
- expect(block).toMatch(/className="h-full w-full cursor-pointer/);
+ expect(block).toContain("isDownloadOnly ? 'cursor-default' : 'cursor-pointer'");
+ expect(block).toContain('disabled={isDownloadOnly}');
// A click handler that delegates to handleOpenPreview must exist.
expect(block).toMatch(/onClick=\{handleOpenPreview\}/);
@@ -76,6 +77,9 @@ describe('Attachment thumbnail — click opens lightbox (attachment-thumb-click)
expect(block).toMatch(/file\.category === 'image'/);
expect(block).toMatch(/<ImageLightbox\s+src=\{lightboxSrc\}/);
expect(block).toMatch(/<TextLightbox[\s\S]+filePath=\{file\.path\}/);
+ expect(block).toMatch(
+ /if \(isDownloadOnly\) return;[\s\S]+shouldOpenTextLightbox\(file\.path\)/,
+ );
});
it('keeps thumbnail hover state on the outer wrapper so the remove button does not dismiss preview', () => {
diff --git a/apps/desktop/src/renderer/__tests__/useAttachmentsRejections.test.ts b/apps/desktop/src/renderer/__tests__/useAttachmentsRejections.test.ts
index 1458746c4d..30774c8f41 100644
--- a/apps/desktop/src/renderer/__tests__/useAttachmentsRejections.test.ts
+++ b/apps/desktop/src/renderer/__tests__/useAttachmentsRejections.test.ts
@@ -14,6 +14,7 @@ import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const toastWarning = vi.hoisted(() => vi.fn());
+const stageChatAttachment = vi.hoisted(() => vi.fn());
vi.mock('react-i18next', () => ({
initReactI18next: { type: '3rdParty', init: vi.fn() },
@@ -38,8 +39,11 @@ function fileListOf(files: Array<{ name: string; size: number }>): FileList {
beforeEach(() => {
toastWarning.mockClear();
+ stageChatAttachment.mockReset();
+ stageChatAttachment.mockResolvedValue({ success: true, path: '/cache/setup.exe.bin' });
(window as unknown as { electronAPI: unknown }).electronAPI = {
getFilePath: (f: { name: string }) => `/tmp/${f.name}`,
+ stageChatAttachment,
};
});
@@ -98,4 +102,39 @@ describe('useAttachments inline rejections', () => {
act(() => rerender({ sid: 'session-B' }));
expect(result.current.rejections).toHaveLength(0);
});
+
+ it('stages a dangerous attachment under an inert path before adding it', async () => {
+ const { result } = renderHook(() => useAttachments());
+
+ await act(async () => {
+ await result.current.addFiles(fileListOf([{ name: 'setup.exe', size: 64 }]));
+ });
+
+ expect(stageChatAttachment).toHaveBeenCalledWith({
+ sourcePath: '/tmp/setup.exe',
+ suggestedName: 'setup.exe',
+ });
+ expect(result.current.rejections).toHaveLength(0);
+ expect(result.current.attachments).toHaveLength(1);
+ expect(result.current.attachments[0]).toMatchObject({
+ name: 'setup.exe',
+ path: '/cache/setup.exe.bin',
+ ext: '.exe',
+ category: 'file',
+ });
+ });
+
+ it('fails closed when dangerous attachment staging fails', async () => {
+ stageChatAttachment.mockResolvedValue({ success: false, code: 'copy_failed' });
+ const { result } = renderHook(() => useAttachments());
+
+ await act(async () => {
+ await result.current.addFiles(fileListOf([{ name: 'setup.exe', size: 64 }]));
+ });
+
+ expect(result.current.attachments).toHaveLength(0);
+ expect(result.current.rejections).toHaveLength(1);
+ expect(result.current.rejections[0].message).toContain('setup.exe');
+ expect(result.current.rejections[0].message).toContain('copy_failed');
+ });
});
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 376b89b6c0..6a705c34d3 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -81,6 +81,7 @@ import {
type DroppedFileItems,
} from '@/lib/fileDrop';
import { shouldOpenTextLightbox } from '@/lib/filePreview';
+import { isDangerousAttachmentName } from '../../../shared/attachmentSafety';
import {
getDraft as getComposerDraft,
saveDraft as saveComposerDraft,
@@ -499,6 +500,7 @@ interface ChatInputProps {
consumePendingFileMentions: () => Array<{ type: 'file'; relPath: string; name: string }>;
removeFile: (id: string) => void;
updateFile: (id: string, patch: Partial<AttachedFile>) => void;
+ discardFiles: () => void;
clearFiles: () => void;
};
/**
@@ -1072,6 +1074,7 @@ export function ChatInput({
consumePendingFileMentions,
removeFile,
updateFile,
+ discardFiles,
clearFiles,
} = attachmentState;
// browser-comment-chip:内置浏览器页面评论(结构化,不进草稿文本),渲染为
@@ -5553,7 +5556,7 @@ export function ChatInput({
} finally {
isRestoringRef.current = false;
}
- clearFiles();
+ discardFiles();
// 页面评论走丢弃语义(清 state + 清截图缓存):目标不接管评论截图,
// 与发送后清空(消息接管截图,不清缓存)不同,这里不清会留磁盘孤儿。
clearBrowserComments();
@@ -6279,6 +6282,7 @@ function ThumbnailItem({
onRemove: (id: string) => void;
onUpdate: (id: string, patch: Partial<AttachedFile>) => void;
}) {
+ const { t } = useTranslation();
const [isHovered, setIsHovered] = useState(false);
const thumbRef = useRef<HTMLDivElement>(null);
const [popoverPos, setPopoverPos] = useState<{ top: number; left: number } | null>(null);
@@ -6290,6 +6294,8 @@ function ThumbnailItem({
// Lightbox state is local to each item so multiple thumbnails don't fight.
const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);
const [textLightboxOpen, setTextLightboxOpen] = useState(false);
+ const isDownloadOnly =
+ isDangerousAttachmentName(file.name) || isDangerousAttachmentName(file.path);
// 非图片附件仍使用路径 tooltip;图片定位由共享 ImageHoverPreview 自己负责。
useLayoutEffect(() => {
@@ -6319,12 +6325,16 @@ function ThumbnailItem({
if (src) setLightboxSrc(src);
return;
}
+ // Historical composer drafts may still contain an executable's original
+ // path from before dangerous attachments were staged as `.bin`. Never pass
+ // those paths to the OS default-app opener from the attachment tray.
+ if (isDownloadOnly) return;
// Non-image text/code/markdown files preview via TextLightbox. Other
// supported attachment categories (PDF, etc.) open in the system app.
if (!file.path) return;
if (!(await shouldOpenTextLightbox(file.path))) return;
setTextLightboxOpen(true);
- }, [file]);
+ }, [file, isDownloadOnly]);
// 图片缩略图恒为 56×56 方块;其余附件走横向文件卡,宽度随文件名自适应
// (上限 220px)。判定条件必须与下面渲染分支一致——缓存写失败、既无 url 也无
@@ -6356,9 +6366,17 @@ function ThumbnailItem({
{/* image-local-cache: prefer xdt-image:// url; fall back to base64 (F6). */}
<button
type="button"
- className="h-full w-full cursor-pointer border-0 bg-transparent p-0 text-left"
+ className={cn(
+ 'h-full w-full border-0 bg-transparent p-0 text-left',
+ isDownloadOnly ? 'cursor-default' : 'cursor-pointer',
+ )}
onClick={handleOpenPreview}
- aria-label={`Preview ${file.name}`}
+ disabled={isDownloadOnly}
+ aria-label={
+ isDownloadOnly
+ ? t('chat.userMessage.attachmentAttachedAria', { name: file.name })
+ : `Preview ${file.name}`
+ }
>
{file.category === 'image' && (file.url || file.base64) ? (
<span className="relative block h-full w-full">
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index fe4b63afd0..a69c52840b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -53,7 +53,7 @@ import {
import { Tooltip } from '@/components/ui/tooltip';
import * as sessionService from '@/lib/sessionService';
import { makerChatStore } from '@/lib/makerChatStore';
-import { clearDraft as clearComposerDraft } from '@/lib/composerDraftStore';
+import { discardDraft as discardComposerDraft } from '@/lib/composerDraftStore';
import { cleanupSessionLayoutPrefs } from '@/lib/sessionLayoutPrefs';
import {
countDirtyWorktreesForRemoval,
@@ -2120,7 +2120,7 @@ function ExpandedView({
// patchMeta 按来源路由:远程会话经隧道写被控端 patch-meta(allowlist 内),本地仍走 update。
await sessionService.patchMeta(session.id, { status: 'deleted' });
makerChatStore.purgeSession(session.id);
- clearComposerDraft(session.id);
+ discardComposerDraft(session.id);
// RSB 布局偏好(fraction / treeWidth / collapsed)走 localStorage 是
// 本机概念,本地 + 远程 session 都要清(被控端的 localStorage 由被控端自己处理)。
cleanupSessionLayoutPrefs(session.id);
@@ -2270,7 +2270,7 @@ function ExpandedView({
patchLocal(session.id, { status: 'archived', pinnedAt: null });
}
makerChatStore.purgeSession(session.id);
- clearComposerDraft(session.id);
+ discardComposerDraft(session.id);
} catch (err) {
log.error('[bulk session archive]', err);
failed.push(session.id);
@@ -2455,7 +2455,7 @@ function ExpandedView({
// 跨 bucket 同步:见 handleConfirm 同位置注释。
patchLocal(s.id, { status: 'archived', pinnedAt: null });
makerChatStore.purgeSession(s.id);
- clearComposerDraft(s.id);
+ discardComposerDraft(s.id);
} catch (err) {
log.error('[archive all]', err);
failed.push(s.id);
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 234410f966..c22e173220 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -115,6 +115,7 @@ import * as sessionService from '@/lib/sessionService';
import { sessionsStore } from '@/lib/sessionsStore';
import { emitAutoTitlePreview, emitAutoTitlePreviewCleared } from '@/lib/sessionsBus';
import { NewGoalDialog } from '@/components/new-chat/NewGoalDialog';
+import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageCleanup';
import type { GoalLimitValues } from '@/components/new-chat/GoalAdvancedLimits';
import { makerChatStore } from '@/lib/makerChatStore';
import { worktreeCreationStore } from '@/lib/worktreeCreationStore';
@@ -1688,6 +1689,9 @@ export function NewMakerDraftRoute() {
// SSH agent 无法读取控制端本地文件;只保留 image 类附件(可 rehome 到 cache URL),
// 丢弃 path-based 非 image 附件(PDF / text 等)。
const imageOnly = existingDraft.attachments.filter((f) => f.category === 'image');
+ cleanupStagedChatAttachmentFiles(
+ existingDraft.attachments.filter((attachment) => attachment.category !== 'image'),
+ );
const rehomedAttachments = await rehomeDraftAttachments(imageOnly, newSession.id);
let rehomedComments = existingDraft.browserComments;
if (rehomedComments && rehomedComments.length > 0) {
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx
index 156d2c692d..896126e827 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx
@@ -42,7 +42,7 @@ vi.mock('@/lib/makerChatStore', () => ({
}));
vi.mock('@/lib/composerDraftStore', () => ({
- clearDraft: mocks.clearComposerDraft,
+ discardDraft: mocks.clearComposerDraft,
}));
vi.mock('@/lib/sessionLayoutPrefs', () => ({
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
index 48554e2cc9..cbb296489c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
@@ -28,7 +28,7 @@ import { useTranslation } from 'react-i18next';
import { toast } from '@/lib/toast';
import * as sessionService from '@/lib/sessionService';
import { makerChatStore } from '@/lib/makerChatStore';
-import { clearDraft as clearComposerDraft } from '@/lib/composerDraftStore';
+import { discardDraft as discardComposerDraft } from '@/lib/composerDraftStore';
import { cleanupSessionLayoutPrefs } from '@/lib/sessionLayoutPrefs';
import { emitRefresh } from '@/lib/sessionsBus';
import { useCCSessions } from '@/hooks/useCCSessions';
@@ -152,7 +152,7 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
// composer-draft-per-session: drop any leftover composer draft (text /
// attachments) for this session — without this the draft Map would
// hold an orphan entry forever.
- clearComposerDraft(sessionId);
+ discardComposerDraft(sessionId);
if (action === 'delete') {
void window.electronAPI.cleanupSessionImages(sessionId).catch((err: unknown) => {
log.warn('[session delete] cleanup images failed', err);
diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx
index 022aa5df21..8013424a88 100644
--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx
@@ -38,7 +38,7 @@ import { createLogger } from '@/lib/logger';
import { toast } from '@/lib/toast';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { makerChatStore } from '@/lib/makerChatStore';
-import { clearDraft as clearComposerDraft } from '@/lib/composerDraftStore';
+import { discardDraft as discardComposerDraft } from '@/lib/composerDraftStore';
import { fetchDirtyWorktreeForRemoval } from '@/lib/worktreeRemovalWarning';
import * as sessionService from '@/lib/sessionService';
import { getDraft, getFastModeForModel } from '@/state/newMakerDraft';
@@ -371,7 +371,7 @@ export function WorkdirBrowseRoute() {
}
makerChatStore.purgeSession(closingId);
- clearComposerDraft(closingId);
+ discardComposerDraft(closingId);
// 跨 bucket 同步:refreshSessions 只刷自己当前 filter 桶 ('all'),sidebar 的
// 'active' 桶不会被刷,导致 sidebar 仍把已归档 session 当 active 渲染。
// patchLocal 遍历所有桶就地合并字段,弥补单桶 refresh 的覆盖盲区。
diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useDeleteScheduleWithSessions.tsx b/apps/desktop/src/renderer/features/scheduler/hooks/useDeleteScheduleWithSessions.tsx
index 8dad9a1151..ec27da5c60 100644
--- a/apps/desktop/src/renderer/features/scheduler/hooks/useDeleteScheduleWithSessions.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useDeleteScheduleWithSessions.tsx
@@ -9,7 +9,7 @@ import { Spinner } from '@/components/ui/spinner';
import { toast } from '@/lib/toast';
import * as sessionService from '@/lib/sessionService';
import { makerChatStore } from '@/lib/makerChatStore';
-import { clearDraft as clearComposerDraft } from '@/lib/composerDraftStore';
+import { discardDraft as discardComposerDraft } from '@/lib/composerDraftStore';
const RUNS_PER_DELETE_PREVIEW_LIMIT = 10000;
@@ -202,7 +202,7 @@ async function applyGeneratedSessionDisposition(
void window.electronAPI.cleanupSessionImages(sessionId).catch(() => undefined);
}
makerChatStore.purgeSession(sessionId);
- clearComposerDraft(sessionId);
+ discardComposerDraft(sessionId);
} catch {
failed.push(sessionId);
}
diff --git a/apps/desktop/src/renderer/hooks/useAttachments.ts b/apps/desktop/src/renderer/hooks/useAttachments.ts
index 1c046463f7..02161c062b 100644
--- a/apps/desktop/src/renderer/hooks/useAttachments.ts
+++ b/apps/desktop/src/renderer/hooks/useAttachments.ts
@@ -19,6 +19,7 @@ import { useTranslation } from 'react-i18next';
import { toast } from '@/lib/toast';
import { createLogger } from '@/lib/logger';
import type { ComposerFileMentionPayload } from '@/lib/composerMentionDrag';
+import { isDangerousAttachmentName } from '../../shared/attachmentSafety';
const log = createLogger('UseAttachments');
import {
@@ -40,6 +41,7 @@ import {
saveDraft as saveComposerDraft,
subscribeDraft as subscribeComposerDraft,
} from '@/lib/composerDraftStore';
+import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageCleanup';
/**
* A single "this file did not get attached" rejection, surfaced inline in the
@@ -83,6 +85,8 @@ export interface UseAttachmentsReturn {
* 就地更新一个附件(标注编辑保存后替换 url / 笔迹数据等)。id 不存在时 no-op。
*/
updateFile: (id: string, patch: Partial<AttachedFile>) => void;
+ /** Discard unsent files and remove any staged dangerous copies. */
+ discardFiles: () => void;
clearFiles: () => void;
}
@@ -426,7 +430,30 @@ export function useAttachments(
const currentSessionId = sessionIdRef.current;
for (const item of valid) {
+ let stagedAttachmentPath: string | null = null;
try {
+ let attachmentPath = item.path;
+ if (
+ isDangerousAttachmentName(item.name) ||
+ isDangerousAttachmentName(item.path)
+ ) {
+ const staged = await window.electronAPI.stageChatAttachment({
+ sourcePath: item.path,
+ suggestedName: item.name,
+ });
+ if (!staged.success) {
+ pushRejections([
+ t('logic.toasts.attachmentReadFailed', {
+ name: item.name,
+ error: staged.code,
+ }),
+ ]);
+ continue;
+ }
+ attachmentPath = staged.path;
+ stagedAttachmentPath = staged.path;
+ }
+
if (item.category === 'image') {
// image-local-cache primary path: IPC copy → xdt-image:// URL.
// Falls back to in-memory base64 if cache write fails (F6).
@@ -435,7 +462,7 @@ export function useAttachments(
try {
cached = await window.electronAPI.cacheImageFromPath({
sessionId: currentSessionId,
- sourcePath: item.path,
+ sourcePath: attachmentPath,
originalName: item.name,
});
} catch (err) {
@@ -448,7 +475,7 @@ export function useAttachments(
newAttachments.push({
id: crypto.randomUUID(),
name: item.name,
- path: item.path,
+ path: attachmentPath,
ext: item.ext,
size: item.size,
category: 'image',
@@ -460,10 +487,11 @@ export function useAttachments(
// F6 fallback: read original file as base64 and warn the user that
// the image is in-memory only (lost on restart).
const result = await window.electronAPI.readFileForAttachment({
- filePath: item.path,
+ filePath: attachmentPath,
encoding: 'base64',
});
if (!result.success) {
+ cleanupStagedChatAttachmentFiles([{ path: stagedAttachmentPath ?? '' }]);
pushRejections([t('logic.toasts.attachmentReadFailed', { name: item.name, error: result.error })]);
continue;
}
@@ -475,7 +503,7 @@ export function useAttachments(
newAttachments.push({
id: crypto.randomUUID(),
name: item.name,
- path: item.path,
+ path: attachmentPath,
ext: item.ext,
size: item.size,
category: 'image',
@@ -491,7 +519,7 @@ export function useAttachments(
newAttachments.push({
id: crypto.randomUUID(),
name: item.name,
- path: item.path,
+ path: attachmentPath,
ext: item.ext,
size: item.size,
category: 'pdf',
@@ -504,7 +532,7 @@ export function useAttachments(
newAttachments.push({
id: crypto.randomUUID(),
name: item.name,
- path: item.path,
+ path: attachmentPath,
ext: item.ext,
size: item.size,
category: item.category,
@@ -512,6 +540,7 @@ export function useAttachments(
});
}
} catch (err) {
+ cleanupStagedChatAttachmentFiles([{ path: stagedAttachmentPath ?? '' }]);
pushRejections([t('logic.toasts.attachmentReadFailed', { name: item.name, error: err instanceof Error ? err.message : String(err) })]);
}
}
@@ -610,6 +639,7 @@ export function useAttachments(
if (!removed?.cacheUrlShared) {
cleanupRemovedCachedImage(removed);
}
+ if (removed) cleanupStagedChatAttachmentFiles([removed]);
setAttachments((prev) => prev.filter((f) => f.id !== id));
}, []);
@@ -617,6 +647,17 @@ export function useAttachments(
setAttachments((prev) => prev.map((f) => (f.id === id ? { ...f, ...patch } : f)));
}, []);
+ const discardFiles = useCallback(() => {
+ const current = attachmentsRef.current;
+ for (const file of current) {
+ if (!file.cacheUrlShared) cleanupRemovedCachedImage(file);
+ }
+ cleanupStagedChatAttachmentFiles(current);
+ setAttachments([]);
+ attachmentsRef.current = [];
+ setRejections([]);
+ }, []);
+
const clearFiles = useCallback(() => {
// Do not delete xdt-image:// cache files here. clearFiles also runs after
// a successful send, when those files are already referenced by history.
@@ -641,6 +682,7 @@ export function useAttachments(
consumePendingFileMentions,
removeFile,
updateFile,
+ discardFiles,
clearFiles,
};
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 6ca03f31a2..420cd87445 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5873,6 +5873,7 @@
},
"userMessage": {
"attachmentPrefix": "Attachments: ",
+ "attachmentAttachedAria": "Attached {{name}}",
"saveAttachmentAs": "Save attachment {{name}} as",
"attachmentSaved": "Attachment {{name}} saved",
"attachmentSavedUnsupported": "Attachment {{name}} saved, but this file type may not work on the current platform",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 0745e2904a..6e7d91114d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5871,6 +5871,7 @@
},
"userMessage": {
"attachmentPrefix": "添付:",
+ "attachmentAttachedAria": "{{name}}を添付済み",
"saveAttachmentAs": "添付ファイル {{name}} を別名で保存",
"attachmentSaved": "添付ファイル {{name}} を保存しました",
"attachmentSavedUnsupported": "添付ファイル {{name}} を保存しましたが、現在のプラットフォームではこのファイル形式を直接使用できない可能性があります",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index e84e78663b..f93dabdda5 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5871,6 +5871,7 @@
},
"userMessage": {
"attachmentPrefix": "첨부: ",
+ "attachmentAttachedAria": "{{name}} 첨부됨",
"saveAttachmentAs": "첨부 파일 {{name}} 다른 이름으로 저장",
"attachmentSaved": "첨부 파일 {{name}} 저장됨",
"attachmentSavedUnsupported": "첨부 파일 {{name}} 저장됨. 현재 플랫폼에서는 이 파일 형식을 직접 사용하지 못할 수 있습니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 743d8a9817..cc5cc40f30 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5871,6 +5871,7 @@
},
"userMessage": {
"attachmentPrefix": "附件:",
+ "attachmentAttachedAria": "已附加 {{name}}",
"saveAttachmentAs": "另存附件 {{name}}",
"attachmentSaved": "附件 {{name}} 已保存",
"attachmentSavedUnsupported": "附件 {{name}} 已保存,但当前平台可能无法直接使用此文件类型",
diff --git a/apps/desktop/src/renderer/lib/chatAttachmentSave.ts b/apps/desktop/src/renderer/lib/chatAttachmentSave.ts
index 2fa45b4816..1634dc1fc5 100644
--- a/apps/desktop/src/renderer/lib/chatAttachmentSave.ts
+++ b/apps/desktop/src/renderer/lib/chatAttachmentSave.ts
@@ -7,6 +7,10 @@
*/
import { i18n } from '@/i18n';
+import {
+ attachmentExtension,
+ isDangerousAttachmentName,
+} from '../../shared/attachmentSafety';
import { toast } from './toast';
import { fetchChatFileWithToasts } from './remoteFileOpen';
import { isRemoteFileOrigin, type SessionFileOrigin } from './sessionFileOrigin';
@@ -22,6 +26,11 @@ type SaveResult = Awaited<ReturnType<typeof window.electronAPI.saveChatAttachmen
/** 安全另存流程依赖;默认接真实 IPC/toast,单测可注入确定性 fake。 */
export interface ChatAttachmentSaveDeps {
platform: string;
+ stageDangerous(params: {
+ sourcePath: string;
+ suggestedName: string;
+ }): ReturnType<typeof window.electronAPI.stageChatAttachment>;
+ cleanupStaged?: (filePaths: readonly string[]) => Promise<void>;
fetchRemoteFile(
origin: Exclude<SessionFileOrigin, { kind: 'local' }>,
workingDir: string,
@@ -33,23 +42,21 @@ export interface ChatAttachmentSaveDeps {
error(message: string): void;
}
-function extensionOf(value: string): string {
- const base = value.split(/[\\/]/).pop() ?? '';
- const dot = base.lastIndexOf('.');
- return dot > 0 ? base.slice(dot).toLowerCase() : '';
-}
-
/**
- * 展示名与实际缓存扩展不一致且实际为 `.bin`,即物化阶段执行过安全降级。
- * 原名本来就是 `.bin` 时保持历史打开行为,不误判为恢复扩展名场景。
+ * 危险原始类型无论当前物理路径是什么都只能另存;历史版本已经把安全格式
+ * 降级成 `.bin` 的附件也继续走另存,以便恢复原始扩展名。
*/
export function isSafetyDowngradedAttachment(file: ChatAttachmentFile): boolean {
- return extensionOf(file.path) === '.bin' && extensionOf(file.name) !== '.bin';
+ return (
+ isDangerousAttachmentName(file.name) ||
+ isDangerousAttachmentName(file.path) ||
+ (attachmentExtension(file.path) === '.bin' && attachmentExtension(file.name) !== '.bin')
+ );
}
/** 已知不能由当前桌面平台直接使用的安装/可执行格式。 */
export function isAttachmentUnsupportedOnPlatform(fileName: string, platform: string): boolean {
- const ext = extensionOf(fileName);
+ const ext = attachmentExtension(fileName);
if (platform === 'darwin') return ext === '.exe' || ext === '.msi';
if (platform === 'win32') return ext === '.dmg' || ext === '.pkg' || ext === '.app';
if (platform === 'linux') {
@@ -61,6 +68,8 @@ export function isAttachmentUnsupportedOnPlatform(fileName: string, platform: st
function defaultDeps(): ChatAttachmentSaveDeps {
return {
platform: window.electronAPI.platform,
+ stageDangerous: (params) => window.electronAPI.stageChatAttachment(params),
+ cleanupStaged: (filePaths) => window.electronAPI.cleanupStagedChatAttachments(filePaths),
fetchRemoteFile: fetchChatFileWithToasts,
saveAs: (params) => window.electronAPI.saveChatAttachmentAs(params),
success: (message) => {
@@ -84,19 +93,53 @@ export async function saveChatAttachmentWithToasts(
file: ChatAttachmentFile,
deps: ChatAttachmentSaveDeps = defaultDeps(),
): Promise<'saved' | 'canceled' | 'failed'> {
- const sourcePath = isRemoteFileOrigin(ctx.origin)
+ let sourcePath = isRemoteFileOrigin(ctx.origin)
? await deps.fetchRemoteFile(ctx.origin, ctx.workingDir, file.path)
: file.path;
if (!sourcePath) return 'failed';
+ let stagedForSave: string | null = null;
+
+ // Messages sent before the staging fix may still reference the user's
+ // original executable path. Copy those legacy local sources into the inert
+ // cache on demand before invoking the cache-only Save As handler.
+ if (
+ !isRemoteFileOrigin(ctx.origin) &&
+ (isDangerousAttachmentName(file.name) || isDangerousAttachmentName(sourcePath)) &&
+ attachmentExtension(sourcePath) !== '.bin'
+ ) {
+ try {
+ const staged = await deps.stageDangerous({
+ sourcePath,
+ suggestedName: file.name,
+ });
+ if (!staged.success) {
+ deps.error(i18n.t('chat.userMessage.attachmentSaveForbidden'));
+ return 'failed';
+ }
+ sourcePath = staged.path;
+ stagedForSave = staged.path;
+ } catch {
+ deps.error(i18n.t('chat.userMessage.attachmentSaveFailed'));
+ return 'failed';
+ }
+ }
+
+ const cleanupStagedForSave = () => {
+ if (!stagedForSave || !deps.cleanupStaged) return;
+ void deps.cleanupStaged([stagedForSave]).catch(() => undefined);
+ };
let result: SaveResult;
try {
result = await deps.saveAs({ sourcePath, suggestedName: file.name });
} catch {
+ cleanupStagedForSave();
deps.error(i18n.t('chat.userMessage.attachmentSaveFailed'));
return 'failed';
}
+ cleanupStagedForSave();
+
if (result.status === 'canceled') return 'canceled';
if (result.status === 'saved') {
if (isAttachmentUnsupportedOnPlatform(file.name, deps.platform)) {
diff --git a/apps/desktop/src/renderer/lib/chatAttachmentStageCleanup.ts b/apps/desktop/src/renderer/lib/chatAttachmentStageCleanup.ts
new file mode 100644
index 0000000000..3cc2caf9c6
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/chatAttachmentStageCleanup.ts
@@ -0,0 +1,36 @@
+import type { AttachedFile } from './fileTypes';
+import { createLogger } from './logger';
+
+const log = createLogger('ChatAttachmentStageCleanup');
+
+function stagedPaths(files: readonly Pick<AttachedFile, 'path'>[]): string[] {
+ return [
+ ...new Set(
+ files
+ .map((file) => file.path)
+ .filter((filePath): filePath is string =>
+ typeof filePath === 'string' && filePath.toLowerCase().endsWith('.bin'),
+ ),
+ ),
+ ];
+}
+
+/**
+ * Best-effort cleanup for physical `.bin` copies owned by an unsent draft.
+ * Main re-checks the controlled cache root, so legacy/original paths are safe
+ * to pass through and are simply ignored there.
+ */
+export function cleanupStagedChatAttachmentFiles(
+ files: readonly Pick<AttachedFile, 'path'>[],
+): void {
+ const paths = stagedPaths(files);
+ if (paths.length === 0) return;
+ try {
+ void window.electronAPI.cleanupStagedChatAttachments(paths).catch((error: unknown) => {
+ log.warn('staged attachment cleanup failed', error);
+ });
+ } catch (error) {
+ log.warn('staged attachment cleanup failed', error);
+ }
+}
+
diff --git a/apps/desktop/src/renderer/lib/composerDraftStore.ts b/apps/desktop/src/renderer/lib/composerDraftStore.ts
index dd51515016..0f8d17980c 100644
--- a/apps/desktop/src/renderer/lib/composerDraftStore.ts
+++ b/apps/desktop/src/renderer/lib/composerDraftStore.ts
@@ -40,6 +40,7 @@ import {
} from '@/lib/composerQuoteDocument';
import type { JSONContent } from '@tiptap/core';
import { createLogger } from '@/lib/logger';
+import { cleanupStagedChatAttachmentFiles } from './chatAttachmentStageCleanup';
import { plainTextToComposerDocument } from './composerListDocument';
const log = createLogger('ComposerDraftStore');
@@ -279,6 +280,18 @@ export function clearDraft(sessionId: string): void {
syncDraftUrlsToMain();
}
+/**
+ * Discard a draft and release dangerous attachment copies owned by it.
+ * `clearDraft` intentionally remains a non-destructive primitive because it
+ * is also used after a successful send, when message history still references
+ * the attachment paths.
+ */
+export function discardDraft(sessionId: string): void {
+ const draft = drafts.get(draftKey(sessionId));
+ if (draft) cleanupStagedChatAttachmentFiles(draft.attachments);
+ clearDraft(sessionId);
+}
+
/**
* Clear the draft for `sessionId` AND notify any mounted ChatInput subscribed
* to this key so it empties its live editor synchronously.
diff --git a/apps/desktop/src/renderer/lib/messageAttachmentPayload.ts b/apps/desktop/src/renderer/lib/messageAttachmentPayload.ts
index 9521fd8099..77ab2c5c4b 100644
--- a/apps/desktop/src/renderer/lib/messageAttachmentPayload.ts
+++ b/apps/desktop/src/renderer/lib/messageAttachmentPayload.ts
@@ -30,6 +30,7 @@ export type SdkAttachmentBlock = {
path?: string;
base64?: string;
mimeType?: string;
+ originalName?: string;
/**
* 显式文件附件的原始磁盘路径(path 为 xdt-image:// 缓存 URL 时携带):
* device-link 出方向据此识别「字节精确」语义跳过压缩;上传后即被剥掉,
@@ -81,7 +82,8 @@ export function serializeAttachedFiles(
size: file.size,
category: file.category,
mimeType: file.mimeType,
- ...(file.url ? { url: file.url, originalName: file.originalName ?? file.name } : {}),
+ originalName: file.originalName ?? file.name,
+ ...(file.url ? { url: file.url } : {}),
...(file.annotated ? { annotated: true } : {}),
...(legacy.base64 ? { base64: legacy.base64 } : {}),
...(legacy.textContent !== undefined ? { textContent: legacy.textContent } : {}),
@@ -148,15 +150,31 @@ function buildAttachmentBlock(file: SerializedAttachedFile): SdkAttachmentBlock
const originalPath = file.path && !file.path.startsWith('clipboard://') && !file.path.startsWith('xdt-image://')
? file.path
: undefined;
- return { type, path: file.url, mimeType: file.mimeType, ...(originalPath ? { originalPath } : {}) };
+ return {
+ type,
+ path: file.url,
+ mimeType: file.mimeType,
+ originalName: file.originalName ?? file.name,
+ ...(originalPath ? { originalPath } : {}),
+ };
}
if (file.path && !file.path.startsWith('clipboard://')) {
- return { type, path: file.path, mimeType: file.mimeType };
+ return {
+ type,
+ path: file.path,
+ mimeType: file.mimeType,
+ originalName: file.originalName ?? file.name,
+ };
}
const legacyBase64 = readLegacyInlineFields(file).base64;
if (legacyBase64) {
- return { type, base64: legacyBase64, mimeType: file.mimeType };
+ return {
+ type,
+ base64: legacyBase64,
+ mimeType: file.mimeType,
+ originalName: file.originalName ?? file.name,
+ };
}
return null;
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 705d441e75..fe4230422e 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2328,6 +2328,27 @@ interface ElectronAPI {
*/
openPath: (filePath: string) => Promise<{ success: boolean; error?: string }>;
+ /** Copy a dangerous local attachment into the controlled inert cache. */
+ stageChatAttachment: (params: {
+ sourcePath: string;
+ suggestedName: string;
+ }) => Promise<
+ | { success: true; path: string }
+ | {
+ success: false;
+ code:
+ | 'invalid_source'
+ | 'forbidden'
+ | 'not_found'
+ | 'not_file'
+ | 'unsupported_type'
+ | 'copy_failed';
+ }
+ >;
+
+ /** Remove staged dangerous attachment copies from the controlled cache. */
+ cleanupStagedChatAttachments: (filePaths: readonly string[]) => Promise<void>;
+
/**
* Save a safely materialized chat attachment under its sanitized original
* filename. The main process validates the source and never opens the target.
diff --git a/apps/desktop/src/shared/__tests__/attachmentSafety.test.ts b/apps/desktop/src/shared/__tests__/attachmentSafety.test.ts
new file mode 100644
index 0000000000..bca5a945a1
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/attachmentSafety.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ attachmentExtension,
+ isDangerousAttachmentName,
+} from '../attachmentSafety';
+
+describe('attachment safety policy', () => {
+ it('normalizes extensions across Windows and POSIX paths', () => {
+ expect(attachmentExtension('C:\\Downloads\\SETUP.EXE')).toBe('.exe');
+ expect(attachmentExtension('/tmp/archive.tar.gz')).toBe('.gz');
+ expect(attachmentExtension('.env')).toBe('');
+ });
+
+ it.each([
+ 'setup.exe',
+ 'installer.msi',
+ 'update.msu',
+ 'package.dmg',
+ 'bundle.pkg',
+ 'tool.app',
+ 'script.cmd',
+ 'script.ps1',
+ 'script.vbs',
+ 'script.js',
+ 'script.jse',
+ 'script.py',
+ 'script.pyw',
+ 'script.rb',
+ 'payload.hta',
+ 'settings.reg',
+ 'launch.command',
+ 'tool.AppImage',
+ 'package.deb',
+ 'payload.jar',
+ 'shortcut.lnk',
+ 'website.url',
+ ])('marks %s as dangerous', (name) => {
+ expect(isDangerousAttachmentName(name)).toBe(true);
+ });
+
+ it.each(['archive.zip', 'model.blend', 'design.psd', 'report.pdf', 'source.ts']) (
+ 'keeps %s outside the executable policy',
+ (name) => {
+ expect(isDangerousAttachmentName(name)).toBe(false);
+ },
+ );
+});
diff --git a/apps/desktop/src/shared/attachmentSafety.ts b/apps/desktop/src/shared/attachmentSafety.ts
new file mode 100644
index 0000000000..8076b2ec73
--- /dev/null
+++ b/apps/desktop/src/shared/attachmentSafety.ts
@@ -0,0 +1,75 @@
+/**
+ * Desktop attachment safety policy shared by renderer and main.
+ *
+ * These extensions can execute code, install software, or redirect to another
+ * executable when opened by the operating system. They must stay download-only
+ * in chat and are staged under an inert `.bin` cache name before sending.
+ */
+const DANGEROUS_ATTACHMENT_EXTS = new Set([
+ // Windows executables / installers / control-panel payloads.
+ '.exe',
+ '.msi',
+ '.msp',
+ '.msu',
+ '.msix',
+ '.msixbundle',
+ '.appx',
+ '.appxbundle',
+ '.com',
+ '.scr',
+ '.cpl',
+ '.pif',
+ '.hta',
+ '.js',
+ '.jse',
+ '.vbs',
+ '.vbe',
+ '.wsf',
+ '.wsh',
+ '.reg',
+ '.application',
+ '.appref-ms',
+ '.gadget',
+ // macOS installers / application bundles and executable command files.
+ '.dmg',
+ '.pkg',
+ '.app',
+ '.command',
+ // Script launchers commonly associated with direct execution.
+ '.bat',
+ '.cmd',
+ '.ps1',
+ '.psm1',
+ '.py',
+ '.pyw',
+ '.pl',
+ '.rb',
+ '.sh',
+ '.bash',
+ '.zsh',
+ '.fish',
+ '.run',
+ '.appimage',
+ '.deb',
+ '.rpm',
+ '.apk',
+ // Runtime packages and shortcuts that may launch code or another target.
+ '.jar',
+ '.jnlp',
+ '.lnk',
+ '.scf',
+ '.desktop',
+ '.url',
+]);
+
+export function attachmentExtension(value: string): string {
+ const base = value.split(/[\\/]/).pop() ?? '';
+ const dot = base.lastIndexOf('.');
+ return dot > 0 ? base.slice(dot).toLowerCase() : '';
+}
+
+export function isDangerousAttachmentName(name: string): boolean {
+ return DANGEROUS_ATTACHMENT_EXTS.has(attachmentExtension(name));
+}
+
+export const __attachmentSafetyTesting = { DANGEROUS_ATTACHMENT_EXTS };