Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 保留列表标记与代码块边界
zhangyongjie4cbf5db2f96a
diff --git a/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts b/apps/desktop/src/renderer/__tests__/composerListDocument.test.tsindex 7885b5ed59..6dd39f890c 100644--- a/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts@@ -151,6 +151,58 @@ describe('composer list document normalization', () => {});});+ it('preserves accepted unordered marker syntax and spacing', () => {+ expect(plainTextToComposerDocument('+ item\n• next')).toEqual({+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ attrs: { marker: '+', separator: ' ' },+ content: [+ {+ type: 'listItem',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'item' }] }],+ },+ ],+ },+ {+ type: 'bulletList',+ attrs: { marker: '•', separator: ' ' },+ content: [+ {+ type: 'listItem',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'next' }] }],+ },+ ],+ },+ ],+ });+ });++ it('does not promote marker-shaped lines inside fenced code', () => {+ expect(+ plainTextToComposerDocument('before\n```js\n1. literal\n```\n2. real'),+ ).toEqual({+ type: 'doc',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'before' }] },+ { type: 'paragraph', content: [{ type: 'text', text: '```js' }] },+ { type: 'paragraph', content: [{ type: 'text', text: '1. literal' }] },+ { type: 'paragraph', content: [{ type: 'text', text: '```' }] },+ {+ type: 'orderedList',+ attrs: { start: 2, marker: '.' },+ content: [+ {+ type: 'listItem',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'real' }] }],+ },+ ],+ },+ ],+ });+ });+it('leaves existing structured content unchanged', () => {const document = {type: 'doc' as const,diff --git a/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.tsindex ab8d6d413b..a5fba9aaf7 100644--- a/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts@@ -15,7 +15,11 @@ import {handleStructuredListBreak,promoteTrailingPlainListParagraph,} from '@/components/new-chat/ComposerListNodes';-import { serializeEditorContent } from '@/components/new-chat/composerContentSerialization';+import {+ serializeEditorContent,+ serializeEditorSlice,+} from '@/components/new-chat/composerContentSerialization';+import { COMPOSER_QUOTE_NODE_TYPE } from '@/lib/composerQuoteDocument';const TestMentionChip = Node.create({name: 'mentionChip',@@ -53,6 +57,24 @@ const TestPastedTextChip = Node.create({},});+const TestQuote = Node.create({+ name: COMPOSER_QUOTE_NODE_TYPE,+ inline: true,+ group: 'inline',+ atom: true,+ addAttributes() {+ return {+ text: { default: '' },+ sourcePath: { default: null },+ startLine: { default: null },+ endLine: { default: null },+ };+ },+ renderHTML({ HTMLAttributes }) {+ return ['span', HTMLAttributes];+ },+});+const editors: Editor[] = [];function makeEditor(content?: Record<string, unknown>): Editor {@@ -68,6 +90,7 @@ function makeEditor(content?: Record<string, unknown>): Editor {HardBreak,TestMentionChip,TestPastedTextChip,+ TestQuote,],content: content ?? { type: 'doc', content: [{ type: 'paragraph' }] },});@@ -108,7 +131,7 @@ describe('composer structured list input rules', () => {{typed: '• ',listType: 'bulletList',- attrs: {},+ attrs: { marker: '•', separator: ' ' },},{typed: '1. ',@@ -137,6 +160,23 @@ describe('composer structured list input rules', () => {expect(list?.firstChild?.firstChild?.type.name).toBe('paragraph');});+ it('does not promote an indented marker to a top-level list', () => {+ const editor = makeEditor();++ typeThroughInputRules(editor, ' - ');++ expect(editor.state.doc.firstChild?.type.name).toBe('paragraph');+ expect(editor.state.doc.firstChild?.textContent).toBe(' - ');+ });++ it('reserves enough marker width for long ordered-list numbers', () => {+ const editor = makeEditor();++ typeThroughInputRules(editor, '123456. ');++ expect(editor.view.dom.querySelector('ol')?.getAttribute('data-marker-digits')).toBe('6');+ });+it.each([{typed: '- ',@@ -171,7 +211,11 @@ describe('composer structured list input rules', () => {},{type: listType,- ...(Object.keys(attrs).length > 0 ? { attrs } : {}),+ ...(listType === 'bulletList'+ ? { attrs: { marker: '-', separator: ' ', ...attrs } }+ : Object.keys(attrs).length > 0+ ? { attrs }+ : {}),content: [{type: 'listItem',@@ -344,6 +388,7 @@ describe('composer structured list keyboard commands', () => {expect(editor.getJSON().content).toEqual([{type: 'bulletList',+ attrs: { marker: '-', separator: ' ' },content: [{type: 'listItem',@@ -412,6 +457,7 @@ describe('composer structured list keyboard commands', () => {expect(editor.getJSON().content).toEqual([{type: 'bulletList',+ attrs: { marker: '-', separator: ' ' },content: [{ type: 'listItem', content: [{ type: 'paragraph' }] },{@@ -454,6 +500,7 @@ describe('composer structured list keyboard commands', () => {expect(editor.getJSON().content).toEqual([{type: 'bulletList',+ attrs: { marker: '-', separator: ' ' },content: [{type: 'listItem',@@ -637,6 +684,81 @@ describe('composer structured list serialization', () => {expect(serializeEditorContent(editor).text).toBe('2、项目\n3、 项目');});+ it('keeps list markers when copying a selected structured fragment', () => {+ 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' }] }],+ },+ ],+ },+ ],+ });++ const slice = editor.state.doc.slice(0, editor.state.doc.content.size);+ expect(serializeEditorSlice(editor, slice)).toBe('1. first\n2. second');+ });++ it('preserves non-default bullet markers and spacing when sending', () => {+ const editor = makeEditor({+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ attrs: { marker: '+', separator: ' ' },+ content: [+ {+ type: 'listItem',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'item' }] }],+ },+ ],+ },+ ],+ });++ expect(serializeEditorContent(editor).text).toBe('+ item');+ });++ it('keeps a dragged quote inside its list item', () => {+ const editor = makeEditor({+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [+ {+ type: 'paragraph',+ content: [+ { type: 'text', text: 'before ' },+ { type: COMPOSER_QUOTE_NODE_TYPE, attrs: { text: 'quoted' } },+ { type: 'text', text: ' after' },+ ],+ },+ ],+ },+ ],+ },+ ],+ });++ expect(serializeEditorContent(editor).text).toBe(+ '- before > <!-- cindy-composer-quote -->\n > quoted after',+ );+ });+it('preserves nested markers and projects atom ranges into wire offsets', () => {const href = 'cindy://session/session-a?message=message-a';const editor = makeEditor({diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 5bdc8bffd0..a9a53bfb59 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -154,7 +154,7 @@ 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 { serializeEditorContent, serializeEditorSlice } from './composerContentSerialization';import {composerDocumentContainsList,normalizeComposerDocumentJSON,@@ -1386,6 +1386,7 @@ export function ChatInput({SlashCommandDecoration,],editorProps: {+ clipboardTextSerializer: (slice) => serializeEditorSlice(editorRef.current, slice),attributes: {class: cn(// py + 负 my:.ProseMirror 自身是 overflow 裁剪容器,inline 装饰diff --git a/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts b/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.tsindex 442cac6a83..b9075780fb 100644--- a/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts+++ b/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts@@ -12,9 +12,11 @@ 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})(、)$/;+const BULLET_MARKER_RE = /^([-+*•])([ \t]+)$/;+const ORDERED_MARKER_RE = /^(\d{1,6})([.)])\s$/;+const CJK_ORDERED_MARKER_RE = /^(\d{1,6})(、)$/;+type BulletMarker = '-' | '+' | '*' | '•';type OrderedMarker = '.' | ')' | '、';interface OrderedListAttrs {@@ -39,7 +41,11 @@ interface PlainListParagraphMarker {function plainListParagraphMarker(text: string): PlainListParagraphMarker | null {const bullet = text.match(/^([-+*•])([ \t]+)/);if (bullet) {- return { kind: 'bullet', prefixLength: bullet[0].length, attrs: {} };+ return {+ kind: 'bullet',+ prefixLength: bullet[0].length,+ attrs: { marker: bullet[1], separator: bullet[2] },+ };}const ordered = text.match(/^(\d{1,6})([.)])([ \t]+)/);if (ordered) {@@ -133,6 +139,25 @@ export const ComposerBulletList = Node.create({group: 'block',content: 'listItem+',defining: true,+ addAttributes() {+ return {+ marker: {+ default: '-',+ parseHTML: (element) => {+ const value = element.getAttribute('data-marker');+ return value === '+' || value === '*' || value === '•' ? value : '-';+ },+ renderHTML: (attributes) =>+ attributes.marker === '-' ? {} : { 'data-marker': attributes.marker },+ },+ separator: {+ default: ' ',+ parseHTML: (element) => element.getAttribute('data-separator') || ' ',+ renderHTML: (attributes) =>+ attributes.separator === ' ' ? {} : { 'data-separator': attributes.separator },+ },+ };+ },parseHTML() {return [{ tag: 'ul' }];},@@ -142,10 +167,17 @@ export const ComposerBulletList = Node.create({addInputRules() {return [wrappingInputRule({- find: /^\s*([-+*•])\s$/,+ find: BULLET_MARKER_RE,type: this.type,+ getAttributes: (match) => ({+ marker: match[1] as BulletMarker,+ separator: match[2],+ }),}),- hardBreakListInputRule(/^\s*([-+*•])\s$/, this.type),+ hardBreakListInputRule(BULLET_MARKER_RE, this.type, (match) => ({+ marker: match[1] as BulletMarker,+ separator: match[2],+ })),];},});@@ -187,8 +219,18 @@ export const ComposerOrderedList = Node.create({parseHTML() {return [{ tag: 'ol' }];},- renderHTML({ HTMLAttributes }) {- return ['ol', mergeAttributes(HTMLAttributes), 0];+ renderHTML({ node, HTMLAttributes }) {+ const start = Number(node.attrs.start);+ const lastItem = start + Math.max(node.childCount - 1, 0);+ const markerDigits =+ Number.isInteger(start) && start > 0 && Number.isInteger(lastItem)+ ? String(lastItem).length+ : 1;+ return [+ 'ol',+ mergeAttributes(HTMLAttributes, { 'data-marker-digits': String(markerDigits) }),+ 0,+ ];},addInputRules() {return [diff --git a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.tsindex 26a44420ac..3de6830da4 100644--- a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts+++ b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts@@ -1,5 +1,6 @@import type { Editor } from '@tiptap/core';-import type { Node as ProseMirrorNode } from '@tiptap/pm/model';+import { 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';import type { MentionedResource } from '@/lib/fileTypes';@@ -40,15 +41,27 @@ function orderedListMarker(node: ProseMirrorNode): OrderedMarker {return node.attrs.marker === ')' || node.attrs.marker === '、' ? node.attrs.marker : '.';}+function bulletListMarker(node: ProseMirrorNode): string {+ const marker = node.attrs.marker;+ return marker === '+' || marker === '*' || marker === '•' ? marker : '-';+}++function bulletListSeparator(node: ProseMirrorNode): string {+ return typeof node.attrs.separator === 'string' && /^[ \t]+$/.test(node.attrs.separator)+ ? node.attrs.separator+ : ' ';+}+/*** 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);+function serializeComposerDocument(+ doc: ProseMirrorNode,+ decoratedSlashMatches: readonly SlashCommandMatch[],+): SerializedComposerContent {const blocks: ComposerSerializedBlock[] = [];const mentions: MentionedResource[] = [];const seenMentions = new Set<string>();@@ -110,15 +123,24 @@ export function serializeEditorContent(editor: Editor): SerializedComposerContenparagraph.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;+ const quoteText = formatQuoteForSend(+ composerQuoteAttrsToChatQuote(child.attrs as ComposerQuoteAttrs),+ );+ if (prefix) {+ // A quote chip inside a list item is part of that item. Keeping it+ // in the current text block preserves the list marker instead of+ // emitting an empty item followed by a top-level quote block.+ const continuationPrefix = ' '.repeat(prefix.length);+ const quoteLines = quoteText.split('\n');+ buffer += quoteLines+ .map((line, index) => (index === 0 ? line : `${continuationPrefix}${line}`))+ .join('\n');+ } else {+ flushText();+ blocks.push({ kind: 'quote', text: quoteText });+ emittedInlineSegment = true;+ }return;}@@ -236,7 +258,7 @@ export function serializeEditorContent(editor: Editor): SerializedComposerContenconst itemPosition = listPosition + 1 + itemOffset;const itemMarker = isOrdered? `${start + itemIndex}${marker}${marker === '、' ? '' : ' '}`- : '- ';+ : `${bulletListMarker(listNode)}${bulletListSeparator(listNode)}`;const itemIndent = `${indent}${' '.repeat(itemMarker.length)}`;let firstParagraph = true;@@ -282,3 +304,28 @@ export function serializeEditorContent(editor: Editor): SerializedComposerContenhasQuotes,};}++export function serializeEditorContent(editor: Editor): SerializedComposerContent {+ return serializeComposerDocument(editor.state.doc, getDecoratedSlashCommandMatches(editor));+}++/**+ * Serialize a selected editor fragment for plain-text clipboard consumers.+ * Replacing an empty document with the open slice lets ProseMirror rebuild+ * list context around selections that begin or end inside a list item.+ */+export function serializeEditorSlice(editor: Editor | null, slice: Slice): string {+ if (!editor) {+ return slice.content.textBetween(0, slice.content.size, '\n');+ }++ try {+ const 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;+ return serializeComposerDocument(replaced, []).text;+ } catch {+ return slice.content.textBetween(0, slice.content.size, '\n');+ }+}diff --git a/apps/desktop/src/renderer/lib/composerListDocument.ts b/apps/desktop/src/renderer/lib/composerListDocument.tsindex d56855a4fa..43caf4e13e 100644--- a/apps/desktop/src/renderer/lib/composerListDocument.ts+++ b/apps/desktop/src/renderer/lib/composerListDocument.ts@@ -7,6 +7,7 @@ interface ListMarker {kind: ListKind;prefixLength: number;marker: string;+ separator: string;start?: number;}@@ -72,7 +73,8 @@ function parseListMarker(text: string): ListMarker | null {return {kind: 'bullet',prefixLength: bullet[0].length,- marker: 'bullet',+ marker: bullet[1],+ separator: bullet[2],};}@@ -88,6 +90,7 @@ function parseListMarker(text: string): ListMarker | null {prefixLength:marker === '、' ? ordered[1].length + marker.length : ordered[0].length,marker,+ separator: marker === '、' ? ordered[3] : ordered[3],start: Number(ordered[1]),};}@@ -126,17 +129,25 @@ function listFromLines(content: [paragraphFromLine({ content, text: '' }, paragraphAttrs)],};});+ const attrs =+ marker.kind === 'ordered'+ ? { start: marker.start ?? 1, marker: marker.marker }+ : marker.marker === '-' && marker.separator === ' '+ ? undefined+ : { marker: marker.marker, separator: marker.separator };return {type: marker.kind === 'ordered' ? 'orderedList' : 'bulletList',- ...(marker.kind === 'ordered'- ? { attrs: { start: marker.start ?? 1, marker: marker.marker } }- : {}),+ ...(attrs ? { attrs } : {}),content: items,};}function sameListMarker(left: ListMarker, right: ListMarker): boolean {- return left.kind === right.kind && left.marker === right.marker;+ return (+ left.kind === right.kind &&+ left.marker === right.marker &&+ left.separator === right.separator+ );}function canAppendListLine(@@ -149,14 +160,47 @@ function canAppendListLine(return next.start === (current.start ?? 1) + currentLineCount;}-function paragraphToBlocks(paragraph: JSONContent): JSONContent[] {+interface FenceState {+ char: '`' | '~';+ length: number;+}++function fenceOpening(text: string): FenceState | null {+ const match = text.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);+ if (!match) return null;+ if (match[1][0] === '`' && match[2].includes('`')) return null;+ return { char: match[1][0] as FenceState['char'], length: match[1].length };+}++function isFenceClosing(text: string, state: FenceState): boolean {+ const escapedChar = state.char === '`' ? '`' : '~';+ const pattern = new RegExp(`^ {0,3}${escapedChar}{${state.length},}[ \\t]*$`);+ return pattern.test(text);+}++function paragraphToBlocks(+ paragraph: JSONContent,+ initialFence: FenceState | null,+): { blocks: JSONContent[]; fence: FenceState | null } {const lines = splitParagraphLines(paragraph);- if (!lines.some((line) => parseListMarker(line.text))) return [paragraph];+ if (!lines.some((line) => parseListMarker(line.text)) && !initialFence) {+ let fence: FenceState | null = initialFence;+ for (const line of lines) {+ const opening = fenceOpening(line.text);+ if (fence) {+ if (isFenceClosing(line.text, fence)) fence = null;+ } else if (opening) {+ fence = opening;+ }+ }+ return { blocks: [paragraph], fence };+ }const blocks: JSONContent[] = [];let plainLines: ComposerLine[] = [];let listLines: ComposerLine[] = [];let listMarker: ListMarker | null = null;+ let fence = initialFence;const flushPlain = () => {if (plainLines.length === 0) return;@@ -171,6 +215,19 @@ function paragraphToBlocks(paragraph: JSONContent): JSONContent[] {};for (const line of lines) {+ if (fence) {+ flushList();+ plainLines.push(line);+ if (isFenceClosing(line.text, fence)) fence = null;+ continue;+ }+ const opening = fenceOpening(line.text);+ if (opening) {+ flushList();+ plainLines.push(line);+ fence = opening;+ continue;+ }const marker = parseListMarker(line.text);if (!marker) {flushList();@@ -190,12 +247,17 @@ function paragraphToBlocks(paragraph: JSONContent): JSONContent[] {}flushList();flushPlain();- return blocks;+ return { blocks, fence };}function canMergeLists(left: JSONContent, right: JSONContent): boolean {if (left.type !== right.type) return false;- if (left.type === 'bulletList') return true;+ if (left.type === 'bulletList') {+ return (+ (left.attrs?.marker ?? '-') === (right.attrs?.marker ?? '-') &&+ (left.attrs?.separator ?? ' ') === (right.attrs?.separator ?? ' ')+ );+ }const leftStart = Number(left.attrs?.start);const rightStart = Number(right.attrs?.start);return (@@ -225,9 +287,14 @@ export function normalizeComposerDocumentJSON(document: JSONContent): JSONContenif (document.type !== 'doc' || !Array.isArray(document.content)) return document;const normalized: JSONContent[] = [];+ let fence: FenceState | null = null;for (const node of document.content) {- const blocks = node.type === 'paragraph' ? paragraphToBlocks(node) : [node];- for (const block of blocks) {+ const result: { blocks: JSONContent[]; fence: FenceState | null } =+ node.type === 'paragraph'+ ? paragraphToBlocks(node, fence)+ : { blocks: [node], fence };+ fence = result.fence;+ for (const block of result.blocks) {const previous = normalized.at(-1);if (previous && canMergeLists(previous, block)) {normalized[normalized.length - 1] = mergeLists(previous, block);diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.cssindex d1c5a77931..a2d16e2eab 100644--- a/apps/desktop/src/renderer/styles/globals.css+++ b/apps/desktop/src/renderer/styles/globals.css@@ -351,7 +351,25 @@ html:lang(ko) {without decoration-owned width measurements. */[data-chat-input-root] .ProseMirror :is(ul, ol) {margin: 0;- padding-inline-start: 1.5em;+ padding-inline-start: var(--composer-list-padding, 1.5em);+}+[data-chat-input-root] .ProseMirror ol[data-marker-digits='2'] {+ --composer-list-padding: 2.2em;+}+[data-chat-input-root] .ProseMirror ol[data-marker-digits='3'] {+ --composer-list-padding: 2.8em;+}+[data-chat-input-root] .ProseMirror ol[data-marker-digits='4'] {+ --composer-list-padding: 3.4em;+}+[data-chat-input-root] .ProseMirror ol[data-marker-digits='5'] {+ --composer-list-padding: 4em;+}+[data-chat-input-root] .ProseMirror ol[data-marker-digits='6'] {+ --composer-list-padding: 4.6em;+}+[data-chat-input-root] .ProseMirror ol[data-marker-digits='7'] {+ --composer-list-padding: 5.2em;}[data-chat-input-root] .ProseMirror ul {list-style-type: disc;