Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 完善列表粘贴与序列化边界

zhangyongjief9cf4eed623b
diff --git a/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts
index 5f3dde9371..29ae5d3501 100644
--- a/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts
+++ b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts
@@ -5,7 +5,6 @@ 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 { Fragment, Slice } from '@tiptap/pm/model';
import { TextSelection } from '@tiptap/pm/state';
import {
@@ -14,9 +13,9 @@ import {
ComposerOrderedList,
handleStructuredListBackspace,
handleStructuredListBreak,
+ isTrailingEmptyTopLevelParagraph,
promoteTrailingPlainListParagraph,
} from '@/components/new-chat/ComposerListNodes';
-import { plainTextToComposerDocument } from '@/lib/composerListDocument';
import {
serializeEditorContent,
serializeEditorSlice,
@@ -293,6 +292,24 @@ describe('composer structured list input rules', () => {
expect(list?.attrs).toMatchObject({ start: 1, marker: '.' });
expect(list?.lastChild?.textContent).toBe('12e21ed');
});
+
+ it('keeps markers literal after a hard break inside a fenced code block', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '```' }, { type: 'hardBreak' }],
+ },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ typeThroughInputRules(editor, '1. ');
+
+ expect(editor.state.doc.firstChild?.type.name).toBe('paragraph');
+ expect(editor.state.doc.firstChild?.textContent).toBe('```1. ');
+ });
});
describe('composer structured list keyboard commands', () => {
@@ -593,6 +610,22 @@ describe('composer structured list keyboard commands', () => {
});
describe('composer live plain-list promotion', () => {
+ it('recognizes only the trailing empty top-level paragraph as a list-paste boundary', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'before' }] },
+ { type: 'paragraph' },
+ ],
+ });
+
+ editor.commands.setTextSelection(2);
+ expect(isTrailingEmptyTopLevelParagraph(editor.view)).toBe(false);
+
+ selectDocumentEnd(editor);
+ expect(isTrailingEmptyTopLevelParagraph(editor.view)).toBe(true);
+ });
+
it('promotes a trailing pasted row beside an existing structured list', () => {
const editor = makeEditor({
type: 'doc',
@@ -883,6 +916,34 @@ describe('composer structured list serialization', () => {
expect(serializeEditorContent(editor).text).toBe('-\tparent\n - child');
});
+ it('indents hard-break continuation lines inside a list item', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'first' },
+ { type: 'hardBreak' },
+ { type: 'text', text: 'second' },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(serializeEditorContent(editor).text).toBe('- first\n second');
+ });
+
it('keeps a dragged quote inside its list item', () => {
const editor = makeEditor({
type: 'doc',
@@ -942,6 +1003,56 @@ describe('composer structured list serialization', () => {
]);
});
+ it('indents a restored quote after a no-space CJK list marker', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'parent' }] },
+ { type: 'paragraph', content: [{ type: 'text', text: ' 2、项目' }] },
+ {
+ type: 'paragraph',
+ content: [{ type: COMPOSER_QUOTE_NODE_TYPE, attrs: { text: 'quoted' } }],
+ },
+ ],
+ });
+
+ expect(serializeEditorContent(editor).text).toBe(
+ 'parent\n 2、项目\n > <!-- cindy-composer-quote -->\n > quoted',
+ );
+ });
+
+ it('keeps quote-like reply text separate from a list quote chip', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: COMPOSER_QUOTE_NODE_TYPE, attrs: { text: 'quoted' } },
+ { type: 'text', text: '> reply' },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+
+ const serialized = serializeEditorContent(editor).text;
+ expect(parseChatQuoteSegments(serialized)).toEqual([
+ { kind: 'text', text: '- ' },
+ { kind: 'quote', quote: { text: 'quoted' } },
+ { kind: 'text', text: ' > reply' },
+ ]);
+ });
+
it('preserves indentation on an empty nested list item', () => {
const editor = makeEditor({
type: 'doc',
@@ -1043,27 +1154,40 @@ describe('composer structured list serialization', () => {
expect(serializeEditorContent(editor).text).toBe('2. ');
});
- it('inserts normalized list blocks at a non-terminal selection', () => {
+ it('keeps partial inline boundaries when copying one ordered-list item', () => {
const editor = makeEditor({
type: 'doc',
content: [
- { type: 'paragraph', content: [{ type: 'text', text: 'before' }] },
- { type: 'paragraph', content: [{ type: 'text', text: 'after' }] },
+ {
+ 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' }] }],
+ },
+ ],
+ },
],
});
- editor.commands.setTextSelection(2);
- const replacement = plainTextToComposerDocument('1. first\n2. second').content!.map((node) =>
- editor.state.schema.nodeFromJSON(node),
- );
- const tr = editor.state.tr.replaceSelection(new Slice(Fragment.from(replacement), 0, 0));
- editor.view.dispatch(tr);
-
- expect(editor.state.doc.textContent).toContain('first');
- expect(editor.state.doc.textContent).toContain('second');
- expect(editor.state.doc.childCount).toBeGreaterThan(2);
- expect(editor.state.doc.content.content.some((node) => node.type.name === 'orderedList')).toBe(
- true,
+ let secondTextPosition = 0;
+ editor.state.doc.descendants((node, position) => {
+ if (node.isText && node.text === 'second') secondTextPosition = position;
+ });
+ editor.commands.setTextSelection({
+ from: secondTextPosition + 1,
+ to: secondTextPosition + 4,
+ });
+ const slice = editor.state.doc.slice(
+ editor.state.selection.from,
+ editor.state.selection.to,
);
+
+ expect(serializeEditorSlice(editor, slice)).toBe('2. eco');
});
it('preserves nested markers and projects atom ranges into wire offsets', () => {
diff --git a/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts b/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts
index 665938183a..ea44a84043 100644
--- a/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts
+++ b/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts
@@ -6,6 +6,11 @@ import Paragraph from '@tiptap/extension-paragraph';
import Text from '@tiptap/extension-text';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ ComposerBulletList,
+ ComposerListItem,
+ ComposerOrderedList,
+} from '@/components/new-chat/ComposerListNodes';
import { placeGhostAtComposerStart } from '@/components/new-chat/ghostComposerPlacement';
import { MentionChipNode } from '@/components/new-chat/MentionChipNode';
import type { InstalledGhost } from '../../shared/ghost';
@@ -80,4 +85,62 @@ describe('placeGhostAtComposerStart', () => {
expect(editor.getText()).toBe('$feishu 帮我整理这段内容');
});
+
+ it('adds a command paragraph before a leading structured list', () => {
+ const editor = new Editor({
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ ComposerListItem,
+ ComposerBulletList,
+ ComposerOrderedList,
+ MentionChipNode,
+ ],
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'first' }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ });
+ editors.push(editor);
+ const selected = ghost('mivo');
+
+ expect(placeGhostAtComposerStart(editor, selected, [selected])).toBe(true);
+ expect(editor.getJSON().content).toEqual([
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '$mivo ' }],
+ },
+ {
+ type: 'bulletList',
+ attrs: { marker: '-', separator: ' ' },
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'first' }],
+ },
+ ],
+ },
+ ],
+ },
+ ]);
+ });
});
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index f213275e1f..f9026af310 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -35,6 +35,7 @@ import {
handleStructuredListBackspace,
handleStructuredListBreak,
hasTrailingPlainListParagraph,
+ isTrailingEmptyTopLevelParagraph,
promoteTrailingPlainListParagraph,
} from './ComposerListNodes';
import { WindowsSelectionReplacement } from './WindowsSelectionReplacement';
@@ -1524,36 +1525,24 @@ export function ChatInput({
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 (composerDocumentContainsList(normalizedPaste)) {
+ const pasteIntoTrailingEmptyLine = isTrailingEmptyTopLevelParagraph(view);
+
+ if (composerDocumentContainsList(normalizedPaste) && pasteIntoTrailingEmptyLine) {
event.preventDefault();
+ const paragraphPosition = $from.before(1);
const replacement = (normalizedPaste.content ?? []).map((node) =>
state.schema.nodeFromJSON(node),
);
- if (paragraphEndsDocument && paragraphIsEmptyLine && $from.parent.content.size > 0) {
+ if ($from.parent.content.size > 0) {
replacement.unshift(state.schema.nodes.paragraph.create());
}
const fragment = Fragment.from(replacement);
- const pasteIntoTrailingEmptyLine = paragraphEndsDocument && paragraphIsEmptyLine;
- const tr =
- pasteIntoTrailingEmptyLine
- ? state.tr.replaceWith(
- paragraphPosition,
- paragraphPosition + $from.parent.nodeSize,
- fragment,
- )
- : state.tr.replaceSelection(new Slice(fragment, 0, 0));
- if (pasteIntoTrailingEmptyLine) tr.setSelection(TextSelection.atEnd(tr.doc));
+ const tr = state.tr.replaceWith(
+ paragraphPosition,
+ paragraphPosition + $from.parent.nodeSize,
+ fragment,
+ );
+ tr.setSelection(TextSelection.atEnd(tr.doc));
view.dispatch(tr.scrollIntoView());
return true;
}
diff --git a/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts b/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts
index 1c6f8a7aac..e19573ceff 100644
--- a/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts
+++ b/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts
@@ -39,6 +39,35 @@ interface PlainListParagraphMarker {
attrs: Record<string, unknown>;
}
+interface FenceState {
+ char: '`' | '~';
+ length: number;
+}
+
+function fenceOpening(text: string): FenceState | null {
+ const match = text.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
+ if (!match || (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 pattern = new RegExp(`^ {0,3}${state.char}{${state.length},}[ \\t]*$`);
+ return pattern.test(text);
+}
+
+function paragraphOffsetIsInsideFence(paragraph: PMNode, offset: number): boolean {
+ const text = paragraph.textBetween(0, offset, '\n', '\n');
+ let fence: FenceState | null = null;
+ for (const line of text.split('\n')) {
+ if (fence) {
+ if (isFenceClosing(line, fence)) fence = null;
+ continue;
+ }
+ fence = fenceOpening(line);
+ }
+ return fence !== null;
+}
+
function plainListParagraphMarker(text: string): PlainListParagraphMarker | null {
const bullet = text.match(/^([-+*•])([ \t]+)/);
if (bullet) {
@@ -96,6 +125,7 @@ function hardBreakListInputRule(
const markerOffset = range.from - paragraphStart;
const hardBreak = paragraph.nodeAt(markerOffset - 1);
if (hardBreak?.type.name !== 'hardBreak') return null;
+ if (paragraphOffsetIsInsideFence(paragraph, markerOffset)) return null;
const before = paragraph.content.cut(0, markerOffset - hardBreak.nodeSize);
const after = paragraph.content.cut(range.to - paragraphStart);
@@ -457,6 +487,24 @@ export function hasTrailingPlainListParagraph(view: EditorView): boolean {
return getTrailingPlainListParagraph(view) !== null;
}
+export function isTrailingEmptyTopLevelParagraph(view: EditorView): boolean {
+ 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 false;
+ }
+ return (
+ $from.parent.content.size === 0 ||
+ ($from.parent.childCount === 1 && $from.parent.firstChild?.type.name === 'hardBreak')
+ );
+}
+
export function promoteTrailingPlainListParagraph(view: EditorView): boolean {
const trailing = getTrailingPlainListParagraph(view);
if (!trailing) return false;
diff --git a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts
index e6d7f42642..84a39d5e83 100644
--- a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts
+++ b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts
@@ -55,7 +55,9 @@ function expandedIndentWidth(text: string): number {
}
function literalListContinuationPrefix(text: string): string | null {
- const match = text.match(/^([ \t]+)(?:[-+*•]|[1-9]\d{0,5}[.)、])([ \t]+)/);
+ const match =
+ text.match(/^([ \t]+)(?:[-+*•]|[1-9]\d{0,5}[.)])([ \t]+)/) ??
+ text.match(/^([ \t]+)[1-9]\d{0,5}、[ \t]*/);
if (!match) return null;
return ' '.repeat(expandedIndentWidth(match[0]));
}
@@ -111,6 +113,7 @@ function serializeComposerDocument(
paragraph: ProseMirrorNode,
paragraphPosition: number,
prefix = '',
+ continuationIndent = '',
) => {
let buffer = prefix;
let bufferAgentReferences: AgentInputReference[] = [];
@@ -163,7 +166,8 @@ 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(expandedIndentWidth(prefix));
+ const continuationPrefix =
+ continuationIndent || ' '.repeat(expandedIndentWidth(prefix));
const quoteLines = quoteText.split('\n');
const quoteSeparator = continuationAfterQuote === null ? '' : '\n';
buffer += `${quoteSeparator}\n${quoteLines
@@ -179,9 +183,16 @@ function serializeComposerDocument(
}
if (continuationAfterQuote !== null) {
+ const childText = child.isText ? (child.text ?? '') : '';
const alreadyIndented =
- child.isText && (child.text ?? '').startsWith(continuationAfterQuote);
- buffer += `\n${alreadyIndented ? '' : continuationAfterQuote}`;
+ child.isText && childText.startsWith(continuationAfterQuote);
+ const textAfterIndent = alreadyIndented
+ ? childText.slice(continuationAfterQuote.length)
+ : childText;
+ const needsQuoteBoundary = /^>[ \t]/.test(textAfterIndent);
+ buffer += `${needsQuoteBoundary ? '\n\n' : '\n'}${
+ alreadyIndented ? '' : continuationAfterQuote
+ }`;
continuationAfterQuote = null;
}
@@ -261,7 +272,7 @@ function serializeComposerDocument(
}
if (child.type.name === 'hardBreak') {
- buffer += '\n';
+ buffer += `\n${continuationIndent}`;
return;
}
@@ -311,6 +322,7 @@ function serializeComposerDocument(
child,
childPosition,
firstParagraph ? `${indent}${itemMarker}` : itemIndent,
+ itemIndent,
);
firstParagraph = false;
return;
@@ -416,14 +428,10 @@ export function serializeEditorSlice(editor: Editor | null, slice: Slice): strin
// 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));
+ const itemType = editor.state.schema.nodes.listItem;
+ if (itemType?.validContent(replaced.content)) {
+ const copiedItem = itemType.create(null, replaced.content);
+ const copiedList = sourceList.copy(Fragment.from(copiedItem));
replaced = state.tr.replace(
0,
state.doc.content.size,
diff --git a/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts b/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts
index 509b72d9c1..d50f32425c 100644
--- a/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts
+++ b/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts
@@ -47,8 +47,16 @@ export function placeGhostAtComposerStart(
);
} else {
const firstBlock = doc.firstChild;
- if (!firstBlock?.isTextblock) return false;
- transaction.insertText(`$${command} `, 1);
+ if (firstBlock?.isTextblock) {
+ transaction.insertText(`$${command} `, 1);
+ } else {
+ const paragraphType = editor.state.schema.nodes.paragraph;
+ if (!paragraphType) return false;
+ transaction.insert(
+ 0,
+ paragraphType.create(null, editor.state.schema.text(`$${command} `)),
+ );
+ }
}
editor.view.dispatch(transaction);