Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 统一聊天输入框的 @ 与 + 建议面板 (#1942)
DavidShenXDa9db6b602c67
diff --git a/apps/desktop/src/renderer/__tests__/atNativeResourcePickerWiring.test.ts b/apps/desktop/src/renderer/__tests__/atNativeResourcePickerWiring.test.tsindex 9444e05d0f..5da816c25c 100644--- a/apps/desktop/src/renderer/__tests__/atNativeResourcePickerWiring.test.ts+++ b/apps/desktop/src/renderer/__tests__/atNativeResourcePickerWiring.test.ts@@ -6,14 +6,18 @@ const chatInputSource = readFileSync(resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),'utf8',);+const suggestionSource = readFileSync(+ resolve(__dirname, '..', 'lib', 'composerSuggestion.ts'),+ 'utf8',+);-describe('@ native resource picker wiring', () => {- it('opens the native picker from the fixed resource row', () => {- expect(chatInputSource).toContain("selectedItem.type === 'file-picker'");- expect(chatInputSource).toContain('window.electronAPI.dialog.showOpenResource(');- expect(chatInputSource).toContain(- 'filePickerEnabled={!!workingDir && localAttachmentPickerEnabled}',- );+describe('@ / + file entry unification', () => {+ it('keeps one attachment action instead of a duplicate native file-picker row', () => {+ expect(chatInputSource).toContain("id: 'attach-files'");+ expect(chatInputSource).toContain('suggestionFileInputRef.current?.click()');+ expect(chatInputSource).not.toContain('AT_FILE_PICKER_RESOURCE');+ expect(chatInputSource).not.toContain('window.electronAPI.dialog.showOpenResource(');+ expect(suggestionSource).not.toContain("item.type === 'file-picker'");});it('does not fall back to the removed in-composer file browser scope', () => {@@ -21,10 +25,8 @@ describe('@ native resource picker wiring', () => {expect(chatInputSource).not.toContain('setAtFileBrowserScopeFrom');});- it('drops a late picker result after the composer target changes', () => {- expect(chatInputSource).toContain('const originDoc = editor.state.doc;');- expect(chatInputSource).toContain('const originStorageKey = storageKey;');- expect(chatInputSource).toContain('isAtResourceInsertTargetCurrent(');- expect(chatInputSource).toContain('currentStorageKeyRef.current');+ it('keeps directory mentions available through scanned resource selection', () => {+ expect(chatInputSource).toContain('getAtDirectoryCompletionQuery(selectedItem)');+ expect(chatInputSource).toContain("selectedItem.type === 'agent'");});});diff --git a/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.tsindex a3153eeef8..3db13aafe7 100644--- a/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts@@ -35,7 +35,7 @@ describe('ChatInput Ghost snapshot contract', () => {'if (deviceLinkDeviceId) return [];',);expect(source).toContain(- '[deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds]',+ '[deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds, t]',);});});diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.tsindex 958a639e5d..cebd5b820d 100644--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts@@ -98,7 +98,12 @@ describe('ChatInput session switch focus contract', () => {expect(pluginPageSource.match(/focusAtEnd: true/g)).toHaveLength(1);expect(chatInputSource.match(/placeGhostAtComposerStart\(editor, ghost, installedGhosts\)/g),- ).toHaveLength(2);+ ).toHaveLength(1);+ expect(+ chatInputSource.match(+ /placeGhostAtComposerStart\(editor, ghost, installedGhostsRef\.current\)/g,+ ),+ ).toHaveLength(1);expect(chatInputSource).toContain('pendingGhostId: undefined');expect(chatInputSource).toContain('focusComposerEndNextFrame(editor);');});diff --git a/apps/desktop/src/renderer/__tests__/composerSuggestion.test.ts b/apps/desktop/src/renderer/__tests__/composerSuggestion.test.tsnew file mode 100644index 0000000000..aa3112459a--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/composerSuggestion.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it, vi } from 'vitest';++import {+ buildComposerSuggestionEntries,+ firstEnabledSuggestionIndex,+ nextEnabledSuggestionIndex,+ resolveComposerAtActivation,+ type ComposerSuggestionAction,+} from '@/lib/composerSuggestion';++const actions: ComposerSuggestionAction[] = [+ { id: 'attach-files', label: 'Add files', run: vi.fn() },+ { id: 'new-goal', label: 'New goal', run: vi.fn() },+ { id: 'plan-mode', label: 'Plan mode', checked: false, run: vi.fn() },+ { id: 'add-extra-dir', label: 'Add directory', run: vi.fn() },+];++describe('composerSuggestion', () => {+ it('显式的 + synthetic 激活优先于光标前残留的 typed @ run', () => {+ expect(+ resolveComposerAtActivation({+ typed: { from: 3, query: 'old' },+ syntheticAnchor: 7,+ syntheticQuery: 'new',+ }),+ ).toEqual({ activation: 'synthetic', from: 7, query: 'new' });+ expect(+ resolveComposerAtActivation({+ typed: { from: 3, query: 'old' },+ syntheticAnchor: null,+ syntheticQuery: null,+ }),+ ).toEqual({ activation: 'typed', from: 3, query: 'old' });+ });++ it('空查询按 Add、上下文、Plugin、引用目录动作装配', () => {+ const entries = buildComposerSuggestionEntries({+ query: '',+ actions,+ resources: [+ { type: 'browser-tab', name: 'Docs', relPath: 'cindy://browser/docs' },+ { type: 'agent', name: 'reviewer', relPath: '.claude/agents/reviewer.md' },+ ],+ plugins: [+ {+ item: {+ type: 'plugin-command',+ name: 'Cindy Art',+ relPath: 'art',+ pluginId: 'cindy-art',+ },+ },+ ],+ });++ expect(entries.map((entry) =>+ entry.kind === 'action' ? entry.action.id : `${entry.item.type}:${entry.item.name}`,+ )).toEqual([+ 'attach-files',+ 'new-goal',+ 'plan-mode',+ 'browser-tab:Docs',+ 'agent:reviewer',+ 'plugin-command:Cindy Art',+ 'add-extra-dir',+ ]);+ });++ it('非空查询把动作与资源放进同一排序池,并排除 disabled 项', () => {+ const entries = buildComposerSuggestionEntries({+ query: 'plan',+ actions: [+ ...actions,+ {+ id: 'collaboration',+ label: 'Planning collaboration',+ disabled: true,+ run: vi.fn(),+ },+ ],+ resources: [+ { type: 'file', name: 'plan.md', relPath: 'docs/plan.md' },+ ],+ plugins: [],+ });++ expect(entries.some((entry) => entry.kind === 'action' && entry.action.id === 'plan-mode')).toBe(+ true,+ );+ expect(entries.some((entry) => entry.kind === 'resource' && entry.item.name === 'plan.md')).toBe(+ true,+ );+ expect(+ entries.some((entry) => entry.kind === 'action' && entry.action.id === 'collaboration'),+ ).toBe(false);+ });++ it('焦点移动会环绕并跳过 disabled 项', () => {+ const entries = buildComposerSuggestionEntries({+ query: '',+ actions: [+ { id: 'new-goal', label: 'Goal', disabled: true, run: vi.fn() },+ { id: 'plan-mode', label: 'Plan', checked: false, run: vi.fn() },+ ],+ resources: [],+ plugins: [],+ });++ expect(firstEnabledSuggestionIndex(entries)).toBe(1);+ expect(nextEnabledSuggestionIndex(entries, 0, 1)).toBe(1);+ expect(nextEnabledSuggestionIndex(entries, 1, 1)).toBe(1);+ expect(nextEnabledSuggestionIndex(entries, 1, -1)).toBe(1);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/composerSuggestionOpenContract.test.ts b/apps/desktop/src/renderer/__tests__/composerSuggestionOpenContract.test.tsnew file mode 100644index 0000000000..ca73a7b292--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/composerSuggestionOpenContract.test.ts@@ -0,0 +1,108 @@+import { readFileSync } from 'node:fs';++import { describe, expect, it } from 'vitest';++const source = readFileSync(+ new URL('../components/new-chat/ChatInput.tsx', import.meta.url),+ 'utf8',+).replace(/\r\n/g, '\n');++describe('composer synthetic suggestion open contract', () => {+ it('device-link 远程草稿没有工作目录时仅为空查询跳过资源扫描', () => {+ const start = source.indexOf('const runAtScan = useCallback');+ const end = source.indexOf('const syntheticAtQuery', start);+ const scanner = source.slice(start, end);+ const normalizedQuery = "const normalizedQuery = query?.trim() ?? '';";+ const guard = 'if (remoteDeviceId && !workingDir?.trim() && !normalizedQuery) {';++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);+ expect(scanner).toContain(normalizedQuery);+ expect(scanner).toContain(guard);+ expect(scanner.indexOf(normalizedQuery)).toBeLessThan(scanner.indexOf(guard));+ expect(scanner.indexOf(guard)).toBeLessThan(scanner.indexOf('scanAtResources('));+ expect(scanner).toContain("setAtState({ kind: 'ready', items: [], truncated: false });");+ });++ it('SSH 远程面板跳过扫描时作废旧的异步扫描', () => {+ const start = source.indexOf('const runAtScan = useCallback');+ const end = source.indexOf('const syntheticAtQuery', start);+ const scanner = source.slice(start, end);+ const guardStart = scanner.indexOf('if (isRemoteSession) {');+ const guardEnd = scanner.indexOf('\n }', guardStart);+ const guard = scanner.slice(guardStart, guardEnd);++ expect(guardStart).toBeGreaterThanOrEqual(0);+ expect(guardEnd).toBeGreaterThan(guardStart);+ expect(guard).toContain('atScanSeqRef.current += 1;');+ expect(guard.indexOf('atScanSeqRef.current += 1;')).toBeLessThan(+ guard.indexOf("setAtState({ kind: 'ready', items: [], truncated: false });"),+ );+ });++ it('synthetic 查询使用映射后的独立范围,typed @ 才向后扫描完整 run', () => {+ const start = source.indexOf('const resolveEffectiveAtRange = useCallback');+ const end = source.indexOf('const insertAtResource', start);+ const resolver = source.slice(start, end);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);+ expect(resolver).toContain("if (effectiveAt.activation === 'synthetic') {");+ expect(resolver).toContain('const to = syntheticAtRangeEndRef.current;');+ expect(resolver).toContain('return to !== null && to >= from ? { from, to } : null;');+ expect(resolver).toContain('const triggerOffset = 1;');+ expect(resolver).toContain('let runEnd = from + triggerOffset;');+ expect(resolver).toContain('const offset = from - parentStart + triggerOffset;');+ });++ it('synthetic 空查询保持零长度替换范围', () => {+ const stateStart = source.indexOf('const syntheticAtAnchorRef = useRef');+ const stateEnd = source.indexOf('const [isDragOver', stateStart);+ const state = source.slice(stateStart, stateEnd);++ expect(stateStart).toBeGreaterThanOrEqual(0);+ expect(stateEnd).toBeGreaterThan(stateStart);+ expect(state).toContain('const syntheticAtRangeEndRef = useRef<number | null>(null);');+ expect(state).toContain('syntheticAtRangeEndRef.current = next;');+ });++ it('synthetic 输入范围随文档 transaction 映射', () => {+ const start = source.indexOf('onUpdate: ({ editor: ed, transaction }) => {');+ const end = source.indexOf('const nextRenderSnapshot', start);+ const updater = source.slice(start, end);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);+ expect(updater).toContain('transaction.docChanged');+ expect(updater).toContain('transaction.mapping.map(syntheticRangeEnd, 1)');+ });++ it('已有文本选区时 + 仍以选区起点打开空查询面板', () => {+ const deriveStart = source.indexOf('function deriveSyntheticAtQuery');+ const deriveEnd = source.indexOf('\n}\n\nexport function ChatInput', deriveStart);+ const derive = source.slice(deriveStart, deriveEnd);+ const handlerStart = source.indexOf('const handleComposerSuggestionOpenChange = useCallback');+ const handlerEnd = source.indexOf('const composerSuggestionFocusTarget', handlerStart);+ const handler = source.slice(handlerStart, handlerEnd);++ expect(deriveStart).toBeGreaterThanOrEqual(0);+ expect(deriveEnd).toBeGreaterThan(deriveStart);+ expect(derive).toContain("if (!selection.empty) return selection.from === anchor ? '' : null;");+ expect(handlerStart).toBeGreaterThanOrEqual(0);+ expect(handlerEnd).toBeGreaterThan(handlerStart);+ expect(handler).toContain('setSyntheticAtAnchor(editor.state.selection.from);');+ });++ it('打开 + 时保留同一 typed @ run 的 Esc suppression', () => {+ const start = source.indexOf('const handleComposerSuggestionOpenChange = useCallback');+ const end = source.indexOf('const composerSuggestionFocusTarget', start);+ const handler = source.slice(start, end);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);+ expect(handler).toContain('setSuppressedAtAt(trigger.from);');+ expect(handler).not.toContain('setSuppressedAtAt(null);');+ expect(handler).not.toContain('if (atOpen)');+ expect(handler).toContain('setSyntheticAtAnchor(editor.state.selection.from);');+ });+});diff --git a/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts b/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.tsindex 90d10ff757..0a93961d21 100644--- a/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts+++ b/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts@@ -6,7 +6,7 @@ import { describe, expect, it } from 'vitest';const chatInputSource = readFileSync(resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),'utf8',-);+).replace(/\r\n?/g, '\n');describe('effort runtime send guard', () => {it('only locks composer mutations during the bounded effort preflight', () => {@@ -17,7 +17,11 @@ describe('effort runtime send guard', () => {expect(chatInputSource).toContain('editable: !composerEditorLocked');expect(chatInputSource).toContain('if (composerMutationLockedRef.current) return true;');expect(chatInputSource).toContain('if (composerMutationLocked) return;');- expect(chatInputSource).toContain('localAttachmentPickerEnabled && !composerMutationLocked ? addFiles : undefined');+ expect(chatInputSource).toContain("id: 'attach-files'");+ expect(chatInputSource).toContain(+ 'disabled: composerMutationLocked,\n run: () => suggestionFileInputRef.current?.click(),',+ );+ expect(chatInputSource).toContain('ref={suggestionFileInputRef}');expect(chatInputSource).toContain('disabled={composerMutationLocked}');expect(chatInputSource).toContain('setSendDispatchInFlight(true);');expect(chatInputSource).toContain('setSendDispatchInFlight(false);');diff --git a/apps/desktop/src/renderer/__tests__/extraDirsButtonPathOverlap.test.ts b/apps/desktop/src/renderer/__tests__/extraDirsButtonPathOverlap.test.tsindex 4fc8e9d95d..bb949d0088 100644--- a/apps/desktop/src/renderer/__tests__/extraDirsButtonPathOverlap.test.ts+++ b/apps/desktop/src/renderer/__tests__/extraDirsButtonPathOverlap.test.ts@@ -1,6 +1,13 @@-import { describe, it, expect } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';-import { __extraDirsPathOverlapForTesting } from '../components/new-chat/ExtraDirsButton';+import {+ __extraDirsPathOverlapForTesting,+ pickAndAddExtraDir,+} from '../components/new-chat/extraDirsActions';++afterEach(() => {+ vi.unstubAllGlobals();+});describe('ExtraDirsButton path overlap normalization', () => {const { hasExtraDir, isParentOrAncestor, isSelfOrSubdir } = __extraDirsPathOverlapForTesting;@@ -15,3 +22,38 @@ describe('ExtraDirsButton path overlap normalization', () => {expect(isSelfOrSubdir('D:\\repo-other', 'D:/repo')).toBe(false);});});++describe('pickAndAddExtraDir', () => {+ it('由调用方提供父目录确认弹窗的本地化文案', async () => {+ vi.stubGlobal('window', {+ electronAPI: {+ dialog: {+ showOpenDirectory: vi.fn(async () => ({ success: true, path: 'D:\\repo' })),+ },+ },+ });+ const confirm = vi.fn(async () => true);+ const onChange = vi.fn();++ await pickAndAddExtraDir({+ extraDirs: [],+ workingDir: 'D:/repo/app',+ onChange,+ confirm,+ parentDirectoryConfirm: {+ title: 'localized title',+ description: (path) => `localized description: ${path}`,+ confirmText: 'localized confirm',+ cancelText: 'localized cancel',+ },+ });++ expect(confirm).toHaveBeenCalledWith({+ title: 'localized title',+ description: 'localized description: D:/repo',+ confirmText: 'localized confirm',+ cancelText: 'localized cancel',+ });+ expect(onChange).toHaveBeenCalledWith(['D:/repo']);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/morphPopover.test.tsx b/apps/desktop/src/renderer/__tests__/morphPopover.test.tsxindex 85d052d8e2..11f54f781c 100644--- a/apps/desktop/src/renderer/__tests__/morphPopover.test.tsx+++ b/apps/desktop/src/renderer/__tests__/morphPopover.test.tsx@@ -105,6 +105,51 @@ describe('MorphPopover interaction contract', () => {await waitFor(() => expect(screen.queryByRole('group', { name: 'Morph panel' })).toBeNull());});+ it('允许显式的外部 autofocus 目标保持焦点且不误关闭面板', async () => {+ function ExternalFocusHarness() {+ const [open, setOpen] = useState(false);+ const composerRef = useRef<HTMLTextAreaElement>(null);+ return (+ <>+ <textarea ref={composerRef} aria-label="Composer" />+ <MorphPopover+ open={open}+ onOpenChange={setOpen}+ autoFocusTarget={() => composerRef.current}+ panelAriaLabel="External focus panel"+ trigger={+ <button type="button" onClick={() => setOpen(true)}>+ Open with composer focus+ </button>+ }+ >+ <button type="button">Suggestion</button>+ </MorphPopover>+ <button type="button">Unrelated control</button>+ </>+ );+ }++ render(<ExternalFocusHarness />);+ const trigger = screen.getByRole('button', { name: 'Open with composer focus' });+ trigger.focus();+ fireEvent.click(trigger);++ const panel = await screen.findByRole('group', { name: 'External focus panel' });+ const composer = screen.getByLabelText('Composer');+ await waitFor(() => expect(document.activeElement).toBe(composer));+ expect(panel).toBeTruthy();++ // autoFocusTarget 属于当前交互层:点击编辑器调整光标时不能被 outside pointerdown 收起。+ fireEvent.pointerDown(composer);+ expect(screen.getByRole('group', { name: 'External focus panel' })).toBeTruthy();++ act(() => screen.getByRole('button', { name: 'Unrelated control' }).focus());+ await waitFor(() =>+ expect(screen.queryByRole('group', { name: 'External focus panel' })).toBeNull(),+ );+ });+it('动作把焦点交接到别处时不抢回 trigger(焦点已在面板外)', async () => {function FocusHandoffHarness() {const [open, setOpen] = useState(false);diff --git a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.tsindex 6859dbb904..6ef794e382 100644--- a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts@@ -278,7 +278,9 @@ describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {expect(chatInputSource).not.toContain("isCreateAgentVariant ? 'flex-wrap gap-2' : 'min-w-0 gap-1'");expect(chatInputSource).not.toContain("'flex min-w-0 flex-1 flex-wrap items-center justify-end gap-2'");expect(source).toContain('className="shrink-0"');- expect(extraDirsButtonSource).toContain("'flex shrink-0 items-center rounded-full transition-colors'");+ expect(extraDirsButtonSource).toContain(+ "'flex h-[30px] shrink-0 items-center rounded-full border border-transparent'",+ );expect(permissionSelectorSource).toContain("'h-[30px] min-w-[72px] max-w-full shrink px-2.5'");expect(permissionSelectorSource).not.toContain("'h-[30px] min-w-[90px] max-w-none shrink-0");expect(permissionSelectorSource).not.toContain("'h-[30px] min-w-[72px] max-w-full shrink border border-[var(--create-agent-control-border)]");@@ -300,16 +302,14 @@ describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {);// 本机会话可选附件,但远程或身份尚未回流的已建会话不能摄入控制端绝对路径。expect(chatInputSource).toContain('const localAttachmentPickerEnabled =');- expect(chatInputSource).toContain(- 'localAttachmentPickerEnabled && !composerMutationLocked ? addFiles : undefined',- );+ expect(chatInputSource).toContain('{localAttachmentPickerEnabled && (');+ expect(chatInputSource).toContain('if (files.length > 0) void addFiles(files);');+ expect(chatInputSource).toContain("id: 'attach-files'");expect(chatInputSource).not.toContain('(extraDirs !== undefined && onExtraDirsChange)');expect(chatInputSource).not.toContain("vendorKey === 'cc' && extraDirs !== undefined && onExtraDirsChange",);- expect(extraDirsButtonSource).toContain(- 'const hasReferenceDirs = onChange !== undefined',- );+ expect(chatInputSource).toContain('hasReferenceDirs={onExtraDirsChange !== undefined}');expect(extraDirsButtonSource).not.toContain("const isCc = agentKind === 'cc'");// ×N 角标在 create-agent(新建草稿)也要外显(2026-07-25 用户定稿):引用目录// 扩大 agent 可见范围,收起态不允许静默。不得回退到 icon-only 紧凑态。diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.tsindex 69aef4b4b4..a340d04000 100644--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts@@ -67,7 +67,7 @@ const scheduleChipsSource = readSource('features', 'scheduler', 'components', 'Sconst newGoalDialogSource = readSource('components', 'new-chat', 'NewGoalDialog.tsx');-const extraDirsButtonSource = readSource('components', 'new-chat', 'ExtraDirsButton.tsx');+const chatInputSource = readSource('components', 'new-chat', 'ChatInput.tsx');const sidebarUpperSource = readSource('features', 'cc-agent', 'CCAgentSidebarUpper.tsx');@@ -1396,10 +1396,9 @@ describe('Shared create project picker', () => {expect(newMakerDraftRouteSource).toContain('onExtraDirsChange={isDeviceLinkDraft ? undefined : handleExtraDirsChange}',);- // ExtraDirsButton 的契约:没有 onChange 就不渲染引用目录段(其余菜单项不受影响)。- expect(extraDirsButtonSource).toContain(- '未提供时只显示目标、计划模式或 Plugin 入口,不显示引用目录段',- );+ // 统一建议面板的契约:没有 onExtraDirsChange 就不装配添加/移除引用目录能力。+ expect(chatInputSource).toContain('if (onExtraDirsChange) {');+ expect(chatInputSource).toContain('hasReferenceDirs={onExtraDirsChange !== undefined}');});// #807 review 第二十四轮:`useAttachments.addFiles` 对未知扩展名要先 await peekFileHeader,附件是diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.tsindex 45947d0ab9..58e00a0892 100644--- a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts+++ b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts@@ -79,8 +79,8 @@ const chatInputSource = readTextLf(resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),'utf8',);-const extraDirsButtonSource = readTextLf(- resolve(__dirname, '..', 'components', 'new-chat', 'ExtraDirsButton.tsx'),+const atMentionPanelSource = readTextLf(+ resolve(__dirname, '..', 'components', 'new-chat', 'AtMentionPanel.tsx'),'utf8',);const sessionStatusIconSource = readTextLf(@@ -158,24 +158,18 @@ describe('OrcaWorkflowRoute source invariants', () => {it('uses the right-sidebar UsersRound mark for every collaboration entry point', () => {expect(rightSidebarTabBarSource).toContain("'orca-workers': UsersRound");expect(orcaWorkersPluginSource).toContain('<UsersRound size={13} />');- expect(extraDirsButtonSource).toContain('<UsersRound');- expect(extraDirsButtonSource).not.toContain('<Puzzle');+ expect(atMentionPanelSource).toContain('collaboration: UsersRound');+ expect(atMentionPanelSource).not.toContain('<Puzzle');expect(sessionStatusIconSource).toContain('<UsersRound');expect(sessionStatusIconSource).not.toContain('<Puzzle');expect(sessionStatusIconSource).toContain("'text-[var(--cmd-palette-item-meta)]'");});it('keeps policy reasons scoped to the disabled collaboration menu item', () => {- expect(extraDirsButtonSource).toContain(- 'const collaborationPolicyDisabled = collaboration?.disabled === true;',- );- expect(extraDirsButtonSource).toContain(- 'text={collaborationPolicyDisabled ? collaboration.disabledReason : null}',- );- expect(extraDirsButtonSource).toContain(- 'collaborationPolicyDisabled && !collaborationRetryable ? true : undefined',- );- expect(extraDirsButtonSource).toContain('collaboration.onDisabledActivate?.();');+ expect(chatInputSource).toContain('const policyDisabled = collaboration.disabled === true;');+ expect(chatInputSource).toContain('disabledReason: collaboration.disabledReason');+ expect(chatInputSource).toContain('policyDisabled && !retryable');+ expect(chatInputSource).toContain('collaboration.onDisabledActivate?.();');});it('keeps the active collaboration tooltip free of policy-disabled reasons', () => {@@ -188,8 +182,8 @@ describe('OrcaWorkflowRoute source invariants', () => {expect(sessionViewSource).toContain('onDisabledActivate: collabPolicy.unavailable');expect(sessionViewSource).toContain('void collabPolicy.refresh().then((policy) => {');expect(sessionViewSource).toContain('if (policy.enabled && !policy.unavailable) {');- expect(chatInputSource).toContain('collaboration={collaboration}');- expect(extraDirsButtonSource).toContain('!!collaboration?.onDisabledActivate');+ expect(chatInputSource).toContain('if (collaboration) {');+ expect(chatInputSource).toContain('!!collaboration.onDisabledActivate');});it('does not subscribe to project policy updates from the legacy Orca route', () => {@@ -287,8 +281,8 @@ describe('OrcaWorkflowRoute source invariants', () => {expect(sessionViewSource).toContain('label: createWorkerLabel(form.role, [])');expect(sessionViewSource).toContain('model: form.model');expect(sessionViewSource).toContain('delegateTask: form.initialTask || undefined');- expect(chatInputSource).toContain('collaboration={collaboration}');- expect(extraDirsButtonSource).toContain('collaboration.onOpenDetails();');+ expect(chatInputSource).toContain('if (collaboration) {');+ expect(chatInputSource).toContain('collaboration.onOpenDetails();');});it('maps manual collaboration start failures through i18n instead of raw IPC messages', () => {diff --git a/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts b/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.tsindex d4b9f79498..a3b4038941 100644--- a/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts+++ b/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts@@ -3,15 +3,16 @@/*** planModeComposerEntry.test.tsx* ---------------------------------------------------------------------------- * issue #475 — 模式菜单一级入口的 DOM 级渲染断言:- * - ExtraDirsButton:「计划模式」/「协同模式」菜单项与「新建目标」同级;- * 勾选态 aria-checked;单独提供任一模式也能渲染「+」按钮+ * issue #475 — 模式入口与统一 composer 建议面板的 DOM 级渲染断言:+ * - ExtraDirsButton 只保留 MorphPopover 触发器;+ * - 计划模式 / 协同模式作为 action 与 @ 资源共用 AtMentionPanel;* - PlanModeIndicator:激活 chip 文案 + 退出按钮;disabled 时隐藏退出按钮* - PlanActionCard:取消收敛为次级动作(仅 Esc,无独立行)与 ⏎ 去重* (编辑反馈时批准行 ⏎ 隐藏,反馈 ⏎ 仅在有文字时出现且可点击发送)*/import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';import { afterEach, describe, expect, it, vi } from 'vitest';import { createElement } from 'react';@@ -31,266 +32,172 @@ vi.mock('@/components/chat/MarkdownRenderer', () => ({}));import { ExtraDirsButton } from '@/components/new-chat/ExtraDirsButton';+import { AtMentionPanel } from '@/components/new-chat/AtMentionPanel';import { PlanActionCard } from '@/components/new-chat/PlanActionCard';import { PlanModeIndicator } from '@/components/new-chat/PlanModeIndicator';import { PlanViewerCard } from '@/components/new-chat/PlanViewerCard';-import type { InstalledGhost } from '../../shared/ghost';--const installedPlugin: InstalledGhost = {- manifest: {- schemaVersion: 2,- id: 'cindy-art',- name: 'Cindy Art',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['tool'],- tools: [{ name: 'draw', description: 'Draw.' }],- command: 'art',- },- dir: '/tmp/cindy-art',- enabled: true,-};--const installedMermaidPlugin: InstalledGhost = {- manifest: {- schemaVersion: 2,- id: 'cindy-mermaid',- name: 'Mermaid',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['tool'],- tools: [{ name: 'render', description: 'Render a Mermaid diagram.' }],- command: 'mermaid',- },- dir: '/tmp/cindy-mermaid',- enabled: true,-};+import {+ buildComposerSuggestionEntries,+ nextEnabledSuggestionIndex,+ type ComposerSuggestionAction,+ type ComposerSuggestionEntry,+} from '@/lib/composerSuggestion';afterEach(() => {cleanup();vi.clearAllMocks();});-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(+describe('统一 composer 建议入口', () => {+ it('ExtraDirsButton 保留 MorphPopover 触发器、按下态与引用目录数量', () => {+ const onOpenChange = vi.fn();+ const { rerender } = render(createElement(ExtraDirsButton, {- extraDirs: [],- planMode: { enabled: false, onToggle },+ extraDirsCount: 2,+ hasReferenceDirs: true,+ open: false,+ onOpenChange,+ panel: createElement('div', {}, 'panel'),}),);+ expect(screen.getByText('×2')).toBeTruthy();const trigger = screen.getByLabelText('extraDirs.menuAria');+ expect(trigger.getAttribute('aria-expanded')).toBe('false');fireEvent.click(trigger);+ expect(onOpenChange).toHaveBeenCalledWith(true);- const item = screen.getByRole('menuitemcheckbox', { name: /planMode\.menuItem/ });- expect(item.getAttribute('aria-checked')).toBe('false');- fireEvent.click(item);- expect(onToggle).toHaveBeenCalledWith(true);- });-- it('开启态菜单项 aria-checked=true, 再点回调 false; 与新建目标同级共存', () => {- const onToggle = vi.fn();- const onNewGoal = vi.fn();- render(+ rerender(createElement(ExtraDirsButton, {- extraDirs: [],- onChange: () => {},- onNewGoal,- planMode: { enabled: true, onToggle },+ extraDirsCount: 2,+ hasReferenceDirs: true,+ open: true,+ onOpenChange,+ panel: createElement('div', {}, 'panel'),}),);- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));-- // 新建目标与计划模式同级出现在同一菜单- expect(screen.getByText('goal.newGoalMenuItem')).toBeTruthy();- const item = screen.getByRole('menuitemcheckbox', { name: /planMode\.menuItem/ });- expect(item.getAttribute('aria-checked')).toBe('true');- fireEvent.click(item);- expect(onToggle).toHaveBeenCalledWith(false);+ expect(+ screen.getByRole('button', { name: 'extraDirs.menuAria' }).getAttribute('aria-pressed'),+ ).toBe('true');});- it('只凭协同模式也渲染「+」入口, 关闭态点击打开完整 Worker 配置', () => {- const onChange = vi.fn();- const onOpenDetails = vi.fn();- render(- createElement(ExtraDirsButton, {- extraDirs: [],- collaboration: {- enabled: false,- worker: 'codex',- onChange,- onOpenDetails,+ it('计划模式、协同与 Plugin 进入同一 AtMentionPanel', () => {+ const onPlanToggle = vi.fn();+ const actions: ComposerSuggestionAction[] = [+ {+ id: 'new-goal',+ label: 'goal.newGoalMenuItem',+ run: vi.fn(),+ },+ {+ id: 'plan-mode',+ label: 'planMode.menuItem',+ checked: true,+ run: () => onPlanToggle(false),+ },+ {+ id: 'collaboration',+ label: 'newChat.collaboration.modeLabel',+ checked: false,+ disabled: true,+ disabledReason: 'policy unavailable',+ run: vi.fn(),+ },+ ];+ const entries = buildComposerSuggestionEntries({+ query: '',+ actions,+ resources: [],+ plugins: [+ {+ item: {+ type: 'plugin-command',+ name: 'Cindy Art',+ relPath: 'art',+ pluginId: 'cindy-art',+ },},- }),- );-- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));- const item = screen.getByRole('menuitemcheckbox', {- name: 'newChat.collaboration.modeLabel',+ ],});- expect(item.getAttribute('aria-checked')).toBe('false');- fireEvent.click(item);- expect(onOpenDetails).toHaveBeenCalledTimes(1);- expect(onChange).not.toHaveBeenCalled();- });-- it('协同开启态与目标/计划同级共存, 使用橙色状态并可直接关闭', () => {- const onChange = vi.fn();+ const onSelect = (entry: ComposerSuggestionEntry) => {+ if (entry.kind === 'action') entry.action.run();+ };render(- createElement(ExtraDirsButton, {- extraDirs: [],- onChange: () => {},- onNewGoal: vi.fn(),- planMode: { enabled: false, onToggle: vi.fn() },- collaboration: { enabled: true, worker: 'cc', onChange },+ createElement(AtMentionPanel, {+ query: '',+ state: { kind: 'ready', items: [], truncated: false },+ entries,+ focusedIndex: 0,+ onFocusedIndexChange: vi.fn(),+ onSelect,+ onClose: vi.fn(),+ onRetry: vi.fn(),}),);- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));expect(screen.getByText('goal.newGoalMenuItem')).toBeTruthy();- expect(screen.getByText('planMode.menuItem')).toBeTruthy();- const item = screen.getByRole('menuitemcheckbox', {- name: 'newChat.collaboration.modeLabel',- });- expect(item.getAttribute('aria-checked')).toBe('true');- expect(item.className).toContain('bg-[var(--model-item-hover)]');- expect(screen.getByText('newChat.collaboration.modeLabel').className).toContain(- 'text-[var(--warning-accent)]',- );- expect(item.querySelector('svg.lucide-check')).toBeTruthy();- fireEvent.click(item);- expect(onChange).toHaveBeenCalledWith({ enabled: false, worker: 'cc' });- });-- it('策略暂不可用时保留可重试的协同菜单项', () => {- const onDisabledActivate = vi.fn();- render(- createElement(ExtraDirsButton, {- extraDirs: [],- collaboration: {- enabled: false,- worker: 'pi',- onChange: vi.fn(),- disabled: true,- disabledReason: 'policy unavailable',- onDisabledActivate,- },- }),- );-- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));- const item = screen.getByRole('menuitemcheckbox', {- name: 'newChat.collaboration.modeLabel: policy unavailable',- });- expect((item as HTMLButtonElement).disabled).toBe(false);- fireEvent.click(item);- expect(onDisabledActivate).toHaveBeenCalledTimes(1);+ expect(screen.getByText('Cindy Art')).toBeTruthy();+ const plan = screen.getByRole('menuitemcheckbox', { name: 'planMode.menuItem' });+ expect(plan.getAttribute('aria-checked')).toBe('true');+ expect(plan.className).toContain('rounded-[8px]');+ expect(plan.className).toContain('px-3');+ expect(plan.className).toContain('py-2');+ expect(plan.className).toContain('hover:bg-[var(--model-item-hover)]');+ fireEvent.click(plan);+ expect(onPlanToggle).toHaveBeenCalledWith(false);+ expect(+ (screen.getByRole('menuitemcheckbox', {+ name: 'newChat.collaboration.modeLabel: policy unavailable',+ }) as HTMLButtonElement).disabled,+ ).toBe(true);});- it('没有任何入口时保持不渲染', () => {- const { container } = render(- createElement(ExtraDirsButton, {- extraDirs: [],- }),- );- expect(container.firstChild).toBeNull();+ it('键盘导航跳过 disabled 条目', () => {+ const entries: ComposerSuggestionEntry[] = [+ {+ kind: 'action',+ action: { id: 'new-goal', label: 'goal', disabled: true, run: vi.fn() },+ },+ {+ kind: 'action',+ action: { id: 'plan-mode', label: 'plan', checked: false, run: vi.fn() },+ },+ ];+ expect(nextEnabledSuggestionIndex(entries, 1, 1)).toBe(1);+ expect(nextEnabledSuggestionIndex(entries, 0, 1)).toBe(1);+ expect(nextEnabledSuggestionIndex(entries, 1, -1)).toBe(1);});- it('Codex 接入 onChange 后显示引用目录、数量与增删入口', () => {- const onChange = vi.fn();+ it('引用目录管理复用统一面板的独立 section,移除按钮支持键盘访问', async () => {+ const user = userEvent.setup();+ const onRemove = vi.fn();+ const entries = buildComposerSuggestionEntries({+ query: '',+ actions: [{ id: 'add-extra-dir', label: 'extraDirs.add', run: vi.fn() }],+ resources: [],+ plugins: [],+ });render(- createElement(ExtraDirsButton, {- extraDirs: ['/repo-shared'],- workingDir: '/repo',- onChange,+ createElement(AtMentionPanel, {+ query: '',+ state: { kind: 'ready', items: [], truncated: false },+ entries,+ focusedIndex: 0,+ onFocusedIndexChange: vi.fn(),+ onSelect: vi.fn(),+ onClose: vi.fn(),+ onRetry: vi.fn(),+ referenceDirs: { dirs: ['/repo-shared'], onRemove },}),);-- expect(screen.getByText('×1')).toBeTruthy();- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));expect(screen.getByText('extraDirs.sectionTitle')).toBeTruthy();expect(screen.getByText('repo-shared')).toBeTruthy();- fireEvent.click(screen.getByLabelText('extraDirs.remove'));- expect(onChange).toHaveBeenCalledWith([]);- });-- it('展示所有已安装 Plugin,并把可用项交给 composer 放置', () => {- const onPluginSelect = vi.fn();- render(- createElement(ExtraDirsButton, {- extraDirs: [],- plugins: [installedPlugin],- onPluginSelect,- }),- );-- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));- expect(screen.getByText('extraDirs.pluginsTitle')).toBeTruthy();- const pluginRow = screen.getByRole('button', { name: 'Cindy Art' });- expect(pluginRow.querySelector('span')?.className).toContain('size-5');- fireEvent.click(pluginRow);- expect(onPluginSelect).toHaveBeenCalledWith(installedPlugin);- });-- it('复用 Plugin 页的功能兜底图标,避免无包内头像时入口不一致', () => {- render(- createElement(ExtraDirsButton, {- extraDirs: [],- plugins: [installedMermaidPlugin],- onPluginSelect: vi.fn(),- }),- );-- fireEvent.click(screen.getByLabelText('extraDirs.menuAria'));- const pluginRow = screen.getByRole('button', { name: 'Mermaid' });- expect(pluginRow.querySelector('svg.lucide-workflow')).toBeTruthy();- expect(pluginRow.querySelector('svg.lucide-package')).toBeNull();+ const removeButton = screen.getByLabelText('extraDirs.remove');+ expect(removeButton.className).toContain('focus-visible:opacity-100');+ expect(removeButton.className).toContain('focus-visible:ring-2');+ removeButton.focus();+ expect(document.activeElement).toBe(removeButton);+ await user.keyboard('{Enter}');+ expect(onRemove).toHaveBeenCalledWith('/repo-shared');});});diff --git a/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.tsindex a5caecb725..0430b84b76 100644--- a/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts+++ b/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts@@ -21,13 +21,11 @@ describe('ChatInput voice lifecycle locks', () => {it('keeps attachments locked while leaving permission mode available', () => {const extraDirsStart = chatInputSource.indexOf('<ExtraDirsButton');expect(extraDirsStart).toBeGreaterThanOrEqual(0);- const extraDirsEnd = chatInputSource.indexOf('/>', extraDirsStart);- expect(extraDirsEnd).toBeGreaterThan(extraDirsStart);- const extraDirsBlock = chatInputSource.slice(extraDirsStart, extraDirsEnd);- expect(extraDirsBlock).toContain('disabled={composerMutationLocked}');-const permissionStart = chatInputSource.indexOf('<PermissionSelector');expect(permissionStart).toBeGreaterThanOrEqual(0);+ const extraDirsBlock = chatInputSource.slice(extraDirsStart, permissionStart);+ expect(extraDirsBlock).toContain('disabled={composerMutationLocked}');+const permissionEnd = chatInputSource.indexOf('/>', permissionStart);expect(permissionEnd).toBeGreaterThan(permissionStart);const permissionBlock = chatInputSource.slice(permissionStart, permissionEnd);diff --git a/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx b/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsxindex 5fe1d1a50d..deda153e8d 100644--- a/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx+++ b/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx@@ -1,42 +1,57 @@/**- * command-palette F2 / F5: `@` resource panel.+ * Unified composer suggestion panel (command-palette F2 / F5, `@` + `+`).*- * Presentational popover that renders the filtered list of files, dirs,- * and agents scanned from workingDir. All scanning / ranking logic lives- * in `atResourceService.ts`; this component handles:- * - focus-row tracking (↑↓ / hover)+ * 2026-08 unification (Codex Desktop pattern): this panel serves BOTH the+ * typed `@` trigger and the composer `+` button (synthetic activation — no+ * `@` char in the doc, typing still filters). It renders the union of:+ * - action rows from the legacy `+` MorphPopover menu (attach files, new+ * goal, plan mode, collaboration, add reference directory)+ * - scanned resources (files / dirs / agents / tabs / windows / tasks)+ * - installed plugins (unavailable ones stay visible but disabled)+ * - the reference-directories management section (empty query only)+ *+ * All scanning / ranking / assembly lives in `atResourceService.ts` ++ * `composerSuggestion.ts`; ChatInput passes the final ordered `entries`.+ * This component handles:+ * - focus-row tracking (↑↓ / hover; disabled rows are skipped by the host)* - empty / loading / error states- * - root-query sections for addable resources and installed plugins- * - click-outside close+ * - root-query sections (Add / Plugins / Reference directories)+ * - click-outside close (ignoring the `+` trigger button)*- * Per F2 spec: 480px width and 44px row height. The root query uses compact- * section labels to separate addable resources from installed plugins.+ * Per F2 spec: 480px width and 44px row height.*/-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { useEffect, useLayoutEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import {+ Check,+ ClipboardList,File as FileIcon,Folder as FolderIcon,+ FolderPlus,Globe2,History,Monitor,Paperclip,Plug,Sparkles,+ Target,+ UsersRound,+ X,} from 'lucide-react';import { cn } from '@/lib/utils';import { Tip } from '@/components/ui/tooltip';import { GhostPluginIcon } from '@/features/plugin/GhostPluginIcon';+import type { AtResourceItem } from '@/lib/atResourceService';import {- AT_FILE_PICKER_RESOURCE,- filterAtResources,- type AtResourceItem,-} from '@/lib/atResourceService';+ composerSuggestionEntryKey,+ type ComposerSuggestionAction,+ type ComposerSuggestionEntry,+} from '@/lib/composerSuggestion';+import { extraDirBasename } from './extraDirsActions';const TOOLTIP_FALLBACK_H = 120;const VIEWPORT_PAD = 8;-const SECTION_HEADER_H = 24;type TooltipMeasure = {key: string | null;@@ -47,36 +62,63 @@ function isPluginItem(item: AtResourceItem): boolean {return item.type === 'plugin-command' || item.type === 'plugin-resource';}+function isPluginEntry(entry: ComposerSuggestionEntry): boolean {+ return entry.kind === 'resource' && isPluginItem(entry.item);+}++function isAddDirEntry(entry: ComposerSuggestionEntry): boolean {+ return entry.kind === 'action' && entry.action.id === 'add-extra-dir';+}+export type AtPanelState =| { kind: 'loading' }| { kind: 'error'; message: string }| { kind: 'ready'; items: AtResourceItem[]; truncated: boolean; searching?: boolean };+interface ReferenceDirsSection {+ dirs: string[];+ onRemove: (path: string) => void;+}+interface AtMentionPanelProps {- /** Query — everything after `@` trigger up to the cursor. */+ /** Query — text after the `@` trigger (typed) or the synthetic anchor (`+`). */query: string;- /** Scan state managed by the host (ChatInput). */+ /** Scan state managed by the host (ChatInput) — drives loading/error/hints. */state: AtPanelState;+ /** Final ordered entry list (actions + resources), assembled by the host. */+ entries: ComposerSuggestionEntry[];focusedIndex: number;onFocusedIndexChange: (i: number) => void;- onSelect: (item: AtResourceItem) => void;+ onSelect: (entry: ComposerSuggestionEntry) => void;onClose: () => void;onRetry: () => void;- /** Whether the local task can launch the native file picker. */- filePickerEnabled?: boolean;+ /** Reference-directories management rows (empty query only; `+`-menu parity). */+ referenceDirs?: ReferenceDirsSection | null;+ /** `+` 的 MorphPopover 内嵌形态;容器、阴影与 outside-click 由 MorphPopover 负责。 */+ embedded?: boolean;/** Panel max-height in px. Defaults to 400 (chat view); NewMaker passes a smaller value so the popover doesn't cover the logo. */maxHeight?: number;}+const ACTION_ICONS: Record<ComposerSuggestionAction['id'], typeof Paperclip> = {+ 'attach-files': Paperclip,+ 'new-goal': Target,+ 'plan-mode': ClipboardList,+ collaboration: UsersRound,+ 'add-extra-dir': FolderPlus,+};+export function AtMentionPanel({query,state,+ entries,focusedIndex,onFocusedIndexChange,onSelect,onClose,onRetry,- filePickerEnabled = false,+ referenceDirs = null,+ embedded = false,maxHeight = 400,}: AtMentionPanelProps) {const { t } = useTranslation();@@ -91,52 +133,54 @@ export function AtMentionPanel({});const [tooltipPos, setTooltipPos] = useState<{ top: number; maxHeight: number } | null>(null);- const filtered = useMemo(() => {- if (state.kind !== 'ready') return [];- const items = filePickerEnabled- ? [AT_FILE_PICKER_RESOURCE, ...state.items]- : state.items;- return filterAtResources(items, query);- }, [state, query, filePickerEnabled]);const isEmptyRootQuery = !query.trim();- const indexedFiltered = useMemo(- () => filtered.map((item, index) => ({ item, index })),- [filtered],- );- const addItems = isEmptyRootQuery- ? indexedFiltered.filter(({ item }) => !isPluginItem(item))+ // Empty-query buckets (assembly order in composerSuggestion.ts guarantees+ // add → plugins → add-extra-dir, so bucketing preserves entry indices).+ const indexed = entries.map((entry, index) => ({ entry, index }));+ const addEntries = isEmptyRootQuery+ ? indexed.filter(({ entry }) => !isPluginEntry(entry) && !isAddDirEntry(entry)): [];- const pluginItems = isEmptyRootQuery- ? indexedFiltered.filter(({ item }) => isPluginItem(item))- : [];- const addSectionVisible = isEmptyRootQuery && addItems.length > 0;- const pluginSectionVisible = isEmptyRootQuery && pluginItems.length > 0;+ const pluginEntries = isEmptyRootQuery ? indexed.filter(({ entry }) => isPluginEntry(entry)) : [];+ const addDirEntry = isEmptyRootQuery ? indexed.find(({ entry }) => isAddDirEntry(entry)) : undefined;+ const addSectionVisible = isEmptyRootQuery && addEntries.length > 0;+ const pluginSectionVisible = isEmptyRootQuery && pluginEntries.length > 0;+ const referenceDirsVisible = isEmptyRootQuery && (!!referenceDirs || !!addDirEntry);useEffect(() => {- if (filtered.length === 0) return;- if (focusedIndex < 0 || focusedIndex >= filtered.length) {+ if (entries.length === 0) return;+ if (focusedIndex < 0 || focusedIndex >= entries.length) {onFocusedIndexChange(0);}- }, [filtered.length, focusedIndex, onFocusedIndexChange]);+ }, [entries.length, focusedIndex, onFocusedIndexChange]);useEffect(() => {- focusedRef.current?.scrollIntoView({ block: 'nearest' });+ focusedRef.current?.scrollIntoView?.({ block: 'nearest' });}, [focusedIndex]);useEffect(() => {+ if (embedded) return;const handleClickOutside = (e: MouseEvent) => {if (!rootRef.current) return;- if (!rootRef.current.contains(e.target as Node)) {- onClose();+ const target = e.target as Node;+ if (rootRef.current.contains(target)) return;+ // The `+` trigger toggles the panel itself — let its own click handler+ // decide, otherwise mousedown-close + click-toggle would reopen it.+ if (+ target instanceof Element &&+ target.closest('[data-composer-suggestion-trigger]')+ ) {+ return;}+ onClose();};document.addEventListener('mousedown', handleClickOutside);return () => document.removeEventListener('mousedown', handleClickOutside);- }, [onClose]);+ }, [embedded, onClose]);- const focusedItem = filtered[focusedIndex];- const showTooltip = !!focusedItem?.description;- const tooltipKey = showTooltip+ const focusedEntry = entries[focusedIndex];+ const focusedItem = focusedEntry?.kind === 'resource' ? focusedEntry.item : undefined;+ const showTooltip = !embedded && !!focusedItem?.description;+ const tooltipKey = showTooltip && focusedItem? `${focusedItem.type}:${focusedItem.relPath}:${focusedItem.name}:${focusedItem.description ?? ''}`: null;const tooltipHeight = tooltipMeasure.key === tooltipKey@@ -150,17 +194,17 @@ export function AtMentionPanel({}const panel = panelRef.current;const root = rootRef.current;- if (!panel || !root) return;+ const focusedEl = focusedRef.current;+ if (!panel || !root || !focusedEl) return;const panelRect = panel.getBoundingClientRect();const rootRect = root.getBoundingClientRect();const bottomBoundary = Math.min(panelRect.bottom, window.innerHeight - VIEWPORT_PAD);const maxTooltipHeight = Math.max(1, Math.min(maxHeight, bottomBoundary - VIEWPORT_PAD));const measuredHeight = Math.min(tooltipHeight, maxTooltipHeight);- const focusedIsPlugin = isEmptyRootQuery && !!focusedItem && isPluginItem(focusedItem);- const sectionOffset = isEmptyRootQuery- ? SECTION_HEADER_H + (focusedIsPlugin && addSectionVisible ? SECTION_HEADER_H : 0)- : 0;- const rawTop = 6 + sectionOffset + focusedIndex * 44 - panelScroll;+ // Anchor the flyout to the focused row's actual on-screen position — the+ // section layout varies (Add / Plugins / Reference dirs headers), so+ // arithmetic row offsets are no longer reliable.+ const rawTop = focusedEl.getBoundingClientRect().top - rootRect.top;const minTop = VIEWPORT_PAD - rootRect.top;const bottomBoundaryInRoot = bottomBoundary - rootRect.top;const top = Math.max(minTop, Math.min(rawTop, bottomBoundaryInRoot - measuredHeight));@@ -168,16 +212,7 @@ export function AtMentionPanel({top: Math.round(top),maxHeight: Math.round(maxTooltipHeight),});- }, [- showTooltip,- focusedIndex,- focusedItem,- panelScroll,- maxHeight,- tooltipHeight,- isEmptyRootQuery,- addSectionVisible,- ]);+ }, [showTooltip, focusedIndex, focusedItem, panelScroll, maxHeight, tooltipHeight]);const tooltipVisible = showTooltip && !!tooltipPos;useLayoutEffect(() => {@@ -198,8 +233,93 @@ export function AtMentionPanel({return () => observer.disconnect();}, [tooltipVisible, tooltipKey]);- const renderItemRow = (item: AtResourceItem, idx: number) => {+ const renderSectionHeader = (label: string) => (+ <div+ className={cn(+ 'flex h-[24px] items-center px-[10px]',+ 'text-[12px] font-medium text-[var(--cmd-palette-item-meta)]',+ )}+ >+ {label}+ </div>+ );++ const renderActionRow = (action: ComposerSuggestionAction, idx: number) => {const focused = idx === focusedIndex;+ const Icon = ACTION_ICONS[action.id];+ const isCheckbox = action.checked !== undefined;+ // Collaboration keeps its Thinking-Orange enabled state from the legacy+ // `+` menu (id-driven presentation; the data model stays lean).+ const emphasized = action.id === 'collaboration' && action.checked === true;+ const row = (+ <button+ key={`action:${action.id}`}+ ref={focused ? focusedRef : undefined}+ type="button"+ role={isCheckbox ? 'menuitemcheckbox' : undefined}+ aria-checked={isCheckbox ? action.checked : undefined}+ aria-disabled={action.disabled ? true : undefined}+ disabled={action.disabled}+ aria-label={+ action.disabledReason ? `${action.label}: ${action.disabledReason}` : undefined+ }+ onMouseDown={(e) => {+ e.preventDefault();+ }}+ onClick={() => {+ if (action.disabled) return;+ onSelect({ kind: 'action', action });+ }}+ onMouseEnter={() => {+ if (!action.disabled) onFocusedIndexChange(idx);+ }}+ className={cn(+ 'flex w-full items-center gap-2',+ 'rounded-[8px] px-3 py-2',+ 'text-left outline-none transition-colors',+ focused && 'bg-[var(--model-item-hover)]',+ 'hover:bg-[var(--model-item-hover)]',+ emphasized && 'bg-[var(--model-item-hover)]',+ action.disabled && 'cursor-not-allowed opacity-50',+ )}+ >+ <Icon+ size={14}+ className={cn(+ 'shrink-0',+ emphasized ? 'text-[var(--warning-accent)]' : 'text-[var(--model-item-text)]',+ )}+ />+ <span+ className={cn(+ 'min-w-0 flex-1 truncate text-[13px]',+ emphasized ? 'text-[var(--warning-accent)]' : 'text-[var(--model-item-text)]',+ )}+ >+ {action.label}+ </span>+ {isCheckbox && action.checked && (+ <Check size={13} className="ml-auto shrink-0 text-[var(--model-item-check)]" />+ )}+ </button>+ );+ if (action.disabled && action.disabledReason) {+ return (+ <Tip key={`action:${action.id}`} text={action.disabledReason} side="right">+ <span className="block">{row}</span>+ </Tip>+ );+ }+ return row;+ };++ const renderResourceRow = (+ entry: Extract<ComposerSuggestionEntry, { kind: 'resource' }>,+ idx: number,+ ) => {+ const item = entry.item;+ const focused = idx === focusedIndex;+ const disabled = entry.disabled === true;let meta: string;if (item.type === 'file-picker') {meta = '';@@ -244,19 +364,27 @@ export function AtMentionPanel({return (<button- key={`${item.type}:${item.relPath}`}+ key={composerSuggestionEntryKey(entry)}ref={focused ? focusedRef : undefined}type="button"+ disabled={disabled}+ aria-disabled={disabled ? true : undefined}onMouseDown={(e) => {e.preventDefault();- onSelect(item);}}- onMouseEnter={() => onFocusedIndexChange(idx)}+ onClick={() => {+ if (disabled) return;+ onSelect(entry);+ }}+ onMouseEnter={() => {+ if (!disabled) onFocusedIndexChange(idx);+ }}className={cn('flex w-full items-center gap-2','h-[44px] px-[10px] rounded-[6px]','text-left outline-none transition-colors',focused && 'bg-[var(--cmd-palette-item-hover)]',+ disabled && 'cursor-not-allowed opacity-45',)}>{isPluginItem(item) ? (@@ -277,7 +405,17 @@ export function AtMentionPanel({>{displayName}</span>- {meta && (+ {disabled && entry.disabledReason ? (+ <span+ className={cn(+ 'shrink-0 text-[12px] truncate max-w-[240px]',+ 'text-[var(--cmd-palette-item-meta)]',+ 'ml-auto',+ )}+ >+ {entry.disabledReason}+ </span>+ ) : meta ? (<Tip text={meta} mono><spanclassName={cn(@@ -289,28 +427,43 @@ export function AtMentionPanel({{meta}</span></Tip>- )}+ ) : null}</button>);};+ const renderEntryRow = ({ entry, index }: { entry: ComposerSuggestionEntry; index: number }) =>+ entry.kind === 'action'+ ? renderActionRow(entry.action, index)+ : renderResourceRow(entry, index);++ const showLoadingSkeleton = state.kind === 'loading' && entries.length === 0;+ const showErrorState = state.kind === 'error' && entries.length === 0;+ const showEmptyState = !showLoadingSkeleton && !showErrorState && entries.length === 0;+return (<divref={rootRef}- className={cn('pointer-events-auto absolute left-0 bottom-full mb-2 z-50')}+ className={cn(+ 'pointer-events-auto',+ embedded ? 'relative' : 'absolute left-0 bottom-full mb-2 z-50',+ )}><divref={panelRef}onScroll={(e) => setPanelScroll(e.currentTarget.scrollTop)}className={cn('w-[480px] overflow-y-auto',- 'rounded-[12px] border p-[6px]',- 'bg-[var(--cmd-palette-bg)]',- 'border-[var(--cmd-palette-border)]',+ 'p-[6px]',+ !embedded && [+ 'rounded-[12px] border',+ 'bg-[var(--cmd-palette-bg)]',+ 'border-[var(--cmd-palette-border)]',+ ],)}- style={{ boxShadow: 'var(--cmd-palette-shadow)', maxHeight }}+ style={{ boxShadow: embedded ? undefined : 'var(--cmd-palette-shadow)', maxHeight }}>- {state.kind === 'loading' && (+ {showLoadingSkeleton && (<div className="space-y-[4px] p-[4px]">{[0, 1, 2].map((i) => (<div@@ -320,18 +473,20 @@ export function AtMentionPanel({))}</div>)}- {state.kind === 'error' && (+ {showErrorState && (<div className="flex flex-col items-center justify-center py-[16px] gap-[10px]"><div className="text-[13px] text-[var(--destructive)]">{t('newChat.atMention.scanFailed')}</div><div className="text-[12px] text-[var(--cmd-palette-item-meta)] px-[12px] text-center">- {state.message}+ {state.kind === 'error' ? state.message : ''}</div><buttontype="button"onMouseDown={(e) => {e.preventDefault();+ }}+ onClick={() => {onRetry();}}className={cn(@@ -343,7 +498,7 @@ export function AtMentionPanel({</button></div>)}- {state.kind === 'ready' && filtered.length === 0 && (+ {showEmptyState && (<divclassName={cn('flex items-center justify-center',@@ -351,42 +506,73 @@ export function AtMentionPanel({'text-[var(--cmd-palette-empty)]',)}>- {state.searching+ {state.kind === 'ready' && state.searching? t('newChat.atMention.searching'): isEmptyRootQuery? t('newChat.atMention.typeToSearchFiles'): t('newChat.atMention.noMatch')}</div>)}- {state.kind === 'ready' && filtered.length > 0 && (+ {entries.length > 0 && (<>{isEmptyRootQuery ? (<>- {addSectionVisible && (- <div- className={cn(- 'flex h-[24px] items-center px-[10px]',- 'text-[12px] font-medium text-[var(--cmd-palette-item-meta)]',+ {addSectionVisible && renderSectionHeader(t('newChat.atMention.add'))}+ {addEntries.map(renderEntryRow)}+ {pluginSectionVisible && renderSectionHeader(t('extraDirs.pluginsTitle'))}+ {pluginEntries.map(renderEntryRow)}+ {referenceDirsVisible && (+ <>+ {renderSectionHeader(t('extraDirs.sectionTitle'))}+ {referenceDirs && referenceDirs.dirs.length > 0 && (+ <div role="list" aria-label={t('extraDirs.sectionTitle')}>+ {referenceDirs.dirs.map((p) => (+ <div+ key={p}+ className={cn(+ 'group flex h-[44px] items-center gap-2 rounded-[6px] px-[10px]',+ 'hover:bg-[var(--cmd-palette-item-hover)]',+ )}+ >+ <FolderPlus+ size={16}+ className="shrink-0 text-[var(--cmd-palette-item-icon)] opacity-60"+ />+ <Tip text={p} mono side="top">+ <span className="min-w-0 flex-1 truncate text-left text-[14px] text-[var(--cmd-palette-item-text)]">+ {extraDirBasename(p)}+ </span>+ </Tip>+ <button+ type="button"+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => referenceDirs.onRemove(p)}+ className={cn(+ 'rounded-full p-1 opacity-0 transition-opacity',+ 'hover:bg-[var(--cmd-palette-item-hover)]',+ 'group-hover:opacity-70 hover:!opacity-100',+ 'focus-visible:opacity-100 focus-visible:outline-none',+ 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ )}+ aria-label={t('extraDirs.remove', { name: extraDirBasename(p) })}+ >+ <X size={12} className="text-[var(--cmd-palette-item-text)]" />+ </button>+ </div>+ ))}+ </div>)}- >- {t('newChat.atMention.add')}- </div>- )}- {addItems.map(({ item, index }) => renderItemRow(item, index))}- {pluginSectionVisible && (- <div- className={cn(- 'flex h-[24px] items-center px-[10px]',- 'text-[12px] font-medium text-[var(--cmd-palette-item-meta)]',+ {referenceDirs && referenceDirs.dirs.length === 0 && (+ <div className="px-[10px] py-[8px] text-[12px] text-[var(--cmd-palette-item-meta)]">+ {t('extraDirs.empty')}+ </div>)}- >- {t('newChat.atMention.plugins')}- </div>+ {addDirEntry && renderEntryRow(addDirEntry)}+ </>)}- {pluginItems.map(({ item, index }) => renderItemRow(item, index))}</>) : (- filtered.map((item, idx) => renderItemRow(item, idx))+ indexed.map(renderEntryRow))}{isEmptyRootQuery && (<div@@ -398,7 +584,7 @@ export function AtMentionPanel({{t('newChat.atMention.typeToSearchFiles')}</div>)}- {!isEmptyRootQuery && state.truncated && (+ {!isEmptyRootQuery && state.kind === 'ready' && state.truncated && (<divclassName={cn('select-none px-[10px] py-[8px] text-[12px]',@@ -408,13 +594,31 @@ export function AtMentionPanel({{t('newChat.atMention.keepTyping')}</div>)}+ {state.kind === 'error' && (+ <button+ type="button"+ onMouseDown={(e) => {+ e.preventDefault();+ }}+ onClick={() => {+ onRetry();+ }}+ className={cn(+ 'flex w-full items-center gap-2 px-[10px] py-[8px] rounded-[6px] text-left',+ 'text-[12px] text-[var(--destructive)]',+ 'transition-colors hover:bg-[var(--cmd-palette-item-hover)]',+ )}+ >+ {t('newChat.atMention.scanFailed')} · {t('newChat.atMention.retry')}+ </button>+ )}</>)}</div>{/* Agent tooltip — same pattern as SlashCommandPalette tooltip.- Only shown for agent items that have a description. */}- {showTooltip && tooltipPos && (+ Only shown for resource entries that have a description. */}+ {showTooltip && tooltipPos && focusedItem && (<divref={tooltipRef}className={cn(diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex dd7cba7b22..f4f6f88c08 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -202,16 +202,23 @@ import * as sessionService from '@/lib/sessionService';import { getModelById } from '@/lib/modelDefinitions';import { loadAllCommands, filterSlashCommands, type UnifiedCommand } from '@/lib/slashCommands';import {- AT_FILE_PICKER_RESOURCE,AT_MENTION_EMPTY_WORKSPACE_SCAN_CAP,- createAtResourceFromNativePath,getAtDirectoryCompletionQuery,mergeAtResourceItems,scanAtResources,- filterAtResources,type AtResourceItem,} from '@/lib/atResourceService';-import { isAtResourceInsertTargetCurrent } from '@/lib/atResourceInsertionGuard';+import {+ buildComposerSuggestionEntries,+ firstEnabledSuggestionIndex,+ isComposerSuggestionEntryDisabled,+ nextEnabledSuggestionIndex,+ resolveComposerAtActivation,+ type ComposerPluginSuggestion,+ type ComposerSuggestionAction,+ type ComposerSuggestionEntry,+} from '@/lib/composerSuggestion';+import { MAX_EXTRA_DIRS, pickAndAddExtraDir } from './extraDirsActions';import { applyListBackspace, applyListContinuation } from '@/lib/composerListContinuation';import type { Effort, PermissionMode } from '@/lib/userPreferences.types';import { getAppShortcutCombos } from '@/lib/appShortcutStore';@@ -878,6 +885,38 @@ function detectTrigger(editor: Editor): TriggerState {return { kind: 'none' };}+/**+ * 合成激活(「+」按钮打开统一建议面板,Codex 模式)的 query 推导:+ * 不向文档插入 `@`,query = 锚点→光标之间的纯文本。返回 null 表示锚点失效+ * (光标移到锚点前 / 跨段落 / 中间出现空白、chip 或换行),此时+ * ChatInput 会清掉合成锚点、关闭面板。+ */+function deriveSyntheticAtQuery(editor: Editor, anchor: number, rangeEnd: number): string | null {+ const { state } = editor;+ const { selection, doc } = state;+ // 点击「+」前可能已有文本选区。synthetic anchor 就落在 selection.from,+ // 选区未变化时仍是空查询;用户继续输入后 ProseMirror 会自然替换选区并折叠光标,+ // 后续字符再按 anchor → caret 推导 query。+ if (!selection.empty) return selection.from === anchor ? '' : null;+ const pos = selection.from;+ if (pos < anchor || pos > rangeEnd || anchor > doc.content.size || rangeEnd > doc.content.size) {+ return null;+ }+ let $anchor;+ let $pos;+ try {+ $anchor = doc.resolve(anchor);+ $pos = doc.resolve(pos);+ } catch {+ return null;+ }+ if ($anchor.parent.type.name !== 'paragraph' || $anchor.parent !== $pos.parent) return null;+ // textBetween 用占位符替换非文本节点(chip / hardBreak),含占位符或空白即失效。+ const text = doc.textBetween(anchor, pos, '', '');+ if (/[\s]/.test(text)) return null;+ return text;+}+export function ChatInput({onSend,sessionId,@@ -1156,6 +1195,43 @@ export function ChatInput({remoteHostId,deviceLinkDeviceId,});+ const suggestionFileInputRef = useRef<HTMLInputElement>(null);++ // ── 「+」合成打开统一建议面板(Codex 模式)────────────────────────────+ // state 在 at-panel 区声明;editor 回调(render gate / blur)先于 state 声明+ // 创建,通过 ref 读最新锚点。锚点 = 打开面板那一刻的光标位,query = 锚点→光标+ // 纯文本(deriveSyntheticAtQuery)。+ const syntheticAtAnchorRef = useRef<number | null>(null);+ // synthetic query 的真实替换终点跟随 ProseMirror transaction mapping;它与+ // 当前光标位置分离,因此光标移回 query 中间时仍能删除完整 filter,同时不会+ // 吞掉「+」激活前就存在于锚点后的连续文本。+ const syntheticAtRangeEndRef = useRef<number | null>(null);+ const [syntheticAtAnchor, setSyntheticAtAnchorState] = useState<number | null>(null);+ const setSyntheticAtAnchor = useCallback((next: number | null) => {+ const previous = syntheticAtAnchorRef.current;+ syntheticAtAnchorRef.current = next;+ if (next === null) {+ syntheticAtRangeEndRef.current = null;+ } else if (previous !== next || syntheticAtRangeEndRef.current === null) {+ syntheticAtRangeEndRef.current = next;+ }+ setSyntheticAtAnchorState(next);+ }, []);+ // render gate 的 trigger 快照:typed 触发优先;合成激活期间以 pseudo-at 快照+ // 参与 diff,保证「+」打开后继续打字仍能触发 React 刷新(否则 gate 会把+ // trigger:none 的普通输入吞掉,面板不过滤)。锚点失效时返回哨兵 query,+ // 放行一次刷新让清锚点 effect 跑掉。+ const composerTriggerSnapshotOf = (ed: Editor): TriggerState => {+ const typed = detectTrigger(ed);+ if (typed.kind !== 'none') return typed;+ const anchor = syntheticAtAnchorRef.current;+ if (anchor != null) {+ const rangeEnd = syntheticAtRangeEndRef.current;+ const q = rangeEnd == null ? null : deriveSyntheticAtQuery(ed, anchor, rangeEnd);+ return { kind: 'at', query: q ?? '__synthetic_invalid__', from: anchor };+ }+ return typed;+ };const [isDragOver, setIsDragOver] = useState(false);const dragCounterRef = useRef(0);@@ -2124,7 +2200,11 @@ export function ChatInput({},},// Tick state on every update so triggerState below recomputes.- onUpdate: ({ editor: ed }) => {+ onUpdate: ({ editor: ed, transaction }) => {+ const syntheticRangeEnd = syntheticAtRangeEndRef.current;+ if (syntheticRangeEnd !== null && transaction.docChanged) {+ syntheticAtRangeEndRef.current = transaction.mapping.map(syntheticRangeEnd, 1);+ }if (!suppressListNormalizationRef.current &&!ed.view.composing &&@@ -2140,7 +2220,7 @@ export function ChatInput({});}const nextRenderSnapshot = composerRenderSnapshot(- detectTrigger(ed),+ composerTriggerSnapshotOf(ed),!composerDocIsEmpty(ed.state.doc),);if (shouldRefreshComposerRender(renderSnapshotRef.current, nextRenderSnapshot)) {@@ -2205,7 +2285,7 @@ export function ChatInput({},onSelectionUpdate: ({ editor: ed }) => {const nextRenderSnapshot = composerRenderSnapshot(- detectTrigger(ed),+ composerTriggerSnapshotOf(ed),!composerDocIsEmpty(ed.state.doc),);if (shouldRefreshComposerRender(renderSnapshotRef.current, nextRenderSnapshot)) {@@ -2233,6 +2313,9 @@ export function ChatInput({const t = detectTrigger(ed);if (t.kind === 'slash') setSuppressedSlashAt(t.from);else if (t.kind === 'at') setSuppressedAtAt(t.from);+ // 合成打开的统一面板同样随失焦关闭(「+」按钮本身 mousedown+ // preventDefault 不夺焦,不会触发这里)。+ setSyntheticAtAnchor(null);}}, 0);},@@ -2392,36 +2475,43 @@ export function ChatInput({),[ghostsForCommand],);- const atPluginItems = useMemo<AtResourceItem[]>(+ // 统一建议面板的插件条目(旧 `+` 菜单口径的并集):可用项可选,无指令或+ // 未生效项保留展示但置灰(entry 级 disabled + 原因)。+ const pluginSuggestions = useMemo<ComposerPluginSuggestion[]>(() => {// device-link 远程会话的插件运行在被控端;控制端清单既不代表远端// 已安装状态,选择后也无法用本地 InstalledGhost 解析并插入命令。if (deviceLinkDeviceId) return [];- return pluginsForMenu- .filter((ghost) => pluginAvailableIds.has(ghost.manifest.id) && ghost.manifest.command)- .map((ghost) => ({- type: 'plugin-command',- name: ghost.manifest.name,- relPath: ghost.manifest.command!,- pluginId: ghost.manifest.id,- ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),- sourceLabel: ghost.manifest.command!,- _nameLower: `${ghost.manifest.name} ${ghost.manifest.command}`.toLowerCase(),- _relPathLower: `${ghost.manifest.command} ${ghost.manifest.id}`.toLowerCase(),- }));+ return pluginsForMenu.map((ghost) => {+ const hasCommand = !!ghost.manifest.command;+ const selectable = pluginAvailableIds.has(ghost.manifest.id) && hasCommand;+ return {+ item: {+ type: 'plugin-command' as const,+ name: ghost.manifest.name,+ relPath: ghost.manifest.command ?? `cindy://plugin/${ghost.manifest.id}`,+ pluginId: ghost.manifest.id,+ ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),+ sourceLabel: ghost.manifest.command ?? '',+ _nameLower: `${ghost.manifest.name} ${ghost.manifest.command ?? ''}`.toLowerCase(),+ _relPathLower: `${ghost.manifest.command ?? ''} ${ghost.manifest.id}`.toLowerCase(),+ },+ ...(selectable+ ? {}+ : {+ disabled: true,+ disabledReason: t(+ hasCommand ? 'extraDirs.pluginDisabled' : 'extraDirs.pluginNoCommand',+ ),+ }),+ };+ });},- [deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds],+ [deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds, t],);useEffect(() => {setGhostCommandRoster(editor, ghostsForCommand);}, [editor, ghostsForCommand]);- const handlePluginSelect = useCallback(- (ghost: (typeof pluginsForMenu)[number]) => {- if (!editor || editor.isDestroyed) return;- placeGhostAtComposerStart(editor, ghost, installedGhosts);- },- [editor, installedGhosts],- );const handleVoiceInputPermissionRequired = useCallback(async () => {const confirmed = await confirmDialog({@@ -3371,26 +3461,35 @@ export function ChatInput({const runAtScan = useCallback((query?: string, reservedSeq?: number) => {- // SSH 远端会话不扫 @ 资源(无隧道);atOpen 也已对其关闭面板,这里再兜一层。- if (isRemoteSession) return;+ // SSH 远端会话不扫 @ 资源(无隧道)。统一面板仍可打开(动作 + 插件条目),+ // 资源区直接置空 ready,不能留 loading 骨架。+ if (isRemoteSession) {+ atScanSeqRef.current += 1;+ setAtState({ kind: 'ready', items: [], truncated: false });+ return;+ }// device-link 远程会话:带 deviceId 经隧道在被控端扫描(workingDir 是被控端路径);// 本机会话 deviceId 为 undefined → 本地扫描。// 远程**草稿**(NewMakerDraftRoute)此时 sessionId 还是 undefined、但 deviceLinkDeviceId prop 已设——// 必须优先用 prop,否则 @ 扫描落到控制端本机 FS(扫到同名目录的错文件),插进首条远程消息的 mention 不可用。const remoteDeviceId =deviceLinkDeviceId ?? (sessionId ? getSessionDeviceId(sessionId) : undefined);+ const normalizedQuery = query?.trim() ?? '';+ // device-link 纯远程草稿尚未选 workspace 时不能把空路径发给被控端扫描。+ // 空查询仅清空资源区;非空查询仍可经隧道搜索被控端任务历史。+ if (remoteDeviceId && !workingDir?.trim() && !normalizedQuery) {+ atScanSeqRef.current += 1;+ setAtState({ kind: 'ready', items: [], truncated: false });+ return;+ }const seq = reservedSeq ?? ++atScanSeqRef.current;if (atScanSeqRef.current !== seq) return;- const normalizedQuery = query?.trim() ?? '';const preservePreviousItems = reservedSeq !== undefined && !!normalizedQuery;atLastScanQueryRef.current = normalizedQuery;setAtState((prev) => {if (prev.kind === 'ready' && normalizedQuery) {return { ...prev, searching: true };}- if (atPluginItems.length > 0) {- return { kind: 'ready', items: atPluginItems, truncated: false, searching: true };- }return { kind: 'loading' };});scanAtResources(@@ -3409,8 +3508,8 @@ export function ChatInput({setAtState((prev) => ({kind: 'ready',items: preservePreviousItems && prev.kind === 'ready'- ? mergeAtResourceItems(prev.items, [...atPluginItems, ...partial.items])- : [...atPluginItems, ...partial.items],+ ? mergeAtResourceItems(prev.items, partial.items)+ : partial.items,truncated: partial.truncated || (prev.kind === 'ready' && prev.truncated),searching: true,}));@@ -3420,16 +3519,14 @@ export function ChatInput({.then((res) => {if (atScanSeqRef.current !== seq) return;if (!res.success) {- if (atPluginItems.length > 0) {- setAtState({ kind: 'ready', items: atPluginItems, truncated: false });- } else {- setAtState({ kind: 'error', message: res.error ?? 'scan failed' });- }+ // 扫描失败不再整面板报错兜底插件:插件/动作条目独立于 atState,+ // 面板在有其它条目时把错误降级为底部一行 + 重试。+ setAtState({ kind: 'error', message: res.error ?? 'scan failed' });return;}setAtState({kind: 'ready',- items: [...atPluginItems, ...res.items],+ items: res.items,truncated: res.truncated,});})@@ -3439,27 +3536,167 @@ export function ChatInput({setAtState({ kind: 'error', message: m });});},- [workingDir, paletteAgentKind, isRemoteSession, sessionId, deviceLinkDeviceId, t, atPluginItems],+ [workingDir, paletteAgentKind, isRemoteSession, sessionId, deviceLinkDeviceId, t],+ );++ const syntheticAtQuery = useMemo(+ () =>+ editor && syntheticAtAnchor !== null+ ? (() => {+ const rangeEnd = syntheticAtRangeEndRef.current;+ return rangeEnd == null+ ? null+ : deriveSyntheticAtQuery(editor, syntheticAtAnchor, rangeEnd);+ })()+ : null,+ [editor, syntheticAtAnchor, trigger],);+ useEffect(() => {+ if (syntheticAtAnchor === null || syntheticAtQuery !== null) return;+ setSyntheticAtAnchor(null);+ }, [setSyntheticAtAnchor, syntheticAtAnchor, syntheticAtQuery]);++ // synthetic 是一次显式激活:打开期间即使光标前仍能匹配 `/` / `@` typed run,+ // 也应继续由「+」锚点解释 query;否则刚打开就会被旧 trigger 抢回并立即收起。+ const effectiveAt = resolveComposerAtActivation({+ typed: trigger.kind === 'at' ? { from: trigger.from, query: trigger.query } : null,+ syntheticAnchor: syntheticAtAnchor,+ syntheticQuery: syntheticAtQuery,+ });+ const atQuery = effectiveAt?.query ?? '';++ const runNewGoalAction = useCallback(() => {+ const activeEditor = editorRef.current;+ const draftText =+ activeEditor && !activeEditor.isDestroyed+ ? serializeEditorContent(activeEditor).text.trim()+ : '';+ if (inSessionGoalEnabled) {+ setNewGoalInitial(draftText);+ setNewGoalOpen(true);+ return;+ }+ onNewGoal?.(draftText);+ }, [inSessionGoalEnabled, onNewGoal]);++ const composerSuggestionActions = useMemo<ComposerSuggestionAction[]>(() => {+ const actions: ComposerSuggestionAction[] = [];+ if (localAttachmentPickerEnabled) {+ actions.push({+ id: 'attach-files',+ label: t('extraDirs.addFiles'),+ disabled: composerMutationLocked,+ run: () => suggestionFileInputRef.current?.click(),+ });+ }+ if (inSessionGoalEnabled || onNewGoal) {+ actions.push({+ id: 'new-goal',+ label: t('goal.newGoalMenuItem'),+ disabled: composerMutationLocked,+ run: runNewGoalAction,+ });+ }+ if (planModeEntry) {+ actions.push({+ id: 'plan-mode',+ label: t('planMode.menuItem'),+ checked: planModeEntry.enabled,+ disabled: composerMutationLocked,+ run: () => planModeEntry.onToggle(!planModeEntry.enabled),+ });+ }+ if (collaboration) {+ const policyDisabled = collaboration.disabled === true;+ const retryable = policyDisabled && !!collaboration.onDisabledActivate;+ actions.push({+ id: 'collaboration',+ label: t('newChat.collaboration.modeLabel'),+ checked: collaboration.enabled,+ disabled: composerMutationLocked || (policyDisabled && !retryable),+ disabledReason: collaboration.disabledReason,+ run: () => {+ if (policyDisabled) {+ collaboration.onDisabledActivate?.();+ return;+ }+ if (collaboration.enabled) {+ collaboration.onChange({ enabled: false, worker: collaboration.worker });+ return;+ }+ if (collaboration.onOpenDetails) {+ collaboration.onOpenDetails();+ return;+ }+ collaboration.onChange({ enabled: true, worker: collaboration.worker });+ },+ });+ }+ if (onExtraDirsChange) {+ const currentExtraDirs = extraDirs ?? [];+ actions.push({+ id: 'add-extra-dir',+ label:+ currentExtraDirs.length >= MAX_EXTRA_DIRS+ ? t('extraDirs.atLimit', { max: MAX_EXTRA_DIRS })+ : t('extraDirs.add'),+ disabled: composerMutationLocked || currentExtraDirs.length >= MAX_EXTRA_DIRS,+ run: () => {+ void pickAndAddExtraDir({+ extraDirs: currentExtraDirs,+ workingDir,+ onChange: onExtraDirsChange,+ confirm: confirmDialog,+ parentDirectoryConfirm: {+ title: t('extraDirs.parentConfirmTitle'),+ description: (path) => t('extraDirs.parentConfirmDescription', { path }),+ confirmText: t('extraDirs.parentConfirmAccept'),+ cancelText: t('extraDirs.parentConfirmCancel'),+ },+ });+ },+ });+ }+ return actions;+ }, [+ collaboration,+ composerMutationLocked,+ confirmDialog,+ extraDirs,+ inSessionGoalEnabled,+ localAttachmentPickerEnabled,+ onExtraDirsChange,+ onNewGoal,+ planModeEntry,+ runNewGoalAction,+ t,+ workingDir,+ ]);- const atQuery = trigger.kind === 'at' ? trigger.query : '';+ const atResources = useMemo(+ () => (atState.kind === 'ready' ? atState.items : []),+ [atState],+ );++ const filteredAt = useMemo(+ () =>+ effectiveAt+ ? buildComposerSuggestionEntries({+ query: atQuery,+ actions: composerSuggestionActions,+ resources: atResources,+ plugins: pluginSuggestions,+ })+ : [],+ [atQuery, atResources, composerSuggestionActions, effectiveAt, pluginSuggestions],+ );// When `@` panel opens, rescan so newly created files/agents show immediately.+ // biome-ignore lint/correctness/useExhaustiveDependencies: 首次打开只按 activation/from/context 扫一次;query 变化由下方 debounce effect 独立负责,避免每次按键立即重复扫描。useEffect(() => {- if (trigger.kind !== 'at') return;- runAtScan();- }, [trigger.kind, workingDir, runAtScan]);-- // Derive query string for stable memo deps — avoids re-filtering on- // every editor tick when only the caret moved but the query didn't change.- const filteredAt = useMemo(() => {- if (!atQuery && trigger.kind !== 'at') return [];- if (atState.kind !== 'ready') return [];- const items = workingDir && localAttachmentPickerEnabled- ? [AT_FILE_PICKER_RESOURCE, ...atState.items]- : atState.items;- return filterAtResources(items, atQuery);- }, [atState, atQuery, trigger.kind, workingDir, localAttachmentPickerEnabled]);+ if (!effectiveAt) return;+ runAtScan(atQuery);+ }, [effectiveAt?.activation, effectiveAt?.from, runAtScan, workingDir]);// Focused row index for each paletteconst [slashFocus, setSlashFocus] = useState(0);@@ -3470,14 +3707,19 @@ export function ChatInput({if (slashFocus >= filteredCommands.length) setSlashFocus(0);}, [filteredCommands.length, slashFocus]);useEffect(() => {- if (atFocus >= filteredAt.length) setAtFocus(0);- }, [filteredAt.length, atFocus]);+ if (+ atFocus >= filteredAt.length ||+ (filteredAt[atFocus] && isComposerSuggestionEntryDisabled(filteredAt[atFocus]))+ ) {+ setAtFocus(firstEnabledSuggestionIndex(filteredAt));+ }+ }, [filteredAt, atFocus]);useEffect(() => {if (atQueryScanTimerRef.current !== null) {window.clearTimeout(atQueryScanTimerRef.current);atQueryScanTimerRef.current = null;}- if (trigger.kind !== 'at') return;+ if (!effectiveAt) return;const normalizedQuery = atQuery.trim();if (normalizedQuery === atLastScanQueryRef.current) return;atLastScanQueryRef.current = normalizedQuery;@@ -3495,7 +3737,7 @@ export function ChatInput({atQueryScanTimerRef.current = null;}};- }, [trigger.kind, workingDir, atQuery, runAtScan]);+ }, [effectiveAt?.activation, effectiveAt?.from, workingDir, atQuery, runAtScan]);// ── Panel-close flags (Esc cancelation) ────────────────────────────// Once the user cancels a panel (Esc), we must NOT reopen it until the@@ -3521,8 +3763,20 @@ export function ChatInput({}, [trigger, suppressedSlashAt, suppressedAtAt]);const slashOpen = trigger.kind === 'slash' && suppressedSlashAt !== trigger.from;- const atOpen =- trigger.kind === 'at' && !isRemoteSession && suppressedAtAt !== trigger.from;+ const typedAtOpen =+ effectiveAt?.activation === 'typed' &&+ !isRemoteSession &&+ suppressedAtAt !== effectiveAt.from;+ const syntheticAtOpen = effectiveAt?.activation === 'synthetic';+ const atOpen = typedAtOpen || syntheticAtOpen;++ const closeAtPanel = useCallback(() => {+ if (effectiveAt?.activation === 'typed') {+ setSuppressedAtAt(effectiveAt.from);+ } else {+ setSyntheticAtAnchor(null);+ }+ }, [effectiveAt, setSyntheticAtAnchor]);useEffect(() => {if (!slashOpen) return;@@ -3547,7 +3801,7 @@ export function ChatInput({return true;}if (atOpen && filteredAt.length > 0) {- setAtFocus((i) => (i + 1) % filteredAt.length);+ setAtFocus((i) => nextEnabledSuggestionIndex(filteredAt, i, 1));return true;}return false;@@ -3557,7 +3811,7 @@ export function ChatInput({return true;}if (atOpen && filteredAt.length > 0) {- setAtFocus((i) => (i - 1 + filteredAt.length) % filteredAt.length);+ setAtFocus((i) => nextEnabledSuggestionIndex(filteredAt, i, -1));return true;}return false;@@ -3567,8 +3821,12 @@ export function ChatInput({insertSlashCommand(filteredCommands[slashFocus]);return true;}- if (atOpen && filteredAt[atFocus]) {- insertAtResource(filteredAt[atFocus]);+ if (+ atOpen &&+ filteredAt[atFocus] &&+ !isComposerSuggestionEntryDisabled(filteredAt[atFocus])+ ) {+ void handleComposerSuggestionSelect(filteredAt[atFocus]);return true;}return false;@@ -3577,13 +3835,18 @@ export function ChatInput({setSuppressedSlashAt(trigger.from);return true;}- if (atOpen && trigger.kind === 'at') {- setSuppressedAtAt(trigger.from);+ if (atOpen) {+ closeAtPanel();return true;}return false;- case 'ArrowLeft':case 'Backspace':+ if (syntheticAtOpen && !atQuery) {+ closeAtPanel();+ return true;+ }+ return false;+ case 'ArrowLeft':return false;default:return false;@@ -3642,72 +3905,63 @@ export function ChatInput({[editor, trigger],);- const insertAtResource = useCallback(- async (item: AtResourceItem) => {- if (!editor || trigger.kind !== 'at') return;- const { from } = trigger;- // Extend replace-range to the end of the @-run (up to whitespace /- // chip boundary / end of paragraph). Same reasoning as- // insertSlashCommand — the caret may sit inside the run.- const $from = editor.state.doc.resolve(from);- const parent = $from.parent;- const parentStart = $from.start();- let runEnd = from + 1;- const offset = from - parentStart + 1;- let stopped = false;- parent.forEach((child, childOffset) => {- if (stopped || childOffset + child.nodeSize <= offset) return;- if (child.type.name === 'mentionChip' || !child.isText) {+ const resolveEffectiveAtRange = useCallback((): { from: number; to: number } | null => {+ if (!editor || !effectiveAt) return null;+ const { from } = effectiveAt;++ // synthetic query 没有文档内触发符,替换范围由 transaction mapping 单独跟踪。+ // 不能像 typed `@` 一样向后扫到空白,否则在已有单词中间激活并输入过滤词时+ // 会把激活前就存在的单词后缀一起删除。+ if (effectiveAt.activation === 'synthetic') {+ const to = syntheticAtRangeEndRef.current;+ return to !== null && to >= from ? { from, to } : null;+ }++ // Extend replace-range to the end of the complete query run (up to+ // whitespace / chip boundary / end of paragraph). The caret may sit+ // inside either a typed `@query` or a synthetic `query`; selecting an+ // entry must not leave the suffix after the caret behind.+ let $from;+ try {+ $from = editor.state.doc.resolve(from);+ } catch {+ return null;+ }+ const parent = $from.parent;+ const parentStart = $from.start();+ const triggerOffset = 1;+ let runEnd = from + triggerOffset;+ const offset = from - parentStart + triggerOffset;+ let stopped = false;+ parent.forEach((child, childOffset) => {+ if (stopped || childOffset + child.nodeSize <= offset) return;+ if (child.type.name === 'mentionChip' || !child.isText) {+ stopped = true;+ return;+ }+ const localStart = Math.max(0, offset - childOffset);+ const text = child.text ?? '';+ for (let i = localStart; i < text.length; i++) {+ if (/\s/.test(text[i])) {+ runEnd = parentStart + childOffset + i;stopped = true;return;}- const localStart = Math.max(0, offset - childOffset);- const text = child.text ?? '';- for (let i = localStart; i < text.length; i++) {- if (/\s/.test(text[i])) {- runEnd = parentStart + childOffset + i;- stopped = true;- return;- }- }- runEnd = parentStart + childOffset + text.length;- });- const to = runEnd;- let selectedItem = item;- let selectedByNativePicker = false;- if (selectedItem.type === 'file-picker') {- const originDoc = editor.state.doc;- const originStorageKey = storageKey;- try {- const picked = await window.electronAPI.dialog.showOpenResource(- workingDir ? { defaultPath: workingDir } : undefined,- );- if (!picked.success || !picked.path || !picked.kind) return;- if (!isAtResourceInsertTargetCurrent(- editor,- editorRef.current,- originDoc,- originStorageKey,- currentStorageKeyRef.current,- )) return;- const nativeResource = createAtResourceFromNativePath(- picked.path,- picked.kind,- workingDir,- );- if (!nativeResource) return;- selectedItem = nativeResource;- selectedByNativePicker = true;- } catch (error) {- log.warn(- 'native @ file picker failed:',- error instanceof Error ? error.message : String(error),- );- return;- }}- // The synthetic action must always resolve to a concrete file/directory- // before it can reach mention serialization.+ runEnd = parentStart + childOffset + text.length;+ });+ return { from, to: runEnd };+ }, [editor, effectiveAt]);++ const insertAtResource = useCallback(+ (selectedItem: AtResourceItem) => {+ if (!editor || !effectiveAt) return;+ const range = resolveEffectiveAtRange();+ if (!range) return;+ const { from, to } = range;+ // `file-picker` remains in the shared AtResourceItem protocol for+ // compatibility, but the unified composer no longer assembles that+ // duplicate row. Keep a defensive guard for exhaustive type narrowing.if (selectedItem.type === 'file-picker') return;if (selectedItem.type === 'plugin-command') {if (!selectedItem.pluginId) return;@@ -3724,21 +3978,26 @@ export function ChatInput({}).run();placeGhostAtComposerStart(editor, ghost, installedGhostsRef.current);- setSuppressedAtAt(from);+ closeAtPanel();return;}- const directoryQuery = selectedByNativePicker- ? null- : getAtDirectoryCompletionQuery(selectedItem);+ const directoryQuery = getAtDirectoryCompletionQuery(selectedItem);if (directoryQuery) {editor.chain().focus().command(({ tr }) => {- tr.replaceWith(from, to, editor.schema.text(`@${directoryQuery}`));+ tr.replaceWith(+ from,+ to,+ editor.schema.text(+ effectiveAt.activation === 'typed' ? `@${directoryQuery}` : directoryQuery,+ ),+ );return true;}).run();+ if (effectiveAt.activation === 'synthetic') setSyntheticAtAnchor(from);setAtFocus(0);return;}@@ -3775,8 +4034,64 @@ export function ChatInput({return true;}).run();+ closeAtPanel();},- [editor, trigger, workingDir, storageKey],+ [+ closeAtPanel,+ editor,+ effectiveAt,+ resolveEffectiveAtRange,+ setSyntheticAtAnchor,+ ],+ );++ const handleComposerSuggestionSelect = useCallback(+ (entry: ComposerSuggestionEntry) => {+ if (isComposerSuggestionEntryDisabled(entry)) return;+ if (entry.kind === 'resource') {+ void insertAtResource(entry.item);+ return;+ }+ if (!editor) return;+ const range = resolveEffectiveAtRange();+ if (!range) return;+ editor+ .chain()+ .focus()+ .command(({ tr }) => {+ tr.delete(range.from, range.to);+ return true;+ })+ .run();+ closeAtPanel();+ entry.action.run();+ },+ [closeAtPanel, editor, insertAtResource, resolveEffectiveAtRange],+ );++ const handleComposerSuggestionOpenChange = useCallback((nextOpen: boolean) => {+ if (!nextOpen) {+ setSyntheticAtAnchor(null);+ return;+ }+ if (!editor || editor.isDestroyed || composerMutationLocked) return;+ if (trigger.kind === 'slash') {+ setSuppressedSlashAt(trigger.from);+ } else if (trigger.kind === 'at') {+ setSuppressedAtAt(trigger.from);+ }+ setSyntheticAtAnchor(editor.state.selection.from);+ setAtFocus(0);+ editor.commands.focus();+ }, [+ composerMutationLocked,+ editor,+ setSyntheticAtAnchor,+ trigger,+ ]);+ const composerSuggestionFocusTarget = useCallback(+ () => editor?.view.dom ?? null,+ [editor],);// ── Send / Stop wiring ─────────────────────────────────────────────@@ -3841,14 +4156,15 @@ export function ChatInput({}serializedContent = serializeEditorContent(editor);}- let {+ const {text: editorText,mentions,hasQuotes,- agentReferences,+ agentReferences: serializedAgentReferences,pastedTextRanges,slashCommandRanges,} = serializedContent;+ let agentReferences = serializedAgentReferences;const attachmentsForSend = optimisticallyClearRemoteComposer? attachmentsBeforeOptimisticClear: [...latestAttachmentsRef.current];@@ -6248,36 +6564,52 @@ export function ChatInput({// create-agent 按 Figma 使用 hug-content pills;默认会话页仍保留左侧优先压缩。)}>- {/* composer 「+」菜单(权限左侧):本机会话提供附件入口;目标、计划/协同模式、- Plugin、引用目录按各自能力与接线显示。远程会话不能把控制端绝对路径- 交给远端 agent,因此不接本机文件选择器。 */}+ {localAttachmentPickerEnabled && (+ <input+ ref={suggestionFileInputRef}+ type="file"+ multiple+ disabled={composerMutationLocked}+ className="hidden"+ onChange={(event) => {+ const files = Array.from(event.currentTarget.files ?? []);+ event.currentTarget.value = '';+ if (files.length > 0) void addFiles(files);+ }}+ />+ )}+ {/* 「+」只负责合成打开统一建议面板;内容与输入 @ 完全共用。 */}<ExtraDirsButton- extraDirs={extraDirs ?? []}- workingDir={workingDir}- onAddFiles={- localAttachmentPickerEnabled && !composerMutationLocked ? addFiles : undefined- }- planMode={planModeEntry}- collaboration={collaboration}- 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+ extraDirsCount={(extraDirs ?? []).length}+ hasReferenceDirs={onExtraDirsChange !== undefined}+ open={syntheticAtOpen}+ onOpenChange={handleComposerSuggestionOpenChange}+ autoFocusTarget={composerSuggestionFocusTarget}+ panel={+ <AtMentionPanel+ embedded+ query={atQuery}+ state={atState}+ entries={filteredAt}+ focusedIndex={atFocus}+ onFocusedIndexChange={setAtFocus}+ onSelect={handleComposerSuggestionSelect}+ onClose={closeAtPanel}+ onRetry={() => runAtScan(atQuery)}+ referenceDirs={+ onExtraDirsChange+ ? {+ dirs: extraDirs ?? [],+ onRemove: (path) => {+ void onExtraDirsChange(+ (extraDirs ?? []).filter((item) => item !== path),+ );+ },+ }+ : null+ }+ maxHeight={paletteMaxHeight}+ />}disabled={composerMutationLocked}dense={effectiveDenseToolbar}@@ -6497,19 +6829,26 @@ export function ChatInput({)}{/* At-mention panel */}- {atOpen && trigger.kind === 'at' && (+ {typedAtOpen && effectiveAt && (<AtMentionPanel- query={trigger.query}+ query={atQuery}state={atState}+ entries={filteredAt}focusedIndex={atFocus}onFocusedIndexChange={setAtFocus}- onSelect={(item) => insertAtResource(item)}- onClose={() => {- if (trigger.kind !== 'at') return;- setSuppressedAtAt(trigger.from);- }}+ onSelect={handleComposerSuggestionSelect}+ onClose={closeAtPanel}onRetry={() => runAtScan(atQuery)}- filePickerEnabled={!!workingDir && localAttachmentPickerEnabled}+ referenceDirs={+ onExtraDirsChange+ ? {+ dirs: extraDirs ?? [],+ onRemove: (path) => {+ void onExtraDirsChange((extraDirs ?? []).filter((item) => item !== path));+ },+ }+ : null+ }maxHeight={paletteMaxHeight}/>)}diff --git a/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx b/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsxindex 8878c2df17..6c8f43c73e 100644--- a/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx@@ -1,51 +1,10 @@-/**- * ExtraDirsButton —— composer 的「+」操作菜单(左置于权限选择器之前)。- *- * 合并了五类入口(参考 Codex 的 + 菜单):- * - 添加文件、图片或视频→ 复用 composer 既有附件管线。- * - 新建目标(`onNewGoal` 提供时显示;仅会话中,父组件按 sessionId 决定)→ 打开 NewGoalDialog。- * - 计划模式 / 协同模式→ 与新建目标同级的模式入口。- * - 已安装 Plugin:选择后由 ChatInput 把 command 放到消息开头,保留正文并聚焦末尾。- * - 附加只读引用目录(Claude vendor;`onChange` 提供时显示)→ 列表 / 添加。- *- * 创建时和 session 中途共用同一组件:父组件传 onChange 决定目录持久化路径:- * - 创建时(NewMakerDraftRoute):写 newMakerDraft store- * - 中途(CCAgentSessionView):同步调 sessionService.update + window.electronAPI.maker.setExtraDirs- *- * 视觉:trigger 是一个「+」(rounded-full / 14px 图标),有引用目录时带 ×N 角标。- * Popover 列出新建目标项 + 引用目录段(可单条删除)+ "添加目录"。- *- * 校验:选中路径与 workingDir 重叠时:子目录静默去重;父目录弹 confirm。- * main 端 extraDirsValidator.ts 兜底 — 这里只做 UX 预判。- */--import { useRef, useState } from 'react';-import {- Check,- ClipboardList,- FolderPlus,- Paperclip,- Plus,- Target,- UsersRound,- X,-} from 'lucide-react';+import type { ReactNode } from 'react';+import { Plus } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { cn } from '@/lib/utils';import { MorphPopover } from '@/components/ui/morph-popover';import { Tip } from '@/components/ui/tooltip';-import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';-import { createLogger } from '@/lib/logger';-import { GhostPluginIcon } from '@/features/plugin/GhostPluginIcon';-import { stripTrailingPathSeparators } from '../../../shared/pathText';-import { normalizeWorkingDirForStorage } from '../../../shared/workingDir';-import type { InstalledGhost } from '../../../shared/ghost';--const log = createLogger('ExtraDirsButton');--/** 与 main 端 EXTRA_DIRS_MAX 保持一致;UI 满了 disable 添加按钮。 */-const MAX_EXTRA_DIRS = 10;+import { cn } from '@/lib/utils';export type CollabWorkerKind = 'cc' | 'codex' | 'pi';@@ -53,7 +12,7 @@ export interface CollaborationMenuConfig {enabled: boolean;worker: CollabWorkerKind;onChange: (next: { enabled: boolean; worker: CollabWorkerKind }) => void;- /** 关闭态优先打开完整 Worker 配置;未提供时直接沿用当前 worker 开启。 */+ /** 关闭态优先打开完整 Worker 配置;未提供时直接沿用当前 worker 开启。 */onOpenDetails?: () => void;/** 策略暂不可用时允许从菜单项触发刷新。 */onDisabledActivate?: () => void;@@ -62,519 +21,91 @@ export interface CollaborationMenuConfig {}export interface ExtraDirsButtonProps {- extraDirs: string[];- workingDir?: string | null;- /** 选择本机文件后交给 composer 的既有附件校验、缓存与发送管线。 */- onAddFiles?: (files: readonly File[]) => void | Promise<void>;- /**- * 父组件实现增删持久化(创建时写 draft store / 中途双 IPC 协调)。- * 未提供时只显示目标、计划模式或 Plugin 入口,不显示引用目录段。- */- onChange?: (next: string[]) => void | Promise<void>;- /** 提供时在菜单顶部显示「新建目标」项(仅会话中;点击 → 父组件打开 NewGoalDialog)。 */- onNewGoal?: () => void;- /**- * 计划模式 toggle(与「新建目标」同级的一级入口)。提供时显示菜单项;- * 父组件负责能力门控(capabilities.planMode)与持久化,这里只做 UI。- */- planMode?: { enabled: boolean; onToggle: (next: boolean) => void };- /** 协同模式入口;与新建目标、计划模式同级显示在「+」菜单。 */- collaboration?: CollaborationMenuConfig;- /** 已安装 Plugin 清单;无指令或未生效项仍展示,但不可选。 */- plugins?: readonly InstalledGhost[];- /** 当前会话范围内可直接使用的 Plugin id;未命中项保留展示但置灰。 */- pluginAvailableIds?: ReadonlySet<string>;- /** 选择后由 ChatInput 把 Plugin command 放到正文开头并把光标落到全文末尾。 */- onPluginSelect?: (ghost: InstalledGhost) => void;+ extraDirsCount: number;+ hasReferenceDirs: boolean;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ panel: ReactNode;+ autoFocusTarget?: () => HTMLElement | null;disabled?: boolean;- /** 窄容器下把 trigger 字号/图标各压一档,默认 false。 */dense?: boolean;- /** CREATE AGENT 首页按 Figma 185:2724 使用独立私有 token。 */visualVariant?: 'default' | 'create-agent';}-function normalizedPathForComparison(raw: string | null | undefined): string | null {- const normalized = normalizeWorkingDirForStorage(raw);- return normalized ? stripTrailingPathSeparators(normalized) : null;-}-/**- * 判断 candidate 是否是 base 自身或子目录(简单字符串前缀,跨平台够用 —— main 端- * extraDirsValidator 用 path.relative 做权威判定)。+ * Composer 的「+」只保留触发器与既定 MorphPopover 容器;列表内容与输入 `@`+ * 共用 AtMentionPanel,避免再次维护独立菜单实现。*/-function isSelfOrSubdir(candidate: string, base: string): boolean {- const c = normalizedPathForComparison(candidate);- const b = normalizedPathForComparison(base);- if (!c || !b) return false;- if (c === b) return true;- return c.startsWith(b + '/');-}--function isSameStoragePath(a: string, b: string): boolean {- const normalizedA = normalizedPathForComparison(a);- const normalizedB = normalizedPathForComparison(b);- return !!normalizedA && !!normalizedB && normalizedA === normalizedB;-}--function hasExtraDir(extraDirs: string[], candidate: string): boolean {- return extraDirs.some((existing) => isSameStoragePath(existing, candidate));-}--/** candidate 是 base 父目录或祖先(反过来:base 是 candidate 的子目录)。 */-function isParentOrAncestor(candidate: string, base: string): boolean {- const c = normalizedPathForComparison(candidate);- const b = normalizedPathForComparison(base);- if (!c || !b || c === b) return false;- return isSelfOrSubdir(b, c);-}--export const __extraDirsPathOverlapForTesting = {- hasExtraDir,- isParentOrAncestor,- isSelfOrSubdir,-};--/** 取目录名做 chip 显示;空回 '/' 。 */-function basename(p: string): string {- const stripped = stripTrailingPathSeparators(p);- const parts = stripped.split(/[\\/]/);- return parts[parts.length - 1] || stripped || '/';-}-export function ExtraDirsButton({- extraDirs,- workingDir,- onAddFiles,- onChange,- onNewGoal,- planMode,- collaboration,- plugins = [],- pluginAvailableIds,- onPluginSelect,+ extraDirsCount,+ hasReferenceDirs,+ open,+ onOpenChange,+ panel,+ autoFocusTarget,disabled,dense = false,visualVariant = 'default',}: ExtraDirsButtonProps) {const { t } = useTranslation();- const [open, setOpen] = useState(false);- const fileInputRef = useRef<HTMLInputElement>(null);- const { confirm } = useConfirmDialog();-- const hasReferenceDirs = onChange !== undefined;- const count = extraDirs.length;+ const count = extraDirsCount;const isCreateAgentVariant = visualVariant === 'create-agent';- // hover 展开「添加」文案已移除(2026-07-22 用户定稿:展开必须承载信息,- // 图标自明的 + 不需要;裸态→hover 外框→点击直接长出菜单)。-- // 能力感知:附件、新建目标、计划/协同模式、Plugin 与引用目录都由父组件是否接线决定。- if (- !onAddFiles &&- !onNewGoal &&- !planMode &&- !collaboration &&- !hasReferenceDirs &&- plugins.length === 0- ) {- return null;- }-- const atLimit = count >= MAX_EXTRA_DIRS;- const collaborationPolicyDisabled = collaboration?.disabled === true;- const collaborationRetryable =- !disabled && collaborationPolicyDisabled && !!collaboration?.onDisabledActivate;- const collaborationAriaLabel = collaboration?.disabledReason- ? `${t('newChat.collaboration.modeLabel')}: ${collaboration.disabledReason}`- : t('newChat.collaboration.modeLabel');-- const handleCollaborationActivate = () => {- if (!collaboration || disabled) return;- setOpen(false);- if (collaborationPolicyDisabled) {- collaboration.onDisabledActivate?.();- return;- }- if (collaboration.enabled) {- collaboration.onChange({ enabled: false, worker: collaboration.worker });- return;- }- if (collaboration.onOpenDetails) {- collaboration.onOpenDetails();- return;- }- collaboration.onChange({ enabled: true, worker: collaboration.worker });- };-- const handleAdd = async () => {- if (atLimit || !onChange) return;- let picked: string | null = null;- try {- const r = await window.electronAPI.dialog.showOpenDirectory({});- picked = r?.success ? r.path : null;- } catch (e) {- log.warn('showOpenDirectory failed', { error: String(e) });- return;- }- const normalizedPicked = normalizeWorkingDirForStorage(picked);- if (!normalizedPicked) return;-- // UX 预判: 完全重复 / 是 workingDir 子目录 → 静默忽略(main validator 也会兜)。- if (hasExtraDir(extraDirs, normalizedPicked)) return;- if (workingDir && isSelfOrSubdir(normalizedPicked, workingDir)) {- log.debug('add: silently skipped (subdir of workingDir)', {- picked: normalizedPicked,- workingDir,- });- return;- }-- // 父目录 / 祖先警告 — 通过则继续。- if (workingDir && isParentOrAncestor(normalizedPicked, workingDir)) {- const ok = await confirm({- title: '添加父目录?',- description: `选中的目录是当前工作目录的父级或祖先。这会扩大 agent 的可见范围 —— 它能看到工作目录之外的内容。\n\n要添加吗?\n\n${normalizedPicked}`,- confirmText: '仍然添加',- cancelText: '取消',- });- if (!ok) return;- }-- await onChange([...extraDirs, normalizedPicked]);- };-- const handleRemove = async (path: string) => {- if (!onChange) return;- await onChange(extraDirs.filter((p) => p !== path));- };-return (<MorphPopoveropen={open}- onOpenChange={setOpen}- panelWidth={360}- panelClassName="p-2"+ onOpenChange={onOpenChange}+ panelWidth={480}+ panelClassName="p-0"panelAriaLabel={t('extraDirs.menuAria')}- startBg="var(--composer-pill-bg)"- startBorderColor="var(--border-default)"+ endBg="var(--cmd-palette-bg)"+ endBorderColor="var(--cmd-palette-border)"wrapperClassName="shrink-0"+ autoFocusTarget={autoFocusTarget}trigger={- <>- {/* 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 && (- <>+ <Tip+ text={count === 0 ? t('extraDirs.tooltipEmpty') : t('extraDirs.tooltipCount', { count })}+ side="top"+ ><buttontype="button"disabled={disabled}- onClick={() => {- fileInputRef.current?.click();- setOpen(false);- }}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => onOpenChange(!open)}+ aria-expanded={open}+ aria-pressed={open}+ data-composer-suggestion-triggerclassName={cn(- 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',- 'transition-colors hover:bg-[var(--model-item-hover)]',+ 'flex h-[30px] shrink-0 items-center rounded-full border border-transparent',+ 'bg-transparent text-[var(--composer-pill-icon,#3C3F43)]',+ 'transition-colors 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',+ open &&+ 'border-[var(--border-default)] bg-[var(--composer-pill-bg,#FCFCFC)] dark:bg-[var(--composer-pill-bg,#393838)]',+ count > 0 && hasReferenceDirs+ ? 'min-w-max justify-center gap-1 px-2.5'+ : 'w-[30px] justify-center p-0',)}+ aria-label={t('extraDirs.menuAria')}>- <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>- {(onNewGoal || planMode || collaboration || plugins.length > 0 || hasReferenceDirs) && (- <div className="my-1 h-px bg-[var(--model-dropdown-border)]" />- )}- </>- )}-- {/* 新建目标(仅会话中;点击关菜单并由父组件打开 NewGoalDialog) */}- {onNewGoal && (- <button- type="button"- onClick={() => {- setOpen(false);- onNewGoal();- }}- className={cn(- 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',- 'transition-colors hover:bg-[var(--model-item-hover)]',- )}- >- <Target size={14} className="shrink-0 text-[var(--model-item-text)]" />- <span className="text-[13px] text-[var(--model-item-text)]">- {t('goal.newGoalMenuItem')}- </span>- </button>- )}-- {/* 计划模式 toggle(与「新建目标」同级):勾选态右侧打勾;点击切换并关菜单。 */}- {planMode && (- <button- type="button"- role="menuitemcheckbox"- aria-checked={planMode.enabled}- onClick={() => {- setOpen(false);- planMode.onToggle(!planMode.enabled);- }}- className={cn(- 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',- 'transition-colors hover:bg-[var(--model-item-hover)]',- )}- >- <ClipboardList size={14} className="shrink-0 text-[var(--model-item-text)]" />- <span className="min-w-0 flex-1 truncate text-left text-[13px] text-[var(--model-item-text)]">- {t('planMode.menuItem')}- </span>- {planMode.enabled && (- <Check size={13} className="shrink-0 text-[var(--model-item-check)]" />- )}- </button>- )}-- {/* 协同模式与目标/计划同级。开启态保留 Thinking Orange,右侧对勾表示当前状态。 */}- {collaboration && (- <Tip- text={collaborationPolicyDisabled ? collaboration.disabledReason : null}- side="right"- >- <span className="block">- <button- type="button"- role="menuitemcheckbox"- aria-checked={collaboration.enabled}- aria-label={collaborationAriaLabel}- aria-disabled={- collaborationPolicyDisabled && !collaborationRetryable ? true : undefined- }- disabled={disabled || (collaborationPolicyDisabled && !collaborationRetryable)}- onClick={handleCollaborationActivate}+ <Plus size={isCreateAgentVariant ? 11 : dense ? 14 : 14} className="shrink-0" />+ {count > 0 && hasReferenceDirs && (+ <spanclassName={cn(- 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2',- 'transition-colors hover:bg-[var(--model-item-hover)]',- collaboration.enabled && 'bg-[var(--model-item-hover)]',- (disabled || collaborationPolicyDisabled) && 'opacity-50',- (disabled || (collaborationPolicyDisabled && !collaborationRetryable)) &&- 'cursor-not-allowed',+ 'font-normal tabular-nums',+ dense ? 'text-[12.5px]' : 'text-[13px]',)}>- <UsersRound- size={14}- className={cn(- 'shrink-0',- collaboration.enabled- ? 'text-[var(--warning-accent)]'- : 'text-[var(--model-item-text)]',- )}- />- <span- className={cn(- 'min-w-0 flex-1 truncate text-left text-[13px]',- collaboration.enabled- ? 'font-medium text-[var(--warning-accent)]'- : 'text-[var(--model-item-text)]',- )}- >- {t('newChat.collaboration.modeLabel')}- </span>- {collaboration.enabled && (- <Check size={13} className="shrink-0 text-[var(--model-item-check)]" />- )}- </button>- </span>- </Tip>- )}-- {plugins.length > 0 && (- <>- {(onNewGoal || planMode || collaboration) && (- <div className="my-1 h-px bg-[var(--model-dropdown-border)]" />- )}- <div className="px-2 pb-1 pt-1 text-[12px] text-[var(--model-trigger-text)] opacity-70">- {t('extraDirs.pluginsTitle')}- </div>- <div- role="list"- aria-label={t('extraDirs.pluginsTitle')}- className="morph-panel-list-scroll plugin-motion-root -mr-2 max-h-[200px] overflow-y-auto [scrollbar-gutter:stable]"- >- {plugins.map((ghost) => {- const availableInScope = pluginAvailableIds- ? pluginAvailableIds.has(ghost.manifest.id)- : ghost.enabled;- const selectable = Boolean(- availableInScope && ghost.manifest.command && onPluginSelect,- );- return (- <button- key={ghost.manifest.id}- type="button"- disabled={!selectable}- onClick={() => {- setOpen(false);- onPluginSelect?.(ghost);- }}- className={cn(- 'flex w-full items-center gap-2 rounded-[8px] px-3 py-2 text-left',- 'transition-colors hover:bg-[var(--model-item-hover)]',- 'disabled:cursor-not-allowed disabled:opacity-45',- )}- >- <GhostPluginIcon- iconDataUrl={ghost.iconDataUrl}- iconId={ghost.manifest.id}- iconName={ghost.manifest.name}- size="menu"- />- <span className="min-w-0 flex-1 truncate text-left text-[13px] text-[var(--model-item-text)]">- {ghost.manifest.name}- </span>- {!selectable ? (- <span className="shrink-0 text-[12px] text-[var(--model-trigger-text)] opacity-70">- {t(- ghost.manifest.command- ? 'extraDirs.pluginDisabled'- : 'extraDirs.pluginNoCommand',- )}- </span>- ) : null}- </button>- );- })}- </div>- </>- )}-- {/* 引用目录段:Claude 与 Codex 共用;未接 onChange 时不暴露空操作入口。 */}- {hasReferenceDirs && (- <>- {(onNewGoal || planMode || collaboration || plugins.length > 0) && (- <div className="my-1 h-px bg-[var(--model-dropdown-border)]" />- )}-- <div className="px-2 pb-1 pt-1 text-[12px] text-[var(--model-trigger-text)] opacity-70">- {t('extraDirs.sectionTitle')}- </div>-- {count > 0 ? (- <div role="list" aria-label="Extra reference directories" className="mb-1">- {extraDirs.map((p) => (- <div- key={p}- className={cn(- 'group flex items-center gap-2 rounded-[8px] px-3 py-2',- 'hover:bg-[var(--model-item-hover)]',- )}- >- <FolderPlus- size={14}- className="shrink-0 text-[var(--model-item-text)] opacity-60"- />- <Tip text={p} mono side="top">- <span className="min-w-0 flex-1 truncate text-left text-[13px] text-[var(--model-item-text)]">- {basename(p)}- </span>- </Tip>- <button- type="button"- onClick={() => void handleRemove(p)}- className={cn(- 'rounded-full p-1 opacity-0 transition-opacity',- 'hover:bg-[var(--model-item-hover)]',- 'group-hover:opacity-70 hover:!opacity-100',- )}- aria-label={t('extraDirs.remove', { name: basename(p) })}- >- <X size={12} className="text-[var(--model-item-text)]" />- </button>- </div>- ))}- </div>- ) : (- <div className="px-3 py-2 text-[12px] text-[var(--model-item-text)] opacity-50">- {t('extraDirs.empty')}- </div>- )}-- <button- type="button"- onClick={() => void handleAdd()}- disabled={atLimit}- className={cn(- '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',- )}- >- <FolderPlus size={14} className="shrink-0 text-[var(--model-item-text)]" />- <span className="text-[13px] text-[var(--model-item-text)]">- {atLimit ? t('extraDirs.atLimit', { max: MAX_EXTRA_DIRS }) : t('extraDirs.add')}+ ×{count}</span>- </button>- </>- )}+ )}+ </button>+ </Tip>+ }+ >+ {panel}</MorphPopover>);}diff --git a/apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts b/apps/desktop/src/renderer/components/new-chat/extraDirsActions.tsnew file mode 100644index 0000000000..162c671aeb--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts@@ -0,0 +1,130 @@+/**+ * 引用目录(extra dirs)增删逻辑 —— 从旧 ExtraDirsButton 菜单中抽出,供统一+ * composer 建议面板的「添加目录…」动作与目录列表行复用。+ *+ * 校验:选中路径与 workingDir 重叠时:子目录静默去重;父目录弹 confirm。+ * main 端 extraDirsValidator.ts 兜底 — 这里只做 UX 预判。+ */++import { createLogger } from '@/lib/logger';+import { stripTrailingPathSeparators } from '../../../shared/pathText';+import { normalizeWorkingDirForStorage } from '../../../shared/workingDir';++const log = createLogger('ExtraDirsActions');++/** 与 main 端 EXTRA_DIRS_MAX 保持一致;UI 满了 disable 添加入口。 */+export const MAX_EXTRA_DIRS = 10;++function normalizedPathForComparison(raw: string | null | undefined): string | null {+ const normalized = normalizeWorkingDirForStorage(raw);+ return normalized ? stripTrailingPathSeparators(normalized) : null;+}++/**+ * 判断 candidate 是否是 base 自身或子目录(简单字符串前缀,跨平台够用 —— main 端+ * extraDirsValidator 用 path.relative 做权威判定)。+ */+function isSelfOrSubdir(candidate: string, base: string): boolean {+ const c = normalizedPathForComparison(candidate);+ const b = normalizedPathForComparison(base);+ if (!c || !b) return false;+ if (c === b) return true;+ return c.startsWith(b + '/');+}++function isSameStoragePath(a: string, b: string): boolean {+ const normalizedA = normalizedPathForComparison(a);+ const normalizedB = normalizedPathForComparison(b);+ return !!normalizedA && !!normalizedB && normalizedA === normalizedB;+}++function hasExtraDir(extraDirs: readonly string[], candidate: string): boolean {+ return extraDirs.some((existing) => isSameStoragePath(existing, candidate));+}++/** candidate 是 base 父目录或祖先(反过来:base 是 candidate 的子目录)。 */+function isParentOrAncestor(candidate: string, base: string): boolean {+ const c = normalizedPathForComparison(candidate);+ const b = normalizedPathForComparison(base);+ if (!c || !b || c === b) return false;+ return isSelfOrSubdir(b, c);+}++export const __extraDirsPathOverlapForTesting = {+ hasExtraDir,+ isParentOrAncestor,+ isSelfOrSubdir,+};++/** 取目录名做行内显示;空回 '/' 。 */+export function extraDirBasename(p: string): string {+ const stripped = stripTrailingPathSeparators(p);+ const parts = stripped.split(/[\\/]/);+ return parts[parts.length - 1] || stripped || '/';+}++export interface PickAndAddExtraDirOptions {+ extraDirs: readonly string[];+ workingDir?: string | null;+ onChange: (next: string[]) => void | Promise<void>;+ /** ConfirmDialogProvider 的 confirm(父目录警告)。 */+ confirm: (opts: {+ title: string;+ description: string;+ confirmText: string;+ cancelText: string;+ }) => Promise<boolean>;+ parentDirectoryConfirm: {+ title: string;+ description: (path: string) => string;+ confirmText: string;+ cancelText: string;+ };+}++/**+ * 打开系统目录选择器并把结果并入 extraDirs(带 UX 预判)。+ * 上限判断由调用方负责(达到 MAX_EXTRA_DIRS 时入口应 disabled)。+ */+export async function pickAndAddExtraDir({+ extraDirs,+ workingDir,+ onChange,+ confirm,+ parentDirectoryConfirm,+}: PickAndAddExtraDirOptions): Promise<void> {+ if (extraDirs.length >= MAX_EXTRA_DIRS) return;+ let picked: string | null = null;+ try {+ const r = await window.electronAPI.dialog.showOpenDirectory({});+ picked = r?.success ? r.path : null;+ } catch (e) {+ log.warn('showOpenDirectory failed', { error: String(e) });+ return;+ }+ const normalizedPicked = normalizeWorkingDirForStorage(picked);+ if (!normalizedPicked) return;++ // UX 预判: 完全重复 / 是 workingDir 子目录 → 静默忽略(main validator 也会兜)。+ if (hasExtraDir(extraDirs, normalizedPicked)) return;+ if (workingDir && isSelfOrSubdir(normalizedPicked, workingDir)) {+ log.debug('add: silently skipped (subdir of workingDir)', {+ picked: normalizedPicked,+ workingDir,+ });+ return;+ }++ // 父目录 / 祖先警告 — 通过则继续。+ if (workingDir && isParentOrAncestor(normalizedPicked, workingDir)) {+ const ok = await confirm({+ title: parentDirectoryConfirm.title,+ description: parentDirectoryConfirm.description(normalizedPicked),+ confirmText: parentDirectoryConfirm.confirmText,+ cancelText: parentDirectoryConfirm.cancelText,+ });+ if (!ok) return;+ }++ await onChange([...extraDirs, normalizedPicked]);+}diff --git a/apps/desktop/src/renderer/components/ui/morph-popover.tsx b/apps/desktop/src/renderer/components/ui/morph-popover.tsxindex 3463e1f9f5..1fc382e2cc 100644--- a/apps/desktop/src/renderer/components/ui/morph-popover.tsx+++ b/apps/desktop/src/renderer/components/ui/morph-popover.tsx@@ -111,6 +111,8 @@ interface MorphPopoverProps {wrapperClassName?: string;/** 面板 aria-label(容器为 group 语义时可选)。 */panelAriaLabel?: string;+ /** 打开完成后的外部焦点目标;未提供时按面板内默认规则聚焦。 */+ autoFocusTarget?: () => HTMLElement | null;}/** 是否处于 reduced-motion(SSR/jsdom 无 matchMedia 时按 false) */@@ -137,6 +139,7 @@ export function MorphPopover({panelClassName,wrapperClassName,panelAriaLabel,+ autoFocusTarget,}: MorphPopoverProps) {// mounted 独立于 open:关闭时先播收合动画,动画完再卸载 portalconst [mounted, setMounted] = useState(false);@@ -321,6 +324,7 @@ export function MorphPopover({// (异步 capability / provider 列表在开场动画内返回时防面板卡旧尺寸)。syncPanelToContent();const target =+ autoFocusTarget?.() ??panel.querySelector<HTMLElement>('[data-morph-autofocus]:not([disabled])') ??panel.querySelector<HTMLElement>('input, textarea') ??panel.querySelector<HTMLElement>(@@ -394,7 +398,17 @@ export function MorphPopover({if (openRaf1Ref.current !== null) cancelAnimationFrame(openRaf1Ref.current);if (openRaf2Ref.current !== null) cancelAnimationFrame(openRaf2Ref.current);};- }, [mounted, open, measure, applyChipGeometry, dockedAnchor, endBg, endBorderColor, syncPanelToContent]);+ }, [+ mounted,+ open,+ measure,+ applyChipGeometry,+ dockedAnchor,+ endBg,+ endBorderColor,+ syncPanelToContent,+ autoFocusTarget,+ ]);/** 打开稳定后跟随内容尺寸变化(搜索过滤 / Edit 面板展宽),同曲线平滑过渡 */useEffect(() => {@@ -423,12 +437,22 @@ export function MorphPopover({/** 打开期间的全局关闭手势:outside pointerdown / Esc(分层) / 窗口 resize */useEffect(() => {if (!mounted || !open) return;+ const isWithinExternalFocusTarget = (target: Node): boolean => {+ const externalFocusTarget = autoFocusTarget?.();+ return Boolean(+ externalFocusTarget &&+ (externalFocusTarget === target || externalFocusTarget.contains(target)),+ );+ };const onPointerDown = (e: PointerEvent) => {const t = e.target as Node;if (panelRef.current?.contains(t) || wrapRef.current?.contains(t)) return;// 面板内容可能再弹 Radix 浮层(portal 到 body,如模型行的 effort/Fast 配置// 子面板)——点它不算 outside,否则子面板永远点不了(整个面板会先被关掉)if ((t as Element).closest?.('[data-radix-popper-content-wrapper]')) return;+ // autoFocusTarget 是当前交互层的一部分(例如统一建议面板外的 composer)。+ // 指针在该目标内调整光标时也不应按 outside pointerdown 收起。+ if (isWithinExternalFocusTarget(t)) return;// outside pointerdown 也是鼠标关闭。目标控件可能 preventDefault 阻止默认聚焦// (如 AgentSelect 为维持 composer focus-within),不能因此把旧层误判成键盘关闭、// 在收合结束后延迟抢回旧 trigger 焦点并关掉刚打开的相邻弹层。@@ -454,6 +478,10 @@ export function MorphPopover({if (!(target instanceof Node) || target === document.body) return;if (panelRef.current?.contains(target) || wrapRef.current?.contains(target)) return;if ((target as Element).closest?.('[data-radix-popper-content-wrapper]')) return;+ // 某些 MorphPopover(如 composer 的统一建议面板)有意把焦点留在+ // 面板外的编辑器上,以便打开后直接输入筛选。这个显式目标仍属于当前+ // 交互层,不能被“焦点离开即关闭”误判;其它外部焦点照常关闭。+ if (isWithinExternalFocusTarget(target)) return;requestClose();};const onResize = () => requestClose();@@ -467,7 +495,7 @@ export function MorphPopover({document.removeEventListener('focusin', onFocusIn, true);window.removeEventListener('resize', onResize);};- }, [mounted, open, requestClose]);+ }, [autoFocusTarget, mounted, open, requestClose]);return (<>diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 9caae34bc7..10167a0ab1 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -8629,7 +8629,11 @@"empty": "No reference directories yet","add": "Add directory…","atLimit": "Limit reached ({{max}})",- "remove": "Remove {{name}}"+ "remove": "Remove {{name}}",+ "parentConfirmTitle": "Add a parent directory?",+ "parentConfirmDescription": "The selected directory is a parent or ancestor of the current working directory. This expands the Agent's visible scope beyond the working directory.\n\nAdd it anyway?\n\n{{path}}",+ "parentConfirmAccept": "Add anyway",+ "parentConfirmCancel": "Cancel"},"commands": {"toast": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex acfe4a7b01..a7c2f3cec7 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -8615,7 +8615,11 @@"empty": "参照ディレクトリはまだありません","add": "ディレクトリを追加…","atLimit": "上限 {{max}} 件に達しました",- "remove": "{{name}} を削除"+ "remove": "{{name}} を削除",+ "parentConfirmTitle": "親ディレクトリを追加しますか?",+ "parentConfirmDescription": "選択したディレクトリは、現在の作業ディレクトリの親または祖先です。Agent が作業ディレクトリ外の内容も参照できるようになり、表示範囲が広がります。\n\nそれでも追加しますか?\n\n{{path}}",+ "parentConfirmAccept": "追加する",+ "parentConfirmCancel": "キャンセル"},"commands": {"toast": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 51e919ca70..7231590a3b 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -8615,7 +8615,11 @@"empty": "아직 참조 디렉터리가 없습니다","add": "디렉터리 추가…","atLimit": "최대 {{max}}개 도달",- "remove": "{{name}} 제거"+ "remove": "{{name}} 제거",+ "parentConfirmTitle": "상위 디렉터리를 추가할까요?",+ "parentConfirmDescription": "선택한 디렉터리는 현재 작업 디렉터리의 상위 또는 조상 디렉터리입니다. Agent가 작업 디렉터리 밖의 내용까지 볼 수 있어 표시 범위가 넓어집니다.\n\n그래도 추가할까요?\n\n{{path}}",+ "parentConfirmAccept": "그래도 추가",+ "parentConfirmCancel": "취소"},"commands": {"toast": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex ca2dba3dbd..ea0ad70fb9 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -8615,7 +8615,11 @@"empty": "还没有引用目录","add": "添加目录…","atLimit": "已达上限 {{max}} 个",- "remove": "移除 {{name}}"+ "remove": "移除 {{name}}",+ "parentConfirmTitle": "添加父目录?",+ "parentConfirmDescription": "选中的目录是当前工作目录的父级或祖先。这会扩大 Agent 的可见范围,使其能看到工作目录之外的内容。\n\n仍要添加吗?\n\n{{path}}",+ "parentConfirmAccept": "仍然添加",+ "parentConfirmCancel": "取消"},"commands": {"toast": {diff --git a/apps/desktop/src/renderer/lib/atResourceService.ts b/apps/desktop/src/renderer/lib/atResourceService.tsindex 026e954027..a61c541a1c 100644--- a/apps/desktop/src/renderer/lib/atResourceService.ts+++ b/apps/desktop/src/renderer/lib/atResourceService.ts@@ -517,6 +517,10 @@ export async function scanAtResources(** Length tiebreak: shorter names score slightly higher (closer to prefix).*/+export function scoreAtResourceItem(item: AtResourceItem, q: string): number {+ return scoreItem(item, q);+}+function scoreItem(item: AtResourceItem, q: string): number {if (!q) return 1; // empty query = everything matches with baseline scoreconst name = item._nameLower ?? item.name.toLowerCase();diff --git a/apps/desktop/src/renderer/lib/composerSuggestion.ts b/apps/desktop/src/renderer/lib/composerSuggestion.tsnew file mode 100644index 0000000000..cde2b26b4d--- /dev/null+++ b/apps/desktop/src/renderer/lib/composerSuggestion.ts@@ -0,0 +1,221 @@+import {+ AT_MENTION_SEARCH_RESULT_LIMIT,+ scoreAtResourceItem,+ type AtResourceItem,+} from './atResourceService';++/**+ * Unified composer suggestion layer — the union of the legacy `@` mention+ * panel (resources) and the legacy `+` MorphPopover menu (actions).+ *+ * Following Codex Desktop's pattern, the `+` button synthetically opens the+ * same panel that typing `@` opens; action rows (attach files, new goal,+ * plan mode, collaboration, add reference directory) live in the same list+ * as scanned resources and are filtered by the same query.+ *+ * Pure TS, no React. ChatInput assembles the inputs; AtMentionPanel renders+ * the resulting entry list. Keyboard focus indexes into the returned array,+ * so the assembly order here IS the visual order.+ */++export type ComposerSuggestionActionId =+ | 'attach-files'+ | 'new-goal'+ | 'plan-mode'+ | 'collaboration'+ | 'add-extra-dir';++export interface ComposerSuggestionAction {+ id: ComposerSuggestionActionId;+ /** Resolved display label (already i18n'd) — also the query match target. */+ label: string;+ /** Extra text matched by the query besides the label (e.g. English alias). */+ searchText?: string;+ /** menuitemcheckbox state (plan mode / collaboration). Absent = plain action. */+ checked?: boolean;+ disabled?: boolean;+ /** Shown as a row tooltip when the action is disabled (e.g. collab policy). */+ disabledReason?: string;+ run: () => void;+}++export type ComposerSuggestionEntry =+ | {+ kind: 'resource';+ item: AtResourceItem;+ /** Plugin rows without a usable command stay visible but unselectable. */+ disabled?: boolean;+ disabledReason?: string;+ }+ | { kind: 'action'; action: ComposerSuggestionAction };++/** Plugin rows carry entry-level availability on top of the resource item. */+export interface ComposerPluginSuggestion {+ item: AtResourceItem;+ disabled?: boolean;+ disabledReason?: string;+}++export type ComposerAtActivation =+ | { activation: 'typed'; from: number; query: string }+ | { activation: 'synthetic'; from: number; query: string };++/**+ * Resolve the shared panel activation. A synthetic `+` open is explicit and+ * therefore owns the panel until its anchor becomes invalid, even when text+ * before the caret still happens to match a typed `@` run.+ */+export function resolveComposerAtActivation({+ typed,+ syntheticAnchor,+ syntheticQuery,+}: {+ typed: { from: number; query: string } | null;+ syntheticAnchor: number | null;+ syntheticQuery: string | null;+}): ComposerAtActivation | null {+ if (syntheticAnchor !== null && syntheticQuery !== null) {+ return { activation: 'synthetic', from: syntheticAnchor, query: syntheticQuery };+ }+ return typed ? { activation: 'typed', ...typed } : null;+}++/** Per-section caps on the empty-query view (tabs / agents only — plugins+ * render in full like the legacy `+` menu did; the panel scrolls). */+export const EMPTY_QUERY_CONTEXT_SECTION_LIMIT = 3;++export function composerSuggestionEntryKey(entry: ComposerSuggestionEntry): string {+ return entry.kind === 'action'+ ? `action:${entry.action.id}`+ : `resource:${entry.item.type}:${entry.item.pluginId ?? ''}:${entry.item.relPath}`;+}++export function isComposerSuggestionEntryDisabled(entry: ComposerSuggestionEntry): boolean {+ return entry.kind === 'action' ? entry.action.disabled === true : entry.disabled === true;+}++/**+ * Move focus by `delta` (+1 / -1) with wraparound, skipping disabled entries.+ * Returns `current` unchanged when every entry is disabled or the list is empty.+ */+export function nextEnabledSuggestionIndex(+ entries: readonly ComposerSuggestionEntry[],+ current: number,+ delta: 1 | -1,+): number {+ if (entries.length === 0) return current;+ let i = current;+ for (let step = 0; step < entries.length; step++) {+ i = (i + delta + entries.length) % entries.length;+ if (!isComposerSuggestionEntryDisabled(entries[i])) return i;+ }+ return current;+}++/** First enabled index, or 0 when nothing is enabled/present. */+export function firstEnabledSuggestionIndex(+ entries: readonly ComposerSuggestionEntry[],+): number {+ const idx = entries.findIndex((entry) => !isComposerSuggestionEntryDisabled(entry));+ return idx >= 0 ? idx : 0;+}++function scoreAction(action: ComposerSuggestionAction, q: string): number {+ // Reuse the resource scorer verbatim so actions and resources rank in one+ // comparable pool (label ≙ name, searchText ≙ relPath).+ return scoreAtResourceItem(+ {+ type: 'file',+ name: action.label,+ relPath: action.searchText ?? '',+ _nameLower: action.label.toLowerCase(),+ _relPathLower: (action.searchText ?? '').toLowerCase(),+ },+ q,+ );+}++interface BuildComposerSuggestionEntriesInput {+ /** Trimmed-or-not raw query; empty string = curated sections view. */+ query: string;+ /** Ordered action list assembled by ChatInput (attach → goal → plan → collab → add-dir). */+ actions: readonly ComposerSuggestionAction[];+ /** Scanned mention resources (workspace/context/task/plugin resources). */+ resources: readonly AtResourceItem[];+ /** Installed plugins incl. unavailable ones (disabled rows, `+`-menu parity). */+ plugins: readonly ComposerPluginSuggestion[];+}++/**+ * Empty query — curated sections, in visual order:+ * 1. attach-files action+ * 2. remaining actions except add-extra-dir (goal / plan mode / collaboration)+ * 3. browser tabs (≤3), agents (≤3)+ * 4. all plugins (unavailable ones disabled)+ * 5. add-extra-dir action (rendered under the reference-dirs section)+ *+ * Non-empty query — one flat pool ranked by the shared scorer, capped to+ * `AT_MENTION_SEARCH_RESULT_LIMIT`. Disabled plugins are excluded from search+ * results; workspace files/directories are searched directly.+ */+export function buildComposerSuggestionEntries(+ input: BuildComposerSuggestionEntriesInput,+): ComposerSuggestionEntry[] {+ const q = input.query.trim().toLowerCase();+ if (!q) {+ const entries: ComposerSuggestionEntry[] = [];+ const attach = input.actions.find((a) => a.id === 'attach-files');+ if (attach) entries.push({ kind: 'action', action: attach });+ for (const action of input.actions) {+ if (action.id === 'attach-files' || action.id === 'add-extra-dir') continue;+ entries.push({ kind: 'action', action });+ }+ for (const type of ['browser-tab', 'agent'] as const) {+ let count = 0;+ for (const item of input.resources) {+ if (item.type !== type) continue;+ entries.push({ kind: 'resource', item });+ count += 1;+ if (count >= EMPTY_QUERY_CONTEXT_SECTION_LIMIT) break;+ }+ }+ for (const plugin of input.plugins) {+ entries.push({+ kind: 'resource',+ item: plugin.item,+ ...(plugin.disabled ? { disabled: true } : {}),+ ...(plugin.disabledReason ? { disabledReason: plugin.disabledReason } : {}),+ });+ }+ const addDir = input.actions.find((a) => a.id === 'add-extra-dir');+ if (addDir) entries.push({ kind: 'action', action: addDir });+ return entries;+ }++ const scored: Array<{ entry: ComposerSuggestionEntry; score: number; label: string }> = [];+ for (const action of input.actions) {+ if (action.disabled) continue;+ const s = scoreAction(action, q);+ if (s >= 0) scored.push({ entry: { kind: 'action', action }, score: s, label: action.label });+ }+ for (const item of input.resources) {+ const s = scoreAtResourceItem(item, q);+ if (s >= 0) scored.push({ entry: { kind: 'resource', item }, score: s, label: item.name });+ }+ for (const plugin of input.plugins) {+ if (plugin.disabled) continue;+ const s = scoreAtResourceItem(plugin.item, q);+ if (s >= 0) {+ scored.push({+ entry: { kind: 'resource', item: plugin.item },+ score: s,+ label: plugin.item.name,+ });+ }+ }+ scored.sort((a, b) => b.score - a.score || a.label.localeCompare(b.label));+ if (scored.length > AT_MENTION_SEARCH_RESULT_LIMIT) {+ scored.length = AT_MENTION_SEARCH_RESULT_LIMIT;+ }+ return scored.map((s) => s.entry);+}