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): 收敛列表恢复与粘贴行为

zhangyongjie5c78dff0ce03
diff --git a/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts b/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts
index 70432ef361..09041fa3ac 100644
--- a/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts
+++ b/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts
@@ -28,6 +28,15 @@ describe('composer list document normalization', () => {
});
});
+ it('restores a generated seven-digit ordered continuation as one list', () => {
+ const document = plainTextToComposerDocument('999999. first\n1000000. second');
+ expect(document.content?.[0]).toMatchObject({
+ type: 'orderedList',
+ attrs: { start: 999999, marker: '.' },
+ });
+ expect(document.content?.[0]?.content).toHaveLength(2);
+ });
+
it('keeps surrounding paragraphs and task bodies intact', () => {
expect(plainTextToComposerDocument('intro\n- [ ] todo\n- [x] done\noutro')).toEqual({
type: 'doc',
diff --git a/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts
index 29ae5d3501..c4a80f0497 100644
--- a/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts
+++ b/apps/desktop/src/renderer/__tests__/composerStructuredLists.test.ts
@@ -13,6 +13,7 @@ import {
ComposerOrderedList,
handleStructuredListBackspace,
handleStructuredListBreak,
+ isTopLevelBlockSelection,
isTrailingEmptyTopLevelParagraph,
promoteTrailingPlainListParagraph,
} from '@/components/new-chat/ComposerListNodes';
@@ -626,6 +627,16 @@ describe('composer live plain-list promotion', () => {
expect(isTrailingEmptyTopLevelParagraph(editor.view)).toBe(true);
});
+ it('recognizes a whole top-level paragraph selection for structured paste', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'replace me' }] }],
+ });
+ editor.commands.setTextSelection({ from: 1, to: 11 });
+
+ expect(isTopLevelBlockSelection(editor.view)).toBe(true);
+ });
+
it('promotes a trailing pasted row beside an existing structured list', () => {
const editor = makeEditor({
type: 'doc',
@@ -660,6 +671,7 @@ describe('composer live plain-list promotion', () => {
const editor = makeEditor({
type: 'doc',
content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'parent' }] },
{
type: 'paragraph',
content: [{ type: 'text', text: '3.14159' }],
@@ -724,6 +736,20 @@ describe('composer live plain-list promotion', () => {
expect(editor.state.doc.firstChild?.type.name).toBe('bulletList');
expect(editor.state.doc.firstChild?.firstChild?.textContent).toBe('item');
});
+
+ it('does not promote a marker inside an unclosed fenced block', () => {
+ const editor = makeEditor({
+ type: 'doc',
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: '```' }] },
+ { type: 'paragraph', content: [{ type: 'text', text: '1. literal' }] },
+ ],
+ });
+ selectDocumentEnd(editor);
+
+ expect(promoteTrailingPlainListParagraph(editor.view)).toBe(false);
+ expect(editor.state.doc.lastChild?.type.name).toBe('paragraph');
+ });
});
describe('composer structured list serialization', () => {
@@ -1021,6 +1047,26 @@ describe('composer structured list serialization', () => {
);
});
+ it('keeps an inline restored 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: COMPOSER_QUOTE_NODE_TYPE, attrs: { text: 'quoted' } },
+ ],
+ },
+ ],
+ });
+
+ expect(serializeEditorContent(editor).text).toBe(
+ 'parent\n - child\n > <!-- cindy-composer-quote -->\n > quoted',
+ );
+ });
+
it('keeps quote-like reply text separate from a list quote chip', () => {
const editor = makeEditor({
type: 'doc',
@@ -1053,6 +1099,37 @@ describe('composer structured list serialization', () => {
]);
});
+ it('keeps a bare quote marker 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: '>' },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(parseChatQuoteSegments(serializeEditorContent(editor).text)).toEqual([
+ { kind: 'text', text: '- ' },
+ { kind: 'quote', quote: { text: 'quoted' } },
+ { kind: 'text', text: ' >' },
+ ]);
+ });
+
it('preserves indentation on an empty nested list item', () => {
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.tsx
index f9026af310..0cff2b46ec 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,
+ isTopLevelBlockSelection,
isTrailingEmptyTopLevelParagraph,
promoteTrailingPlainListParagraph,
} from './ComposerListNodes';
@@ -1526,23 +1527,29 @@ export function ChatInput({
const { state } = view;
const { $from } = state.selection;
const pasteIntoTrailingEmptyLine = isTrailingEmptyTopLevelParagraph(view);
+ const pasteIntoBlockSelection = isTopLevelBlockSelection(view);
- if (composerDocumentContainsList(normalizedPaste) && pasteIntoTrailingEmptyLine) {
+ if (
+ composerDocumentContainsList(normalizedPaste) &&
+ (pasteIntoTrailingEmptyLine || pasteIntoBlockSelection)
+ ) {
event.preventDefault();
const paragraphPosition = $from.before(1);
const replacement = (normalizedPaste.content ?? []).map((node) =>
state.schema.nodeFromJSON(node),
);
- if ($from.parent.content.size > 0) {
+ if (pasteIntoTrailingEmptyLine && $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));
+ 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));
view.dispatch(tr.scrollIntoView());
return true;
}
@@ -1692,6 +1699,20 @@ export function ChatInput({
return false;
}
+ // A history undo intentionally restores the marker as plain text. Keep
+ // the queued live promotion from immediately converting it again.
+ if (
+ event.key.toLowerCase() === 'z' &&
+ (event.metaKey || event.ctrlKey) &&
+ !event.shiftKey &&
+ !event.altKey
+ ) {
+ suppressListNormalizationRef.current = true;
+ queueMicrotask(() => {
+ suppressListNormalizationRef.current = false;
+ });
+ }
+
// ↑ / ↓ — browse user message history when editor is empty
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
const history = userHistoryRef.current;
@@ -2555,7 +2576,7 @@ export function ChatInput({
// alone.
if (storageKey !== undefined) {
const draft = getComposerDraft(storageKey);
- if (draft?.text && editor.isEmpty) {
+ if (draft?.text && composerDocIsEmpty(editor.state.doc)) {
isRestoringRef.current = true;
try {
editor.commands.setContent(normalizeComposerDocumentJSON(draft.text));
@@ -2691,7 +2712,7 @@ export function ChatInput({
: null;
const textUnchanged =
JSON.stringify(normalizedDraftText) ===
- JSON.stringify(editor.isEmpty ? null : editor.getJSON());
+ JSON.stringify(composerDocIsEmpty(editor.state.doc) ? null : editor.getJSON());
if (textUnchanged) {
if (!editor.isFocused) editor.commands.focus();
return;
diff --git a/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts b/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts
index e19573ceff..5fdfac531b 100644
--- a/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts
+++ b/apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts
@@ -13,8 +13,8 @@ import { Selection, TextSelection } from '@tiptap/pm/state';
import type { EditorView } from '@tiptap/pm/view';
const BULLET_MARKER_RE = /^([-+*•])([ \t]+)$/;
-const ORDERED_MARKER_RE = /^([1-9]\d{0,5})([.)])([ \t]+)$/;
-const CJK_ORDERED_MARKER_RE = /^([1-9]\d{0,5})(、)$/;
+const ORDERED_MARKER_RE = /^([1-9]\d{0,6})([.)])([ \t]+)$/;
+const CJK_ORDERED_MARKER_RE = /^([1-9]\d{0,6})(、)$/;
type BulletMarker = '-' | '+' | '*' | '•';
type OrderedMarker = '.' | ')' | '、';
@@ -55,9 +55,8 @@ function isFenceClosing(text: string, state: FenceState): boolean {
return pattern.test(text);
}
-function paragraphOffsetIsInsideFence(paragraph: PMNode, offset: number): boolean {
- const text = paragraph.textBetween(0, offset, '\n', '\n');
- let fence: FenceState | null = null;
+function scanFenceState(text: string, initialFence: FenceState | null): FenceState | null {
+ let fence = initialFence;
for (const line of text.split('\n')) {
if (fence) {
if (isFenceClosing(line, fence)) fence = null;
@@ -65,7 +64,20 @@ function paragraphOffsetIsInsideFence(paragraph: PMNode, offset: number): boolea
}
fence = fenceOpening(line);
}
- return fence !== null;
+ return fence;
+}
+
+function paragraphOffsetIsInsideFence(paragraph: PMNode, offset: number): boolean {
+ return scanFenceState(paragraph.textBetween(0, offset, '\n', '\n'), null) !== null;
+}
+
+function documentFenceStateBefore(doc: PMNode, position: number): FenceState | null {
+ let fence: FenceState | null = null;
+ doc.forEach((node, nodeOffset) => {
+ if (nodeOffset >= position || node.type.name !== 'paragraph') return;
+ fence = scanFenceState(node.textBetween(0, node.content.size, '\n', '\n'), fence);
+ });
+ return fence;
}
function plainListParagraphMarker(text: string): PlainListParagraphMarker | null {
@@ -77,7 +89,7 @@ function plainListParagraphMarker(text: string): PlainListParagraphMarker | null
attrs: { marker: bullet[1], separator: bullet[2] },
};
}
- const ordered = text.match(/^([1-9]\d{0,5})([.)])([ \t]+)/);
+ const ordered = text.match(/^([1-9]\d{0,6})([.)])([ \t]+)/);
if (ordered) {
return {
kind: 'ordered',
@@ -85,7 +97,7 @@ function plainListParagraphMarker(text: string): PlainListParagraphMarker | null
attrs: { start: Number(ordered[1]), marker: ordered[2], separator: ordered[3] },
};
}
- const cjkOrdered = text.match(/^([1-9]\d{0,5})(、)([ \t]*)/);
+ const cjkOrdered = text.match(/^([1-9]\d{0,6})(、)([ \t]*)/);
if (cjkOrdered) {
return {
kind: 'ordered',
@@ -134,7 +146,7 @@ function hardBreakListInputRule(
if (!paragraphType || !itemType) return null;
const leadingParagraph = paragraph.type.create(paragraph.attrs, before, paragraph.marks);
- const listParagraph = paragraphType.create(null, after);
+ const listParagraph = paragraph.type.create(paragraph.attrs, after, paragraph.marks);
const list = type.create(
(match.data?.attributes as Record<string, unknown> | undefined) ?? {},
itemType.create(null, listParagraph),
@@ -505,11 +517,24 @@ export function isTrailingEmptyTopLevelParagraph(view: EditorView): boolean {
);
}
+export function isTopLevelBlockSelection(view: EditorView): boolean {
+ const { state } = view;
+ const { $from, $to } = state.selection;
+ return (
+ !state.selection.empty &&
+ $from.depth === 1 &&
+ $to.depth === 1 &&
+ $from.parentOffset === 0 &&
+ $to.parentOffset === $to.parent.content.size
+ );
+}
+
export function promoteTrailingPlainListParagraph(view: EditorView): boolean {
const trailing = getTrailingPlainListParagraph(view);
if (!trailing) return false;
const { state } = view;
const { paragraph, marker, paragraphPosition } = trailing;
+ if (documentFenceStateBefore(state.doc, paragraphPosition)) return false;
const paragraphType = state.schema.nodes.paragraph;
const itemType = state.schema.nodes.listItem;
diff --git a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts
index 84a39d5e83..985095aaf5 100644
--- a/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts
+++ b/apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts
@@ -38,7 +38,7 @@ export interface SerializedComposerContent {
type OrderedMarker = '.' | ')' | '、';
const EMPTY_LIST_ITEM_MARKER_RE =
- /(?:^|\n)[ \t]*(?:[1-9]\d{0,5}[.)][ \t]+|[1-9]\d{0,5}、[ \t]*|[-+*•][ \t]+)$/;
+ /(?:^|\n)[ \t]*(?:[1-9]\d{0,6}[.)][ \t]+|[1-9]\d{0,6}、[ \t]*|[-+*•][ \t]+)$/;
const TAB_SIZE = 4;
@@ -56,8 +56,8 @@ function expandedIndentWidth(text: string): number {
function literalListContinuationPrefix(text: string): string | null {
const match =
- text.match(/^([ \t]+)(?:[-+*•]|[1-9]\d{0,5}[.)])([ \t]+)/) ??
- text.match(/^([ \t]+)[1-9]\d{0,5}、[ \t]*/);
+ text.match(/^([ \t]+)(?:[-+*•]|[1-9]\d{0,6}[.)])([ \t]+)/) ??
+ text.match(/^([ \t]+)[1-9]\d{0,6}、[ \t]*/);
if (!match) return null;
return ' '.repeat(expandedIndentWidth(match[0]));
}
@@ -161,7 +161,7 @@ function serializeComposerDocument(
const quoteText = formatQuoteForSend(
composerQuoteAttrsToChatQuote(child.attrs as ComposerQuoteAttrs),
);
- if (prefix) {
+ if (prefix || continuationIndent) {
// A quote chip inside a list item is part of that item. Keeping it
// in the current text block preserves the list marker. Put the
// encoded quote on its own continuation lines so history parsing
@@ -189,7 +189,7 @@ function serializeComposerDocument(
const textAfterIndent = alreadyIndented
? childText.slice(continuationAfterQuote.length)
: childText;
- const needsQuoteBoundary = /^>[ \t]/.test(textAfterIndent);
+ const needsQuoteBoundary = /^>(?:[ \t]|$)/.test(textAfterIndent);
buffer += `${needsQuoteBoundary ? '\n\n' : '\n'}${
alreadyIndented ? '' : continuationAfterQuote
}`;
@@ -365,6 +365,25 @@ function serializeComposerDocument(
});
return;
}
+ const inlineQuoteOffset = (() => {
+ let offset = 0;
+ for (let index = 0; index < node.childCount; index += 1) {
+ const child = node.child(index);
+ if (child.type.name === COMPOSER_QUOTE_NODE_TYPE) return offset;
+ offset += child.nodeSize;
+ }
+ return null;
+ })();
+ const inlineLiteralContinuation =
+ inlineQuoteOffset !== null
+ ? literalListContinuationPrefix(
+ node.textBetween(0, inlineQuoteOffset, '\n', '\uFFFC'),
+ )
+ : null;
+ if (inlineLiteralContinuation) {
+ serializeParagraph(node, nodeOffset, '', inlineLiteralContinuation);
+ return;
+ }
serializeParagraph(node, nodeOffset);
return;
}
diff --git a/apps/desktop/src/renderer/lib/composerListDocument.ts b/apps/desktop/src/renderer/lib/composerListDocument.ts
index ff6c44e022..6da2ce61da 100644
--- a/apps/desktop/src/renderer/lib/composerListDocument.ts
+++ b/apps/desktop/src/renderer/lib/composerListDocument.ts
@@ -17,7 +17,7 @@ interface ComposerLine {
}
const BULLET_RE = /^([-+*•])([ \t]+)/;
-const ORDERED_RE = /^([1-9]\d{0,5})([.)、])([ \t]*)/;
+const ORDERED_RE = /^([1-9]\d{0,6})([.)、])([ \t]*)/;
function inlineNodeText(node: JSONContent): string {
if (node.type === 'text') return node.text ?? '';
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index 6e4e1e7cfa..103be32e0d 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -326,14 +326,14 @@ html:lang(ko) {
(command-palette F2.5). The Placeholder extension injects
`p.is-editor-empty::before` with the placeholder text in a `data-*`
attribute; we style it to match the old textarea placeholder. */
-.ProseMirror p.is-editor-empty:first-child::before {
+.ProseMirror > p.is-editor-empty:first-child::before {
content: attr(data-placeholder);
color: var(--chat-input-placeholder-subtle);
float: left;
height: 0;
pointer-events: none;
}
-[data-voice-draft-active='true'] .ProseMirror p.is-editor-empty:first-child::before {
+[data-voice-draft-active='true'] .ProseMirror > p.is-editor-empty:first-child::before {
content: none;
}
.ProseMirror {