Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 完善列表恢复与编辑边界
zhangyongjiee86d764ef707
diff --git a/apps/desktop/src/renderer/__tests__/composerDocState.test.ts b/apps/desktop/src/renderer/__tests__/composerDocState.test.tsindex 46018bedbc..7b22009994 100644--- a/apps/desktop/src/renderer/__tests__/composerDocState.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerDocState.test.ts@@ -9,7 +9,9 @@ import { afterEach, describe, expect, it } from 'vitest';import {composerDocIsEmpty,docContainsAtomChip,+ docContainsStructuredList,} from '@/components/new-chat/composerDocState';+import { ComposerBulletList, ComposerListItem } from '@/components/new-chat/ComposerListNodes';import { ComposerQuoteNode } from '@/components/new-chat/ComposerQuoteNode';import { MentionChipNode } from '@/components/new-chat/MentionChipNode';import { PastedTextChipNode } from '@/components/new-chat/PastedTextChipNode';@@ -23,7 +25,16 @@ afterEach(() => {function makeEditor(): Editor {const editor = new Editor({- extensions: [Document, Paragraph, Text, MentionChipNode, PastedTextChipNode, ComposerQuoteNode],+ extensions: [+ Document,+ Paragraph,+ Text,+ ComposerListItem,+ ComposerBulletList,+ MentionChipNode,+ PastedTextChipNode,+ ComposerQuoteNode,+ ],content: { type: 'doc', content: [{ type: 'paragraph', content: [] }] },});editors.push(editor);@@ -45,6 +56,21 @@ describe('composerDocState', () => {expect(composerDocIsEmpty(editor.state.doc)).toBe(false);});+ it('treats an empty structured list item as non-empty content', () => {+ const editor = makeEditor();+ editor.commands.setContent({+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ content: [{ type: 'listItem', content: [{ type: 'paragraph' }] }],+ },+ ],+ });+ expect(docContainsStructuredList(editor.state.doc)).toBe(true);+ expect(composerDocIsEmpty(editor.state.doc)).toBe(false);+ });+it('treats a chip-only doc as non-empty (review P2)', () => {// atom chip 无文本投影,textContent 判空会把只含 chip 的草稿误当空,// ↑ 历史回填 replaceWith 整段覆盖丢 payload。diff --git a/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.tsindex b52d1cb522..5f3dde9371 100644--- a/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts@@ -782,6 +782,36 @@ describe('composer structured list serialization', () => {expect(serializeEditorSlice(editor, slice)).toBe('1. first\n2. second');});+ it('keeps the original ordinal when copying from the middle of an ordered 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: 'listItem',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'second' }] }],+ },+ ],+ },+ ],+ });+ let secondTextPosition = 0;+ editor.state.doc.descendants((node, position) => {+ if (node.isText && node.text === 'second') secondTextPosition = position;+ });+ editor.commands.setTextSelection(secondTextPosition + 1);+ const slice = editor.state.doc.slice(secondTextPosition, editor.state.doc.content.size);++ expect(serializeEditorSlice(editor, slice)).toBe('2. second');+ });+it('preserves non-default bullet markers and spacing when sending', () => {const editor = makeEditor({type: 'doc',@@ -822,6 +852,37 @@ describe('composer structured list serialization', () => {expect(serializeEditorContent(editor).text).toBe('1.\titem');});+ it('expands tab separators when indenting nested list content', () => {+ const editor = makeEditor({+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ attrs: { marker: '-', separator: '\t' },+ 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('-\tparent\n - child');+ });+it('keeps a dragged quote inside its list item', () => {const editor = makeEditor({type: 'doc',@@ -858,6 +919,54 @@ describe('composer structured list serialization', () => {]);});+ it('keeps a restored nested list quote under its literal list row', () => {+ const editor = makeEditor({+ type: 'doc',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'parent' }] },+ { type: 'paragraph', content: [{ type: 'text', text: ' - child' }] },+ {+ type: 'paragraph',+ content: [{ type: COMPOSER_QUOTE_NODE_TYPE, attrs: { text: 'quoted' } }],+ },+ ],+ });++ const serialized = serializeEditorContent(editor).text;+ expect(serialized).toBe(+ 'parent\n - child\n > <!-- cindy-composer-quote -->\n > quoted',+ );+ expect(parseChatQuoteSegments(serialized)).toEqual([+ { kind: 'text', text: 'parent\n - child' },+ { kind: 'quote', quote: { text: 'quoted' } },+ ]);+ });++ it('preserves indentation on an empty nested list item', () => {+ const editor = makeEditor({+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'parent' }] },+ {+ type: 'bulletList',+ content: [{ type: 'listItem', content: [{ type: 'paragraph' }] }],+ },+ ],+ },+ ],+ },+ ],+ });++ expect(serializeEditorContent(editor).text).toBe('- parent\n - ');+ });+it('does not duplicate restored continuation indentation after a list quote', () => {const editor = makeEditor({type: 'doc',diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex bee11c2ae9..f213275e1f 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -129,7 +129,7 @@ import {pastedProjectChipAttrs,} from './pastePipeline';import { upgradePastedPathsToChips, type PendingPathRange } from './pathPaste';-import { docContainsAtomChip } from './composerDocState';+import { composerDocIsEmpty } from './composerDocState';import {isComposerBlankPointerTarget,isInteractiveFocusedElement,@@ -640,26 +640,7 @@ function hasFocusMovedToInteractiveElement(focusAnchor: Element | null, editor:*/function isEditorEmpty(editor: Editor | null): boolean {if (!editor) return true;- const doc = editor.state.doc;- if (doc.childCount === 0) return true;- let hasContent = false;- doc.descendants((node) => {- if (hasContent) return false;- if (- node.type.name === 'mentionChip' ||- node.type.name === 'pastedTextChip' ||- node.type.name === COMPOSER_QUOTE_NODE_TYPE- ) {- hasContent = true;- return false;- }- if (node.isText && (node.text ?? '').trim().length > 0) {- hasContent = true;- return false;- }- return true;- });- return !hasContent;+ return composerDocIsEmpty(editor.state.doc);}/**@@ -1563,15 +1544,16 @@ export function ChatInput({replacement.unshift(state.schema.nodes.paragraph.create());}const fragment = Fragment.from(replacement);+ const pasteIntoTrailingEmptyLine = paragraphEndsDocument && paragraphIsEmptyLine;const tr =- paragraphEndsDocument && paragraphIsEmptyLine+ pasteIntoTrailingEmptyLine? state.tr.replaceWith(paragraphPosition,paragraphPosition + $from.parent.nodeSize,fragment,): state.tr.replaceSelection(new Slice(fragment, 0, 0));- tr.setSelection(TextSelection.atEnd(tr.doc));+ if (pasteIntoTrailingEmptyLine) tr.setSelection(TextSelection.atEnd(tr.doc));view.dispatch(tr.scrollIntoView());return true;}@@ -1735,8 +1717,8 @@ export function ChatInput({// 浏览中途新增/修改任意 chip 后 eq 失配,仍不介入。const isUnmodifiedHydratedHistory =idx >= 0 && hydratedHistoryDocumentRef.current?.eq(editorInstance) === true;- if (docContainsAtomChip(editorInstance) && !isUnmodifiedHydratedHistory) return false;- const isEmpty = editorInstance.textContent.trim().length === 0;+ if (!isUnmodifiedHydratedHistory && !composerDocIsEmpty(editorInstance)) return false;+ const isEmpty = composerDocIsEmpty(editorInstance);const replaceWithHistoryEntry = (entry: ComposerHistoryEntry) => {const historyDocument = view.state.schema.nodeFromJSON(composerHistoryEntryToDocument(entry),diff --git a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.tsindex 8e2e8b6714..e6d7f42642 100644--- a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts+++ b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts@@ -1,5 +1,5 @@import type { Editor } from '@tiptap/core';-import { Slice, type Node as ProseMirrorNode } from '@tiptap/pm/model';+import { Fragment, Slice, type Node as ProseMirrorNode } from '@tiptap/pm/model';import { EditorState } from '@tiptap/pm/state';import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';@@ -38,7 +38,27 @@ export interface SerializedComposerContent {type OrderedMarker = '.' | ')' | '、';const EMPTY_LIST_ITEM_MARKER_RE =- /(?:^|\n)(?:[1-9]\d{0,5}[.)][ \t]+|[1-9]\d{0,5}、[ \t]*|[-+*•][ \t]+)$/;+ /(?:^|\n)[ \t]*(?:[1-9]\d{0,5}[.)][ \t]+|[1-9]\d{0,5}、[ \t]*|[-+*•][ \t]+)$/;++const TAB_SIZE = 4;++function expandedIndentWidth(text: string): number {+ let column = 0;+ for (const character of text) {+ if (character === '\t') {+ column += TAB_SIZE - (column % TAB_SIZE);+ } else {+ column += 1;+ }+ }+ return column;+}++function literalListContinuationPrefix(text: string): string | null {+ const match = text.match(/^([ \t]+)(?:[-+*•]|[1-9]\d{0,5}[.)、])([ \t]+)/);+ if (!match) return null;+ return ' '.repeat(expandedIndentWidth(match[0]));+}function orderedListMarker(node: ProseMirrorNode): OrderedMarker {return node.attrs.marker === ')' || node.attrs.marker === '、' ? node.attrs.marker : '.';@@ -143,7 +163,7 @@ function serializeComposerDocument(// in the current text block preserves the list marker. Put the// encoded quote on its own continuation lines so history parsing// can still recognize the private marker and source metadata.- const continuationPrefix = ' '.repeat(prefix.length);+ const continuationPrefix = ' '.repeat(expandedIndentWidth(prefix));const quoteLines = quoteText.split('\n');const quoteSeparator = continuationAfterQuote === null ? '' : '\n';buffer += `${quoteSeparator}\n${quoteLines@@ -281,7 +301,7 @@ function serializeComposerDocument(const itemMarker = isOrdered? `${start + itemIndex}${marker}${separator}`: `${bulletListMarker(listNode)}${bulletListSeparator(listNode)}`;- const itemIndent = `${indent}${' '.repeat(itemMarker.length)}`;+ const itemIndent = ' '.repeat(expandedIndentWidth(`${indent}${itemMarker}`));let firstParagraph = true;item.forEach((child, childOffset) => {@@ -302,7 +322,7 @@ function serializeComposerDocument(});};- doc.forEach((node, nodeOffset) => {+ doc.forEach((node, nodeOffset, nodeIndex) => {if (node.type.name === COMPOSER_QUOTE_NODE_TYPE) {hasQuotes = true;blocks.push({@@ -312,6 +332,27 @@ function serializeComposerDocument(return;}if (node.type.name === 'paragraph') {+ const onlyQuote =+ node.childCount === 1 && node.firstChild?.type.name === COMPOSER_QUOTE_NODE_TYPE;+ const previous = nodeIndex > 0 ? doc.child(nodeIndex - 1) : null;+ const literalContinuation =+ onlyQuote && previous?.type.name === 'paragraph'+ ? literalListContinuationPrefix(previous.textContent)+ : null;+ if (literalContinuation) {+ hasQuotes = true;+ const quoteText = formatQuoteForSend(+ composerQuoteAttrsToChatQuote(node.firstChild!.attrs as ComposerQuoteAttrs),+ );+ blocks.push({+ kind: 'text',+ text: quoteText+ .split('\n')+ .map((line) => `${literalContinuation}${line}`)+ .join('\n'),+ });+ return;+ }serializeParagraph(node, nodeOffset);return;}@@ -348,7 +389,77 @@ export function serializeEditorSlice(editor: Editor | null, slice: Slice): strinconst emptyDoc = editor.state.schema.topNodeType.createAndFill();if (!emptyDoc) throw new Error('composer schema cannot create an empty document');const state = EditorState.create({ schema: editor.state.schema, doc: emptyDoc });- const replaced = state.tr.replace(0, state.doc.content.size, slice).doc;+ const { $from } = editor.state.selection;+ let sourceList: ProseMirrorNode | null = null;+ let sourceListDepth: number | null = null;+ for (let depth = $from.depth; depth > 0; depth -= 1) {+ const list = $from.node(depth);+ if (list.type.name !== 'orderedList') continue;+ sourceList = list;+ sourceListDepth = depth;+ break;+ }+ let replaced = state.tr.replace(0, state.doc.content.size, slice).doc;+ const sourceIndex = sourceListDepth === null ? null : $from.index(sourceListDepth);+ const firstOrderedList = (() => {+ let found: { node: ProseMirrorNode; position: number } | null = null;+ replaced.descendants((node, position) => {+ if (found === null && node.type.name === 'orderedList') {+ found = { node, position };+ return false;+ }+ return found === null;+ });+ return found;+ })();++ // A text-only slice from inside a list item loses the enclosing list.+ // Rebuild the selected source items so plain-text copies keep their marker.+ if (sourceList && sourceIndex !== null && firstOrderedList === null) {+ const endResolved = editor.state.doc.resolve(editor.state.selection.to);+ const endIndex =+ sourceListDepth !== null && endResolved.node(sourceListDepth) === sourceList+ ? endResolved.index(sourceListDepth) + 1+ : sourceIndex;+ const items = sourceList.content.content.slice(sourceIndex, Math.max(sourceIndex + 1, endIndex));+ if (items.length > 0) {+ const copiedList = sourceList.copy(Fragment.from(items));+ replaced = state.tr.replace(+ 0,+ state.doc.content.size,+ new Slice(Fragment.from(copiedList), 0, 0),+ ).doc;+ }+ }++ // A partial selection keeps the source list's attrs but may omit earlier+ // siblings. Shift the copied ordered-list start to the selected item.+ const copiedStart =+ sourceList && sourceIndex !== null+ ? Number(sourceList.attrs.start) + sourceIndex+ : null;+ if (copiedStart !== null) {+ let orderedListPosition: number | null = null;+ replaced.descendants((node, position) => {+ if (orderedListPosition === null && node.type.name === 'orderedList') {+ orderedListPosition = position;+ return false;+ }+ return orderedListPosition === null;+ });+ if (orderedListPosition !== null) {+ const node = replaced.nodeAt(orderedListPosition);+ if (node) {+ const replacedState = EditorState.create({ schema: editor.state.schema, doc: replaced });+ replaced = replacedState.tr+ .setNodeMarkup(orderedListPosition, node.type, {+ ...node.attrs,+ start: copiedStart,+ })+ .doc;+ }+ }+ }return serializeComposerDocument(replaced, []).text;} catch {return slice.content.textBetween(0, slice.content.size, '\n');diff --git a/apps/desktop/src/renderer/components/new-chat/composerDocState.ts b/apps/desktop/src/renderer/components/new-chat/composerDocState.tsindex 1e0c50ca03..47534a4f8d 100644--- a/apps/desktop/src/renderer/components/new-chat/composerDocState.ts+++ b/apps/desktop/src/renderer/components/new-chat/composerDocState.ts@@ -23,7 +23,24 @@ export function docContainsAtomChip(doc: ProseMirrorNode): boolean {return found;}+/** Structured list nodes carry a visible marker even when their paragraph is empty. */+export function docContainsStructuredList(doc: ProseMirrorNode): boolean {+ let found = false;+ doc.descendants((node) => {+ if (node.type.name === 'bulletList' || node.type.name === 'orderedList') {+ found = true;+ return false;+ }+ return !found;+ });+ return found;+}+/** 输入框文档是否"真空"(无文本且无 chip)——textContent 判空的 chip-aware 版。 */export function composerDocIsEmpty(doc: ProseMirrorNode): boolean {- return !docContainsAtomChip(doc) && doc.textContent.trim().length === 0;+ return (+ !docContainsAtomChip(doc) &&+ !docContainsStructuredList(doc) &&+ doc.textContent.trim().length === 0+ );}diff --git a/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.ts b/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.tsindex 6614901cdb..453f8c9c52 100644--- a/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.ts@@ -89,6 +89,24 @@ describe('draftHasContent', () => {),).toBe(true);});++ it('counts an empty structured list item as content', () => {+ expect(+ draftHasContent(+ draft({+ text: {+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ content: [{ type: 'listItem', content: [{ type: 'paragraph' }] }],+ },+ ],+ },+ }),+ ),+ ).toBe(true);+ });});describe('owner isolation', () => {diff --git a/apps/desktop/src/renderer/lib/__tests__/composerListContinuation.test.ts b/apps/desktop/src/renderer/lib/__tests__/composerListContinuation.test.tsindex e4163225b8..da99c9ce28 100644--- a/apps/desktop/src/renderer/lib/__tests__/composerListContinuation.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/composerListContinuation.test.ts@@ -44,8 +44,9 @@ describe('computeListContinuation', () => {});describe('无序列表', () => {- it('`- ` / `* ` / `• ` 原样接续', () => {+ it('`- ` / `+ ` / `* ` / `• ` 原样接续', () => {expect(computeListContinuation('- item')).toEqual({ action: 'continue', insert: '- ' });+ expect(computeListContinuation('+ item')).toEqual({ action: 'continue', insert: '+ ' });expect(computeListContinuation('* item')).toEqual({ action: 'continue', insert: '* ' });expect(computeListContinuation('• item')).toEqual({ action: 'continue', insert: '• ' });});diff --git a/apps/desktop/src/renderer/lib/composerDraftStore.ts b/apps/desktop/src/renderer/lib/composerDraftStore.tsindex 6d17fffd70..e7738a4633 100644--- a/apps/desktop/src/renderer/lib/composerDraftStore.ts+++ b/apps/desktop/src/renderer/lib/composerDraftStore.ts@@ -141,6 +141,7 @@ function tiptapDocHasContent(node: JSONContent | null | undefined): boolean {node.type === 'pastedTextChip' ||node.type === COMPOSER_QUOTE_NODE_TYPE) return true;+ if (node.type === 'bulletList' || node.type === 'orderedList') return true;if (typeof node.text === 'string' && node.text.trim().length > 0) return true;if (Array.isArray(node.content)) {return node.content.some(tiptapDocHasContent);diff --git a/apps/desktop/src/renderer/lib/composerListContinuation.ts b/apps/desktop/src/renderer/lib/composerListContinuation.tsindex e831006338..e17427cfac 100644--- a/apps/desktop/src/renderer/lib/composerListContinuation.ts+++ b/apps/desktop/src/renderer/lib/composerListContinuation.ts@@ -21,8 +21,8 @@ export interface ListPrefixMatch {// 顺序敏感:checkbox 必须先于 bullet 匹配(`- [ ] ` 也满足 bullet 的模式)。// checkbox 允许行在 `]` 处截止(`(\s+|$)`),这样 "- [ ]" 也能识别成空项退出。-const CHECKBOX_RE = /^(\s*)([-*])(\s+)\[[ xX]\](\s+|$)/;-const BULLET_RE = /^(\s*)([-*•])(\s+)/;+const CHECKBOX_RE = /^(\s*)([-+*])(\s+)\[[ xX]\](\s+|$)/;+const BULLET_RE = /^(\s*)([-+*•])(\s+)/;const ORDERED_RE = /^(\s*)(\d{1,6})([.)])(\s+)/;// 中文顿号序号(`1、`)不要求后随空格,符合中文输入习惯。const ORDERED_CJK_RE = /^(\s*)(\d{1,6})(、)(\s*)/;diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.cssindex a2d16e2eab..6e4e1e7cfa 100644--- a/apps/desktop/src/renderer/styles/globals.css+++ b/apps/desktop/src/renderer/styles/globals.css@@ -351,6 +351,7 @@ html:lang(ko) {without decoration-owned width measurements. */[data-chat-input-root] .ProseMirror :is(ul, ol) {margin: 0;+ --composer-list-padding: 1.5em;padding-inline-start: var(--composer-list-padding, 1.5em);}[data-chat-input-root] .ProseMirror ol[data-marker-digits='2'] {