Skip to content

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

fix(web): apply AI replacements to table selections

tianma-ifc674719e80ac
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index 912f9340..0c1ed5cb 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -159,6 +159,7 @@ import { useStandaloneMobileEditor } from "@/hooks/useStandaloneMobileEditor";
import { statusSettleMotion } from "@/lib/motion";
import {
getRichTextAiSelectionContext,
+ getRichTextAiReplacementRange,
getRichTextAiSelectionReplacement,
normalizeAiSelectionReplacement,
} from "@/lib/ai-selection-replacement";
@@ -1940,7 +1941,7 @@ const RichEditorPane = ({
const applyAiDraft = useCallback((draft: string, mode: "append" | "replace") => {
if (mode === "replace" && aiSelection) {
const replacementDraft = normalizeAiSelectionReplacement(draft);
- if (!replacementDraft) return;
+ if (!replacementDraft) return false;
if (aiSelection.kind === "plain") {
const source = getMobilePlainTextValue();
@@ -1962,17 +1963,24 @@ const RichEditorPane = ({
});
} 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 },
- getRichTextAiSelectionReplacement(replacementDraft, aiSelection.isInline),
- ).run();
+ const { from, to } = getRichTextAiReplacementRange(aiSelection.from, aiSelection.to, maxPos);
+ try {
+ const applied = editor.commands.insertContentAt(
+ { from, to },
+ getRichTextAiSelectionReplacement(replacementDraft, aiSelection.isInline),
+ );
+ if (!applied) return false;
+ editor.commands.focus();
+ } catch {
+ return false;
+ }
+ } else {
+ return false;
}
markDirty();
setAiSelection(null);
setAiAssistantOpen(false);
- return;
+ return true;
}
const current = getCurrentMarkdownForAi();
@@ -1986,11 +1994,18 @@ const RichEditorPane = ({
} else if (useMarkdownSourceEditor) {
setMarkdownSource(next);
} else if (isEditorReady(editor)) {
- editor.commands.setContent(markdownToDoc(next));
+ try {
+ if (!editor.commands.setContent(markdownToDoc(next))) return false;
+ } catch {
+ return false;
+ }
+ } else {
+ return false;
}
markDirty();
setAiSelection(null);
setAiAssistantOpen(false);
+ return true;
}, [aiSelection, editor, getCurrentMarkdownForAi, getMobilePlainTextValue, markDirty, markdownSource, persistCurrentDraft, tagsText, title, useMarkdownSourceEditor, useMobilePlainTextEditor]);
const getCurrentContentJson = useCallback((): TiptapDoc | null => {
diff --git a/apps/web/src/components/dialogs/AiAssistantDialog.tsx b/apps/web/src/components/dialogs/AiAssistantDialog.tsx
index 39957598..24718498 100644
--- a/apps/web/src/components/dialogs/AiAssistantDialog.tsx
+++ b/apps/web/src/components/dialogs/AiAssistantDialog.tsx
@@ -61,7 +61,7 @@ export const AiAssistantDialog = ({
contentMarkdown: string;
selectionMarkdown?: string | null;
onOpenChange: (open: boolean) => void;
- onApply: (text: string, mode: "append" | "replace") => void;
+ onApply: (text: string, mode: "append" | "replace") => boolean;
onOpenPromptLibrary?: () => void;
}) => {
const { t, i18n } = useTranslation();
@@ -245,6 +245,13 @@ export const AiAssistantDialog = ({
return generate();
};
+ const applyOutput = (mode: "append" | "replace") => {
+ setError(null);
+ if (!onApply(output, mode)) {
+ setError(t("aiAssistant.applyFailed"));
+ }
+ };
+
const copy = async () => {
if (await copyTextToClipboard(output)) {
setCopied(true);
@@ -488,12 +495,12 @@ export const AiAssistantDialog = ({
</div>
<div className="flex flex-wrap gap-2">
{promptAllowsReplace(effectiveResultMode) ? (
- <Button type="button" variant={hasSelection ? "solid" : "outline"} disabled={isGenerating} onClick={() => onApply(output, "replace")}>
+ <Button type="button" variant={hasSelection ? "solid" : "outline"} disabled={isGenerating} onClick={() => applyOutput("replace")}>
{t(hasSelection ? "aiAssistant.replaceSelection" : "aiAssistant.replace")}
</Button>
) : null}
{promptAllowsAppend(effectiveResultMode) ? (
- <Button type="button" variant={hasSelection && promptAllowsReplace(effectiveResultMode) ? "outline" : "solid"} disabled={isGenerating} onClick={() => onApply(output, "append")}>{t("aiAssistant.append")}</Button>
+ <Button type="button" variant={hasSelection && promptAllowsReplace(effectiveResultMode) ? "outline" : "solid"} disabled={isGenerating} onClick={() => applyOutput("append")}>{t("aiAssistant.append")}</Button>
) : null}
</div>
</DialogFooter>
diff --git a/apps/web/src/lib/ai-selection-replacement.test.mjs b/apps/web/src/lib/ai-selection-replacement.test.mjs
index 5e30b863..ae29473d 100644
--- a/apps/web/src/lib/ai-selection-replacement.test.mjs
+++ b/apps/web/src/lib/ai-selection-replacement.test.mjs
@@ -1,10 +1,12 @@
import { describe, expect, test } from "bun:test";
import { Editor } from "@tiptap/core";
+import { TableKit } from "@tiptap/extension-table";
import { NodeSelection } from "@tiptap/pm/state";
import StarterKit from "@tiptap/starter-kit";
import { markdownToDoc } from "@edgeever/shared";
import {
getRichTextAiSelectionContext,
+ getRichTextAiReplacementRange,
getRichTextAiSelectionReplacement,
normalizeAiSelectionReplacement,
} from "./ai-selection-replacement.ts";
@@ -99,4 +101,42 @@ describe("getRichTextAiSelectionReplacement", () => {
test("keeps block parsing when the original selection spans blocks", () => {
expect(getRichTextAiSelectionReplacement("1. - 校对", false)[0]?.type).toBe("orderedList");
});
+
+ test("replaces a table node selected at the start of the document", () => {
+ const editor = new Editor({
+ extensions: [StarterKit, TableKit],
+ content: markdownToDoc([
+ "| A | B |",
+ "| --- | --- |",
+ "| foo | bar |",
+ ].join("\n")),
+ });
+ const context = getRichTextAiSelectionContext(
+ editor.state.doc,
+ NodeSelection.create(editor.state.doc, 0),
+ );
+
+ expect(context).not.toBeNull();
+ const range = getRichTextAiReplacementRange(
+ context.from,
+ context.to,
+ editor.state.doc.content.size,
+ );
+ expect(range.from).toBe(0);
+
+ editor.commands.insertContentAt(
+ range,
+ getRichTextAiSelectionReplacement([
+ "| X | Y |",
+ "| --- | --- |",
+ "| one | two |",
+ ].join("\n"), context.isInline),
+ );
+
+ expect(editor.getJSON().content).toHaveLength(1);
+ expect(editor.getJSON().content[0]?.type).toBe("table");
+ expect(JSON.stringify(editor.getJSON())).toContain("one");
+ expect(JSON.stringify(editor.getJSON())).not.toContain("foo");
+ editor.destroy();
+ });
});
diff --git a/apps/web/src/lib/ai-selection-replacement.ts b/apps/web/src/lib/ai-selection-replacement.ts
index 336e9d01..82f6d7de 100644
--- a/apps/web/src/lib/ai-selection-replacement.ts
+++ b/apps/web/src/lib/ai-selection-replacement.ts
@@ -1,5 +1,6 @@
export {
getRichTextAiSelectionContext,
+ getRichTextAiReplacementRange,
getRichTextAiSelectionReplacement,
normalizeAiSelectionReplacement,
type RichTextAiSelectionContext,
diff --git a/packages/shared/src/ai-selection.ts b/packages/shared/src/ai-selection.ts
index 2dde967d..9e169190 100644
--- a/packages/shared/src/ai-selection.ts
+++ b/packages/shared/src/ai-selection.ts
@@ -41,6 +41,22 @@ export type RichTextAiSelectionContext = {
/** AI output may be streamed with formatting whitespace around the response. */
export const normalizeAiSelectionReplacement = (draft: string): string => draft.trim();
+/**
+ * Clamp a stored rich-text selection without discarding valid block-node
+ * positions. A node selection for the first document block starts at 0.
+ */
+export const getRichTextAiReplacementRange = (
+ from: number,
+ to: number,
+ documentSize: number,
+) => {
+ const safeFrom = Math.max(0, Math.min(from, documentSize));
+ return {
+ from: safeFrom,
+ to: Math.max(safeFrom, Math.min(to, documentSize)),
+ };
+};
+
/**
* Resolve the Markdown and replacement range for a rich-text selection.
* A single selected text block stays inside its existing paragraph/list item.
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 42563d39..0bacfec6 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -539,6 +539,7 @@ export const enUS = {
append: "Append to note",
replace: "Replace note",
replaceSelection: "Accept and replace selection",
+ applyFailed: "Could not apply the generated result. Select the content again and retry.",
configure: "Configure an AI model in Me → AI Integrations first.",
},
accountInfo: {
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index f54cd7fd..00fbdbcf 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -539,6 +539,7 @@ export const zhCN = {
append: "追加到笔记",
replace: "替换笔记",
replaceSelection: "接受并替换选中内容",
+ applyFailed: "无法应用生成结果。请重新选择内容后再试。",
configure: "请先在“我的 → AI 集成”中配置 AI 模型。",
},
accountInfo: {