Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 在对话框菜单添加附件选择 (#1155)
Chris Zhang5ef6d467e4cc
diff --git a/apps/desktop/src/renderer/__tests__/localAttachmentPicker.test.ts b/apps/desktop/src/renderer/__tests__/localAttachmentPicker.test.tsnew file mode 100644index 0000000000..1c1c7f5526--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/localAttachmentPicker.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import { canUseLocalAttachmentPicker } from '../components/new-chat/localAttachmentPicker';++describe('canUseLocalAttachmentPicker', () => {+ it('allows a local new-chat draft before a session exists', () => {+ expect(canUseLocalAttachmentPicker({})).toBe(true);+ });++ it('waits for an existing session identity before exposing controller-local files', () => {+ expect(+ canUseLocalAttachmentPicker({+ sessionId: 'session-loading',+ runtimeAgentKind: null,+ }),+ ).toBe(false);+ });++ it('allows an existing session after its local runtime identity resolves', () => {+ expect(+ canUseLocalAttachmentPicker({+ sessionId: 'session-local',+ runtimeAgentKind: 'claude-code',+ }),+ ).toBe(true);+ });++ it('rejects SSH and device-link execution contexts', () => {+ expect(+ canUseLocalAttachmentPicker({+ sessionId: 'session-ssh',+ runtimeAgentKind: 'claude-code',+ remoteHostId: 'ssh-host',+ }),+ ).toBe(false);+ expect(+ canUseLocalAttachmentPicker({+ runtimeAgentKind: 'codex',+ deviceLinkDeviceId: 'remote-device',+ }),+ ).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.tsindex a56005b478..81e2ec6d14 100644--- a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts@@ -283,9 +283,12 @@ describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {expect(chatInputSource).toContain("className={isCreateAgentVariant && !useNarrowToolbar ? 'ml-[7px]' : undefined}",);+ // 本机会话可选附件,但远程或身份尚未回流的已建会话不能摄入控制端绝对路径。+ expect(chatInputSource).toContain('const localAttachmentPickerEnabled =');expect(chatInputSource).toContain(- '(extraDirs !== undefined && onExtraDirsChange)',+ 'onAddFiles={localAttachmentPickerEnabled ? addFiles : undefined}',);+ expect(chatInputSource).not.toContain('(extraDirs !== undefined && onExtraDirsChange)');expect(chatInputSource).not.toContain("vendorKey === 'cc' && extraDirs !== undefined && onExtraDirsChange",);diff --git a/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts b/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.tsindex 1ae575437f..6855b62da9 100644--- a/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts+++ b/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts@@ -74,6 +74,49 @@ afterEach(() => {});describe('ExtraDirsButton 计划模式菜单项', () => {+ it('附件接线单独存在时也渲染「+」入口,并把多选文件交给 composer', () => {+ const onAddFiles = vi.fn();+ const { container } = render(+ createElement(ExtraDirsButton, {+ extraDirs: [],+ onAddFiles,+ }),+ );+ const fileInput = container.querySelector<HTMLInputElement>('input[type="file"]');+ expect(fileInput).toBeTruthy();+ expect(fileInput?.multiple).toBe(true);++ const trigger = screen.getByLabelText('extraDirs.menuAria');+ expect(trigger.getAttribute('aria-haspopup')).toBeNull();+ fireEvent.click(trigger);+ const openPicker = screen.getByRole('button', { name: 'extraDirs.addFiles' });+ const inputClick = vi.spyOn(fileInput!, 'click');+ fireEvent.click(openPicker);+ expect(inputClick).toHaveBeenCalledTimes(1);++ const image = new File(['image'], 'photo.png', { type: 'image/png' });+ const video = new File(['video'], 'clip.mp4', { type: 'video/mp4' });+ fireEvent.change(fileInput!, { target: { files: [image, video] } });+ expect(onAddFiles).toHaveBeenCalledWith([image, video]);+ expect(fileInput?.value).toBe('');+ });++ it('菜单打开后 composer 变为 disabled 时,附件行同步禁用', () => {+ const onAddFiles = vi.fn();+ const props = { extraDirs: [], onAddFiles };+ const { container, rerender } = render(createElement(ExtraDirsButton, props));+ const fileInput = container.querySelector<HTMLInputElement>('input[type="file"]');+ const inputClick = vi.spyOn(fileInput!, 'click');++ fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));+ rerender(createElement(ExtraDirsButton, { ...props, disabled: true }));++ const openPicker = screen.getByRole('button', { name: 'extraDirs.addFiles' });+ expect((openPicker as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(openPicker);+ expect(inputClick).not.toHaveBeenCalled();+ });+it('codex 只凭 planMode 也渲染「+」入口, 菜单里出现计划模式 toggle', () => {const onToggle = vi.fn();render(diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 86865fa451..5d776eb669 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -148,6 +148,7 @@ import {} from './pastePipeline';import { upgradePastedPathsToChips, type PendingPathRange } from './pathPaste';import { composerDocIsEmpty } from './composerDocState';+import { canUseLocalAttachmentPicker } from './localAttachmentPicker';import {isComposerBlankPointerTarget,isInteractiveFocusedElement,@@ -1069,6 +1070,12 @@ export function ChatInput({addFilesRef.current = addFiles;const addFolderPathRef = useRef(addFolderPath);addFolderPathRef.current = addFolderPath;+ const localAttachmentPickerEnabled = canUseLocalAttachmentPicker({+ sessionId,+ runtimeAgentKind,+ remoteHostId,+ deviceLinkDeviceId,+ });const [isDragOver, setIsDragOver] = useState(false);const dragCounterRef = useRef(0);@@ -5223,43 +5230,38 @@ export function ChatInput({// create-agent 按 Figma 使用 hug-content pills;默认会话页仍保留左侧优先压缩。)}>- {/* composer 「+」菜单(权限左侧):新建目标 + 计划模式 + 引用目录(两端通用、同级)。- 显示条件:有新建目标入口(会话内 → 内部 NewGoalDialog;首页 → onNewGoal 回调)、- 计划模式入口(capability + 接线齐备),或有引用目录接线。 */}- {(inSessionGoalEnabled ||- onNewGoal ||- planModeEntry ||- pluginsForMenu.length > 0 ||- (extraDirs !== undefined && onExtraDirsChange)) && (- <ExtraDirsButton- extraDirs={extraDirs ?? []}- workingDir={workingDir}- planMode={planModeEntry}- plugins={pluginsForMenu}- pluginAvailableIds={pluginAvailableIds}- onPluginSelect={handlePluginSelect}- onChange={onExtraDirsChange}- onNewGoal={- inSessionGoalEnabled || onNewGoal- ? () => {- // 把输入框当前文字(去空白)作为目标默认内容。- const ed = editorRef.current;- const draftText =- ed && !ed.isDestroyed ? serializeEditorContent(ed).text.trim() : '';- if (inSessionGoalEnabled) {- setNewGoalInitial(draftText);- setNewGoalOpen(true);- } else {- onNewGoal?.(draftText);- }+ {/* composer 「+」菜单(权限左侧):本机会话提供附件入口;目标、计划模式、+ Plugin、引用目录按各自能力与接线显示。远程会话不能把控制端绝对路径+ 交给远端 agent,因此不接本机文件选择器。 */}+ <ExtraDirsButton+ extraDirs={extraDirs ?? []}+ workingDir={workingDir}+ onAddFiles={localAttachmentPickerEnabled ? addFiles : undefined}+ planMode={planModeEntry}+ plugins={pluginsForMenu}+ pluginAvailableIds={pluginAvailableIds}+ onPluginSelect={handlePluginSelect}+ onChange={onExtraDirsChange}+ onNewGoal={+ inSessionGoalEnabled || onNewGoal+ ? () => {+ // 把输入框当前文字(去空白)作为目标默认内容。+ const ed = editorRef.current;+ const draftText =+ ed && !ed.isDestroyed ? serializeEditorContent(ed).text.trim() : '';+ if (inSessionGoalEnabled) {+ setNewGoalInitial(draftText);+ setNewGoalOpen(true);+ } else {+ onNewGoal?.(draftText);}- : undefined- }- disabled={disabled}- dense={effectiveDenseToolbar}- visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}- />- )}+ }+ : undefined+ }+ disabled={disabled}+ dense={effectiveDenseToolbar}+ visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}+ /><PermissionSelectorpermissionMode={activePermissionMode}onPermissionModeChange={handlePermissionModeChange}diff --git a/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx b/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsxindex 7d70fd3aa7..65fd184039 100644--- a/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx@@ -1,7 +1,8 @@/*** ExtraDirsButton —— composer 的「+」操作菜单(左置于权限选择器之前)。*- * 合并了三类入口(参考 Codex 的 + 菜单):+ * 合并了四类入口(参考 Codex 的 + 菜单):+ * - 添加文件、图片或视频→ 复用 composer 既有附件管线。* - 新建目标(`onNewGoal` 提供时显示;仅会话中,父组件按 sessionId 决定)→ 打开 NewGoalDialog。* - 已安装 Plugin:选择后由 ChatInput 把 command 放到消息开头,保留正文并聚焦末尾。* - 附加只读引用目录(Claude vendor;`onChange` 提供时显示)→ 列表 / 添加。@@ -17,8 +18,8 @@* main 端 extraDirsValidator.ts 兜底 — 这里只做 UX 预判。*/-import { useState } from 'react';-import { Check, ClipboardList, FolderPlus, Plus, Target, X } from 'lucide-react';+import { useRef, useState } from 'react';+import { Check, ClipboardList, FolderPlus, Paperclip, Plus, Target, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';@@ -39,6 +40,8 @@ const MAX_EXTRA_DIRS = 10;export interface ExtraDirsButtonProps {extraDirs: string[];workingDir?: string | null;+ /** 选择本机文件后交给 composer 的既有附件校验、缓存与发送管线。 */+ onAddFiles?: (files: readonly File[]) => void | Promise<void>;/*** 父组件实现增删持久化(创建时写 draft store / 中途双 IPC 协调)。* 未提供时只显示目标、计划模式或 Plugin 入口,不显示引用目录段。@@ -115,6 +118,7 @@ function basename(p: string): string {export function ExtraDirsButton({extraDirs,workingDir,+ onAddFiles,onChange,onNewGoal,planMode,@@ -127,6 +131,7 @@ export function ExtraDirsButton({}: ExtraDirsButtonProps) {const { t } = useTranslation();const [open, setOpen] = useState(false);+ const fileInputRef = useRef<HTMLInputElement>(null);const { confirm } = useConfirmDialog();const hasReferenceDirs = onChange !== undefined;@@ -136,8 +141,9 @@ export function ExtraDirsButton({// hover 展开「添加」文案已移除(2026-07-22 用户定稿:展开必须承载信息,// 图标自明的 + 不需要;裸态→hover 外框→点击直接长出菜单)。- // 能力感知:新建目标、计划模式、Plugin 与引用目录都由父组件是否接线决定。- if (!onNewGoal && !planMode && !hasReferenceDirs && plugins.length === 0) return null;+ // 能力感知:附件、新建目标、计划模式、Plugin 与引用目录都由父组件是否接线决定。+ if (!onAddFiles && !onNewGoal && !planMode && !hasReferenceDirs && plugins.length === 0)+ return null;const atLimit = count >= MAX_EXTRA_DIRS;@@ -194,52 +200,95 @@ export function ExtraDirsButton({startBorderColor="var(--border-default)"wrapperClassName="shrink-0"trigger={- <Tip- text={count === 0 ? t('extraDirs.tooltipEmpty') : t('extraDirs.tooltipCount', { count })}- side="top"- >+ <>+ {/* input 始终挂载:系统文件选择器打开期间菜单收合也不会卸载它。 */}+ {onAddFiles && (+ <input+ ref={fileInputRef}+ type="file"+ multiple+ disabled={disabled}+ className="hidden"+ onChange={(event) => {+ const files = Array.from(event.currentTarget.files ?? []);+ // 允许用户连续两次选择同一个文件。+ event.currentTarget.value = '';+ if (files.length > 0) void onAddFiles(files);+ }}+ />+ )}+ <Tip+ text={count === 0 ? t('extraDirs.tooltipEmpty') : t('extraDirs.tooltipCount', { count })}+ side="top"+ >+ <button+ type="button"+ disabled={disabled}+ onClick={() => setOpen((prev) => !prev)}+ aria-expanded={open}+ className={cn(+ 'flex shrink-0 items-center rounded-full transition-colors',+ // 裸态工具条(2026-07-22 用户定稿):默认无框,hover 才浮现胶囊外框。+ // create-agent(新建对话框)与会话内共用同一套裸态,不再分叉 —— 静息/hover 逐字一致。+ // 透明 border 常驻占位,避免 hover 时 1px 布局跳动。+ 'h-[30px]',+ // count>0 加宽显示 ×N —— 会话内与新建草稿(create-agent)一致:引用目录+ // 扩大 agent 可见范围,必须在收起态外显,不允许静默(2026-07-25 用户定稿,+ // 取代此前 create-agent icon-only 紧凑态的决定)。+ count > 0 && hasReferenceDirs+ ? 'min-w-max justify-center gap-1 px-2.5'+ : 'w-[30px] justify-center p-0',+ 'border border-transparent bg-transparent text-[var(--composer-pill-icon,#3C3F43)] dark:text-[var(--composer-pill-icon,#D9D9D9)]',+ 'hover:border-[var(--border-default)] hover:bg-[var(--composer-pill-bg,#FCFCFC)] dark:hover:bg-[var(--composer-pill-bg,#393838)]',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ )}+ aria-label={t('extraDirs.menuAria')}+ >+ <Plus+ size={isCreateAgentVariant ? 11 : dense ? 14 : 14}+ className="shrink-0"+ />+ {count > 0 && hasReferenceDirs && (+ <span+ className={cn(+ 'font-normal tabular-nums',+ dense ? 'text-[12.5px]' : 'text-[13px]',+ )}+ >+ ×{count}+ </span>+ )}+ </button>+ </Tip>+ </>+ }+ >+ {onAddFiles && (+ <><buttontype="button"disabled={disabled}- onClick={() => setOpen((prev) => !prev)}- aria-expanded={open}- aria-haspopup="menu"+ onClick={() => {+ fileInputRef.current?.click();+ setOpen(false);+ }}className={cn(- 'flex shrink-0 items-center rounded-full transition-colors',- // 裸态工具条(2026-07-22 用户定稿):默认无框,hover 才浮现胶囊外框。- // create-agent(新建对话框)与会话内共用同一套裸态,不再分叉 —— 静息/hover 逐字一致。- // 透明 border 常驻占位,避免 hover 时 1px 布局跳动。- 'h-[30px]',- // count>0 加宽显示 ×N —— 会话内与新建草稿(create-agent)一致:引用目录- // 扩大 agent 可见范围,必须在收起态外显,不允许静默(2026-07-25 用户定稿,- // 取代此前 create-agent icon-only 紧凑态的决定)。- count > 0 && hasReferenceDirs- ? 'min-w-max justify-center gap-1 px-2.5'- : 'w-[30px] justify-center p-0',- 'border border-transparent bg-transparent text-[var(--composer-pill-icon,#3C3F43)] dark:text-[var(--composer-pill-icon,#D9D9D9)]',- 'hover:border-[var(--border-default)] hover:bg-[var(--composer-pill-bg,#FCFCFC)] dark:hover:bg-[var(--composer-pill-bg,#393838)]',+ 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',+ 'transition-colors hover:bg-[var(--model-item-hover)]','disabled:cursor-not-allowed disabled:opacity-50',)}- aria-label={t('extraDirs.menuAria')}>- <Plus- size={isCreateAgentVariant ? 11 : dense ? 14 : 14}- className="shrink-0"- />- {count > 0 && hasReferenceDirs && (- <span- className={cn(- 'font-normal tabular-nums',- dense ? 'text-[12.5px]' : 'text-[13px]',- )}- >- ×{count}- </span>- )}+ <Paperclip size={14} className="shrink-0 text-[var(--model-item-text)]" />+ <span className="text-[13px] text-[var(--model-item-text)]">+ {t('extraDirs.addFiles')}+ </span></button>- </Tip>- }- >+ {(onNewGoal || planMode || plugins.length > 0 || hasReferenceDirs) && (+ <div className="my-1 h-px bg-[var(--model-dropdown-border)]" />+ )}+ </>+ )}+{/* 新建目标(仅会话中;点击关菜单并由父组件打开 NewGoalDialog) */}{onNewGoal && (<buttondiff --git a/apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts b/apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.tsnew file mode 100644index 0000000000..7c2ab7ba5e--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts@@ -0,0 +1,23 @@+interface LocalAttachmentPickerContext {+ sessionId?: string;+ runtimeAgentKind?: string | null;+ remoteHostId?: string | null;+ deviceLinkDeviceId?: string;+}++/**+ * 本机文件选择器只能在本机执行语境已经确认后开放。+ *+ * 新建草稿没有 sessionId,可直接按远程标记判定;已建会话则必须等 runtime+ * 身份回流,避免 SSH / device-link 冷启动首帧把控制端路径摄入附件状态。+ */+export function canUseLocalAttachmentPicker({+ sessionId,+ runtimeAgentKind,+ remoteHostId,+ deviceLinkDeviceId,+}: LocalAttachmentPickerContext): boolean {+ if (remoteHostId || deviceLinkDeviceId) return false;+ if (sessionId && !runtimeAgentKind) return false;+ return true;+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 0497536c50..c3b7f25408 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -7662,6 +7662,7 @@"menuAria": "Composer actions","tooltipEmpty": "More actions","tooltipCount": "{{count}} reference directories",+ "addFiles": "Add files, images, or videos…","pluginsTitle": "Installed Plugins","pluginDisabled": "Disabled","pluginNoCommand": "Not available here",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 2ce3d83481..e44524498d 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -7650,6 +7650,7 @@"menuAria": "操作メニュー","tooltipEmpty": "その他の操作","tooltipCount": "参照ディレクトリ {{count}} 件",+ "addFiles": "ファイル、画像、動画を追加…","pluginsTitle": "インストール済みプラグイン","pluginDisabled": "無効","pluginNoCommand": "ここでは使用できません",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 765b5c89e2..f9c0bb2f3c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -7650,6 +7650,7 @@"menuAria": "작업 메뉴","tooltipEmpty": "더 많은 작업","tooltipCount": "참조 디렉터리 {{count}}개",+ "addFiles": "파일, 이미지 또는 동영상 추가…","pluginsTitle": "설치된 플러그인","pluginDisabled": "비활성화됨","pluginNoCommand": "여기에서 사용할 수 없음",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 4781988273..99076e86f8 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -7650,6 +7650,7 @@"menuAria": "操作菜单","tooltipEmpty": "更多操作","tooltipCount": "{{count}} 个附加引用目录",+ "addFiles": "添加文件、图片或视频…","pluginsTitle": "已安装的插件","pluginDisabled": "未生效","pluginNoCommand": "不可直接使用",