Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 空输入框全选与删空后不再留幽灵选区 (#896)

Dash80faa4ce397b
diff --git a/apps/desktop/src/renderer/__tests__/emptyDocSelectionGuard.test.ts b/apps/desktop/src/renderer/__tests__/emptyDocSelectionGuard.test.ts
new file mode 100644
index 0000000000..a253d8eb92
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/emptyDocSelectionGuard.test.ts
@@ -0,0 +1,251 @@
+// @vitest-environment jsdom
+// (Editor 构造需要 DOM。)
+import { Editor } from '@tiptap/core';
+import Document from '@tiptap/extension-document';
+import HardBreak from '@tiptap/extension-hard-break';
+import Paragraph from '@tiptap/extension-paragraph';
+import Text from '@tiptap/extension-text';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ collapseBlankDocDomSelection,
+ EmptyDocSelectionGuard,
+ isBlankParagraphDoc,
+ normalizeBlankDocSelection,
+ type BlankDocSelectionView,
+} from '@/components/new-chat/EmptyDocSelectionGuard';
+import { ComposerBulletList, ComposerListItem } from '@/components/new-chat/ComposerListNodes';
+import { MentionChipNode } from '@/components/new-chat/MentionChipNode';
+
+// Editor 必须逐个 destroy:EditorView 的异步回调会在 jsdom 环境拆除后触发
+// `document is not defined` 未处理异常,vitest 全绿也会 exit 1(CI 实撞)。
+const editors: Editor[] = [];
+afterEach(() => {
+ for (const editor of editors.splice(0)) editor.destroy();
+});
+
+function makeEditor(options: { guard?: boolean } = {}): Editor {
+ const { guard = true } = options;
+ const editor = new Editor({
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ ComposerListItem,
+ ComposerBulletList,
+ MentionChipNode,
+ ...(guard ? [EmptyDocSelectionGuard] : []),
+ ],
+ content: { type: 'doc', content: [{ type: 'paragraph', content: [] }] },
+ });
+ editors.push(editor);
+ return editor;
+}
+
+describe('isBlankParagraphDoc', () => {
+ it('只把单个空 paragraph 认作真空', () => {
+ expect(isBlankParagraphDoc(makeEditor().state.doc)).toBe(true);
+ });
+
+ it('有文本时不是真空', () => {
+ const editor = makeEditor();
+ editor.commands.insertContent('draft');
+ expect(isBlankParagraphDoc(editor.state.doc)).toBe(false);
+ });
+
+ // 多段落来自引用回填 / 历史草稿等程序化构造与多段粘贴;Shift/Alt/Mod+Enter 是
+ // hardBreak(留在同一 paragraph 内),plain Enter 是发送,都不产生新段落。
+ it('多个空段落不是真空(多段结构本身是真实内容)', () => {
+ const editor = makeEditor();
+ editor.commands.setContent({
+ type: 'doc',
+ content: [{ type: 'paragraph' }, { type: 'paragraph' }],
+ });
+ expect(isBlankParagraphDoc(editor.state.doc)).toBe(false);
+ });
+
+ it('只含 atom chip 的草稿不是真空(chip 没有文本投影)', () => {
+ const editor = makeEditor();
+ editor.commands.insertContent({
+ type: 'mentionChip',
+ attrs: { kind: 'file', label: 'main.ts', path: 'src/main.ts' },
+ });
+ expect(editor.state.doc.textContent).toBe('');
+ expect(isBlankParagraphDoc(editor.state.doc)).toBe(false);
+ });
+
+ it('空列表项不是真空', () => {
+ const editor = makeEditor();
+ editor.commands.setContent({
+ type: 'doc',
+ content: [
+ { type: 'bulletList', content: [{ type: 'listItem', content: [{ type: 'paragraph' }] }] },
+ ],
+ });
+ expect(isBlankParagraphDoc(editor.state.doc)).toBe(false);
+ });
+});
+
+describe('normalizeBlankDocSelection', () => {
+ it('真空文档的全选被折叠成光标', () => {
+ const editor = makeEditor();
+ editor.commands.selectAll();
+ expect(editor.state.selection.empty).toBe(true);
+ expect(editor.state.selection.from).toBe(1);
+ });
+
+ it('没有 guard 时全选会框住整个空段落(回归基线)', () => {
+ // 这就是幽灵高亮的来源:AllSelection(0..2) 把空 paragraph 节点整体框进选区,
+ // Chromium 于是在行首画出一块可见高亮。
+ const editor = makeEditor({ guard: false });
+ editor.commands.selectAll();
+ expect(editor.state.selection.empty).toBe(false);
+ expect(editor.state.selection.from).toBe(0);
+ expect(editor.state.selection.to).toBe(2);
+ });
+
+ it('有内容时全选照旧生效', () => {
+ const editor = makeEditor();
+ editor.commands.insertContent('hello');
+ editor.commands.selectAll();
+ expect(editor.state.selection.empty).toBe(false);
+ });
+
+ it('多个空段落全选照旧生效', () => {
+ const editor = makeEditor();
+ editor.commands.setContent({
+ type: 'doc',
+ content: [{ type: 'paragraph' }, { type: 'paragraph' }],
+ });
+ editor.commands.selectAll();
+ expect(editor.state.selection.empty).toBe(false);
+ });
+
+ it('全选后删空,状态层落在折叠光标上', () => {
+ const editor = makeEditor();
+ editor.commands.insertContent('123');
+ editor.commands.selectAll();
+ editor.commands.deleteSelection();
+ expect(editor.state.doc.textContent).toBe('');
+ expect(editor.state.selection.empty).toBe(true);
+ });
+
+ it('选区本就折叠时不产生多余 transaction', () => {
+ const editor = makeEditor();
+ expect(normalizeBlankDocSelection(editor.state)).toBeNull();
+ });
+});
+
+describe('collapseBlankDocDomSelection', () => {
+ interface FakeSelection {
+ rangeCount: number;
+ isCollapsed: boolean;
+ anchorNode: Node | null;
+ focusNode: Node | null;
+ collapse: (node: Node, offset: number) => void;
+ }
+
+ function makeView(
+ overrides: {
+ composing?: boolean;
+ docHasText?: boolean;
+ selection?: Partial<FakeSelection> | null;
+ anchorInside?: boolean;
+ focusInside?: boolean;
+ } = {},
+ ): { view: BlankDocSelectionView; selection: FakeSelection } {
+ const {
+ composing = false,
+ docHasText = false,
+ anchorInside = true,
+ focusInside = true,
+ } = overrides;
+ const editor = makeEditor();
+ if (docHasText) editor.commands.insertContent('draft');
+ const paragraph = { nodeName: 'P' } as unknown as Node;
+ const anchor = { nodeName: '#text' } as unknown as Node;
+ const focus = { nodeName: '#text' } as unknown as Node;
+ const selection: FakeSelection = {
+ rangeCount: 1,
+ isCollapsed: false,
+ anchorNode: anchor,
+ focusNode: focus,
+ collapse: vi.fn(),
+ ...overrides.selection,
+ };
+ const inside = new Set<Node>([paragraph]);
+ if (anchorInside) inside.add(anchor);
+ if (focusInside) inside.add(focus);
+ const dom = {
+ ownerDocument: { getSelection: () => (overrides.selection === null ? null : selection) },
+ contains: (node: Node) => inside.has(node),
+ firstChild: paragraph,
+ } as unknown as HTMLElement;
+ return {
+ view: { composing, dom, state: { doc: editor.state.doc } },
+ selection,
+ };
+ }
+
+ it('真空文档 + 跨节点 DOM 选区 → 折叠到段落起点', () => {
+ const { view, selection } = makeView();
+ expect(collapseBlankDocDomSelection(view)).toBe(true);
+ expect(selection.collapse).toHaveBeenCalledWith(view.dom.firstChild, 0);
+ });
+
+ it('DOM 选区已折叠时不动作(收敛性:第二轮直接返回)', () => {
+ const { view, selection } = makeView({ selection: { isCollapsed: true } });
+ expect(collapseBlankDocDomSelection(view)).toBe(false);
+ expect(selection.collapse).not.toHaveBeenCalled();
+ });
+
+ it('文档非真空时不动作', () => {
+ const { view, selection } = makeView({ docHasText: true });
+ expect(collapseBlankDocDomSelection(view)).toBe(false);
+ expect(selection.collapse).not.toHaveBeenCalled();
+ });
+
+ it('IME 组字期间不介入', () => {
+ const { view, selection } = makeView({ composing: true });
+ expect(collapseBlankDocDomSelection(view)).toBe(false);
+ expect(selection.collapse).not.toHaveBeenCalled();
+ });
+
+ it('anchor 不在本 editor 内时不动作(反向拖选:从外部拖进空输入框)', () => {
+ const { view, selection } = makeView({ anchorInside: false });
+ expect(collapseBlankDocDomSelection(view)).toBe(false);
+ expect(selection.collapse).not.toHaveBeenCalled();
+ });
+
+ it('focus 不在本 editor 内时不动作(从空输入框内起手往外拖选)', () => {
+ // 只校验 anchor 会把这种跨边界选区当成自己的并折叠掉,清掉用户合法的选择
+ // (PR #896 review:copilot + greptile P2)。
+ const { view, selection } = makeView({ focusInside: false });
+ expect(collapseBlankDocDomSelection(view)).toBe(false);
+ expect(selection.collapse).not.toHaveBeenCalled();
+ });
+
+ it('两端都不在本 editor 内时不动作(同页多个 composer 互不干扰)', () => {
+ const { view, selection } = makeView({ anchorInside: false, focusInside: false });
+ expect(collapseBlankDocDomSelection(view)).toBe(false);
+ expect(selection.collapse).not.toHaveBeenCalled();
+ });
+
+ it('focusNode 缺失时安全返回', () => {
+ const { view, selection } = makeView({ selection: { focusNode: null } });
+ expect(collapseBlankDocDomSelection(view)).toBe(false);
+ expect(selection.collapse).not.toHaveBeenCalled();
+ });
+
+ it('没有 selection 对象时安全返回', () => {
+ const { view } = makeView({ selection: null });
+ expect(collapseBlankDocDomSelection(view)).toBe(false);
+ });
+
+ it('rangeCount 为 0 时不动作', () => {
+ const { view, selection } = makeView({ selection: { rangeCount: 0 } });
+ expect(collapseBlankDocDomSelection(view)).toBe(false);
+ expect(selection.collapse).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index aa35862e19..cec617008c 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -41,6 +41,7 @@ import {
promoteTrailingPlainListParagraph,
} from './ComposerListNodes';
import { WindowsSelectionReplacement } from './WindowsSelectionReplacement';
+import { EmptyDocSelectionGuard } from './EmptyDocSelectionGuard';
import {
setVoiceInputDraftDecoration,
VoiceInputDraftDecoration,
@@ -1389,6 +1390,9 @@ export function ChatInput({
WindowsSelectionReplacement.configure({
enabled: window.electronAPI.platform === 'win32',
}),
+ // 空输入框全选 / 全选后删空都会在行首留一块幽灵高亮(空 paragraph 被整体框进
+ // AllSelection,删空后 Chromium 的 DOM selection 也不跟着折叠)。见模块头注释。
+ EmptyDocSelectionGuard,
CjkPunctDecoration,
ComposerListIndentDecoration,
VoiceInputDraftDecoration,
diff --git a/apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts b/apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts
new file mode 100644
index 0000000000..73e8fcf482
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts
@@ -0,0 +1,107 @@
+/**
+ * EmptyDocSelectionGuard —— 空输入框不留可见选区。
+ *
+ * Tiptap 的「空」文档不是空字符串,而是 `doc(paragraph())`,`content.size === 2`。
+ * `Cmd+A` 走 baseKeymap 的 selectAll 得到 `AllSelection(0..2)`:它把那个空段落节点
+ * 整体框进选区,Chromium 于是在行首画出一块约半字宽、一行高的高亮。原生 `<textarea>`
+ * 空的时候全选什么都选不到,两者观感不一致。
+ *
+ * 实测(隔离沙箱 + DOM 探针)确认要治两层,缺一层都不够:
+ *
+ * - 空框按 `Cmd+A`:PM 状态层是非空的 `AllSelection`,DOM 层 `anchor=DIV:0 → focus=DIV:1`
+ * (选中 `.ProseMirror` 的整个 `<p>`)。→ 靠 `appendTransaction` 归一化成折叠光标。
+ * - 输入文字后全选再删除:`AllSelection.replace()` 已把 PM 状态层折叠到 `TextSelection(1,1)`,
+ * **但 Chromium 的 DOM selection 仍跨着节点**(`collapsed=false`,rect `910x22`),高亮留在屏上。
+ * → 靠 view 层兜底折叠 DOM selection。
+ *
+ * 两层互相需要:只折叠 DOM 而把 `AllSelection` 留在状态层,PM 下一次 `selectionToDOM`
+ * 会把它重新写回 DOM,高亮复现。
+ *
+ * 只认「单个空 paragraph」这一种真空形态,其余一律不介入:多个空段落、只含 atom chip 的
+ * 草稿、结构化列表都带着真实内容,选中它们是合理的。
+ *
+ * 多段落文档在本 composer 里来自程序化构造(引用回填、历史草稿等,见
+ * `lib/composerQuoteDocument.ts`)与多段粘贴,**不是**敲键敲出来的:Shift / Alt / Mod+Enter
+ * 都是 hardBreak(`<br>` 留在同一个 paragraph 内),plain Enter 是发送。
+ */
+import { Extension } from '@tiptap/core';
+import { Plugin, TextSelection } from '@tiptap/pm/state';
+import type { EditorState, Transaction } from '@tiptap/pm/state';
+import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+
+/** 文档是否为「真空」——只有一个空 paragraph,没有文本也没有 atom chip。 */
+export function isBlankParagraphDoc(doc: ProseMirrorNode): boolean {
+ if (doc.childCount !== 1) return false;
+ const only = doc.firstChild;
+ return only !== null && only.type.name === 'paragraph' && only.content.size === 0;
+}
+
+/**
+ * 真空文档上的非空选区(`Cmd+A` / 菜单「编辑 → 全选」得到的 `AllSelection`)归一化为
+ * 段落内的折叠光标。非真空文档或选区本就折叠时返回 null(不产生多余 transaction)。
+ */
+export function normalizeBlankDocSelection(state: EditorState): Transaction | null {
+ if (!isBlankParagraphDoc(state.doc)) return null;
+ if (state.selection.empty) return null;
+ return state.tr.setSelection(TextSelection.create(state.doc, 1));
+}
+
+/** `collapseBlankDocDomSelection` 用到的最小 view 投影 —— 便于单测注入假对象。 */
+export interface BlankDocSelectionView {
+ readonly composing: boolean;
+ readonly dom: HTMLElement;
+ readonly state: { readonly doc: ProseMirrorNode };
+}
+
+/**
+ * DOM 层兜底:文档已是真空、PM 状态层也已折叠,但浏览器仍持有跨节点选区时把它折叠掉。
+ *
+ * 只在选区**两端**都落在本 editor 内时动手。只校验 anchor 不够:从空输入框内起手往外
+ * 拖选时 anchor 在 editor 内、focus 在外,折叠会清掉用户合法的跨边界选区(反向拖选时
+ * anchor 已在 editor 外,本来就不会命中)。两端都查同时也让同页多个 composer 互不干扰。
+ * IME 组字期间一律不介入 —— 组字的 DOM selection 归 ProseMirror 的原生 composition
+ * 生命周期所有。
+ *
+ * 收敛性:`collapse()` 触发的 selectionchange 会被 PM 的 DOMObserver 读回并 dispatch,
+ * 下一轮进来时 DOM 已折叠,直接返回 false。
+ */
+export function collapseBlankDocDomSelection(view: BlankDocSelectionView): boolean {
+ if (view.composing) return false;
+ if (!isBlankParagraphDoc(view.state.doc)) return false;
+ const selection = view.dom.ownerDocument?.getSelection?.() ?? null;
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return false;
+ const { anchorNode, focusNode } = selection;
+ if (
+ !anchorNode ||
+ !focusNode ||
+ !view.dom.contains(anchorNode) ||
+ !view.dom.contains(focusNode)
+ ) {
+ return false;
+ }
+ const paragraph = view.dom.firstChild;
+ if (!paragraph) return false;
+ selection.collapse(paragraph, 0);
+ return true;
+}
+
+/** 供 ChatInput 与单测共享的 plugin 工厂。 */
+export function createEmptyDocSelectionGuardPlugin(): Plugin {
+ return new Plugin({
+ appendTransaction: (_transactions, _oldState, newState) => normalizeBlankDocSelection(newState),
+ view: (view) => ({
+ update: () => {
+ collapseBlankDocDomSelection(view);
+ },
+ }),
+ });
+}
+
+/** 空 composer 幽灵选区守卫。 */
+export const EmptyDocSelectionGuard = Extension.create({
+ name: 'emptyDocSelectionGuard',
+
+ addProseMirrorPlugins() {
+ return [createEmptyDocSelectionGuardPlugin()];
+ },
+});