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。

refactor(desktop): 重构输入框结构化列表

zhangyongjiec9cef450f25c
diff --git a/apps/desktop/src/renderer/__tests__/chatInputListContinuation.test.ts b/apps/desktop/src/renderer/__tests__/chatInputListContinuation.test.ts
index 229a748b62..3e3ddbf056 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputListContinuation.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputListContinuation.test.ts
@@ -9,31 +9,33 @@ const chatInputSource = readFileSync(
/**
* ChatInput 列表接续接线契约:
- * - Shift/Alt+Enter 换行前先尝试列表接续;
+ * - Shift/Alt+Enter 优先处理结构化列表,再兼容旧纯文本列表;
* - 普通 Enter 一律保持"发送"语义,绝不被列表接续拦截(2026-07 产品定案:
- * Enter=发送的肌肉记忆优先,不做 Claude 式"列表内 Enter 继续列表");
+ * Enter=发送的肌肉记忆优先);
* - 守住 IME composition 边界。
- * 接续行为本身的用例见 lib/__tests__/composerListContinuation*.test.ts
- * (纯前缀匹配 + 真实编辑器)。
+ * 结构化与旧纯文本接续行为由各自的编辑器测试覆盖。
*/
describe('ChatInput list continuation wiring contract', () => {
- it('imports the shared helper from lib/composerListContinuation', () => {
- expect(chatInputSource).toContain(
- "import { applyListBackspace, applyListContinuation } from '@/lib/composerListContinuation';",
- );
+ it('imports both structured-list commands and the legacy plain-text fallback', () => {
+ expect(chatInputSource).toContain('handleStructuredListBackspace');
+ expect(chatInputSource).toContain('handleStructuredListBreak');
+ expect(chatInputSource).toContain('applyListBackspace');
+ expect(chatInputSource).toContain('applyListContinuation');
});
- it('tries list continuation on Shift/Alt+Enter before the default hard break', () => {
+ it('tries structured and legacy continuation on Shift/Alt+Enter', () => {
const block = extractBetween(
chatInputSource,
- '// Shift/Alt+Enter — markdown 列表接续',
+ '// Shift/Alt+Enter — split or exit a structured item.',
'// Plain Enter keeps the existing queue semantics.',
);
expect(block).toContain('(event.shiftKey || event.altKey) &&');
expect(block).toContain('!event.metaKey');
expect(block).toContain('!event.ctrlKey');
expect(block).toContain('!event.isComposing');
- expect(block).toContain('if (applyListContinuation(view)) {');
+ expect(block).toContain(
+ 'if (handleStructuredListBreak(view) || applyListContinuation(view)) {',
+ );
// 非列表行必须放行给 ComposerHardBreak 默认换行
expect(block).toContain('return false;');
});
@@ -41,8 +43,8 @@ describe('ChatInput list continuation wiring contract', () => {
it('intercepts bare Backspace for empty-item deletion, leaving modified backspace alone', () => {
const block = extractBetween(
chatInputSource,
- '// Backspace — 空列表项整体回删',
- '// Shift/Alt+Enter — markdown 列表接续',
+ '// Backspace — structured list items exit through the schema command;',
+ '// Shift/Alt+Enter — split or exit a structured item.',
);
expect(block).toContain("event.key === 'Backspace'");
expect(block).toContain('!event.metaKey');
@@ -50,7 +52,7 @@ describe('ChatInput list continuation wiring contract', () => {
expect(block).toContain('!event.altKey');
expect(block).toContain('!event.shiftKey');
expect(block).toContain('!event.isComposing');
- expect(block).toContain('applyListBackspace(view)');
+ expect(block).toContain('(handleStructuredListBackspace(view) || applyListBackspace(view))');
});
it('never intercepts plain Enter — send semantics stay untouched', () => {
@@ -59,6 +61,7 @@ describe('ChatInput list continuation wiring contract', () => {
'// Plain Enter keeps the existing queue semantics.',
"void dispatchSendRef.current(wantsSteer ? 'steer' : 'queue');",
);
+ expect(plainEnterBlock).not.toContain('handleStructuredListBreak');
expect(plainEnterBlock).not.toContain('applyListContinuation');
});
diff --git a/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts b/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts
new file mode 100644
index 0000000000..1bc4e52561
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ normalizeComposerDocumentJSON,
+ plainTextToComposerDocument,
+} from '@/lib/composerListDocument';
+
+describe('composer list document normalization', () => {
+ it('promotes plain ordered rows into one structured list', () => {
+ expect(plainTextToComposerDocument('1. first\n2. second')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'orderedList',
+ attrs: { start: 1, marker: '.' },
+ content: [
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'first' }] }],
+ },
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'second' }] }],
+ },
+ ],
+ },
+ ],
+ });
+ });
+
+ it('keeps surrounding paragraphs and task bodies intact', () => {
+ expect(plainTextToComposerDocument('intro\n- [ ] todo\n- [x] done\noutro')).toEqual({
+ type: 'doc',
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'intro' }] },
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: '[ ] todo' }] }],
+ },
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: '[x] done' }] }],
+ },
+ ],
+ },
+ { type: 'paragraph', content: [{ type: 'text', text: 'outro' }] },
+ ],
+ });
+ });
+
+ it('does not consume indented rows as top-level lists', () => {
+ expect(plainTextToComposerDocument('1. parent\n - child')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'orderedList',
+ attrs: { start: 1, marker: '.' },
+ content: [
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'parent' }] }],
+ },
+ ],
+ },
+ { type: 'paragraph', content: [{ type: 'text', text: ' - child' }] },
+ ],
+ });
+ });
+
+ it('strips each ordered marker at its own width and ignores decimal text', () => {
+ expect(plainTextToComposerDocument('9. nine\n10. ten').content?.[0]?.content).toEqual([
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'nine' }] }],
+ },
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'ten' }] }],
+ },
+ ]);
+ expect(plainTextToComposerDocument('3.14159')).toEqual({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: '3.14159' }] }],
+ });
+ });
+
+ it('leaves existing structured content unchanged', () => {
+ const document = {
+ type: 'doc' as const,
+ content: [
+ {
+ type: 'orderedList',
+ attrs: { start: 3, marker: ')' },
+ content: [
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'existing' }] }],
+ },
+ ],
+ },
+ ],
+ };
+ expect(normalizeComposerDocumentJSON(document)).toEqual(document);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts b/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
index 5ccb77dc33..1a60a4f055 100644
--- a/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
@@ -48,7 +48,7 @@ const TestAtom = TiptapNode.create({
},
});
-function makeEditor(lines: string[]): Editor {
+function makeEditor(lines: string[], structuredLists = false): Editor {
const content: Array<Record<string, unknown>> = [];
lines.forEach((line, i) => {
if (i > 0) content.push({ type: 'hardBreak' });
@@ -56,7 +56,14 @@ function makeEditor(lines: string[]): Editor {
});
editor = new Editor({
element: document.createElement('div'),
- extensions: [Document, Paragraph, Text, HardBreak, TestAtom, ComposerListIndentDecoration],
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ TestAtom,
+ ComposerListIndentDecoration.configure({ structuredLists }),
+ ],
content: { type: 'doc', content: [{ type: 'paragraph', content }] },
});
return editor;
@@ -75,6 +82,11 @@ afterEach(() => {
});
describe('buildListIndentDecorations', () => {
+ it('leaves promotable top-level rows to structured-list normalization', () => {
+ const ed = makeEditor(['1. one', ' - nested', '> quote'], true);
+ expect(indentSpans(ed)).toEqual([' - nested', '> quote']);
+ });
+
it('builds paired hanging-indent variables without embedding user text', () => {
const latinStyle = listPrefixIndentStyle('2. ');
expect(latinStyle).toContain('--composer-list-hang:1.8ch;');
@@ -908,7 +920,9 @@ describe('wiring contract', () => {
expect(src).toContain(
"import { ComposerListIndentDecoration } from './ComposerListIndentDecoration';",
);
- expect(src).toMatch(/CjkPunctDecoration,\s*\n\s*ComposerListIndentDecoration,/);
+ expect(src).toMatch(
+ /CjkPunctDecoration,\s*\n\s*ComposerListIndentDecoration\.configure\(\{ structuredLists: true \}\),/,
+ );
});
it('globals.css defines the indent class', () => {
diff --git a/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts
new file mode 100644
index 0000000000..1daf96a6a0
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts
@@ -0,0 +1,701 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it } from 'vitest';
+import { Editor, Node } from '@tiptap/core';
+import Document from '@tiptap/extension-document';
+import Paragraph from '@tiptap/extension-paragraph';
+import Text from '@tiptap/extension-text';
+import HardBreak from '@tiptap/extension-hard-break';
+import { TextSelection } from '@tiptap/pm/state';
+
+import {
+ ComposerBulletList,
+ ComposerListItem,
+ ComposerOrderedList,
+ handleStructuredListBackspace,
+ handleStructuredListBreak,
+ promoteTrailingPlainListParagraph,
+} from '@/components/new-chat/ComposerListNodes';
+import { serializeEditorContent } from '@/components/new-chat/composerContentSerialization';
+
+const TestMentionChip = Node.create({
+ name: 'mentionChip',
+ inline: true,
+ group: 'inline',
+ atom: true,
+ addAttributes() {
+ return {
+ kind: { default: 'file' },
+ label: { default: '' },
+ path: { default: '' },
+ titled: { default: false },
+ agentText: { default: undefined },
+ agentTextTruncated: { default: undefined },
+ };
+ },
+ renderHTML({ HTMLAttributes }) {
+ return ['span', HTMLAttributes];
+ },
+});
+
+const TestPastedTextChip = Node.create({
+ name: 'pastedTextChip',
+ inline: true,
+ group: 'inline',
+ atom: true,
+ addAttributes() {
+ return {
+ text: { default: '' },
+ display: { default: '' },
+ };
+ },
+ renderHTML({ HTMLAttributes }) {
+ return ['span', HTMLAttributes];
+ },
+});
+
+const editors: Editor[] = [];
+
+function makeEditor(content?: Record<string, unknown>): Editor {
+ const editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ ComposerListItem,
+ ComposerBulletList,
+ ComposerOrderedList,
+ HardBreak,
+ TestMentionChip,
+ TestPastedTextChip,
+ ],
+ content: content ?? { type: 'doc', content: [{ type: 'paragraph' }] },
+ });
+ editors.push(editor);
+ return editor;
+}
+
+function typeThroughInputRules(editor: Editor, text: string): void {
+ for (const character of text) {
+ const { from, to } = editor.state.selection;
+ const handled =
+ editor.view.someProp('handleTextInput', (handler) =>
+ handler(editor.view, from, to, character, () =>
+ editor.state.tr.insertText(character, from, to),
+ ),
+ ) === true;
+ if (!handled) {
+ editor.view.dispatch(editor.state.tr.insertText(character, from, to));
+ }
+ }
+}
+
+function selectDocumentEnd(editor: Editor): void {
+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
+}
+
+afterEach(() => {
+ for (const editor of editors.splice(0)) editor.destroy();
+});
+
+describe('composer structured list input rules', () => {
+ it.each([
+ {
+ typed: '- ',
+ listType: 'bulletList',
+ attrs: {},
+ },
+ {
+ typed: '1. ',
+ listType: 'orderedList',
+ attrs: { start: 1, marker: '.' },
+ },
+ {
+ typed: '3) ',
+ listType: 'orderedList',
+ attrs: { start: 3, marker: ')' },
+ },
+ {
+ typed: '2、',
+ listType: 'orderedList',
+ attrs: { start: 2, marker: '、' },
+ },
+ ])('turns $typed into a $listType node', ({ typed, listType, attrs }) => {
+ const editor = makeEditor();
+
+ typeThroughInputRules(editor, typed);
+
+ const list = editor.state.doc.firstChild;
+ expect(list?.type.name).toBe(listType);
+ expect(list?.attrs).toMatchObject(attrs);
+ expect(list?.firstChild?.type.name).toBe('listItem');
+ expect(list?.firstChild?.firstChild?.type.name).toBe('paragraph');
+ });
+
+ it.each([
+ {
+ typed: '- ',
+ listType: 'bulletList',
+ attrs: {},
+ },
+ {
+ typed: '1. ',
+ listType: 'orderedList',
+ attrs: { start: 1, marker: '.' },
+ },
+ ])(
+ 'turns $typed after a hard break into the same structured $listType',
+ ({ typed, listType, attrs }) => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'intro' }, { type: 'hardBreak' }],
+ },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ typeThroughInputRules(editor, typed);
+
+ expect(editor.getJSON().content).toEqual([
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'intro' }],
+ },
+ {
+ type: listType,
+ ...(Object.keys(attrs).length > 0 ? { attrs } : {}),
+ content: [
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph' }],
+ },
+ ],
+ },
+ ]);
+ },
+ );
+
+ it('turns a marker after an empty hard-break paragraph following a list into structure', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'orderedList',
+ attrs: { start: 1, marker: '.' },
+ content: [
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'item' }] }],
+ },
+ ],
+ },
+ {
+ type: 'paragraph',
+ content: [{ type: 'hardBreak' }],
+ },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ typeThroughInputRules(editor, '1. 12e21ed');
+
+ const list = editor.state.doc.lastChild;
+ expect(list?.type.name).toBe('orderedList');
+ expect(list?.attrs).toMatchObject({ start: 1, marker: '.' });
+ expect(list?.lastChild?.textContent).toBe('12e21ed');
+ });
+});
+
+describe('composer structured list keyboard commands', () => {
+ it('splits a non-empty item and exits from the empty continuation item', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'orderedList',
+ attrs: { start: 1, marker: '.' },
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'first' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ expect(handleStructuredListBreak(editor.view)).toBe(true);
+ expect(editor.state.doc.firstChild?.childCount).toBe(2);
+ expect(editor.state.selection.$from.parent.type.name).toBe('paragraph');
+ expect(editor.state.selection.$from.parent.content.size).toBe(0);
+
+ expect(handleStructuredListBreak(editor.view)).toBe(true);
+ expect(editor.getJSON().content).toEqual([
+ {
+ type: 'orderedList',
+ attrs: { start: 1, marker: '.' },
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'first' }],
+ },
+ ],
+ },
+ ],
+ },
+ { type: 'paragraph' },
+ ]);
+ });
+
+ it('lifts an empty list item on Backspace', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph' }],
+ },
+ ],
+ },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ expect(handleStructuredListBackspace(editor.view)).toBe(true);
+ expect(editor.getJSON().content).toEqual([{ type: 'paragraph' }]);
+ });
+
+ it('does not lift a non-empty item from a later empty paragraph', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'kept content' }],
+ },
+ { type: 'paragraph' },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ expect(handleStructuredListBackspace(editor.view)).toBe(false);
+ expect(editor.state.doc.firstChild?.type.name).toBe('bulletList');
+ });
+
+ it('continues task syntax as an unchecked item and exits from an empty task', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '[x] completed' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ expect(handleStructuredListBreak(editor.view)).toBe(true);
+ const list = editor.state.doc.firstChild;
+ expect(list?.childCount).toBe(2);
+ expect(list?.lastChild?.textContent).toBe('[ ] ');
+ expect(serializeEditorContent(editor).text).toBe('- [x] completed\n- [ ]');
+
+ expect(handleStructuredListBreak(editor.view)).toBe(true);
+ expect(editor.getJSON().content).toEqual([
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '[x] completed' }],
+ },
+ ],
+ },
+ ],
+ },
+ { type: 'paragraph' },
+ ]);
+ });
+
+ it('removes an empty task prefix before lifting on Backspace', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '[ ] ' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ expect(handleStructuredListBackspace(editor.view)).toBe(true);
+ expect(editor.getJSON().content).toEqual([{ type: 'paragraph' }]);
+ });
+
+ it('does not add a task prefix when splitting before the task marker', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '[x] hello' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ editor.commands.setTextSelection(3);
+
+ expect(handleStructuredListBreak(editor.view)).toBe(true);
+ expect(editor.getJSON().content).toEqual([
+ {
+ type: 'bulletList',
+ content: [
+ { type: 'listItem', content: [{ type: 'paragraph' }] },
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: '[x] hello' }] }],
+ },
+ ],
+ },
+ ]);
+ });
+
+ it('does not lift earlier content when the current paragraph only has a task prefix', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'kept' }],
+ },
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '[ ] ' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ expect(handleStructuredListBreak(editor.view)).toBe(false);
+ expect(handleStructuredListBackspace(editor.view)).toBe(false);
+ expect(editor.getJSON().content).toEqual([
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'kept' }] },
+ { type: 'paragraph', content: [{ type: 'text', text: '[ ] ' }] },
+ ],
+ },
+ ],
+ },
+ ]);
+ });
+
+ it('returns from an empty paragraph after a list to the final item on Backspace', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'orderedList',
+ attrs: { start: 1, marker: '.' },
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'first' }],
+ },
+ ],
+ },
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'second' }],
+ },
+ ],
+ },
+ ],
+ },
+ { type: 'paragraph' },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ expect(handleStructuredListBackspace(editor.view)).toBe(true);
+ expect(editor.state.doc.childCount).toBe(1);
+ expect(editor.state.doc.firstChild?.childCount).toBe(2);
+ expect(editor.state.selection.$from.parent.textContent).toBe('second');
+ expect(editor.state.selection.$from.parentOffset).toBe('second'.length);
+ });
+});
+
+describe('composer live plain-list promotion', () => {
+ it('promotes a trailing pasted row beside an existing structured list', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'orderedList',
+ attrs: { start: 1, marker: '.' },
+ content: [
+ {
+ type: 'listItem',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'first' }] }],
+ },
+ ],
+ },
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '1. 12e21ed' }],
+ },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ expect(promoteTrailingPlainListParagraph(editor.view)).toBe(true);
+
+ const list = editor.state.doc.lastChild;
+ expect(list?.type.name).toBe('orderedList');
+ expect(list?.lastChild?.textContent).toBe('12e21ed');
+ expect(editor.state.doc.textContent).not.toContain('1. 12e21ed');
+ });
+
+ it('leaves decimal text as a paragraph', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '3.14159' }],
+ },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ expect(promoteTrailingPlainListParagraph(editor.view)).toBe(false);
+ expect(editor.state.doc.lastChild?.type.name).toBe('paragraph');
+ });
+});
+
+describe('composer structured list serialization', () => {
+ it('uses the full parent marker width for nested list indentation', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'orderedList',
+ attrs: { start: 10, marker: '.' },
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'parent' }],
+ },
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'child' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(serializeEditorContent(editor).text).toBe('10. parent\n - child');
+ });
+
+ it('preserves nested markers and projects atom ranges into wire offsets', () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'parent' }],
+ },
+ {
+ type: 'orderedList',
+ attrs: { start: 3, marker: ')' },
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'open ' },
+ {
+ type: 'mentionChip',
+ attrs: {
+ kind: 'session',
+ label: 'message',
+ path: href,
+ titled: false,
+ },
+ },
+ { type: 'text', text: ' then ' },
+ {
+ type: 'pastedTextChip',
+ attrs: {
+ text: 'pasted text',
+ display: 'Pasted text (1 line)',
+ },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'read ' },
+ {
+ type: 'mentionChip',
+ attrs: {
+ kind: 'file',
+ label: 'guide.md',
+ path: 'docs/guide.md',
+ },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+
+ const serialized = serializeEditorContent(editor);
+ expect(serialized.text).toBe(
+ `- parent\n 3) open ${href} then pasted text\n- read @docs/guide.md`,
+ );
+ expect(serialized.mentions).toEqual([
+ { type: 'file', name: 'guide.md', path: 'docs/guide.md' },
+ ]);
+
+ const referenceStart = serialized.text.indexOf(href);
+ expect(serialized.agentReferences).toEqual([
+ {
+ kind: 'message',
+ start: referenceStart,
+ end: referenceStart + href.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ },
+ ]);
+ expect(
+ serialized.text.slice(serialized.agentReferences[0].start, serialized.agentReferences[0].end),
+ ).toBe(href);
+
+ const pastedStart = serialized.text.indexOf('pasted text');
+ expect(serialized.pastedTextRanges).toEqual([
+ {
+ start: pastedStart,
+ end: pastedStart + 'pasted text'.length,
+ display: 'Pasted text (1 line)',
+ },
+ ]);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index c61cfea10c..f26b412c68 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -25,9 +25,18 @@ import Text from '@tiptap/extension-text';
import History from '@tiptap/extension-history';
import Placeholder from '@tiptap/extension-placeholder';
import HardBreak from '@tiptap/extension-hard-break';
-import type { Editor } from '@tiptap/core';
+import type { Editor, JSONContent } from '@tiptap/core';
import { CjkPunctDecoration } from './CjkPunctDecoration';
import { ComposerListIndentDecoration } from './ComposerListIndentDecoration';
+import {
+ ComposerBulletList,
+ ComposerListItem,
+ ComposerOrderedList,
+ handleStructuredListBackspace,
+ handleStructuredListBreak,
+ hasTrailingPlainListParagraph,
+ promoteTrailingPlainListParagraph,
+} from './ComposerListNodes';
import { WindowsSelectionReplacement } from './WindowsSelectionReplacement';
import {
setVoiceInputDraftDecoration,
@@ -37,7 +46,6 @@ import {
import { MentionDragCaretDecoration, setMentionDragCaret } from './MentionDragCaretDecoration';
import { GhostCommandDecoration, setGhostCommandRoster } from './GhostCommandDecoration';
import {
- getDecoratedSlashCommandMatches,
replaceSlashCommandRunWithText,
setSlashCommandRoster,
SlashCommandDecoration,
@@ -49,19 +57,12 @@ import { toast } from '@/lib/toast';
import { mapIpcErrorToI18nKey } from '@/utils/ipcError';
import { Tip } from '@/components/ui/tooltip';
import type { AttachedFile, MentionedResource, ImageAnnotationStroke } from '@/lib/fileTypes';
-import { formatQuoteForSend } from '@/lib/chatQuotes';
import {
commentPreviewTag,
formatBrowserCommentsForSend,
removeBrowserCommentAndRepairChains,
type BrowserCommentDraftItem,
} from '@/lib/browserComments';
-import { formatMentionRef } from '@/lib/mentionRefFormat';
-import {
- parseProjectDeepLinkHref,
- parseSessionDeepLinkHref,
- projectDisplayName,
-} from '@/lib/deepLink';
import { isGlobalDropIntercepted } from '@/lib/globalDropIntercept';
import { shouldOpenTextLightbox } from '@/lib/filePreview';
import {
@@ -111,17 +112,12 @@ import { ComposerQuoteNode } from './ComposerQuoteNode';
import {
COMPOSER_QUOTE_NODE_TYPE,
composerHistoryEntryToDocument,
- composerQuoteAttrsToChatQuote,
- serializeComposerContentBlocksWithRanges,
type ComposerHistoryEntry,
- type ComposerQuoteAttrs,
- type ComposerSerializedBlock,
} from '@/lib/composerQuoteDocument';
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
import {
pastedSessionChipAttrs,
resolveSessionMessageReferencesForSend,
- serializeSessionChipText,
resolveSessionChipTitles,
} from './sessionLinkPaste';
import {
@@ -131,7 +127,6 @@ import {
LONG_PASTE_MAX_CHARS,
segmentPastedContent,
pastedProjectChipAttrs,
- serializeProjectChipText,
} from './pastePipeline';
import { upgradePastedPathsToChips, type PendingPathRange } from './pathPaste';
import { docContainsAtomChip } from './composerDocState';
@@ -148,17 +143,23 @@ import {
} from './PastedTextChipNode';
import { ToolPayloadLightbox } from '@/components/chat/ToolPayloadLightbox';
import { Fragment, Slice, type Node as ProseMirrorNode } from '@tiptap/pm/model';
-import { Selection } from '@tiptap/pm/state';
+import { Selection, TextSelection } from '@tiptap/pm/state';
import * as sessionService from '@/lib/sessionService';
import { getModelById } from '@/lib/modelDefinitions';
import { loadAllCommands, filterSlashCommands, type UnifiedCommand } from '@/lib/slashCommands';
-import { applyListBackspace, applyListContinuation } from '@/lib/composerListContinuation';
import { scanAtResources, filterAtResources, type AtResourceItem } from '@/lib/atResourceService';
+import { applyListBackspace, applyListContinuation } from '@/lib/composerListContinuation';
import type { Effort, PermissionMode } from '@/lib/userPreferences.types';
import { getAppShortcutCombos } from '@/lib/appShortcutStore';
import { getNextPermissionMode } from '@/lib/permissionModeCycle';
import { matchesKeyboardEvent } from '../../../shared/appShortcuts';
import { createLogger } from '@/lib/logger';
+import { serializeEditorContent } from './composerContentSerialization';
+import {
+ composerDocumentContainsList,
+ normalizeComposerDocumentJSON,
+ plainTextToComposerDocument,
+} from '@/lib/composerListDocument';
import { useAgentCapabilities, type AgentKind } from '@/hooks/useAgentCapabilities';
import { useConnectedSource } from '@/hooks/useConnectedSource';
import { useProviders } from '@/hooks/useProviders';
@@ -633,196 +634,6 @@ function hasFocusMovedToInteractiveElement(focusAnchor: Element | null, editor:
return isInteractiveFocusedElement(activeElement);
}
-/**
- * Serialize the Tiptap document to the plain-string format the Agent SDK
- * expects (command-palette F6):
- * - file chip → `@{relPath}`
- * - dir chip → `@{relPath}/`
- * - agent chip → `@.claude/agents/{name}.md` (falls back to `@{name}` when
- * the host tells us the mapping is stale — see submit handler)
- * - session chip → `[title](cindy://session/…)` / bare deep link href
- * - plain text → as-is
- * Paragraphs are joined with `\n`.
- */
-function serializeEditorContent(editor: Editor): {
- text: string;
- mentions: MentionedResource[];
- hasQuotes: boolean;
- agentReferences: AgentInputReference[];
- pastedTextRanges: PastedTextRange[];
- slashCommandRanges: SlashCommandRange[];
-} {
- const doc = editor.state.doc;
- const decoratedSlashMatches = getDecoratedSlashCommandMatches(editor);
- const blocks: ComposerSerializedBlock[] = [];
- const mentions: MentionedResource[] = [];
- const seenMentions = new Set<string>();
- let hasQuotes = false;
-
- const addMention = (attrs: MentionChipAttrs) => {
- // slash 不是资源;session / project 深链不进 mentions(不是文件系统资源,
- // MentionedResource.type 也不含它们)——只序列化进正文文本。
- if (attrs.kind === 'slash' || attrs.kind === 'session' || attrs.kind === 'project') return;
- const key = `${attrs.kind}:${attrs.path}`;
- if (seenMentions.has(key)) return;
- seenMentions.add(key);
- mentions.push({ type: attrs.kind, name: attrs.label, path: attrs.path });
- };
-
- doc.forEach((pNode, paragraphOffset) => {
- if (pNode.type.name === COMPOSER_QUOTE_NODE_TYPE) {
- hasQuotes = true;
- blocks.push({
- kind: 'quote',
- text: formatQuoteForSend(composerQuoteAttrsToChatQuote(pNode.attrs as ComposerQuoteAttrs)),
- });
- return;
- }
- if (pNode.type.name !== 'paragraph') return;
- let buf = '';
- let bufAgentReferences: AgentInputReference[] = [];
- let bufPastedTextRanges: PastedTextRange[] = [];
- let bufSlashCommandRanges: SlashCommandRange[] = [];
- let emittedInlineSegment = false;
- const flushText = (force = false) => {
- if (!force && !buf) return;
- blocks.push({
- kind: 'text',
- text: buf,
- ...(bufAgentReferences.length > 0 ? { agentReferences: bufAgentReferences } : {}),
- ...(bufPastedTextRanges.length > 0 ? { pastedTextRanges: bufPastedTextRanges } : {}),
- ...(bufSlashCommandRanges.length > 0 ? { slashCommandRanges: bufSlashCommandRanges } : {}),
- });
- buf = '';
- bufAgentReferences = [];
- bufPastedTextRanges = [];
- bufSlashCommandRanges = [];
- emittedInlineSegment = true;
- };
- pNode.forEach((child, childOffset) => {
- if (child.type.name === COMPOSER_QUOTE_NODE_TYPE) {
- flushText();
- hasQuotes = true;
- blocks.push({
- kind: 'quote',
- text: formatQuoteForSend(
- composerQuoteAttrsToChatQuote(child.attrs as ComposerQuoteAttrs),
- ),
- });
- emittedInlineSegment = true;
- } else if (child.type.name === 'mentionChip') {
- const attrs = child.attrs as MentionChipAttrs;
- addMention(attrs);
- if (attrs.kind === 'slash') {
- buf += `/${attrs.path} `;
- } else if (attrs.kind === 'session') {
- // 会话深链 chip:有标题 → `[标题](href)`(消息侧 / 手机端 markdown
- // 链路显式 label 优先),标题未解析 → 裸 href。
- const wire = serializeSessionChipText(attrs);
- const start = buf.length;
- buf += wire;
- const target = parseSessionDeepLinkHref(attrs.path);
- if (target?.messageClientId) {
- bufAgentReferences.push({
- kind: 'message',
- start,
- end: buf.length,
- href: attrs.path,
- sessionId: target.sessionId,
- messageClientId: target.messageClientId,
- ...(attrs.agentText ? { text: attrs.agentText } : {}),
- ...(attrs.agentTextTruncated ? { truncated: true } : {}),
- });
- } else if (target) {
- bufAgentReferences.push({
- kind: 'session',
- start,
- end: buf.length,
- href: attrs.path,
- sessionId: target.sessionId,
- ...(attrs.titled && attrs.label ? { title: attrs.label } : {}),
- });
- }
- } else if (attrs.kind === 'project') {
- // 项目深链 chip:同 session 的取舍——显式标题走 markdown 形式,
- // 目录名占位是 href 可推导的,裸 href 即可(消息侧自行取 basename)。
- const wire = serializeProjectChipText(attrs);
- const start = buf.length;
- buf += wire;
- const target = parseProjectDeepLinkHref(attrs.path);
- if (target) {
- bufAgentReferences.push({
- kind: 'project',
- start,
- end: buf.length,
- href: attrs.path,
- name: attrs.label || projectDisplayName(target.workingDir),
- workingDir: target.workingDir,
- });
- }
- } else if (attrs.kind === 'dir') {
- // 含空格的 path 用 `@"..."` 引号形式序列化(formatMentionRef),否则
- // 下游 `@\S+` 切词会从空格处把 chip 截断。dir 的尾 `/` 一并纳入引号内,
- // 与 maker-core quotedMentionText 的 dir 形式 `@"path/"` 对齐。
- buf += `@${formatMentionRef(`${attrs.path}/`)}`;
- } else if (attrs.kind === 'agent') {
- // F2.7: agent chip serializes to `@.claude/agents/{name}.md` when
- // the stored path is canonical (contains `/`), else falls back to
- // `@{name}` — spec: "映射失败按裸名 @{name} 退化发送".
- // insertAtResource stores the canonical path when the scan found
- // the file; the fallback branch fires for chips whose source file
- // vanished between scan and submit (or any future code path that
- // can only recover the bare name) so Agent reports the error back
- // inline instead of us silently dropping the mention.
- const p = attrs.path;
- if (p.includes('/')) {
- // Canonical path — emit as-is (already `.claude/agents/foo.md`)
- buf += `@${formatMentionRef(p)}`;
- } else {
- // Bare-name fallback — strip any accidental `.md` tail, emit
- // just the label so Agent can diagnose "unknown agent"
- const bare = p.replace(/\.md$/, '');
- buf += `@${formatMentionRef(bare)}`;
- }
- } else {
- buf += `@${formatMentionRef(attrs.path)}`;
- }
- } else if (child.type.name === 'pastedTextChip') {
- // Agent 仍收到完整原文;本地只记录纯展示 range,让发送后能恢复同款
- // chip,而不往 prompt 塞任何 marker 或改变缓存前缀。
- const attrs = child.attrs as PastedTextChipAttrs;
- const start = buf.length;
- buf += attrs.text;
- bufPastedTextRanges.push({ start, end: buf.length, display: attrs.display });
- } else if (child.type.name === 'hardBreak') {
- // Shift+Enter inserts a Tiptap HardBreak node (inline <br>).
- // Without this branch the node is silently dropped and the sent
- // message loses all line breaks. Translate to '\n' here so the
- // downstream UserMessage (whitespace-pre-wrap) renders it correctly.
- buf += '\n';
- } else if (child.isText) {
- const childText = child.text ?? '';
- const bufferStart = buf.length;
- const documentStart = paragraphOffset + 1 + childOffset;
- buf += childText;
- for (const match of decoratedSlashMatches) {
- if (match.from < documentStart || match.to > documentStart + childText.length) continue;
- bufSlashCommandRanges.push({
- start: bufferStart + match.from - documentStart,
- end: bufferStart + match.to - documentStart,
- });
- }
- }
- });
- // Preserve truly empty paragraphs as line breaks, but do not synthesize an
- // empty text segment after a quote chip at the end of a paragraph.
- flushText(!emittedInlineSegment);
- });
-
- const serialized = serializeComposerContentBlocksWithRanges(blocks);
- return { ...serialized, mentions, hasQuotes };
-}
-
/**
* Is the editor document "empty" (no text and no chips)? Used to mimic the
* textarea's `message.trim().length > 0` gate for the Send button.
@@ -927,9 +738,8 @@ function detectTrigger(editor: Editor): TriggerState {
// Slash detection — mirror @ semantics: trigger when `/` sits at the start
// of the current paragraph OR is preceded by whitespace, with no whitespace
- // between it and the caret. Matches Codex desktop behaviour. (The old
- // "must be doc[0]" rule was too strict — users couldn't fire / after a
- // Shift+Enter or in the middle of a sentence.)
+ // between it and the caret. The previous "must be doc[0]" rule was too
+ // strict — users couldn't fire / after a Shift+Enter or in a sentence.
const slashIdx = textSoFar.lastIndexOf('/');
if (slashIdx >= 0) {
const beforeSlash = slashIdx === 0 ? '' : textSoFar[slashIdx - 1];
@@ -1184,7 +994,7 @@ export function ChatInput({
const userHistoryRef = useRef(userHistory);
userHistoryRef.current = userHistory;
const historyIndexRef = useRef(-1); // -1 = current draft (not browsing)
- const draftRef = useRef(''); // saves draft when user starts browsing
+ const draftRef = useRef<JSONContent | null>(null); // saves draft when user starts browsing
const hydratedHistoryDocumentRef = useRef<ProseMirrorNode | null>(null);
// ── composer-draft-per-session ─────────────────────────────────────
@@ -1257,6 +1067,8 @@ export function ChatInput({
const [isDragOver, setIsDragOver] = useState(false);
const dragCounterRef = useRef(0);
const composerMentionDragActiveRef = useRef(false);
+ const suppressListNormalizationRef = useRef(false);
+ const listPromotionQueuedRef = useRef(false);
const lastComposerSelectionFromRef = useRef<number | null>(null);
const internalMentionDragActiveRef = useRef(false);
const [workingDir, setWorkingDir] = useState<string | null>(initialWorkingDir ?? null);
@@ -1531,9 +1343,10 @@ export function ChatInput({
}, [initialWorkingDir]);
// ── Tiptap editor ──────────────────────────────────────────────────
- // A minimal editor: plain text + hard-break + history + our atomic
- // mention chip node. We do NOT include StarterKit because it brings
- // headings / lists / marks we don't want in a chat input.
+ // The composer remains intentionally small: it has paragraphs, hard breaks,
+ // atomic chips, and only the list nodes needed to preserve Markdown list
+ // structure while editing. It does not use StarterKit, whose headings and
+ // marks are not part of the chat input contract.
const editor = useEditor({
// Match the legacy textarea's `autoFocus` prop — on mount, focus the
// editor at the end so the user can continue typing after restored text.
@@ -1546,6 +1359,9 @@ export function ChatInput({
Document,
Paragraph,
Text,
+ ComposerListItem,
+ ComposerBulletList,
+ ComposerOrderedList,
ComposerHardBreak,
History,
Placeholder.configure({
@@ -1563,7 +1379,7 @@ export function ChatInput({
enabled: window.electronAPI.platform === 'win32',
}),
CjkPunctDecoration,
- ComposerListIndentDecoration,
+ ComposerListIndentDecoration.configure({ structuredLists: true }),
VoiceInputDraftDecoration,
MentionDragCaretDecoration,
GhostCommandDecoration,
@@ -1606,6 +1422,16 @@ export function ChatInput({
setMentionDragCaret(editorRef.current, null);
return false;
},
+ compositionend: (view) => {
+ // The final IME commit can bypass input rules. Wait until
+ // ProseMirror releases its native composition DOM, then promote a
+ // trailing Markdown list row if one was committed as plain text.
+ setTimeout(() => {
+ if (view.isDestroyed || view.composing) return;
+ promoteTrailingPlainListParagraph(view);
+ }, 0);
+ return false;
+ },
},
handleClickOn(_view, _pos, node, nodePos, _event, direct) {
// 长文本粘贴 chip:点击打开 ToolPayloadLightbox 的可编辑 text 模式。
@@ -1709,6 +1535,48 @@ export function ChatInput({
const segments = text
? segmentPastedContent(text, { workingDir: workingDirRef.current })
: null;
+ // Plain Markdown pasted into the final empty row should enter the same
+ // structured document model as a typed list marker. Paste does not run
+ // Tiptap input rules, so normalize it explicitly at this boundary.
+ if (text && !segments) {
+ const normalizedPaste = plainTextToComposerDocument(text);
+ const { state } = view;
+ const { $from } = state.selection;
+ const paragraphPosition = $from.depth === 1 ? $from.before(1) : -1;
+ const paragraphEndsDocument =
+ paragraphPosition >= 0 &&
+ paragraphPosition + $from.parent.nodeSize === state.doc.content.size;
+ const paragraphIsEmptyLine =
+ $from.parent.type.name === 'paragraph' &&
+ ($from.parent.content.size === 0 ||
+ ($from.parent.childCount === 1 &&
+ $from.parent.firstChild?.type.name === 'hardBreak')) &&
+ $from.parentOffset === $from.parent.content.size;
+
+ if (
+ state.selection.empty &&
+ paragraphEndsDocument &&
+ paragraphIsEmptyLine &&
+ composerDocumentContainsList(normalizedPaste)
+ ) {
+ event.preventDefault();
+ const replacement = (normalizedPaste.content ?? []).map((node) =>
+ state.schema.nodeFromJSON(node),
+ );
+ if ($from.parent.content.size > 0) {
+ replacement.unshift(state.schema.nodes.paragraph.create());
+ }
+ const fragment = Fragment.from(replacement);
+ const tr = state.tr.replaceWith(
+ paragraphPosition,
+ paragraphPosition + $from.parent.nodeSize,
+ fragment,
+ );
+ tr.setSelection(TextSelection.atEnd(tr.doc));
+ view.dispatch(tr.scrollIntoView());
+ return true;
+ }
+ }
if (segments) {
event.preventDefault();
const { state } = view;
@@ -1759,9 +1627,14 @@ export function ChatInput({
}
}
flushText();
- view.dispatch(
- state.tr.replaceSelection(new Slice(Fragment.from(nodes), 0, 0)).scrollIntoView(),
- );
+ suppressListNormalizationRef.current = true;
+ try {
+ view.dispatch(
+ state.tr.replaceSelection(new Slice(Fragment.from(nodes), 0, 0)).scrollIntoView(),
+ );
+ } finally {
+ suppressListNormalizationRef.current = false;
+ }
const ed = editorRef.current;
if (ed) {
resolveSessionChipTitles(ed);
@@ -1883,7 +1756,7 @@ export function ChatInput({
if (idx === -1 && !isEmpty) return false;
if (idx === -1) {
// Save current draft before browsing
- draftRef.current = editorInstance.textContent;
+ draftRef.current = view.state.doc.toJSON();
}
const next = Math.min(idx + 1, history.length - 1);
if (next === idx) return false; // already at oldest
@@ -1901,12 +1774,14 @@ export function ChatInput({
// Restore draft
const draft = draftRef.current;
if (draft) {
- tr.replaceWith(0, view.state.doc.content.size, view.state.schema.text(draft));
+ const draftDocument = view.state.schema.nodeFromJSON(draft);
+ tr.replaceWith(0, view.state.doc.content.size, draftDocument.content);
} else {
tr.delete(0, view.state.doc.content.size);
}
view.dispatch(tr);
hydratedHistoryDocumentRef.current = null;
+ draftRef.current = null;
} else {
replaceWithHistoryEntry(history[next]);
}
@@ -1915,9 +1790,9 @@ export function ChatInput({
}
}
- // Backspace — 空列表项整体回删(对齐 Claude):行内容只剩前缀(如
- // "2. ")且光标在行尾时,一次退格删掉整个前缀并回到上一行行尾,
- // 而不是一个字符一个字符啃前缀。带修饰键(词删 / 行删)不拦截。
+ // Backspace — structured list items exit through the schema command;
+ // legacy plain Markdown rows keep the prefix-deletion fallback so
+ // pasted and restored text remains editable without a migration pass.
if (
event.key === 'Backspace' &&
!event.metaKey &&
@@ -1925,15 +1800,15 @@ export function ChatInput({
!event.altKey &&
!event.shiftKey &&
!event.isComposing &&
- applyListBackspace(view)
+ (handleStructuredListBackspace(view) || applyListBackspace(view))
) {
event.preventDefault();
return true;
}
- // Shift/Alt+Enter — markdown 列表接续(纯文本):当前行以列表 / 待办 /
- // 引用前缀开头时,换行后自动补下一个前缀(序号 +1);前缀后无内容时改为
- // 清掉前缀退出列表。其余情况 return false 走 ComposerHardBreak 默认换行。
+ // Shift/Alt+Enter — split or exit a structured item. The plain-text
+ // fallback remains for old drafts and pasted Markdown that has not
+ // gone through an input rule.
if (
event.key === 'Enter' &&
(event.shiftKey || event.altKey) &&
@@ -1941,7 +1816,7 @@ export function ChatInput({
!event.ctrlKey &&
!event.isComposing
) {
- if (applyListContinuation(view)) {
+ if (handleStructuredListBreak(view) || applyListContinuation(view)) {
event.preventDefault();
return true;
}
@@ -1991,6 +1866,24 @@ export function ChatInput({
},
// Tick state on every update so triggerState below recomputes.
onUpdate: ({ editor: ed }) => {
+ if (
+ !suppressListNormalizationRef.current &&
+ !ed.view.composing &&
+ !listPromotionQueuedRef.current &&
+ hasTrailingPlainListParagraph(ed.view)
+ ) {
+ listPromotionQueuedRef.current = true;
+ queueMicrotask(() => {
+ listPromotionQueuedRef.current = false;
+ if (
+ !ed.isDestroyed &&
+ !suppressListNormalizationRef.current &&
+ !ed.view.composing
+ ) {
+ promoteTrailingPlainListParagraph(ed.view);
+ }
+ });
+ }
setTick((t) => t + 1);
if (!composerMentionDragActiveRef.current) {
lastComposerSelectionFromRef.current = ed.state.selection.from;
@@ -2695,7 +2588,7 @@ export function ChatInput({
if (draft?.text && editor.isEmpty) {
isRestoringRef.current = true;
try {
- editor.commands.setContent(draft.text);
+ editor.commands.setContent(normalizeComposerDocumentJSON(draft.text));
} finally {
isRestoringRef.current = false;
}
@@ -2753,7 +2646,7 @@ export function ChatInput({
try {
const draft = storageKey !== undefined ? getComposerDraft(storageKey) : undefined;
if (draft?.text) {
- editor.commands.setContent(draft.text);
+ editor.commands.setContent(normalizeComposerDocumentJSON(draft.text));
} else {
editor.commands.clearContent();
}
@@ -2768,7 +2661,7 @@ export function ChatInput({
// arrow-key history was relative to the previous session.
historyIndexRef.current = -1;
hydratedHistoryDocumentRef.current = null;
- draftRef.current = '';
+ draftRef.current = null;
if (!focusOnStorageKeyChangeRef.current) return;
if (disableAutofocusRef.current || disabledRef.current) return;
@@ -2833,7 +2726,7 @@ export function ChatInput({
isRestoringRef.current = true;
try {
if (draft.text) {
- editor.commands.setContent(draft.text);
+ editor.commands.setContent(normalizeComposerDocumentJSON(draft.text));
editor.commands.focus('end');
} else {
editor.commands.clearContent();
@@ -3537,7 +3430,7 @@ export function ChatInput({
setBrowserComments([]);
historyIndexRef.current = -1;
hydratedHistoryDocumentRef.current = null;
- draftRef.current = '';
+ draftRef.current = null;
// composer-draft-per-session: drop the saved draft now that this
// session's content has been sent. Without this, switching away then
// back would re-restore the just-sent text/files into the composer.
@@ -5109,9 +5002,9 @@ export function ChatInput({
/>
)}
- {/* browser-comment-chip(Codex 风格):页面评论收敛为一个「N 条注释」
- 胶囊,hover 浮出逐条预览(截图缩略 + 目标标签 + 评论文字,可逐条删),
- X 清空全部。发送时序列化为 `# Browser comments:` 段 + 截图附件。 */}
+ {/* Browser comment chip:页面评论收敛为一个「N 条注释」胶囊,
+ hover 浮出逐条预览(截图缩略 + 目标标签 + 评论文字,可逐条删),
+ X 清空全部。发送时序化为 `# Browser comments:` 段 + 截图附件。 */}
{browserComments.length > 0 && (
<div className="pb-1.5">
<div className="group/bcomment relative inline-flex">
@@ -5254,7 +5147,7 @@ export function ChatInput({
// 页面评论走丢弃语义(清 state + 清截图缓存):目标不接管评论截图,
// 与发送后清空(消息接管截图,不清缓存)不同,这里不清会留磁盘孤儿。
clearBrowserComments();
- draftRef.current = '';
+ draftRef.current = null;
if (storageKey) clearComposerDraft(storageKey);
}}
/>
@@ -5618,7 +5511,6 @@ function VoiceInputButton({
canReleaseToSend,
releaseToSendActive,
onReleaseToSendChange,
- visualVariant,
className,
}: {
state: import('@cindy/voice-input-core').VoiceInputState;
diff --git a/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts b/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
index 3089b169c1..f68e9e462e 100644
--- a/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
+++ b/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
@@ -1,8 +1,9 @@
/**
- * Tiptap 扩展 —— composer 列表行缩进(纯视觉,对齐 Claude 原生 App 的
- * "进入列表模式"反馈)。
+ * Tiptap 扩展 —— composer 纯文本 Markdown 列表的兼容缩进。
*
- * 行为:当某一"行"(段落内以 hardBreak 划分)以列表 / 待办 / 引用前缀开头
+ * 结构化 bullet / ordered list 由 schema 和原生列表布局负责;本扩展只处理
+ * 粘贴或旧草稿中仍为文本的列表,以及待办 / 引用前缀。当某一"行"
+ * (段落内以 hardBreak 划分)以列表 / 待办 / 引用前缀开头
* (`1. ` / `- ` / `- [ ] ` / `> ` 等,与列表接续共用 matchListPrefix 判定),
* 单行段落使用 node decoration,hardBreak 分隔的多行段落按行使用 inline
* decoration;连续数字/字母正文使用 marker/body 两个盒子,避免长串把
@@ -21,7 +22,7 @@
* 全量成本可忽略,不值得做增量映射);
* - IME composition 开始前临时移除 decoration,结束后的下一轮 task 再按
* 当前 doc 补算,避免微软拼音输入时改写 composition DOM;
- * - 这是纯文本编辑器的视觉缩进,不改变 doc JSON / 发送文本。
+ * - 这是兼容文本行的视觉缩进,不改变 doc JSON / 发送文本。
*/
import { Extension } from '@tiptap/core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
@@ -49,6 +50,10 @@ type ListDecorationPluginState = {
type CompositionMeta = 'suspend' | 'resume';
+interface ComposerListIndentOptions {
+ structuredLists: boolean;
+}
+
const PLUGIN_STATE_KEY = new PluginKey<ListDecorationPluginState>(
'composerListIndentDecorationState',
);
@@ -60,6 +65,8 @@ const CJK_PUNCTUATION_RE = /[\u3000-\u303f\uff00-\uffef]/;
// 普通句子里偶然出现长 token 时,交给 overflow-wrap:anywhere,保留空格
// 的自然断词行为,避免把整句变成逐字断行。
const LONG_ALPHANUMERIC_BODY_RE = /^\s*[A-Za-z0-9]{12,}\s*$/;
+const PROMOTABLE_TOP_LEVEL_LIST_RE =
+ /^(?:[-+*•][ \t]+|\d{1,6}[.)][ \t]+|\d{1,6}、[ \t]*)/;
interface ListIndentValues {
ch: number;
@@ -149,6 +156,7 @@ export function buildListIndentDecorations(
doc: PMNode,
slashCommandMatches: ReadonlyArray<Pick<SlashCommandMatch, 'from' | 'to'>> = [],
voiceReplacementRange: VoiceInputReplacementRange | null = null,
+ structuredLists = false,
): DecorationSet {
const decorations: Decoration[] = [];
@@ -200,9 +208,21 @@ export function buildListIndentDecorations(
lineEndOffset = block.content.size;
flushLine(); // 段落最后一行
+ const compatibilityMatch = (line: (typeof lines)[number]) => {
+ const match = matchListPrefix(line.text);
+ if (
+ match &&
+ structuredLists &&
+ !line.hasInlineAtom &&
+ PROMOTABLE_TOP_LEVEL_LIST_RE.test(line.text)
+ ) {
+ return null;
+ }
+ return match;
+ };
const lineMatches = lines.map((line) => ({
line,
- match: matchListPrefix(line.text),
+ match: compatibilityMatch(line),
}));
const hasFallbackLine = lineMatches.some(({ line, match }) => {
if (!match) return false;
@@ -243,7 +263,7 @@ export function buildListIndentDecorations(
}
const addLineDecoration = (line: (typeof lines)[number]) => {
- const match = matchListPrefix(line.text);
+ const match = compatibilityMatch(line);
if (!match) {
if (hasFallbackLine && lines.length > 1 && line.end > line.start) {
const hasCjkPunctuation = CJK_PUNCTUATION_RE.test(line.text);
@@ -316,7 +336,7 @@ export function buildListIndentDecorations(
if (lines.length === 1) {
const [line] = lines;
- const match = line && matchListPrefix(line.text);
+ const match = line && compatibilityMatch(line);
const prefix = match ? line.text.slice(0, match.prefixLength) : '';
const body = line && match ? line.text.slice(match.prefixLength) : '';
const from = line ? contentBase + line.start : contentBase;
@@ -398,11 +418,18 @@ export function buildListIndentDecorations(
return DecorationSet.create(doc, decorations);
}
-export const ComposerListIndentDecoration = Extension.create({
+export const ComposerListIndentDecoration = Extension.create<ComposerListIndentOptions>({
name: 'composerListIndentDecoration',
+ addOptions() {
+ return {
+ structuredLists: false,
+ };
+ },
+
addProseMirrorPlugins() {
let resumeTimer: ReturnType<typeof setTimeout> | null = null;
+ const structuredLists = this.options.structuredLists;
return [
new Plugin<ListDecorationPluginState>({
@@ -414,6 +441,8 @@ export const ComposerListIndentDecoration = Extension.create({
decorations: buildListIndentDecorations(
state.doc,
findSlashCommandMatches(state.doc, roster),
+ null,
+ structuredLists,
),
suspendedForComposition: false,
};
@@ -446,6 +475,7 @@ export const ComposerListIndentDecoration = Extension.create({
tr.doc,
findSlashCommandMatches(tr.doc, roster),
voiceReplacement.range,
+ structuredLists,
),
suspendedForComposition: false,
};
diff --git a/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts b/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts
new file mode 100644
index 0000000000..3e6b90a756
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts
@@ -0,0 +1,405 @@
+/**
+ * Structured list nodes for the chat composer.
+ *
+ * The composer stores list structure in its ProseMirror document and only
+ * turns it back into Markdown at send time. This keeps wrapping, nested
+ * items, and inline atoms in one layout tree instead of estimating marker
+ * widths with decorations.
+ */
+import { InputRule, Node, mergeAttributes, wrappingInputRule, type NodeConfig } from '@tiptap/core';
+import { Fragment, type Node as PMNode, type NodeType } from '@tiptap/pm/model';
+import { liftListItem, splitListItem } from '@tiptap/pm/schema-list';
+import { Selection, TextSelection } from '@tiptap/pm/state';
+import type { EditorView } from '@tiptap/pm/view';
+
+const ORDERED_MARKER_RE = /^\s*(\d{1,6})([.)])\s$/;
+const CJK_ORDERED_MARKER_RE = /^\s*(\d{1,6})(、)$/;
+
+type OrderedMarker = '.' | ')' | '、';
+
+interface OrderedListAttrs {
+ start: number;
+ marker: OrderedMarker;
+}
+
+interface SelectedTaskPrefix {
+ from: number;
+ to: number;
+ bodyIsEmpty: boolean;
+ caretAtOrAfterPrefix: boolean;
+ caretAtParagraphEnd: boolean;
+}
+
+interface PlainListParagraphMarker {
+ kind: 'bullet' | 'ordered';
+ prefixLength: number;
+ attrs: Record<string, unknown>;
+}
+
+function plainListParagraphMarker(text: string): PlainListParagraphMarker | null {
+ const bullet = text.match(/^([-+*•])([ \t]+)/);
+ if (bullet) {
+ return { kind: 'bullet', prefixLength: bullet[0].length, attrs: {} };
+ }
+ const ordered = text.match(/^(\d{1,6})([.)])([ \t]+)/);
+ if (ordered) {
+ return {
+ kind: 'ordered',
+ prefixLength: ordered[0].length,
+ attrs: { start: Number(ordered[1]), marker: ordered[2] },
+ };
+ }
+ const cjkOrdered = text.match(/^(\d{1,6})(、)([ \t]*)/);
+ if (cjkOrdered) {
+ return {
+ kind: 'ordered',
+ prefixLength: cjkOrdered[0].length,
+ attrs: { start: Number(cjkOrdered[1]), marker: '、' },
+ };
+ }
+ return null;
+}
+
+function hardBreakListInputRule(
+ find: RegExp,
+ type: NodeType,
+ getAttributes: (match: RegExpMatchArray) => object = () => ({}),
+): InputRule {
+ return new InputRule({
+ find: (text) => {
+ const lineStart = text.lastIndexOf('\n');
+ if (lineStart < 0) return null;
+ const line = text.slice(lineStart + 1);
+ const match = line.match(find);
+ if (!match) return null;
+ return {
+ text: line,
+ index: lineStart + 1,
+ data: { attributes: getAttributes(match) },
+ };
+ },
+ handler: ({ state, range, match }) => {
+ const $markerStart = state.doc.resolve(range.from);
+ if ($markerStart.depth !== 1 || $markerStart.parent.type.name !== 'paragraph') return null;
+
+ const paragraph = $markerStart.parent;
+ const paragraphStart = $markerStart.start();
+ const markerOffset = range.from - paragraphStart;
+ const hardBreak = paragraph.nodeAt(markerOffset - 1);
+ if (hardBreak?.type.name !== 'hardBreak') return null;
+
+ const before = paragraph.content.cut(0, markerOffset - hardBreak.nodeSize);
+ const after = paragraph.content.cut(range.to - paragraphStart);
+ const paragraphType = state.schema.nodes.paragraph;
+ const itemType = state.schema.nodes.listItem;
+ if (!paragraphType || !itemType) return null;
+
+ const leadingParagraph = paragraph.type.create(paragraph.attrs, before, paragraph.marks);
+ const listParagraph = paragraphType.create(null, after);
+ const list = type.create(
+ (match.data?.attributes as Record<string, unknown> | undefined) ?? {},
+ itemType.create(null, listParagraph),
+ );
+ const paragraphPosition = $markerStart.before(1);
+ const replacement = Fragment.fromArray([leadingParagraph, list]);
+ const tr = state.tr.replaceWith(
+ paragraphPosition,
+ paragraphPosition + paragraph.nodeSize,
+ replacement,
+ );
+ const listPosition = paragraphPosition + leadingParagraph.nodeSize;
+ tr.setSelection(TextSelection.create(tr.doc, listPosition + 3));
+ },
+ });
+}
+
+const listItemConfig: NodeConfig = {
+ name: 'listItem',
+ group: 'block',
+ content: 'paragraph block*',
+ defining: true,
+ parseHTML() {
+ return [{ tag: 'li' }];
+ },
+ renderHTML({ HTMLAttributes }) {
+ return ['li', mergeAttributes(HTMLAttributes), 0];
+ },
+};
+
+export const ComposerListItem = Node.create(listItemConfig);
+
+export const ComposerBulletList = Node.create({
+ name: 'bulletList',
+ group: 'block',
+ content: 'listItem+',
+ defining: true,
+ parseHTML() {
+ return [{ tag: 'ul' }];
+ },
+ renderHTML({ HTMLAttributes }) {
+ return ['ul', mergeAttributes(HTMLAttributes), 0];
+ },
+ addInputRules() {
+ return [
+ wrappingInputRule({
+ find: /^\s*([-+*])\s$/,
+ type: this.type,
+ }),
+ hardBreakListInputRule(/^\s*([-+*])\s$/, this.type),
+ ];
+ },
+});
+
+function orderedAttrs(match: RegExpMatchArray): OrderedListAttrs {
+ const marker = (match[2] ?? '、') as OrderedMarker;
+ return {
+ start: Number(match[1] ?? 1),
+ marker,
+ };
+}
+
+export const ComposerOrderedList = Node.create({
+ name: 'orderedList',
+ group: 'block',
+ content: 'listItem+',
+ defining: true,
+ addAttributes() {
+ return {
+ start: {
+ default: 1,
+ parseHTML: (element) => {
+ const value = Number(element.getAttribute('start'));
+ return Number.isInteger(value) && value > 0 ? value : 1;
+ },
+ renderHTML: (attributes) => (attributes.start === 1 ? {} : { start: attributes.start }),
+ },
+ marker: {
+ default: '.',
+ parseHTML: (element) => {
+ const value = element.getAttribute('data-marker');
+ return value === ')' || value === '、' ? value : '.';
+ },
+ renderHTML: (attributes) =>
+ attributes.marker === '.' ? {} : { 'data-marker': attributes.marker },
+ },
+ };
+ },
+ parseHTML() {
+ return [{ tag: 'ol' }];
+ },
+ renderHTML({ HTMLAttributes }) {
+ return ['ol', mergeAttributes(HTMLAttributes), 0];
+ },
+ addInputRules() {
+ return [
+ wrappingInputRule({
+ find: ORDERED_MARKER_RE,
+ type: this.type,
+ getAttributes: orderedAttrs,
+ }),
+ wrappingInputRule({
+ find: CJK_ORDERED_MARKER_RE,
+ type: this.type,
+ getAttributes: orderedAttrs,
+ }),
+ hardBreakListInputRule(ORDERED_MARKER_RE, this.type, orderedAttrs),
+ hardBreakListInputRule(CJK_ORDERED_MARKER_RE, this.type, orderedAttrs),
+ ];
+ },
+});
+
+function selectedListItemDepth(view: EditorView): number | null {
+ const { $from } = view.state.selection;
+ for (let depth = $from.depth; depth > 0; depth -= 1) {
+ if ($from.node(depth).type.name === 'listItem') return depth;
+ }
+ return null;
+}
+
+function selectedListItemIsEmpty(view: EditorView, depth: number): boolean {
+ const item = view.state.selection.$from.node(depth);
+ return (
+ item.childCount === 1 &&
+ item.firstChild?.type.name === 'paragraph' &&
+ item.firstChild.content.size === 0
+ );
+}
+
+function selectedListItemIsOnlyTaskParagraph(view: EditorView, depth: number): boolean {
+ const item = view.state.selection.$from.node(depth);
+ return item.childCount === 1 && item.firstChild === view.state.selection.$from.parent;
+}
+
+function selectedTaskPrefix(view: EditorView): SelectedTaskPrefix | null {
+ const { $from } = view.state.selection;
+ const paragraph = $from.parent;
+ if (paragraph.type.name !== 'paragraph') return null;
+ const text = paragraph.textBetween(0, paragraph.content.size, '\uFFFC', '\uFFFC');
+ const match = text.match(/^\[[ xX]\](?:[ \t]+|$)/);
+ if (!match) return null;
+ return {
+ from: $from.start(),
+ to: $from.start() + match[0].length,
+ bodyIsEmpty: text.slice(match[0].length).trim().length === 0,
+ caretAtOrAfterPrefix: $from.parentOffset >= match[0].length,
+ caretAtParagraphEnd: $from.parentOffset === paragraph.content.size,
+ };
+}
+
+function clearTaskPrefixAndLift(
+ view: EditorView,
+ itemDepth: number,
+ taskPrefix: SelectedTaskPrefix,
+): boolean {
+ if (
+ !taskPrefix.bodyIsEmpty ||
+ !taskPrefix.caretAtParagraphEnd ||
+ !selectedListItemIsOnlyTaskParagraph(view, itemDepth)
+ ) {
+ return false;
+ }
+ view.dispatch(view.state.tr.delete(taskPrefix.from, taskPrefix.to));
+ const itemType = view.state.schema.nodes.listItem;
+ if (itemType) liftListItem(itemType)(view.state, view.dispatch);
+ return true;
+}
+
+function backspaceAfterStructuredList(view: EditorView): boolean {
+ const { state } = view;
+ const { $from } = state.selection;
+ if (
+ !state.selection.empty ||
+ $from.depth !== 1 ||
+ $from.parent.type.name !== 'paragraph' ||
+ $from.parent.content.size !== 0 ||
+ $from.parentOffset !== 0
+ ) {
+ return false;
+ }
+ const paragraphPosition = $from.before(1);
+ const previous = state.doc.resolve(paragraphPosition).nodeBefore;
+ if (previous?.type.name !== 'bulletList' && previous?.type.name !== 'orderedList') return false;
+
+ const tr = state.tr.delete(paragraphPosition, paragraphPosition + $from.parent.nodeSize);
+ tr.setSelection(Selection.near(tr.doc.resolve(paragraphPosition), -1));
+ view.dispatch(tr.scrollIntoView());
+ return true;
+}
+
+/**
+ * Continue a structured list on the composer's explicit newline shortcuts.
+ * An empty item exits the list; a non-empty item becomes two sibling items.
+ * Markdown task prefixes remain editable text, with new items reset to
+ * unchecked state.
+ */
+export function handleStructuredListBreak(view: EditorView): boolean {
+ const { state } = view;
+ const itemType = state.schema.nodes.listItem;
+ const itemDepth = selectedListItemDepth(view);
+ if (!itemType || !state.selection.empty || itemDepth === null) return false;
+ const taskPrefix = selectedTaskPrefix(view);
+ if (
+ taskPrefix?.bodyIsEmpty &&
+ taskPrefix.caretAtOrAfterPrefix &&
+ taskPrefix.caretAtParagraphEnd
+ ) {
+ if (!selectedListItemIsOnlyTaskParagraph(view, itemDepth)) return false;
+ return clearTaskPrefixAndLift(view, itemDepth, taskPrefix);
+ }
+ if (selectedListItemIsEmpty(view, itemDepth)) {
+ return liftListItem(itemType)(state, view.dispatch);
+ }
+ const split = splitListItem(itemType)(state, view.dispatch);
+ if (split && taskPrefix?.caretAtOrAfterPrefix) {
+ view.dispatch(view.state.tr.insertText('[ ] ').scrollIntoView());
+ }
+ return split;
+}
+
+/** Exit an empty structured item with one Backspace, matching plain-list input. */
+export function handleStructuredListBackspace(view: EditorView): boolean {
+ const { state } = view;
+ if (backspaceAfterStructuredList(view)) return true;
+ const itemType = state.schema.nodes.listItem;
+ const { $from } = state.selection;
+ const itemDepth = selectedListItemDepth(view);
+ const taskPrefix = selectedTaskPrefix(view);
+ if (
+ !itemType ||
+ !state.selection.empty ||
+ itemDepth === null ||
+ (taskPrefix
+ ? !taskPrefix.bodyIsEmpty ||
+ !taskPrefix.caretAtOrAfterPrefix ||
+ !taskPrefix.caretAtParagraphEnd ||
+ !selectedListItemIsOnlyTaskParagraph(view, itemDepth)
+ : $from.parentOffset !== 0 || !selectedListItemIsEmpty(view, itemDepth))
+ ) {
+ return false;
+ }
+ if (taskPrefix) return clearTaskPrefixAndLift(view, itemDepth, taskPrefix);
+ return liftListItem(itemType)(state, view.dispatch);
+}
+
+/**
+ * Upgrade a plain list row appended by paste, IME, dictation, or another
+ * direct transaction that does not run input rules.
+ *
+ * The command is intentionally scoped to the final top-level paragraph and
+ * an end-of-document caret. Restored documents and multi-row text are
+ * normalized before insertion; this closes the remaining live-editing gap
+ * without rescanning or rebuilding the full document after every keystroke.
+ */
+function getTrailingPlainListParagraph(view: EditorView): {
+ paragraph: PMNode;
+ marker: PlainListParagraphMarker;
+ paragraphPosition: number;
+} | null {
+ const { state } = view;
+ const { $from } = state.selection;
+ if (
+ !state.selection.empty ||
+ $from.depth !== 1 ||
+ $from.parent.type.name !== 'paragraph' ||
+ $from.parentOffset !== $from.parent.content.size ||
+ $from.after(1) !== state.doc.content.size
+ ) {
+ return null;
+ }
+
+ const paragraph = $from.parent;
+ const text = paragraph.textBetween(0, paragraph.content.size, '\uFFFC', '\uFFFC');
+ const marker = plainListParagraphMarker(text);
+ const first = paragraph.firstChild;
+ if (!marker || first?.type.name !== 'text' || (first.text?.length ?? 0) < marker.prefixLength) {
+ return null;
+ }
+ return { paragraph, marker, paragraphPosition: $from.before(1) };
+}
+
+export function hasTrailingPlainListParagraph(view: EditorView): boolean {
+ return getTrailingPlainListParagraph(view) !== null;
+}
+
+export function promoteTrailingPlainListParagraph(view: EditorView): boolean {
+ const trailing = getTrailingPlainListParagraph(view);
+ if (!trailing) return false;
+ const { state } = view;
+ const { paragraph, marker, paragraphPosition } = trailing;
+
+ const paragraphType = state.schema.nodes.paragraph;
+ const itemType = state.schema.nodes.listItem;
+ const listType =
+ marker.kind === 'ordered' ? state.schema.nodes.orderedList : state.schema.nodes.bulletList;
+ if (!paragraphType || !itemType || !listType) return false;
+
+ const body = paragraph.content.cut(marker.prefixLength);
+ const list = listType.create(
+ marker.attrs,
+ itemType.create(null, paragraphType.create(paragraph.attrs, body)),
+ );
+ const tr = state.tr.replaceWith(paragraphPosition, paragraphPosition + paragraph.nodeSize, list);
+ tr.setSelection(TextSelection.atEnd(tr.doc));
+ view.dispatch(tr.scrollIntoView());
+ return true;
+}
diff --git a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts
new file mode 100644
index 0000000000..5ccafe80be
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts
@@ -0,0 +1,282 @@
+import type { Editor } from '@tiptap/core';
+import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
+
+import type { MentionedResource } from '@/lib/fileTypes';
+import { formatQuoteForSend } from '@/lib/chatQuotes';
+import { formatMentionRef } from '@/lib/mentionRefFormat';
+import {
+ parseProjectDeepLinkHref,
+ parseSessionDeepLinkHref,
+ projectDisplayName,
+} from '@/lib/deepLink';
+import {
+ COMPOSER_QUOTE_NODE_TYPE,
+ composerQuoteAttrsToChatQuote,
+ serializeComposerContentBlocksWithRanges,
+ type ComposerQuoteAttrs,
+ type ComposerSerializedBlock,
+} from '@/lib/composerQuoteDocument';
+import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
+
+import type { MentionChipAttrs } from './MentionChipNode';
+import type { PastedTextChipAttrs } from './PastedTextChipNode';
+import { getDecoratedSlashCommandMatches, type SlashCommandMatch } from './SlashCommandDecoration';
+import { serializeSessionChipText } from './sessionLinkPaste';
+import { serializeProjectChipText } from './pastePipeline';
+
+export interface SerializedComposerContent {
+ text: string;
+ mentions: MentionedResource[];
+ hasQuotes: boolean;
+ agentReferences: AgentInputReference[];
+ pastedTextRanges: PastedTextRange[];
+ slashCommandRanges: SlashCommandRange[];
+}
+
+type OrderedMarker = '.' | ')' | '、';
+
+function orderedListMarker(node: ProseMirrorNode): OrderedMarker {
+ return node.attrs.marker === ')' || node.attrs.marker === '、' ? node.attrs.marker : '.';
+}
+
+/**
+ * Convert the composer's structured document into the Markdown wire format.
+ *
+ * List markers are editor structure rather than paragraph text, so their
+ * serialized width is included when projecting inline reference ranges.
+ */
+export function serializeEditorContent(editor: Editor): SerializedComposerContent {
+ const doc = editor.state.doc;
+ const decoratedSlashMatches = getDecoratedSlashCommandMatches(editor);
+ const blocks: ComposerSerializedBlock[] = [];
+ const mentions: MentionedResource[] = [];
+ const seenMentions = new Set<string>();
+ let hasQuotes = false;
+
+ const addMention = (attrs: MentionChipAttrs) => {
+ // Slash commands and deep links are represented in the wire text but are
+ // not filesystem resources.
+ if (attrs.kind === 'slash' || attrs.kind === 'session' || attrs.kind === 'project') return;
+ const key = `${attrs.kind}:${attrs.path}`;
+ if (seenMentions.has(key)) return;
+ seenMentions.add(key);
+ mentions.push({ type: attrs.kind, name: attrs.label, path: attrs.path });
+ };
+
+ const serializeParagraph = (
+ paragraph: ProseMirrorNode,
+ paragraphPosition: number,
+ prefix = '',
+ ) => {
+ let buffer = prefix;
+ let bufferAgentReferences: AgentInputReference[] = [];
+ let bufferPastedTextRanges: PastedTextRange[] = [];
+ let bufferSlashCommandRanges: SlashCommandRange[] = [];
+ let emittedInlineSegment = false;
+
+ const flushText = (force = false) => {
+ if (!force && !buffer) return;
+ blocks.push({
+ kind: 'text',
+ text: buffer,
+ ...(bufferAgentReferences.length > 0 ? { agentReferences: bufferAgentReferences } : {}),
+ ...(bufferPastedTextRanges.length > 0 ? { pastedTextRanges: bufferPastedTextRanges } : {}),
+ ...(bufferSlashCommandRanges.length > 0
+ ? { slashCommandRanges: bufferSlashCommandRanges }
+ : {}),
+ });
+ buffer = '';
+ bufferAgentReferences = [];
+ bufferPastedTextRanges = [];
+ bufferSlashCommandRanges = [];
+ emittedInlineSegment = true;
+ };
+
+ const appendSlashCommandRanges = (
+ matches: readonly SlashCommandMatch[],
+ documentStart: number,
+ textLength: number,
+ bufferStart: number,
+ ) => {
+ for (const match of matches) {
+ if (match.from < documentStart || match.to > documentStart + textLength) continue;
+ bufferSlashCommandRanges.push({
+ start: bufferStart + match.from - documentStart,
+ end: bufferStart + match.to - documentStart,
+ });
+ }
+ };
+
+ paragraph.forEach((child, childOffset) => {
+ if (child.type.name === COMPOSER_QUOTE_NODE_TYPE) {
+ flushText();
+ hasQuotes = true;
+ blocks.push({
+ kind: 'quote',
+ text: formatQuoteForSend(
+ composerQuoteAttrsToChatQuote(child.attrs as ComposerQuoteAttrs),
+ ),
+ });
+ emittedInlineSegment = true;
+ return;
+ }
+
+ if (child.type.name === 'mentionChip') {
+ const attrs = child.attrs as MentionChipAttrs;
+ addMention(attrs);
+ if (attrs.kind === 'slash') {
+ buffer += `/${attrs.path} `;
+ return;
+ }
+ if (attrs.kind === 'session') {
+ const wire = serializeSessionChipText(attrs);
+ const start = buffer.length;
+ buffer += wire;
+ const target = parseSessionDeepLinkHref(attrs.path);
+ if (target?.messageClientId) {
+ bufferAgentReferences.push({
+ kind: 'message',
+ start,
+ end: buffer.length,
+ href: attrs.path,
+ sessionId: target.sessionId,
+ messageClientId: target.messageClientId,
+ ...(attrs.agentText ? { text: attrs.agentText } : {}),
+ ...(attrs.agentTextTruncated ? { truncated: true } : {}),
+ });
+ } else if (target) {
+ bufferAgentReferences.push({
+ kind: 'session',
+ start,
+ end: buffer.length,
+ href: attrs.path,
+ sessionId: target.sessionId,
+ ...(attrs.titled && attrs.label ? { title: attrs.label } : {}),
+ });
+ }
+ return;
+ }
+ if (attrs.kind === 'project') {
+ const wire = serializeProjectChipText(attrs);
+ const start = buffer.length;
+ buffer += wire;
+ const target = parseProjectDeepLinkHref(attrs.path);
+ if (target) {
+ bufferAgentReferences.push({
+ kind: 'project',
+ start,
+ end: buffer.length,
+ href: attrs.path,
+ name: attrs.label || projectDisplayName(target.workingDir),
+ workingDir: target.workingDir,
+ });
+ }
+ return;
+ }
+ if (attrs.kind === 'dir') {
+ buffer += `@${formatMentionRef(`${attrs.path}/`)}`;
+ return;
+ }
+ if (attrs.kind === 'agent') {
+ const path = attrs.path;
+ buffer += path.includes('/')
+ ? `@${formatMentionRef(path)}`
+ : `@${formatMentionRef(path.replace(/\.md$/, ''))}`;
+ return;
+ }
+ buffer += `@${formatMentionRef(attrs.path)}`;
+ return;
+ }
+
+ if (child.type.name === 'pastedTextChip') {
+ const attrs = child.attrs as PastedTextChipAttrs;
+ const start = buffer.length;
+ buffer += attrs.text;
+ bufferPastedTextRanges.push({ start, end: buffer.length, display: attrs.display });
+ return;
+ }
+
+ if (child.type.name === 'hardBreak') {
+ buffer += '\n';
+ return;
+ }
+
+ if (child.isText) {
+ const childText = child.text ?? '';
+ const bufferStart = buffer.length;
+ const documentStart = paragraphPosition + 1 + childOffset;
+ buffer += childText;
+ appendSlashCommandRanges(
+ decoratedSlashMatches,
+ documentStart,
+ childText.length,
+ bufferStart,
+ );
+ }
+ });
+
+ // Preserve truly empty paragraphs as line breaks, but do not synthesize an
+ // empty text segment after a quote chip at the end of a paragraph.
+ flushText(!emittedInlineSegment);
+ };
+
+ const serializeList = (listNode: ProseMirrorNode, listPosition: number, indent: string) => {
+ const isOrdered = listNode.type.name === 'orderedList';
+ const start =
+ typeof listNode.attrs.start === 'number' &&
+ Number.isInteger(listNode.attrs.start) &&
+ listNode.attrs.start > 0
+ ? listNode.attrs.start
+ : 1;
+ const marker = orderedListMarker(listNode);
+
+ listNode.forEach((item, itemOffset, itemIndex) => {
+ if (item.type.name !== 'listItem') return;
+ const itemPosition = listPosition + 1 + itemOffset;
+ const itemMarker = isOrdered ? `${start + itemIndex}${marker} ` : '- ';
+ const itemIndent = `${indent}${' '.repeat(itemMarker.length)}`;
+ let firstParagraph = true;
+
+ item.forEach((child, childOffset) => {
+ const childPosition = itemPosition + 1 + childOffset;
+ if (child.type.name === 'paragraph') {
+ serializeParagraph(
+ child,
+ childPosition,
+ firstParagraph ? `${indent}${itemMarker}` : itemIndent,
+ );
+ firstParagraph = false;
+ return;
+ }
+ if (child.type.name === 'bulletList' || child.type.name === 'orderedList') {
+ serializeList(child, childPosition, itemIndent);
+ }
+ });
+ });
+ };
+
+ doc.forEach((node, nodeOffset) => {
+ if (node.type.name === COMPOSER_QUOTE_NODE_TYPE) {
+ hasQuotes = true;
+ blocks.push({
+ kind: 'quote',
+ text: formatQuoteForSend(composerQuoteAttrsToChatQuote(node.attrs as ComposerQuoteAttrs)),
+ });
+ return;
+ }
+ if (node.type.name === 'paragraph') {
+ serializeParagraph(node, nodeOffset);
+ return;
+ }
+ if (node.type.name === 'bulletList' || node.type.name === 'orderedList') {
+ serializeList(node, nodeOffset, '');
+ }
+ });
+
+ return {
+ ...serializeComposerContentBlocksWithRanges(blocks),
+ mentions,
+ hasQuotes,
+ };
+}
diff --git a/apps/desktop/src/renderer/lib/composerDraftStore.ts b/apps/desktop/src/renderer/lib/composerDraftStore.ts
index 3d92069ec4..6d17fffd70 100644
--- a/apps/desktop/src/renderer/lib/composerDraftStore.ts
+++ b/apps/desktop/src/renderer/lib/composerDraftStore.ts
@@ -40,6 +40,7 @@ import {
} from '@/lib/composerQuoteDocument';
import type { JSONContent } from '@tiptap/core';
import { createLogger } from '@/lib/logger';
+import { plainTextToComposerDocument } from './composerListDocument';
const log = createLogger('ComposerDraftStore');
@@ -241,14 +242,15 @@ export function saveDraft(
opts?: { silent?: boolean },
): void {
const key = draftKey(sessionId);
- const normalized = draft.quotes && draft.quotes.length > 0
- ? {
- ...draft,
- text: prependLegacyQuotesToComposerDocument(draft.text, draft.quotes),
- quotes: [],
- }
- : draft;
- drafts.set(key, normalized);
+ const withQuotes =
+ draft.quotes && draft.quotes.length > 0
+ ? {
+ ...draft,
+ text: prependLegacyQuotesToComposerDocument(draft.text, draft.quotes),
+ quotes: [],
+ }
+ : draft;
+ drafts.set(key, withQuotes);
if (!opts?.silent) {
const set = listeners.get(key);
if (set) for (const fn of set) {
@@ -395,17 +397,7 @@ export function appendBrowserCommentToDraft(
* (e.g. `@some/path`), which is acceptable for an undo affordance.
*/
export function plainTextToTiptapDoc(text: string): JSONContent {
- if (!text) {
- return { type: 'doc', content: [{ type: 'paragraph' }] };
- }
- return {
- type: 'doc',
- content: text.split('\n').map((line) =>
- line.length === 0
- ? { type: 'paragraph' }
- : { type: 'paragraph', content: [{ type: 'text', text: line }] },
- ),
- };
+ return plainTextToComposerDocument(text);
}
/**
diff --git a/apps/desktop/src/renderer/lib/composerListContinuation.ts b/apps/desktop/src/renderer/lib/composerListContinuation.ts
index b75bc6f664..e831006338 100644
--- a/apps/desktop/src/renderer/lib/composerListContinuation.ts
+++ b/apps/desktop/src/renderer/lib/composerListContinuation.ts
@@ -2,15 +2,10 @@ import type { EditorView } from '@tiptap/pm/view';
import type { ResolvedPos } from '@tiptap/pm/model';
/**
- * Composer 列表接续(纯文本 markdown 辅助):Shift/Alt+Enter 换行时,若当前行
- * 以列表 / 待办 / 引用前缀开头且有内容,自动在新行补下一个前缀(有序列表序号
- * +1);前缀后没有内容时(空项)则清掉前缀退出列表。普通 Enter 保持"发送"
- * 语义不变(2026-07 产品定案:Enter=发送的
- * 肌肉记忆优先,不做 Claude 式"列表内 Enter 继续列表")。
- *
- * ChatInput 是刻意的纯文本编辑器(不引入富文本 list schema),这里是 GitHub
- * 评论框式的"前缀接续"实现:发送给 agent 的内容仍是纯 markdown 文本,
- * 消息管线 / 草稿存储 / mention chip 均不受影响。
+ * Composer 纯文本 Markdown 列表的兼容接续。结构化 bullet / ordered list
+ * 由编辑器 schema 处理;本模块继续覆盖粘贴或旧草稿中的文本前缀,以及尚未
+ * 结构化的待办和引用前缀。Shift/Alt+Enter 接续或退出当前项,普通 Enter
+ * 始终保持发送语义。
*/
export type ListContinuation =
@@ -84,7 +79,7 @@ export function computeListContinuation(
if (!match) return null;
const rest = lineBeforeCaret.slice(match.prefixLength);
// 空项判定看**整行**(光标前 rest + 光标后正文):否则 `1. |todo`(光标在标记后、
- // 正文前)会被当成空项退出、删掉标记留下裸 "todo"(codex P2)。光标后仍有正文时
+ // 正文前)会被当成空项退出、删掉标记留下裸 "todo"。光标后仍有正文时
// 走 continue —— 在光标处插换行 + 下一前缀,把 "todo" 顺成下一项(拆分列表)。
if (rest.trim().length === 0 && lineAfterCaret.trim().length === 0) return { action: 'exit' };
return { action: 'continue', insert: match.nextPrefix };
@@ -162,7 +157,7 @@ export function applyListContinuation(view: EditorView): boolean {
}
/**
- * 空列表项整体回删(对齐 Claude):当前行只剩前缀(如 "2. ")且光标在行尾时,
+ * 空列表项整体回删:当前行只剩前缀(如 "2. ")且光标在行尾时,
* 一次 Backspace 删掉整个前缀——有上一行则连同前面的换行一起删,光标落到
* 上一行行尾;是首行则只删前缀(等效退出列表)。其余情况返回 false,调用方
* 走默认退格。
diff --git a/apps/desktop/src/renderer/lib/composerListDocument.ts b/apps/desktop/src/renderer/lib/composerListDocument.ts
new file mode 100644
index 0000000000..149e2a8f3c
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/composerListDocument.ts
@@ -0,0 +1,247 @@
+import type { JSONContent } from '@tiptap/core';
+
+type ListKind = 'bullet' | 'ordered';
+type OrderedMarker = '.' | ')' | '、';
+
+interface ListMarker {
+ kind: ListKind;
+ prefixLength: number;
+ marker: string;
+ start?: number;
+}
+
+interface ComposerLine {
+ content: JSONContent[];
+ text: string;
+}
+
+const BULLET_RE = /^([-+*•])([ \t]+)/;
+const ORDERED_RE = /^(\d{1,6})([.)、])([ \t]*)/;
+
+function inlineNodeText(node: JSONContent): string {
+ if (node.type === 'text') return node.text ?? '';
+ return '\uFFFC';
+}
+
+function pushLine(lines: ComposerLine[], content: JSONContent[]): void {
+ lines.push({
+ content,
+ text: content.map(inlineNodeText).join(''),
+ });
+}
+
+function splitParagraphLines(paragraph: JSONContent): ComposerLine[] {
+ const lines: ComposerLine[] = [];
+ let current: JSONContent[] = [];
+
+ const appendText = (text: string, node: JSONContent) => {
+ const parts = text.split('\n');
+ parts.forEach((part, index) => {
+ if (part) current.push({ ...node, text: part });
+ if (index < parts.length - 1) {
+ pushLine(lines, current);
+ current = [];
+ }
+ });
+ };
+
+ for (const node of paragraph.content ?? []) {
+ if (node.type === 'hardBreak') {
+ pushLine(lines, current);
+ current = [];
+ continue;
+ }
+ if (node.type === 'text' && (node.text ?? '').includes('\n')) {
+ appendText(node.text ?? '', node);
+ continue;
+ }
+ current.push(node);
+ }
+ pushLine(lines, current);
+ return lines;
+}
+
+function parseListMarker(text: string): ListMarker | null {
+ // Only unindented rows are promoted here. Indented rows may be nested
+ // Markdown, and the visual fallback remains responsible for those until
+ // their parent item is also represented structurally.
+ if (/^[ \t]/.test(text)) return null;
+
+ const bullet = text.match(BULLET_RE);
+ if (bullet) {
+ return {
+ kind: 'bullet',
+ prefixLength: bullet[0].length,
+ marker: 'bullet',
+ };
+ }
+
+ const ordered = text.match(ORDERED_RE);
+ if (ordered) {
+ const marker = ordered[2] as OrderedMarker;
+ if (marker !== '、' && ordered[3].length === 0) return null;
+ return {
+ kind: 'ordered',
+ prefixLength: ordered[0].length,
+ marker,
+ start: Number(ordered[1]),
+ };
+ }
+ return null;
+}
+
+function stripPrefix(content: JSONContent[], prefixLength: number): JSONContent[] | null {
+ const first = content[0];
+ if (!first || first.type !== 'text') return null;
+ const text = first.text ?? '';
+ if (text.length < prefixLength) return null;
+ const remaining = text.slice(prefixLength);
+ const rest = remaining ? [{ ...first, text: remaining }, ...content.slice(1)] : content.slice(1);
+ return rest;
+}
+
+function paragraphFromLine(line: ComposerLine, attrs?: JSONContent['attrs']): JSONContent {
+ return {
+ type: 'paragraph',
+ ...(attrs ? { attrs } : {}),
+ ...(line.content.length > 0 ? { content: line.content } : {}),
+ };
+}
+
+function listFromLines(
+ lines: ComposerLine[],
+ marker: ListMarker,
+ paragraphAttrs?: JSONContent['attrs'],
+): JSONContent {
+ const items = lines.map((line) => {
+ const lineMarker = parseListMarker(line.text);
+ const content =
+ stripPrefix(line.content, lineMarker?.prefixLength ?? marker.prefixLength) ?? line.content;
+ return {
+ type: 'listItem',
+ content: [paragraphFromLine({ content, text: '' }, paragraphAttrs)],
+ };
+ });
+ return {
+ type: marker.kind === 'ordered' ? 'orderedList' : 'bulletList',
+ ...(marker.kind === 'ordered'
+ ? { attrs: { start: marker.start ?? 1, marker: marker.marker } }
+ : {}),
+ content: items,
+ };
+}
+
+function sameListMarker(left: ListMarker, right: ListMarker): boolean {
+ return left.kind === right.kind && left.marker === right.marker;
+}
+
+function paragraphToBlocks(paragraph: JSONContent): JSONContent[] {
+ const lines = splitParagraphLines(paragraph);
+ if (!lines.some((line) => parseListMarker(line.text))) return [paragraph];
+
+ const blocks: JSONContent[] = [];
+ let plainLines: ComposerLine[] = [];
+ let listLines: ComposerLine[] = [];
+ let listMarker: ListMarker | null = null;
+
+ const flushPlain = () => {
+ if (plainLines.length === 0) return;
+ plainLines.forEach((line) => blocks.push(paragraphFromLine(line, paragraph.attrs)));
+ plainLines = [];
+ };
+ const flushList = () => {
+ if (listLines.length === 0 || !listMarker) return;
+ blocks.push(listFromLines(listLines, listMarker, paragraph.attrs));
+ listLines = [];
+ listMarker = null;
+ };
+
+ for (const line of lines) {
+ const marker = parseListMarker(line.text);
+ if (!marker) {
+ flushList();
+ plainLines.push(line);
+ continue;
+ }
+ const stripped = stripPrefix(line.content, marker.prefixLength);
+ if (!stripped) {
+ flushList();
+ plainLines.push(line);
+ continue;
+ }
+ if (listMarker && !sameListMarker(listMarker, marker)) flushList();
+ flushPlain();
+ listMarker ??= marker;
+ listLines.push(line);
+ }
+ flushList();
+ flushPlain();
+ return blocks;
+}
+
+function canMergeLists(left: JSONContent, right: JSONContent): boolean {
+ if (left.type !== right.type) return false;
+ if (left.type === 'bulletList') return true;
+ const leftStart = Number(left.attrs?.start);
+ const rightStart = Number(right.attrs?.start);
+ return (
+ left.attrs?.marker === right.attrs?.marker &&
+ Number.isInteger(leftStart) &&
+ Number.isInteger(rightStart) &&
+ leftStart + (left.content?.length ?? 0) === rightStart
+ );
+}
+
+function mergeLists(left: JSONContent, right: JSONContent): JSONContent {
+ return {
+ ...left,
+ content: [...(left.content ?? []), ...(right.content ?? [])],
+ };
+}
+
+/**
+ * Promote plain Markdown list rows at composer document boundaries to the
+ * structured list nodes used by the editor.
+ *
+ * This is deliberately a one-way normalization: malformed rows, indented
+ * nested rows, and paragraphs containing inline atoms that obscure the marker
+ * remain plain text and can still use the compatibility renderer.
+ */
+export function normalizeComposerDocumentJSON(document: JSONContent): JSONContent {
+ if (document.type !== 'doc' || !Array.isArray(document.content)) return document;
+
+ const normalized: JSONContent[] = [];
+ for (const node of document.content) {
+ const blocks = node.type === 'paragraph' ? paragraphToBlocks(node) : [node];
+ for (const block of blocks) {
+ const previous = normalized.at(-1);
+ if (previous && canMergeLists(previous, block)) {
+ normalized[normalized.length - 1] = mergeLists(previous, block);
+ } else {
+ normalized.push(block);
+ }
+ }
+ }
+ return { ...document, content: normalized };
+}
+
+/** Build a normalized composer document from plain clipboard/history text. */
+export function plainTextToComposerDocument(text: string): JSONContent {
+ const content = text
+ .split('\n')
+ .map((line) =>
+ line.length > 0
+ ? { type: 'paragraph', content: [{ type: 'text', text: line }] }
+ : { type: 'paragraph' },
+ );
+ return normalizeComposerDocumentJSON({ type: 'doc', content });
+}
+
+export function composerDocumentContainsList(document: JSONContent): boolean {
+ return (
+ document.type === 'doc' &&
+ (document.content ?? []).some(
+ (node) => node.type === 'bulletList' || node.type === 'orderedList',
+ )
+ );
+}
diff --git a/apps/desktop/src/renderer/lib/composerQuoteDocument.ts b/apps/desktop/src/renderer/lib/composerQuoteDocument.ts
index 2ac934c060..a79ca25232 100644
--- a/apps/desktop/src/renderer/lib/composerQuoteDocument.ts
+++ b/apps/desktop/src/renderer/lib/composerQuoteDocument.ts
@@ -11,6 +11,7 @@ import type { JSONContent } from '@tiptap/core';
import type { AgentInputReference } from '../../shared/agentInputQueue';
import { parseChatQuoteSegments, type ChatQuote, type ChatQuoteSegment } from '@/lib/chatQuotes';
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
+import { normalizeComposerDocumentJSON } from './composerListDocument';
export const COMPOSER_QUOTE_NODE_TYPE = 'composerQuote';
@@ -192,12 +193,12 @@ export function quoteSegmentsToComposerDocument(
export function composerHistoryEntryToDocument(entry: ComposerHistoryEntry): JSONContent {
if (entry.quotesEncoded === true) {
const quotedDocument = quoteSegmentsToComposerDocument(parseChatQuoteSegments(entry.content));
- if (quotedDocument) return quotedDocument;
+ if (quotedDocument) return normalizeComposerDocumentJSON(quotedDocument);
}
- return {
+ return normalizeComposerDocumentJSON({
type: 'doc',
content: [paragraph(entry.content ? [{ type: 'text', text: entry.content }] : [])],
- };
+ });
}
/**
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index 2d4a5cb2e4..d1c5a77931 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -13,7 +13,7 @@
'Inter Variable', Inter, -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB',
'HarmonyOS Sans SC', 'Microsoft YaHei UI', 'Microsoft YaHei', 'Noto Sans CJK SC',
'Source Han Sans SC', 'Segoe UI', Roboto, sans-serif;
- /* 默认代码字体走 Codex / 系统等宽风格(mac 上 SF Mono 不对网页暴露字体名,
+ /* 默认代码字体使用系统等宽字体(mac 上 SF Mono 不对网页暴露字体名,
实际命中 Menlo;Win 命中 Consolas)。JetBrains Mono 已降级为可选预设、不再是
默认。CJK 显式回退 PingFang/雅黑,保证代码块中英混排统一等宽。 */
--app-font-code-default:
@@ -346,6 +346,33 @@ html:lang(ko) {
.cm-editor .cm-dropCursor {
border-left-color: var(--caret-accent) !important;
}
+/* Structured composer lists keep markers and body text in the same layout
+ tree. Continuation lines therefore follow the list item content edge
+ without decoration-owned width measurements. */
+[data-chat-input-root] .ProseMirror :is(ul, ol) {
+ margin: 0;
+ padding-inline-start: 1.5em;
+}
+[data-chat-input-root] .ProseMirror ul {
+ list-style-type: disc;
+}
+[data-chat-input-root] .ProseMirror ol {
+ list-style-type: decimal;
+}
+[data-chat-input-root] .ProseMirror ol[data-marker=')'] > li::marker {
+ content: counter(list-item) ') ';
+}
+[data-chat-input-root] .ProseMirror ol[data-marker='、'] > li::marker {
+ content: counter(list-item) '、';
+}
+[data-chat-input-root] .ProseMirror li {
+ padding-inline-start: 0.15em;
+ overflow-wrap: anywhere;
+}
+[data-chat-input-root] .ProseMirror li > p {
+ margin: 0;
+}
+
/* composer 列表行缩进(ComposerListIndentDecoration):单行列表使用段落级
decoration,多行列表的无特殊标点行使用 inline-block 换行容器。padding-left
留出"基础缩进 + 前缀宽度",首行再用负 text-indent 把列表标记悬挂回基础