Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
test(desktop): preserve historical interaction regressions
MagicLizi968677d3b720
diff --git a/apps/desktop/src/main/__tests__/directSessionSendGuard.test.ts b/apps/desktop/src/main/__tests__/directSessionSendGuard.test.tsindex e71d1a2d09..b5aabf8af0 100644--- a/apps/desktop/src/main/__tests__/directSessionSendGuard.test.ts+++ b/apps/desktop/src/main/__tests__/directSessionSendGuard.test.ts@@ -423,6 +423,9 @@ function createProgramWithSources(noResolve: true,};const defaultHost = ts.createCompilerHost(options, true);+ // This guard needs receiver type information, not JSDoc diagnostics. Let+ // TypeScript skip comment ASTs while preserving type info and every root.+ defaultHost.jsDocParsingMode = ts.JSDocParsingMode.ParseForTypeInfo;const originalFileExists = defaultHost.fileExists.bind(defaultHost);const originalReadFile = defaultHost.readFile.bind(defaultHost);const originalGetSourceFile = defaultHost.getSourceFile.bind(defaultHost);diff --git a/apps/desktop/src/renderer/__tests__/botGroupLampRendering.test.tsx b/apps/desktop/src/renderer/__tests__/botGroupLampRendering.test.tsxindex e26f75725f..0bb7271e9e 100644--- a/apps/desktop/src/renderer/__tests__/botGroupLampRendering.test.tsx+++ b/apps/desktop/src/renderer/__tests__/botGroupLampRendering.test.tsx@@ -1,6 +1,7 @@// @vitest-environment jsdomimport type { ReactNode } from 'react';+import Sortable, { type SortableEvent } from 'sortablejs';import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getStartingSessionIds, markSessionStarting, resetSessionStartingStoreForTests, useStartingSessionIds } from '@/lib/sessionStartingStore';@@ -23,7 +24,6 @@ vi.mock('../features/cc-agent/hooks/useRemoteHostProjectOrders', () => ({useRemoteHostProjectOrders: () => ({ orders: new Map() }),}));vi.mock('../features/cc-agent/sidebar/MainListScopeHeader', () => ({ MainListScopeHeader: ({ fold }: { fold: { label: string; onClick: () => void } | null }) => fold ? <button onClick={fold.onClick}>{fold.label}</button> : null }));-vi.mock('@/components/sidebar/SortableList', () => ({ SortableList: () => null }));// main 633e27c76 起设备段头包了远程桌面快捷入口(挂 device-link presence 订阅,需要// preload 桥);本文件只验证段头灯语与折叠豁免,段头壳层直接透传子节点。vi.mock('../features/cc-agent/sidebar/DeviceSectionHeader', () => ({@@ -84,6 +84,48 @@ function activity(phase: typeof phases[number]) {applyRemoteSessionActivity('remote', { sessionId: 'lit', phase, attention: true, compactDetail: '' });}+// PR #6196 / manualProjectSortDrag: the historical handle/filter overlap made+// every project header reject drag start. Existing lamp tests use activity order,+// so they never mount SortableList. Reuse this real ProjectsSection/ProjectNode+// unit harness with two projects in custom order; selectors come from the actual+// SortableJS instance, and its real onEnd must persist the reordered projects.+describe('Manual project sorting', () => {+ it('leaves the real project header draggable and persists a completed reorder', () => {+ const p = props(false);+ p.bots = [];+ p.projects = ['First', 'Second'].map((name) => ({+ projectKey: 'local:/' + name, workingDir: '/' + name, displayName: name,+ scope: 'local', sessions: [], segments: 1, latestActivityAt: '2026-09-03T00:00:00Z',+ remoteHostId: null, deviceLinkDeviceId: null,+ deviceLinkDeviceName: null, deviceLinkConnectionStatus: null,+ }));+ p.allProjectKeysForOrder = p.projects.map((project) => project.projectKey);+ p.filter.projectOrder = 'custom';+ p.filter.manualProjectOrder = [...p.allProjectKeysForOrder];+ render(<ProjectsSection {...p} />);++ const header = screen.getByText('First').closest<HTMLElement>('[data-project-header]')!;+ const moved = header.closest<HTMLElement>('[data-sortable-id]')!;+ const list = moved.parentElement!;+ const sortable = Sortable.get(list)!;+ expect(sortable.option('disabled')).toBe(false);+ expect(header.matches(sortable.option('handle') as string)).toBe(true);+ expect(header.closest(sortable.option('filter') as string)).toBeNull();++ // Sortable owns pointer geometry; replay its drop boundary against the real+ // list and DOM move rather than copying its reorder or persistence logic.+ list.append(moved);+ act(() => {+ sortable.option('onEnd')!.call(sortable, Object.assign(new Event('end'), {+ item: moved, from: list, oldIndex: 0, newIndex: 1,+ }) as SortableEvent);+ });+ expect(p.filter.setManualProjectOrder).toHaveBeenCalledWith(+ ['local:/Second', 'local:/First'], p.allProjectKeysForOrder,+ );+ });+});+describe.each([false, true])('Bot groups with device grouping %s', (groupDevice) => {it.each(phases)('renders the collapsed Bot header lamp for remote %s', (phase) => {activity(phase);diff --git a/apps/desktop/src/renderer/__tests__/chatMediaLightboxFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatMediaLightboxFocus.test.tsindex d598e4b799..0c70a1fcc6 100644--- a/apps/desktop/src/renderer/__tests__/chatMediaLightboxFocus.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatMediaLightboxFocus.test.ts@@ -8,8 +8,8 @@* 关闭后回到预览触发器。图片路径同时保留 gallery 定位标记的既有断言。*/import React from 'react';-import { describe, expect, it, vi } from 'vitest';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string, fallback?: string) => fallback ?? key }),@@ -18,10 +18,36 @@ vi.mock('react-i18next', () => ({vi.mock('@/hooks/useRemoteMediaUrl', () => ({useRemoteMediaUrl: (url: string) => url,}));+vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn() } }));import { ChatImageView } from '../components/chat/ChatImageView';+import { ModelLightbox } from '../components/chat/ModelLightbox';+import { toast } from '@/lib/toast';++afterEach(() => { cleanup(); vi.useRealTimers(); vi.clearAllMocks(); });describe('ChatImageView 键盘交互(真实 ImageLightbox / ModelLightbox)', () => {+ // ModelLightbox's 2026-06 scheme regression: the custom element reports a+ // parse/load error, but its poster must stay usable and the user gets a+ // toast. Existing focus tests never dispatch that event. Reuse the real+ // lightbox unit harness, with fake time to detect delayed unwanted closure.+ it('reports a model load error and keeps the preview open', async () => {+ vi.useFakeTimers();+ const onClose = vi.fn();+ const url = 'cindy-media://blobs/' + 'f'.repeat(64) + '.glb';+ render(React.createElement(ModelLightbox, { source: { kind: 'blob', url }, onClose }));+ const viewer = document.body.querySelector('model-viewer')!;+ expect(viewer).not.toBeNull();+ await act(async () => {+ fireEvent.error(viewer);+ await vi.advanceTimersByTimeAsync(300);+ });+ expect(toast.error).toHaveBeenCalledExactlyOnceWith('Failed to load 3D model');+ expect(onClose).not.toHaveBeenCalled();+ expect(viewer.isConnected).toBe(true);+ expect(viewer.getAttribute('src')).toBe(url);+ });+it('Enter 打开图片预览:焦点进入 lightbox,Esc 延迟关闭后回到触发器', async () => {render(React.createElement(ChatImageView, {diff --git a/apps/desktop/src/renderer/__tests__/fileBodySelectionQuote.test.ts b/apps/desktop/src/renderer/__tests__/fileBodySelectionQuote.test.tsnew file mode 100644index 0000000000..047625a311--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/fileBodySelectionQuote.test.ts@@ -0,0 +1,122 @@+// @vitest-environment jsdom++import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { createElement } from 'react';+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { EditorView } from '@codemirror/view';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { FileBodyView } from '@/features/cc-agent/workdir-browse/FileBodyView';+import { clearDraft, getDraft } from '@/lib/composerDraftStore';++vi.mock('react-i18next', () => {+ const t = (key: string) => key;+ return { useTranslation: () => ({ t, i18n: { language: 'en' } }) };+});+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));+// These media/host branches do not participate in text selection or quoting.+vi.mock('@/components/markdown/MermaidLightboxHost', () => ({ MermaidLightboxHost: () => null }));+vi.mock('@/components/markdown/MermaidSourceEditor', () => ({ MermaidSourceEditorHost: () => null }));+vi.mock('@/components/markdown/MarkdownImageLightboxHost', () => ({ MarkdownImageLightboxHost: () => null }));+vi.mock('@/features/cc-agent/workdir-browse/ImagePreview', () => ({ ImagePreview: () => null }));+vi.mock('@/features/cc-agent/workdir-browse/PdfPreview', () => ({ PdfPreview: () => null }));+vi.mock('@/features/cc-agent/workdir-browse/DrawioPreview', () => ({ DrawioPreview: () => null }));+vi.mock('@/lib/fileBrowserTransport', () => ({ fileBrowserApiFor: () => ({}) }));++const sessionId = 'file-body-selection-quote';+const workdir = resolve(tmpdir(), 'cindy-file-body-selection-quote');+const rect = new DOMRect(120, 100, 160, 20);+const rangeDescriptors = {+ getClientRects: Object.getOwnPropertyDescriptor(Range.prototype, 'getClientRects'),+ getBoundingClientRect: Object.getOwnPropertyDescriptor(Range.prototype, 'getBoundingClientRect'),+};++beforeEach(() => {+ vi.useFakeTimers({ toFake: ['requestAnimationFrame', 'cancelAnimationFrame'] });+ vi.stubGlobal('electronAPI', {+ onSelectionContextMenuAddToChat: () => () => {},+ });+ // jsdom has real ranges/selections but no layout. Supply geometry only;+ // neither CodeMirror's selection state nor DOM selection text is mocked.+ Object.defineProperty(Range.prototype, 'getClientRects', {+ configurable: true, value: () => [rect],+ });+ Object.defineProperty(Range.prototype, 'getBoundingClientRect', {+ configurable: true, value: () => rect,+ });+});++afterEach(() => {+ cleanup();+ clearDraft(sessionId);+ window.getSelection()?.removeAllRanges();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ for (const [key, descriptor] of Object.entries(rangeDescriptors)) {+ if (descriptor) Object.defineProperty(Range.prototype, key, descriptor);+ else Reflect.deleteProperty(Range.prototype, key);+ }+});++// PR #6196 discussion_r4293711863 / engineering-conventions §3.2: the former+// source scan could not detect DOM text replacing the selected document slice.+// chatQuotes and selectionQuoteUserMessage cover formatting/message ownership,+// not FileBodyView -> real CodeMirror -> quote action -> composer draft. Restore+// this module's original unit file because it owns an editor/DOM lifecycle absent+// from those helper tests. Minimal input: one rendered Markdown table whose DOM+// text differs from its selected source, followed by one Add to chat click.+describe('FileBodyView selection quotes', () => {+ it('adds the CodeMirror source slice, path and line range instead of rendered widget text', () => {+ const tableSource = '| Name | Value |\n| --- | --- |\n| Ada | 1 |';+ const source = '# Notes\n\n' + tableSource + '\n\nAfter';+ const { container } = render(createElement(FileBodyView, {+ workdir,+ sessionId,+ relPath: 'notes.md',+ content: {+ kind: 'text', relPath: 'notes.md', content: source,+ size: source.length, mtimeMs: 0, truncated: false,+ },+ }));+ const editor = container.querySelector<HTMLElement>('.cm-editor')!;+ const view = EditorView.findFromDOM(editor)!;+ const table = screen.getByRole('table');+ const from = source.indexOf(tableSource);+ act(() => {+ view.focus();+ view.dispatch({ selection: { anchor: from, head: from + tableSource.length } });+ // Settle CodeMirror's own DOM selection write before selecting its widget.+ vi.advanceTimersByTime(32);+ });++ const domRange = document.createRange();+ domRange.selectNodeContents(table);+ const selection = window.getSelection()!;+ selection.removeAllRanges();+ selection.addRange(domRange);+ expect(view.hasFocus).toBe(true);+ expect(view.state.selection.main.empty).toBe(false);+ expect(selection.toString()).toContain('Ada');+ expect(selection.toString()).not.toBe(tableSource);++ fireEvent.mouseUp(table);+ act(() => { vi.advanceTimersByTime(16); });+ expect(selection.isCollapsed).toBe(false);+ expect(view.hasFocus).toBe(true);+ expect(view.state.selection.main.empty).toBe(false);+ expect(selection.toString()).not.toBe(tableSource);+ const quoteButton = screen.getByRole('button', { name: 'chat.quote.addToChat' });+ fireEvent.mouseDown(quoteButton);+ fireEvent.click(quoteButton);++ expect(getDraft(sessionId)?.text?.content?.[0]?.content).toEqual([+ {+ type: 'composerQuote',+ attrs: { text: tableSource, sourcePath: 'notes.md', startLine: 3, endLine: 5 },+ },+ ]);+ expect(selection.isCollapsed).toBe(true);+ expect(screen.queryByRole('button', { name: 'chat.quote.addToChat' })).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorCustomProviderCodexGate.test.tsx b/apps/desktop/src/renderer/__tests__/modelSelectorCustomProviderCodexGate.test.tsxindex ade471014a..25f8ad7f8f 100644--- a/apps/desktop/src/renderer/__tests__/modelSelectorCustomProviderCodexGate.test.tsx+++ b/apps/desktop/src/renderer/__tests__/modelSelectorCustomProviderCodexGate.test.tsx@@ -8,7 +8,7 @@* 不得因缺少 Cindy AI 网关 key 被置灰。*/-import { act, fireEvent, render, screen, within } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';import React from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -164,6 +164,7 @@ vi.mock('@/state/deviceLinkModelMirror', () => ({}));import { ModelSelector } from '@/components/new-chat/ModelSelector';+import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';const requestProviderModelsAutoRefresh = vi.fn(async () => ({ ok: true as const }));@@ -175,18 +176,22 @@ beforeEach(() => {};});-function renderSelector(props: Partial<React.ComponentProps<typeof ModelSelector>> = {}) {+function renderSelector(+ props: Partial<React.ComponentProps<typeof ModelSelector>> = {},+ withConfirmDialog = false,+) {+ const selector = React.createElement(ModelSelector, {+ modelId: 'codex/gpt-5.5',+ effort: 'high',+ onModelChange: vi.fn(),+ onEffortChange: vi.fn(),+ vendorKey: 'codex',+ currentProviderId: 'xd',+ onProviderChange: vi.fn(),+ ...props,+ });return render(- React.createElement(ModelSelector, {- modelId: 'codex/gpt-5.5',- effort: 'high',- onModelChange: vi.fn(),- onEffortChange: vi.fn(),- vendorKey: 'codex',- currentProviderId: 'xd',- onProviderChange: vi.fn(),- ...props,- }),+ withConfirmDialog ? <ConfirmDialogProvider>{selector}</ConfirmDialogProvider> : selector,);}@@ -219,3 +224,71 @@ describe('ModelSelector codex/ key gate scope (#1568)', () => {expect(gatewayRow?.getAttribute('aria-disabled')).toBe('true');});});++// Production entry/result: a real ModelSelector and ConfirmDialogProvider route+// a requires_payment row to billing only after the user's confirmation.+// Historical bug: modelSelectorPaymentNavigation used to guard the HashRouter+// boundary: pushState(pathname) does not make the Desktop hash router navigate.+// Coverage gap: UnifiedModelPanel tests stop at onPaymentRequired; the removed+// source test never clicked the confirmation or observed the resulting URL.+// Minimal input: one paid model, cancel once, then accept; tier: unit (jsdom).+// Reuse this file's real selector harness; no new environment or real waits.+// Standalone (2026-10-16): 3 passed; pnpm exec vitest run <this file>+// --maxWorkers=1: 5.93s process wall, 4.92s Vitest (3.64s collect, 474ms tests).+// This existing selector harness's module collection dominates the 5s target;+// the new case shares those imports and uses fake time for the provider queue.+it('keeps a paid-model cancellation on the current route, then confirms the billing hash route', async () => {+ const originalHref = window.location.href;+ const originalHistoryState = window.history.state;+ vi.useFakeTimers();+ window.location.hash = '#/model-selector';+ const onModelChange = vi.fn();+ const onProviderChange = vi.fn();+ providersRef.providers = [{+ ...(providersRef.DEFAULT_PROVIDERS[1] as Record<string, unknown>),+ models: {+ codex: [{+ id: 'codex/gpt-paid',+ name: 'Paid model',+ contextWindow: 200000,+ efforts: ['high'],+ defaultEffort: 'high',+ availability: 'requires_payment',+ }],+ },+ }];++ try {+ renderSelector({ onModelChange, onProviderChange }, true);+ await openDropdown();+ await act(async () => {+ fireEvent.click(screen.getByRole('option', { name: /Paid model/ }));+ });+ expect(window.location.hash).toBe('#/model-selector');+ await act(async () => {+ fireEvent.click(within(screen.getByRole('alertdialog')).getByRole('button', {+ name: 'commonUi.confirmDialog.cancel',+ }));+ });+ expect(window.location.hash).toBe('#/model-selector');+ expect(screen.queryByRole('alertdialog')).toBeNull();++ // The real provider drains its dismissed-dialog queue after 200ms.+ await act(async () => { vi.advanceTimersByTime(200); });+ await act(async () => {+ fireEvent.click(screen.getByRole('option', { name: /Paid model/ }));+ });+ await act(async () => {+ fireEvent.click(within(screen.getByRole('alertdialog')).getByRole('button', {+ name: 'newChat.modelSelector.paymentRequired.action',+ }));+ });+ expect(window.location.hash).toBe('#/settings?tab=billing');+ expect(onModelChange).not.toHaveBeenCalled();+ expect(onProviderChange).not.toHaveBeenCalled();+ } finally {+ cleanup();+ vi.useRealTimers();+ window.history.replaceState(originalHistoryState, '', originalHref);+ }+});diff --git a/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts b/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.tsnew file mode 100644index 0000000000..7f57d4134a--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/thumbnailClickPreview.test.ts@@ -0,0 +1,101 @@+// @vitest-environment jsdom+/**+ * attachment-thumb-click (2026-04-19), PR #6196 thread PRRT_kwDOTgdRUs6tKu23.+ * Production entry: mount ComposerAttachments.ThumbnailStrip and click its real+ * preview/remove buttons; observe the selected lightbox's source/path/name or+ * the removal callback without a preview or bubbled click.+ * The removed source guard and existing file-card/lightbox tests never exercised+ * this tray. Minimal inputs: one cached image, one .txt file and their remove+ * buttons. tier: unit (jsdom); no disk, Electron or editor runtime is needed.+ * Restore this module's original path because no existing component harness+ * mounts ThumbnailStrip; do not add these cases to the source-only guard files.+ * Standalone: pnpm exec vitest run src/renderer/__tests__/thumbnailClickPreview.test.ts+ * --maxWorkers=1: 3 passed, 2.04 s wall (Vitest 1.14 s; tests 122 ms), 2026-10-16.+ */+import { createElement } from 'react';+import { resolve } from 'node:path';+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';+import { afterEach, expect, it, vi } from 'vitest';+import { ThumbnailStrip } from '../components/new-chat/ComposerAttachments';+import type { AttachedFile } from '../lib/fileTypes';++// These adapters expose the lightbox boundary's actual props as DOM. Routing,+// preview state and click handling all remain in the real ThumbnailStrip.+vi.mock('@/components/chat/ImageLightbox', () => ({+ ImageLightbox: ({ src, onClose }: { src: string; onClose: () => void }) =>+ createElement('div', { role: 'dialog', 'aria-label': 'image preview' },+ createElement('img', { src, alt: 'preview image' }),+ createElement('button', { onClick: onClose }, 'Close preview')),+}));+vi.mock('@/components/chat/TextLightbox', () => ({+ TextLightbox: ({ filePath, fileName, onClose }: {+ filePath: string; fileName: string; onClose: () => void;+ }) => createElement('div', { role: 'dialog', 'aria-label': fileName },+ createElement('output', null, filePath),+ createElement('button', { onClick: onClose }, 'Close preview')),+ // Size formatting is outside this preview-routing regression.+ formatBytes: vi.fn(() => 'fixture size'),+}));+vi.mock('@/components/chat/ImageHoverPreview', () => ({ ImageHoverPreview: () => null }));+vi.mock('../components/new-chat/AttachmentTypeThumb', () => ({ AttachmentTypeThumb: () => null }));+vi.mock('@/hooks/useStableTranslation', () => ({+ useStableTranslation: () => ({ t: (key: string) => key }),+}));+// Keep the real shouldOpenTextLightbox extension decision, replacing only its+// external error/remote-opening dependencies (unused for the .txt fixture).+vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn() } }));+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));+vi.mock('@/lib/remoteFileOpen', () => ({ openRemoteChatFile: vi.fn() }));++const image: AttachedFile = {+ id: 'image', name: 'shot.png', path: 'clipboard://shot.png', ext: '.png',+ size: 20, category: 'image', mimeType: 'image/png', url: 'cindy-media://blobs/shot.png',+};+const text: AttachedFile = {+ id: 'text', name: 'notes.txt', path: resolve('preview-fixture', 'notes.txt'), ext: '.txt',+ size: 10, category: 'text', mimeType: 'text/plain',+};++afterEach(cleanup);++it('opens the clicked image in ImageLightbox with its original source', () => {+ render(createElement(ThumbnailStrip, {+ attachments: [image, text], onRemove: vi.fn(), onUpdate: vi.fn(),+ }));+ expect(screen.queryByRole('dialog')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Preview shot.png' }));+ const preview = screen.getByRole('dialog', { name: 'image preview' });+ expect(within(preview).getByAltText('preview image').getAttribute('src')).toBe(image.url);+ expect(screen.queryByRole('dialog', { name: text.name })).toBeNull();+ fireEvent.click(within(preview).getByRole('button', { name: 'Close preview' }));+ expect(screen.queryByRole('dialog')).toBeNull();+});++it('opens the clicked text file in TextLightbox with the matching path and name', async () => {+ render(createElement(ThumbnailStrip, {+ attachments: [image, text], onRemove: vi.fn(), onUpdate: vi.fn(),+ }));+ expect(screen.queryByRole('dialog')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Preview notes.txt' }));+ const preview = await screen.findByRole('dialog', { name: text.name });+ expect(within(preview).getByRole('status').textContent).toBe(text.path);+ expect(screen.queryByRole('dialog', { name: 'image preview' })).toBeNull();+ fireEvent.click(within(preview).getByRole('button', { name: 'Close preview' }));+ expect(screen.queryByRole('dialog')).toBeNull();+});++it('removes image and text attachments without bubbling or opening a preview', async () => {+ const onRemove = vi.fn();+ const onTrayClick = vi.fn();+ render(createElement('div', { onClick: onTrayClick },+ createElement(ThumbnailStrip, { attachments: [image, text], onRemove, onUpdate: vi.fn() })));+ for (const file of [image, text]) {+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: `Remove ${file.name}` }));+ });+ expect(onRemove).toHaveBeenLastCalledWith(file.id);+ expect(onTrayClick).not.toHaveBeenCalled();+ expect(screen.queryByRole('dialog')).toBeNull();+ }+ expect(onRemove).toHaveBeenCalledTimes(2);+});diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputAnnotationAbort.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputAnnotationAbort.test.tsxindex b1b4261dc9..f6efb8fb32 100644--- a/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputAnnotationAbort.test.tsx+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputAnnotationAbort.test.tsx@@ -17,6 +17,9 @@ import { clearDraft, saveDraft } from '@/lib/composerDraftStore';import type { AtMentionPanel } from '../AtMentionPanel';import type { scanAtResources } from '@/lib/atResourceService';import type { ExtraDirsButton } from '../ExtraDirsButton';+import type { PermissionSelector } from '../PermissionSelector';+import type { UseVoiceInputResult } from '@/voice-input/useVoiceInput';+import { useAttachments } from '@/hooks/useAttachments';const h = vi.hoisted(() => ({ t: (key: string) => key, confirm: vi.fn(), editor: null as Editor | null, listening: false, stop: vi.fn().mockResolvedValue(undefined),setModel: vi.fn(), selectModel: undefined as undefined | ((id: string) => Promise<void | boolean>), remoteProviders: [] as ProviderView[],@@ -24,6 +27,8 @@ const h = vi.hoisted(() => ({ t: (key: string) => key, confirm: vi.fn(), editor:scan: vi.fn<typeof scanAtResources>(),atPanel: null as ComponentProps<typeof AtMentionPanel> | null,documentChanged: vi.fn(),+ voiceState: null as UseVoiceInputResult['state'] | null,+ cancel: vi.fn().mockResolvedValue(undefined),}));vi.mock('react-i18next', async (original) => ({ ...await original<typeof import('react-i18next')>(), useTranslation: () => ({ t: h.t }) }));@@ -55,8 +60,8 @@ vi.mock('../ModelSelector', async (original) => ({ ...await original<typeof imporeturn <span data-testid="model-selector">{modelId}</span>;} }));vi.mock('@/hooks/useSshCodexProviders', () => ({ useSshCodexProviders: () => ({ providers: h.remoteProviders, status: h.remoteStatus, refresh: () => {} }) }));-vi.mock('../ExtraDirsButton', () => ({ ExtraDirsButton: ({ open, onOpenChange, panel }: ComponentProps<typeof ExtraDirsButton>) => <><button aria-label="test-suggestions" onClick={() => onOpenChange?.(!open)} />{open && panel}</> }));-vi.mock('../PermissionSelector', () => ({ PermissionSelector: () => <span data-testid="permission-selector" /> }));+vi.mock('../ExtraDirsButton', () => ({ ExtraDirsButton: ({ open, onOpenChange, panel, disabled }: ComponentProps<typeof ExtraDirsButton>) => <><button aria-label="test-suggestions" disabled={disabled} onClick={() => onOpenChange?.(!open)} />{open && panel}</> }));+vi.mock('../PermissionSelector', () => ({ PermissionSelector: ({ disabled }: ComponentProps<typeof PermissionSelector>) => <button data-testid="permission-selector" disabled={disabled} /> }));vi.mock('../NewGoalDialog', () => ({ NewGoalDialog: () => null }));vi.mock('../FolderPickerPopover', () => ({ FolderPickerPopover: () => null, addRecentFolder: vi.fn() }));vi.mock('../AtMentionPanel', () => ({ AtMentionPanel: (props: ComponentProps<typeof AtMentionPanel>) => { h.atPanel = props; return null; } }));@@ -69,7 +74,8 @@ vi.mock('@/voice-input/useVoiceInput', () => ({ useVoiceInput: (editor: Editor |// replacement on initial mount cannot hide from the regression assertion.if (editor && editor !== h.editor) editor.on('transaction', ({ transaction }) => { if (transaction.docChanged) h.documentChanged(); });h.editor = editor;- return { state: h.listening ? 'listening' : 'idle', isListening: h.listening, isBusy: h.listening, draftText: '', start: vi.fn(), stop: h.stop, cancel: vi.fn() };+ const state = h.voiceState ?? (h.listening ? 'listening' : 'idle');+ return { state, isListening: state === 'listening', isBusy: state === 'listening' || state === 'submitting' || state === 'refining', draftText: '', start: vi.fn(), stop: h.stop, cancel: h.cancel };} }));vi.mock('@/hooks/useProviders', () => ({ useProviders: () => ({ providers: [], loading: false }) }));vi.mock('@/hooks/useDeviceProviders', () => ({ useDeviceProviders: () => ({ providers: [], loading: false, unsupported: false }) }));@@ -107,6 +113,8 @@ beforeEach(() => {h.editor = null;h.documentChanged.mockClear();h.listening = false;+ h.voiceState = null;+ h.cancel.mockReset().mockResolvedValue(undefined);h.atPanel = null;h.scan.mockReset().mockResolvedValue({ success: true, items: [], truncated: false });window.electronAPI = api;@@ -160,6 +168,46 @@ it('does not rehydrate an empty stored document when voice busy state changes',expect(h.editor!.state.selection.from).toBe(1);});+// Replaces voiceInputEditorEditability's source guard (PR #6196, section 3.2).+// The voice hook is an external boundary; the editor and ChatInput lock effects+// are real. Existing hydration tests never observe editability, attachment+// controls, permission availability or Escape ownership. Minimal unit inputs:+// one idle -> listening -> submitting -> refining -> idle run and Escape on+// two top-level surfaces followed by the same editor. Reuse this jsdom harness.+it('locks editor and attachments for the whole voice run, but keeps permissions available', async () => {+ const view = renderComposer();+ await waitFor(() => expect(h.editor).not.toBeNull());+ for (const state of ['idle', 'listening', 'submitting', 'refining', 'idle'] as const) {+ h.voiceState = state;+ view.rerender(<ChatInput {...view.props} />);+ const busy = state !== 'idle';+ expect(h.editor!.isEditable, state).toBe(!busy);+ expect((screen.getByRole('button', { name: 'test-suggestions' }) as HTMLButtonElement).disabled, state).toBe(busy);+ expect((screen.getByTestId('permission-selector') as HTMLButtonElement).disabled, state).toBe(false);+ }+});++it('defers Escape on top-level surfaces and cancels voice once from the editor', async () => {+ h.listening = true;+ renderComposer();+ await waitFor(() => expect(h.editor).not.toBeNull());+ const surfaces = render(<>+ <div role="alertdialog"><button>Dialog action</button></div>+ <div data-morph-side="bottom"><button>Permission action</button></div>+ </>);+ for (const name of ['Dialog action', 'Permission action']) {+ expect(fireEvent.keyDown(screen.getByRole('button', { name }), { key: 'Escape', code: 'Escape' })).toBe(true);+ expect(h.cancel).not.toHaveBeenCalled();+ }+ surfaces.unmount();+ let allowed = true;+ await act(async () => {+ allowed = fireEvent.keyDown(h.editor!.view.dom, { key: 'Escape', code: 'Escape' });+ });+ expect(allowed).toBe(false);+ expect(h.cancel).toHaveBeenCalledExactlyOnceWith();+});+// A prompt preview hides the old draft. Its first key must only dismiss the// preview; dispatch tests without a preview cannot catch this accidental send.it('dismisses a preview on Enter without sending or changing the hidden draft', async () => {@@ -198,6 +246,43 @@ it.each(['Enter', 'Tab'])('consumes %s for an empty slash result without sendingexpect(screen.queryByTestId('test-slash-palette')).toBeNull();});+// PR #6196 / pendingFolderMention: the hook-only drag test proves enqueueing,+// but not that an already-mounted editor wakes and consumes the queue. Reuse+// this unit harness with the real hook; choosing another folder must append+// once without reinserting the first. Paths are serialized mention targets.+it('inserts queued folders into the mounted editor when the real attachment hook changes', async () => {+ // jsdom has no layout; ProseMirror measures a Range when insertion focuses+ // and scrolls the editor. Supply geometry without replacing its selection.+ const createRange = document.createRange.bind(document);+ vi.spyOn(document, 'createRange').mockImplementation(() => {+ const range = createRange();+ const rect = new DOMRect();+ range.getClientRects = () => Object.assign([rect], { item: (index: number) => index === 0 ? rect : null });+ range.getBoundingClientRect = () => rect;+ return range;+ });+ function AttachmentComposer() {+ const attachmentState = useAttachments(undefined, 'composer-regression');+ return <>+ <button onClick={() => attachmentState.addFolderPath('/workspace/docs')}>Choose docs</button>+ <button onClick={() => attachmentState.addFolderPath('/workspace/src')}>Choose src</button>+ <ChatInput draftKey="composer-regression" deviceLinkDeviceId={null}+ attachmentState={attachmentState} hideRuntimeControls showFolderPicker={false}+ disableAutofocus onSend={vi.fn().mockResolvedValue(true)} />+ </>;+ }+ const view = render(<AttachmentComposer />);+ await waitFor(() => expect(h.editor).not.toBeNull());+ fireEvent.click(screen.getByRole('button', { name: 'Choose docs' }));+ await waitFor(() => expect(screen.getByText('docs/')).toBeTruthy());+ fireEvent.click(screen.getByRole('button', { name: 'Choose src' }));+ await waitFor(() => expect(screen.getByText('src/')).toBeTruthy());+ const chips = view.container.querySelectorAll('[data-mention-chip][data-kind="dir"]');+ expect(Array.from(chips, chip => chip.getAttribute('data-path'))).toEqual([+ '/workspace/docs', '/workspace/src',+ ]);+});+it('does not let a pending local resource scan repopulate an SSH composer', async () => {let finish!: (value: Awaited<ReturnType<typeof scanAtResources>>) => void;h.scan.mockReturnValue(new Promise(resolve => { finish = resolve; }));diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsxindex 659e81782a..153dab90b8 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsx@@ -128,6 +128,10 @@ describe('sidebar display settings menu', () => {expect(rows[0].textContent).toContain('项目、对话、设备');expect(rows[2].textContent).toContain('跟随任务');const submenu = await openSubmenu(/^任务排序/);+ // PR #6196: preserve the historical glass-menu clipping regression through+ // real unit DOM containment; content/click assertions alone miss a lost portal.+ expect(root.contains(submenu)).toBe(false);+ expect(document.body.contains(submenu)).toBe(true);expect(within(submenu).getAllByRole('menuitem')diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.mdindex 6a27f6202e..f4fc4e7db5 100644--- a/docs/dev-rules/desktop-unit-test-performance.md+++ b/docs/dev-rules/desktop-unit-test-performance.md@@ -69,6 +69,11 @@ Linux 及 package script 的启动方式不变。回归测试通过真实 runner80 份无关 `@types` 和 DOM 声明;2,238 个运行时根文件、类型检查器和失败关闭行为不变。同机 4 项测试从 7.14 秒降到 4.95 秒,原有超时未提高;别名与 continuation方法正反例验证仍能区分 maker Session 与其它同名 send。最终 CI 另行复验。+后续 head `e4466fe2b6` 的 CI 再次在该 guard 用时 15.21 秒时触发原 15 秒限制;+现进一步使用 TypeScript 的 `ParseForTypeInfo` 模式,跳过无关的 JSDoc 注释 AST,+保留接收者类型信息。独立核实全部 2,238 个根文件、2,297 个 Program 文件及 6 个+有类型身份的发送位置完全一致,未改检查器、违规判定或超时。一次本机独立进程对照+为 6.93→6.10 秒;这只是解析成本对照,CI 并发下是否解决超时仍由新 head 验证。随后补齐 Promise 定时器的首参数时长、导入别名与遮蔽判定;基线逐文件、逐规则与可信 Git 基准比较,拒绝同一提交手改抬高额度,缺失基准或格式错误均失败。真实临时 Git@@ -79,10 +84,15 @@ Linux 及 package script 的启动方式不变。回归测试通过真实 runner本地准备/清理函数;同名参数和非 Vitest 对象不会误判。既有账号用量初始化回归改为带明确理由的单次直接重载,原 34 项通过(约 0.7 秒),不新增逐用例重载。导入设置恢复真实组件挂载回归,验证首次自动扫描与重入时先显示缓存、再更新结果,-2 项单文件命令约 2.2 秒。slash 无匹配结果的 Enter/Tab 回归并入既有 ChatInput 文件,-经真实编辑器键盘入口确认阻止发送、保留正文并关闭面板;整文件 8 项通过,冷启动-16.64 秒(收集 14.86 秒、执行 0.83 秒)。该文件已有重型编辑器依赖,继续复用同一-harness,未新增重复环境或放宽超时。+2 项单文件命令约 2.2 秒。slash 空结果、目录队列插入与语音输入保护并入既有 ChatInput+文件,经过真实编辑器/hook 验证键盘消费、目录 chip、语音全生命周期只读与顶层弹层+优先消费 Esc;整文件 11 项通过,完整命令 12.29 秒(收集 9.28 秒、执行 1.10 秒)。+该文件已有重型编辑器依赖,继续复用同一 harness,未新增重复环境或放宽超时。+文件正文引用恢复为真实 CodeMirror 表格源码选区→引用按钮→草稿的 1 项回归(3.72 秒);+附件托盘恢复图片/文本点击与移除不冒泡的 3 项回归(2.04 秒)。模型加载错误提示、+子菜单 Portal、项目头拖动与付费模型计费页跳转都并入已有组件文件,完整文件分别+为 3/4/39/3 项,完整命令分别 4.00/4.60/5.79/5.93 秒;后两者收集初始化+占主导,没有新建环境、增加真实等待或修改产品代码。### 2026-10-16 实验与落地@@ -127,7 +137,7 @@ harness,未新增重复环境或放宽超时。和设计契约,已恢复 30 个完整文件,并从 `homeUsageDashboardSource.test.ts` 保留账号隔离的 3 条契约(含同步主干时保留的 `botChatSurface.test.ts`)。后续逐文件复核另保留分享脱敏的两条契约、侧栏折叠时通知订阅归属的一条契约。随后将 Mobile 混合文件逐项行为化、合并必要原生契约,- 最终相对当前 main 删除 52 个测试文件(包含已迁入其他文件的覆盖),+ 最终相对当前 main 删除 50 个测试文件(包含已迁入其他文件的覆盖),不能沿用最初的「488 条无效用例」结论。`FileTreeView.horizontalScroll.test.tsx` 真实挂载组件并断言可见宽度,已恢复。IM 启动补全、空草稿水合与语音切换、预览误发送、远程扫描旧回包、图片标注误关闭、