Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix AI selection replacement line breaks

tianma-if91f5fe7f9e3b
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index 742b09e3..29814d2b 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -148,6 +148,11 @@ import { processFilesSequentially } from "@/lib/file-batch";
import { MEMO_ID_REMAPPED_EVENT, MEMO_SYNC_ACKNOWLEDGED_EVENT } from "@/lib/sync-events";
import { useStandaloneMobileEditor } from "@/hooks/useStandaloneMobileEditor";
import { statusSettleMotion } from "@/lib/motion";
+import {
+ getRichTextAiSelectionContext,
+ getRichTextAiSelectionReplacement,
+ normalizeAiSelectionReplacement,
+} from "@/lib/ai-selection-replacement";
import { getAttachmentFilenameFromLabel, getAttachmentResourceId } from "@/lib/attachment-links";
import {
IMAGE_MENU_HIDE_EVENT,
@@ -205,10 +210,16 @@ type NoteLinkHintPosition = {
};
type AiSelectionContext = {
- kind: "rich" | "markdown" | "plain";
+ kind: "markdown" | "plain";
+ from: number;
+ to: number;
+ contentMarkdown: string;
+} | {
+ kind: "rich";
from: number;
to: number;
contentMarkdown: string;
+ isInline: boolean;
};
const getAttachmentLinkFromEventTarget = (target: EventTarget | null) =>
@@ -1824,15 +1835,8 @@ const RichEditorPane = ({
const contentMarkdown = markdownSource.slice(from, to).trim();
if (to > from && contentMarkdown) selection = { kind: "markdown", from, to, contentMarkdown };
} else if (isEditorReady(editor)) {
- const { from, to, empty } = editor.state.selection;
- if (!empty) {
- const selectedContent = editor.state.selection.content().content.toJSON() as TiptapDoc["content"];
- const contentMarkdown = (
- docToMarkdown({ type: "doc", content: selectedContent }) ||
- editor.state.doc.textBetween(from, to, "\n")
- ).trim();
- if (contentMarkdown) selection = { kind: "rich", from, to, contentMarkdown };
- }
+ const richSelection = getRichTextAiSelectionContext(editor.state.doc, editor.state.selection);
+ if (richSelection) selection = { kind: "rich", ...richSelection };
}
setAiSelection(selection);
@@ -1846,9 +1850,12 @@ const RichEditorPane = ({
const applyAiDraft = useCallback((draft: string, mode: "append" | "replace") => {
if (mode === "replace" && aiSelection) {
+ const replacementDraft = normalizeAiSelectionReplacement(draft);
+ if (!replacementDraft) return;
+
if (aiSelection.kind === "plain") {
const source = getMobilePlainTextValue();
- const { next, caret } = insertMarkdownSnippet(source, draft, aiSelection.from, aiSelection.to);
+ const { next, caret } = insertMarkdownSnippet(source, replacementDraft, aiSelection.from, aiSelection.to);
setMobilePlainText(next);
setMobilePlainTextElementValue(mobileTextAreaRef.current, next);
persistCurrentDraft(title, tagsText, next);
@@ -1858,17 +1865,20 @@ const RichEditorPane = ({
if (plainTextElement instanceof HTMLTextAreaElement) plainTextElement.setSelectionRange(caret, caret);
});
} else if (aiSelection.kind === "markdown") {
- const { next, caret } = insertMarkdownSnippet(markdownSource, draft, aiSelection.from, aiSelection.to);
+ const { next, caret } = insertMarkdownSnippet(markdownSource, replacementDraft, aiSelection.from, aiSelection.to);
setMarkdownSource(next);
window.requestAnimationFrame(() => {
markdownTextAreaRef.current?.focus();
markdownTextAreaRef.current?.setSelectionRange(caret, caret);
});
- } else if (isEditorReady(editor)) {
+ } else if (aiSelection.kind === "rich" && isEditorReady(editor)) {
const maxPos = editor.state.doc.content.size;
const from = Math.max(1, Math.min(aiSelection.from, maxPos));
const to = Math.max(from, Math.min(aiSelection.to, maxPos));
- editor.chain().focus().insertContentAt({ from, to }, markdownToDoc(draft).content).run();
+ editor.chain().focus().insertContentAt(
+ { from, to },
+ getRichTextAiSelectionReplacement(replacementDraft, aiSelection.isInline),
+ ).run();
}
markDirty();
setAiSelection(null);
diff --git a/apps/web/src/lib/ai-selection-replacement.test.mjs b/apps/web/src/lib/ai-selection-replacement.test.mjs
new file mode 100644
index 00000000..01d840d4
--- /dev/null
+++ b/apps/web/src/lib/ai-selection-replacement.test.mjs
@@ -0,0 +1,103 @@
+import { describe, expect, test } from "bun:test";
+import { Editor } from "@tiptap/core";
+import { NodeSelection } from "@tiptap/pm/state";
+import StarterKit from "@tiptap/starter-kit";
+import { markdownToDoc } from "@edgeever/shared";
+import {
+ getRichTextAiSelectionContext,
+ getRichTextAiSelectionReplacement,
+ normalizeAiSelectionReplacement,
+} from "./ai-selection-replacement.ts";
+
+describe("getRichTextAiSelectionReplacement", () => {
+ test("removes streamed whitespace around selected-text replacements", () => {
+ expect(normalizeAiSelectionReplacement("\n 1. - 校对 \n")).toBe("1. - 校对");
+ expect(normalizeAiSelectionReplacement("第一段\n\n第二段")).toBe("第一段\n\n第二段");
+ });
+
+ test("keeps list-like single-line output inline inside a paragraph", () => {
+ expect(getRichTextAiSelectionReplacement("1. - 校对", true)).toEqual([
+ { type: "text", text: "1. - 校对" },
+ ]);
+ });
+
+ test("does not split the surrounding paragraph when applying the replacement", () => {
+ const text = "入口放在笔记栏中,1. - 校对先预览结果,再进行写入。";
+ const selectedText = "1. - 校对";
+ const from = text.indexOf(selectedText) + 1;
+ const editor = new Editor({
+ extensions: [StarterKit],
+ content: {
+ type: "doc",
+ content: [{ type: "paragraph", content: [{ type: "text", text }] }],
+ },
+ });
+
+ editor.commands.insertContentAt(
+ { from, to: from + selectedText.length },
+ getRichTextAiSelectionReplacement(selectedText, true),
+ );
+
+ expect(editor.getJSON()).toEqual({
+ type: "doc",
+ content: [{ type: "paragraph", content: [{ type: "text", text }] }],
+ });
+ editor.destroy();
+ });
+
+ test("keeps a selected list item in its existing list instead of nesting another list", () => {
+ const originalMarkdown = [
+ "入口放在选中文本菜单和笔记栏中,",
+ "",
+ "1. - 校对",
+ "",
+ "先预览结果,再进行写入。",
+ ].join("\n");
+ const editor = new Editor({
+ extensions: [StarterKit],
+ content: markdownToDoc(originalMarkdown),
+ });
+ const originalDoc = editor.getJSON();
+ let listPosition = null;
+ editor.state.doc.descendants((node, pos) => {
+ if (listPosition === null && node.type.name === "orderedList") listPosition = pos;
+ });
+ expect(listPosition).not.toBeNull();
+
+ const context = getRichTextAiSelectionContext(
+ editor.state.doc,
+ NodeSelection.create(editor.state.doc, listPosition),
+ );
+ expect(context).toMatchObject({
+ contentMarkdown: "- 校对",
+ isInline: true,
+ });
+
+ editor.commands.insertContentAt(
+ { from: context.from, to: context.to },
+ getRichTextAiSelectionReplacement(context.contentMarkdown, context.isInline),
+ );
+
+ expect(editor.getJSON()).toEqual(originalDoc);
+ editor.destroy();
+ });
+
+ test("preserves inline Markdown marks", () => {
+ expect(getRichTextAiSelectionReplacement("改得 **自然** 一些", true)).toEqual([
+ { type: "text", text: "改得 " },
+ { type: "text", text: "自然", marks: [{ type: "bold" }] },
+ { type: "text", text: " 一些" },
+ ]);
+ });
+
+ test("keeps genuine multi-block output as blocks", () => {
+ expect(getRichTextAiSelectionReplacement("第一段\n\n第二段", true)).toEqual([
+ { type: "paragraph", content: [{ type: "text", text: "第一段" }] },
+ { type: "paragraph", content: [{ type: "text", text: "第二段" }] },
+ ]);
+ });
+
+ test("keeps block parsing when the original selection spans blocks", () => {
+ expect(getRichTextAiSelectionReplacement("1. - 校对", false)[0]?.type).toBe("orderedList");
+ });
+});
diff --git a/apps/web/src/lib/ai-selection-replacement.ts b/apps/web/src/lib/ai-selection-replacement.ts
new file mode 100644
index 00000000..76a447f0
--- /dev/null
+++ b/apps/web/src/lib/ai-selection-replacement.ts
@@ -0,0 +1,125 @@
+import {
+ docToMarkdown,
+ markdownToDoc,
+ type TiptapNode,
+ type TiptapTextNode,
+} from "@edgeever/shared";
+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
+import type { Selection } from "@tiptap/pm/state";
+
+type TiptapInlineContent = NonNullable<TiptapNode["content"]>;
+
+const INLINE_SENTINEL = "edgeever-inline-sentinel";
+
+const isTextNode = (node: TiptapNode | TiptapTextNode): node is TiptapTextNode =>
+ node.type === "text" && "text" in node;
+
+export type RichTextAiSelectionContext = {
+ from: number;
+ to: number;
+ contentMarkdown: string;
+ isInline: boolean;
+};
+
+/** AI output may be streamed with formatting whitespace around the response. */
+export const normalizeAiSelectionReplacement = (draft: string): string => draft.trim();
+
+/**
+ * Resolve the text that should be sent to AI and the range that should later
+ * be replaced. Selecting a whole list item can include its ordered/bullet-list
+ * wrappers even though it contains only one editable paragraph. In that case,
+ * keep the wrappers in the document and narrow the operation to that textblock.
+ */
+export const getRichTextAiSelectionContext = (
+ doc: ProseMirrorNode,
+ selection: Selection,
+): RichTextAiSelectionContext | null => {
+ if (selection.empty) return null;
+
+ const selectedTextblocks: Array<{
+ node: ProseMirrorNode;
+ contentFrom: number;
+ contentTo: number;
+ from: number;
+ to: number;
+ }> = [];
+
+ doc.nodesBetween(selection.from, selection.to, (node, pos) => {
+ if (!node.isTextblock) return true;
+
+ const contentFrom = pos + 1;
+ const contentTo = contentFrom + node.content.size;
+ const from = Math.max(selection.from, contentFrom);
+ const to = Math.min(selection.to, contentTo);
+ if (to > from) selectedTextblocks.push({ node, contentFrom, contentTo, from, to });
+ return false;
+ });
+
+ if (selectedTextblocks.length === 1) {
+ const block = selectedTextblocks[0];
+ const selectedBlock = block.node.cut(
+ block.from - block.contentFrom,
+ block.to - block.contentFrom,
+ ).toJSON() as TiptapNode;
+ const contentMarkdown = (
+ docToMarkdown({
+ type: "doc",
+ content: [{ type: "paragraph", content: selectedBlock.content }],
+ }) || doc.textBetween(block.from, block.to, "\n")
+ ).trim();
+
+ return contentMarkdown
+ ? { from: block.from, to: block.to, contentMarkdown, isInline: true }
+ : null;
+ }
+
+ const selectedContent = selection.content().content.toJSON() as TiptapNode[];
+ const contentMarkdown = (
+ docToMarkdown({ type: "doc", content: selectedContent }) ||
+ doc.textBetween(selection.from, selection.to, "\n")
+ ).trim();
+
+ return contentMarkdown
+ ? {
+ from: selection.from,
+ to: selection.to,
+ contentMarkdown,
+ isInline: false,
+ }
+ : null;
+};
+
+/**
+ * Parse an AI draft for a rich-text selection.
+ *
+ * A Markdown parser treats list-like text such as `1. - review` as a block.
+ * Inserting that block into a selection inside a paragraph splits the paragraph
+ * and creates an unwanted line break. Prefixing inline selections with an
+ * internal sentinel keeps single-block output in an inline parsing context;
+ * the sentinel is removed before insertion. Genuine multi-block output still
+ * falls back to normal block Markdown parsing.
+ */
+export const getRichTextAiSelectionReplacement = (
+ draft: string,
+ selectionIsInline: boolean,
+): TiptapInlineContent => {
+ const blockContent = markdownToDoc(draft).content;
+ if (!selectionIsInline) return blockContent;
+
+ const inlineDoc = markdownToDoc(`${INLINE_SENTINEL}${draft}`);
+ if (inlineDoc.content.length !== 1 || inlineDoc.content[0]?.type !== "paragraph") {
+ return blockContent;
+ }
+
+ const inlineContent = inlineDoc.content[0].content ?? [];
+ const firstNode = inlineContent[0];
+ if (!firstNode || !isTextNode(firstNode) || !firstNode.text.startsWith(INLINE_SENTINEL)) {
+ return blockContent;
+ }
+
+ const firstText = firstNode.text.slice(INLINE_SENTINEL.length);
+ return [
+ ...(firstText ? [{ ...firstNode, text: firstText }] : []),
+ ...inlineContent.slice(1),
+ ];
+};
diff --git a/tests/e2e/ai-selection-replacement.spec.ts b/tests/e2e/ai-selection-replacement.spec.ts
new file mode 100644
index 00000000..32fab17c
--- /dev/null
+++ b/tests/e2e/ai-selection-replacement.spec.ts
@@ -0,0 +1,141 @@
+import { expect, test, type Locator, type Page } from "@playwright/test";
+
+const selectEditorText = async (page: Page, editor: Locator, text: string) => {
+ const selected = await editor.evaluate((element, needle) => {
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
+ let node = walker.nextNode();
+ while (node) {
+ const value = node.textContent ?? "";
+ const start = value.indexOf(needle);
+ if (start >= 0) {
+ const range = document.createRange();
+ range.setStart(node, start);
+ range.setEnd(node, start + needle.length);
+ const selection = window.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ element.dispatchEvent(new Event("selectionchange", { bubbles: true }));
+ element.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
+ return selection?.toString() ?? "";
+ }
+ node = walker.nextNode();
+ }
+ return "";
+ }, text);
+
+ expect(selected).toBe(text);
+ await expect(page.getByRole("button", { name: "用 AI 处理" })).toBeVisible();
+};
+
+const mockAiReplacement = async (page: Page, replacement: string) => {
+ await page.route("**/api/v1/ai/generate", async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: "text/event-stream; charset=utf-8",
+ body: [
+ `data: ${JSON.stringify({ type: "start" })}`,
+ `data: ${JSON.stringify({ type: "text-delta", text: replacement })}`,
+ `data: ${JSON.stringify({ type: "finish", finishReason: "stop" })}`,
+ "",
+ ].join("\n\n"),
+ });
+ });
+};
+
+const openMemo = async (page: Page, memoId: string, notebookName: string) => {
+ await page.goto("/");
+ await page.getByRole("button", { name: new RegExp(notebookName) }).click();
+ await page.locator(`[data-memo-id="${memoId}"]`).locator("button").first().click();
+ return page.locator(".ProseMirror[contenteditable='true']");
+};
+
+const applyAiReplacement = async (page: Page) => {
+ await page.getByRole("button", { name: "用 AI 处理" }).click();
+ const dialog = page.getByRole("dialog", { name: "AI 笔记助手" });
+ await dialog.getByRole("button", { name: "生成", exact: true }).click();
+ await expect(dialog.getByRole("button", { name: "接受并替换选中内容" })).toBeEnabled();
+ await dialog.getByRole("button", { name: "接受并替换选中内容" }).click();
+ await expect(dialog).toBeHidden();
+};
+
+test.describe("AI selected-text replacement", () => {
+ let notebookId: string;
+ let notebookName: string;
+ const createdMemoIds: string[] = [];
+
+ test.beforeAll(async ({ request }) => {
+ const response = await request.get("/api/v1/notebooks");
+ expect(response.ok()).toBe(true);
+ const body = await response.json() as { notebooks: Array<{ id: string; name: string }> };
+ notebookId = body.notebooks[0]?.id;
+ notebookName = body.notebooks[0]?.name;
+ expect(notebookId).toBeTruthy();
+ expect(notebookName).toBeTruthy();
+ });
+
+ test.afterEach(async ({ request }) => {
+ while (createdMemoIds.length) {
+ const memoId = createdMemoIds.pop();
+ if (!memoId) continue;
+ await request.delete(`/api/v1/memos/${memoId}`);
+ await request.delete(`/api/v1/memos/${memoId}?permanent=1`);
+ }
+ });
+
+ const createMemo = async (page: Page, title: string, contentMarkdown: string) => {
+ const response = await page.request.post("/api/v1/memos", {
+ data: { notebookId, title, contentMarkdown },
+ });
+ expect(response.status()).toBe(201);
+ const memo = (await response.json() as { memo: { id: string } }).memo;
+ createdMemoIds.push(memo.id);
+ return memo;
+ };
+
+ test("keeps list-like replacement text inside its surrounding paragraph", async ({ page }) => {
+ const marker = `ai-inline-replace-${Date.now()}`;
+ const content = "入口放在笔记栏中,1. - 校对先预览结果,再进行写入。";
+ const memo = await createMemo(page, marker, content);
+ await mockAiReplacement(page, "\n1. - 校对\n");
+
+ const editor = await openMemo(page, memo.id, notebookName);
+ await expect(editor).toHaveText(content);
+ await selectEditorText(page, editor, "1. - 校对");
+ await applyAiReplacement(page);
+
+ await expect(editor.locator(":scope > p")).toHaveCount(1);
+ await expect(editor.locator(":scope > p")).toHaveText(content);
+ await expect(editor.locator("ol, ul")).toHaveCount(0);
+ });
+
+ test("keeps a whole selected list item in its original list", async ({ page }) => {
+ const marker = `ai-list-replace-${Date.now()}`;
+ const content = [
+ "入口放在选中文本菜单和笔记栏中,",
+ "",
+ "1. - 校对",
+ "",
+ "先预览结果,再进行写入。",
+ ].join("\n");
+ const memo = await createMemo(page, marker, content);
+ await mockAiReplacement(page, "\n- 已校对\n");
+
+ const editor = await openMemo(page, memo.id, notebookName);
+ await selectEditorText(page, editor, "- 校对");
+ await page.getByRole("button", { name: "用 AI 处理" }).click();
+ const dialog = page.getByRole("dialog", { name: "AI 笔记助手" });
+ await expect(dialog.getByText("- 校对", { exact: true })).toBeVisible();
+ await expect(dialog.getByText("1. - 校对", { exact: true })).toHaveCount(0);
+ await dialog.getByRole("button", { name: "生成", exact: true }).click();
+ await expect(dialog.getByRole("button", { name: "接受并替换选中内容" })).toBeEnabled();
+ await dialog.getByRole("button", { name: "接受并替换选中内容" }).click();
+ await expect(dialog).toBeHidden();
+
+ await expect(editor.locator(":scope > p")).toHaveCount(2);
+ await expect(editor.locator(":scope > ol")).toHaveCount(1);
+ await expect(editor.locator(":scope > ol > li > p")).toHaveText("- 已校对");
+ await expect(editor.locator("ol ol, ol ul")).toHaveCount(0);
+ await expect(editor.locator(":scope > p").first()).toHaveText("入口放在选中文本菜单和笔记栏中,");
+ await expect(editor.locator(":scope > p").last()).toHaveText("先预览结果,再进行写入。");
+ });
+});