Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复 Windows 文件拖入附件 (#756)
zhangyongjie8aedb3a79667
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 20480ffce5..734beddb52 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -2101,6 +2101,10 @@ const createWindow = () => {// Feishu OAuth 走 will-navigate 自定义 scheme + 主窗自身 webContents,// 跟嵌套 webview 是两条独立路径,不受影响。webviewTag: true,+ // File drops are handled by renderer attachment/global-drop handlers.+ // Do not let Chromium navigate the main window to a local dropped path+ // when a platform-specific drag event misses a target.+ navigateOnDragDrop: false,},});markAppContentWindow(mainWindow);diff --git a/apps/desktop/src/renderer/__tests__/fileDrop.test.ts b/apps/desktop/src/renderer/__tests__/fileDrop.test.tsnew file mode 100644index 0000000000..5cc4b0edb6--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/fileDrop.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from 'vitest';+import { classifyUnclassifiedDroppedItems, getDroppedFileItems } from '@/lib/fileDrop';++function transfer(+ items: Array<{+ kind: 'file';+ file: File;+ directory?: boolean;+ }>,+ files: File[] = items.map((item) => item.file),+): DataTransfer {+ return {+ items: items.map((item) => ({+ kind: item.kind,+ getAsFile: () => item.file,+ webkitGetAsEntry: () => ({ isDirectory: item.directory === true }),+ })),+ files,+ } as unknown as DataTransfer;+}++describe('getDroppedFileItems', () => {+ it('keeps the original File objects so native paths survive Windows drops', () => {+ const file = { name: 'report.txt' } as File;++ expect(getDroppedFileItems(transfer([{ kind: 'file', file }]))).toEqual({+ files: [file],+ directories: [],+ unclassified: [],+ });+ });++ it('separates directories without rebuilding the remaining files', () => {+ const file = { name: 'report.txt' } as File;+ const directory = { name: 'project' } as File;++ expect(+ getDroppedFileItems(+ transfer([+ { kind: 'file', file: directory, directory: true },+ { kind: 'file', file },+ ]),+ ),+ ).toEqual({+ files: [file],+ directories: [directory],+ unclassified: [],+ });+ });++ it('preserves item-less Windows drops for native path classification', () => {+ const file = { name: 'report.txt' } as File;++ expect(getDroppedFileItems(transfer([], [file]))).toEqual({+ files: [],+ directories: [],+ unclassified: [file],+ });+ });++ it('classifies item-less directories without replacing the original File objects', async () => {+ const file = { name: 'report.txt' } as File;+ const directory = { name: 'project' } as File;++ await expect(+ classifyUnclassifiedDroppedItems([file, directory], {+ getFilePath: (item) => `C:\\drop\\${item.name}`,+ classifyPath: async (path) => ({+ kind: path.endsWith('\\project') ? 'directory' : 'other',+ }),+ }),+ ).resolves.toEqual({+ files: [file],+ directories: [directory],+ });+ });++ it('keeps item-less files attachable when native path classification fails', async () => {+ const file = { name: 'report.txt' } as File;++ await expect(+ classifyUnclassifiedDroppedItems([file], {+ getFilePath: () => 'C:\\drop\\report.txt',+ classifyPath: async () => {+ throw new Error('stat failed');+ },+ }),+ ).resolves.toEqual({+ files: [file],+ directories: [],+ });+ });+});diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 001df513e0..c1c4b5d218 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -67,6 +67,11 @@ import {type BrowserCommentDraftItem,} from '@/lib/browserComments';import { isGlobalDropIntercepted } from '@/lib/globalDropIntercept';+import {+ classifyUnclassifiedDroppedItems,+ getDroppedFileItems,+ type DroppedFileItems,+} from '@/lib/fileDrop';import { shouldOpenTextLightbox } from '@/lib/filePreview';import {getDraft as getComposerDraft,@@ -430,7 +435,7 @@ interface ChatInputProps {attachmentState: {attachments: AttachedFile[];hasAttachments: boolean;- addFiles: (fileList: FileList) => Promise<void>;+ addFiles: (fileList: FileList | readonly File[]) => Promise<void>;addClipboardImage: (blob: Blob) => Promise<void>;rejections: { id: string; message: string }[];dismissRejection: (id: string) => void;@@ -1478,11 +1483,7 @@ export function ChatInput({handledAny = true;}}- if (filesWithPath.length > 0) {- const dt = new DataTransfer();- for (const f of filesWithPath) dt.items.add(f);- addFilesRef.current(dt.files);- }+ if (filesWithPath.length > 0) addFilesRef.current(filesWithPath);if (handledAny) {// Prevent default so the file/image doesn't insert as inline// content — we handle it as an attachment instead. Text content@@ -4958,32 +4959,28 @@ export function ChatInput({if (storageKey) void attachGhostMediaToSession(ghostMediaUri, storageKey, t);return;}- if (e.dataTransfer.files.length > 0) {- // Separate files from folders using webkitGetAsEntry()- const files: File[] = [];- for (let i = 0; i < e.dataTransfer.items.length; i++) {- const item = e.dataTransfer.items[i];- const entry = item.webkitGetAsEntry?.();- const file = e.dataTransfer.files[i];- if (!file) continue;- if (entry?.isDirectory) {- let folderPath = '';- try {- folderPath = window.electronAPI.getFilePath(file);- } catch {- /* ignore */- }- if (folderPath) addFolderPath(folderPath);- } else {- files.push(file);+ const attachDroppedItems = (+ items: Pick<DroppedFileItems, 'files' | 'directories'>,+ ) => {+ for (const directory of items.directories) {+ let folderPath = '';+ try {+ folderPath = window.electronAPI.getFilePath(directory);+ } catch {+ /* ignore */}+ if (folderPath) addFolderPath(folderPath);}- if (files.length > 0) {- // Build a synthetic FileList-compatible object- const dt = new DataTransfer();- for (const f of files) dt.items.add(f);- addFiles(dt.files);- }+ if (items.files.length > 0) addFiles(items.files);+ };+ const droppedItems = getDroppedFileItems(e.dataTransfer);+ attachDroppedItems(droppedItems);+ if (droppedItems.unclassified.length > 0) {+ void classifyUnclassifiedDroppedItems(droppedItems.unclassified, {+ getFilePath: (file) => window.electronAPI.getFilePath(file),+ classifyPath: (path) =>+ window.electronAPI.localDb.sessionShare.classifyPath({ path }),+ }).then(attachDroppedItems);}}}>diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex ae7623fb16..73daa1eca0 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -150,6 +150,11 @@ import {getGhostMediaUriFromDataTransfer,} from '@/cindy-brain/ghostMediaHandover';import { isGlobalDropIntercepted } from '@/lib/globalDropIntercept';+import {+ classifyUnclassifiedDroppedItems,+ getDroppedFileItems,+ type DroppedFileItems,+} from '@/lib/fileDrop';import { getCollaborationStartErrorMessage } from './collaborationErrors';import { useCollabProjectPolicy } from './hooks/useCollabProjectPolicy';import { shouldFallbackVendorModel } from './lib/vendorModelFallback';@@ -2748,30 +2753,26 @@ export function CCAgentSessionView({if (sessionId) void attachGhostMediaToSession(ghostMediaUri, sessionId, t);return;}- if (e.dataTransfer.files.length > 0) {- const files: File[] = [];- for (let i = 0; i < e.dataTransfer.items.length; i++) {- const item = e.dataTransfer.items[i];- const entry = item.webkitGetAsEntry?.();- const file = e.dataTransfer.files[i];- if (!file) continue;- if (entry?.isDirectory) {- let folderPath = '';- try {- folderPath = window.electronAPI.getFilePath(file);- } catch {- /* ignore */- }- if (folderPath) attachmentState.addFolderPath(folderPath);- } else {- files.push(file);+ const attachDroppedItems = (items: Pick<DroppedFileItems, 'files' | 'directories'>) => {+ for (const directory of items.directories) {+ let folderPath = '';+ try {+ folderPath = window.electronAPI.getFilePath(directory);+ } catch {+ /* ignore */}+ if (folderPath) attachmentState.addFolderPath(folderPath);}- if (files.length > 0) {- const dt = new DataTransfer();- for (const f of files) dt.items.add(f);- attachmentState.addFiles(dt.files);- }+ if (items.files.length > 0) attachmentState.addFiles(items.files);+ };+ const droppedItems = getDroppedFileItems(e.dataTransfer);+ attachDroppedItems(droppedItems);+ if (droppedItems.unclassified.length > 0) {+ void classifyUnclassifiedDroppedItems(droppedItems.unclassified, {+ getFilePath: (file) => window.electronAPI.getFilePath(file),+ classifyPath: (path) =>+ window.electronAPI.localDb.sessionShare.classifyPath({ path }),+ }).then(attachDroppedItems);}}}>diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex c1d8903006..720fb0e464 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -129,6 +129,7 @@ import {getGhostMediaUriFromDataTransfer,} from '@/cindy-brain/ghostMediaHandover';import { isGlobalDropIntercepted } from '@/lib/globalDropIntercept';+import { classifyUnclassifiedDroppedItems, getDroppedFileItems } from '@/lib/fileDrop';import { createLogger } from '@/lib/logger';import { getRemoteWorkingDirErrorMessage } from './remoteWorkingDirErrors';import { matchNavigationCommandName, tryHandleNavigationCommand } from '@/lib/navigationCommands';@@ -2256,22 +2257,23 @@ export function NewMakerDraftRoute() {void attachGhostMediaToSession(ghostMediaUri, NEW_MAKER_DRAFT_KEY, t);return;}- if (e.dataTransfer.files.length > 0) {- const files: File[] = [];- for (let i = 0; i < e.dataTransfer.items.length; i++) {- const item = e.dataTransfer.items[i];- const entry = item.webkitGetAsEntry?.();- const file = e.dataTransfer.files[i];- if (!file) continue;- if (!entry?.isDirectory) files.push(file);- }- if (files.length > 0) {- e.preventDefault();- e.stopPropagation();- const dt = new DataTransfer();- for (const f of files) dt.items.add(f);- attachmentState.addFiles(dt.files);- }+ const droppedItems = getDroppedFileItems(e.dataTransfer);+ if (droppedItems.files.length > 0) {+ e.preventDefault();+ e.stopPropagation();+ attachmentState.addFiles(droppedItems.files);+ }+ if (droppedItems.unclassified.length > 0) {+ // Do not synchronously consume item-less entries: a single+ // directory must keep bubbling to GlobalDropImportListener so it+ // can become the new session's working directory.+ void classifyUnclassifiedDroppedItems(droppedItems.unclassified, {+ getFilePath: (file) => window.electronAPI.getFilePath(file),+ classifyPath: (path) =>+ window.electronAPI.localDb.sessionShare.classifyPath({ path }),+ }).then(({ files }) => {+ if (files.length > 0) attachmentState.addFiles(files);+ });}}}>diff --git a/apps/desktop/src/renderer/hooks/useAttachments.ts b/apps/desktop/src/renderer/hooks/useAttachments.tsindex 74cfee284d..1c046463f7 100644--- a/apps/desktop/src/renderer/hooks/useAttachments.ts+++ b/apps/desktop/src/renderer/hooks/useAttachments.ts@@ -54,7 +54,7 @@ export interface AttachmentRejection {export interface UseAttachmentsReturn {attachments: AttachedFile[];hasAttachments: boolean;- addFiles: (fileList: FileList) => Promise<void>;+ addFiles: (fileList: FileList | readonly File[]) => Promise<void>;addClipboardImage: (blob: Blob) => Promise<void>;/*** Files rejected on the most recent add attempt (oversize / empty / blocked@@ -302,7 +302,7 @@ export function useAttachments(return payloads;}, []);- const addFiles = useCallback(async (fileList: FileList) => {+ const addFiles = useCallback(async (fileList: FileList | readonly File[]) => {// Fresh attempt: clear stale rejections so the inline strip reflects only// this drop's failures.setRejections([]);@@ -312,8 +312,7 @@ export function useAttachments(type RawFile = { name: string; path: string; size: number; file: File };const rawFiles: RawFile[] = [];const earlyErrors: { name: string; reason: string }[] = [];- for (let i = 0; i < fileList.length; i++) {- const f = fileList[i];+ for (const f of Array.from(fileList)) {let filePath = '';try {filePath = window.electronAPI.getFilePath(f);diff --git a/apps/desktop/src/renderer/lib/fileDrop.ts b/apps/desktop/src/renderer/lib/fileDrop.tsnew file mode 100644index 0000000000..79e4a826b9--- /dev/null+++ b/apps/desktop/src/renderer/lib/fileDrop.ts@@ -0,0 +1,86 @@+/**+ * Extract files from an OS drag without rebuilding them through a synthetic+ * DataTransfer. Electron associates the native filesystem path with the+ * original File object; rebuilding it can drop that metadata on Windows.+ */+export interface DroppedFileItems {+ files: File[];+ directories: File[];+ /**+ * Original File objects whose kind cannot be inferred synchronously because+ * the drag source omitted DataTransferItem entries.+ */+ unclassified: File[];+}++interface DroppedPathClassifier {+ getFilePath: (file: File) => string;+ classifyPath: (path: string) => Promise<{ kind: 'share' | 'directory' | 'other' }>;+}++export function getDroppedFileItems(dataTransfer: DataTransfer): DroppedFileItems {+ const files: File[] = [];+ const directories: File[] = [];+ const unclassified: File[] = [];++ let fileIndex = 0;+ for (const item of Array.from(dataTransfer.items ?? [])) {+ if (item.kind !== 'file') continue;+ // Prefer the FileList entry: it is the same native object exposed by the+ // OS drag source and is the most reliable one for Electron path lookup.+ const file = dataTransfer.files[fileIndex] ?? item.getAsFile();+ fileIndex += 1;+ if (!file) continue;+ const entry = item.webkitGetAsEntry?.();+ if (entry?.isDirectory) directories.push(file);+ else files.push(file);+ }++ // Some Windows drag sources expose files but no DataTransferItem entries.+ // Keep those original File objects unresolved rather than manufacturing a+ // new FileList or assuming that every entry is a regular file. Callers can+ // classify their native paths without losing Electron's path metadata.+ if (files.length === 0 && directories.length === 0) {+ unclassified.push(...Array.from(dataTransfer.files ?? []));+ }++ return { files, directories, unclassified };+}++/**+ * Resolve item-less Windows drops by asking the main process about each+ * original File object's native path. Fail open as a regular file so a+ * transient classification failure does not make valid attachments vanish.+ */+export async function classifyUnclassifiedDroppedItems(+ unclassified: readonly File[],+ classifier: DroppedPathClassifier,+): Promise<Pick<DroppedFileItems, 'files' | 'directories'>> {+ const files: File[] = [];+ const directories: File[] = [];++ const kinds = await Promise.all(+ unclassified.map(async (file) => {+ let path = '';+ try {+ path = classifier.getFilePath(file);+ } catch {+ return 'file' as const;+ }+ if (!path) return 'file' as const;+ try {+ const result = await classifier.classifyPath(path);+ return result.kind === 'directory' ? ('directory' as const) : ('file' as const);+ } catch {+ return 'file' as const;+ }+ }),+ );++ unclassified.forEach((file, index) => {+ if (kinds[index] === 'directory') directories.push(file);+ else files.push(file);+ });++ return { files, directories };+}