Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): cell-insertion gates and list paste placement (#2599)

Nick Gomez54619a2b6c07
diff --git a/.changeset/insertion-route-cell-gates-list-paste.md b/.changeset/insertion-route-cell-gates-list-paste.md
new file mode 100644
index 000000000..56b110b6f
--- /dev/null
+++ b/.changeset/insertion-route-cell-gates-list-paste.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Two editor insertion-route fixes.
+
+Block components (Callout, and any block-level JSX component) can no longer be placed inside a table cell, where they previously disappeared on save: a table cell has no markdown spelling for block content, so the component serialized to zero bytes while still showing in the editor. Every insertion route now refuses it as a silent no-op — the slash menu omits block-component entries when the caret is in a cell, and pasting or dropping a block component into a cell leaves the document unchanged. Placing the same component outside a cell is unaffected, and content that already carries a component in a cell (from a collaborator or a raw file edit) is left alone rather than fought.
+
+Pasting copied list items at a list-item boundary now lands them as sibling items instead of mis-placing them (inkeep/open-knowledge#609). Pasting at the start of an item puts the copied items above it, at the end puts them below it, and mid-item splits the item at the caret. Task, bullet, and ordered lists behave the same way, nested lists inside the pasted items are preserved, and pasting a whole component or table still reproduces it byte-for-byte.
diff --git a/packages/app/src/editor/clipboard/handle-paste.list-placement.test.ts b/packages/app/src/editor/clipboard/handle-paste.list-placement.test.ts
new file mode 100644
index 000000000..6257eea24
--- /dev/null
+++ b/packages/app/src/editor/clipboard/handle-paste.list-placement.test.ts
@@ -0,0 +1,494 @@
+/**
+ * List-aware paste placement (#609 cause 1).
+ *
+ * OK→OK paste of list content at a list-item boundary must splice the pasted
+ * items as SIBLINGS at the caret's list level — above the item at item-start,
+ * below at item-end, split around the caret mid-item — never nesting the
+ * pasted list as a child of the target item or minting an empty-leading
+ * -paragraph orphan shape.
+ *
+ * Each test mounts a real TipTap editor over the core schema (real list nodes,
+ * real MarkdownManager) and drives the REAL createHandlePaste dispatcher, so
+ * the whole path runs: markdown-first tiebreak → MarkdownManager.parse →
+ * applyJsonSlice → buildListSiblingSpliceTr. Assertions cover the resulting PM
+ * structure AND the serialized markdown (the sibling shapes serialize
+ * correctly on today's engine — these pins do not depend on the engine
+ * strip×glue fix that ships separately).
+ */
+
+import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
+import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
+import { Editor, type JSONContent } from '@tiptap/core';
+import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import { TextSelection } from '@tiptap/pm/state';
+import * as actualSonner from 'sonner';
+import { installDomGlobals } from '../walk-currency-test-harness';
+import { createHandlePaste } from './handle-paste';
+import { createClipboardTextSerializer } from './serialize';
+
+// The dispatcher pulls the degrade-path toast (sonner) into its import graph;
+// stub it so module load stays inert. The splice path never degrades.
+mock.module('sonner', () => ({ ...actualSonner, toast: { error: mock(() => {}) } }));
+
+const mdManager = new MarkdownManager({ extensions: sharedExtensions });
+
+let restoreDomGlobals: (() => void) | null = null;
+const editors: Editor[] = [];
+
+beforeAll(() => {
+ restoreDomGlobals = installDomGlobals();
+});
+
+afterAll(() => {
+ restoreDomGlobals?.();
+ restoreDomGlobals = null;
+});
+
+afterEach(() => {
+ while (editors.length > 0) editors.pop()?.destroy();
+});
+
+function mountEditor(md: string): Editor {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const editor = new Editor({
+ element: host,
+ content: mdManager.parse(md) as JSONContent,
+ extensions: [...sharedExtensions],
+ });
+ editors.push(editor);
+ return editor;
+}
+
+/** text/plain + a dummy text/html sibling — the shape an OK→OK copy carries,
+ * so the dispatcher's markdown-first tiebreak routes through the markdown
+ * parse (the branch applyJsonSlice's placement fix lives on). */
+function pasteMarkdown(editor: Editor, payload: string): boolean {
+ const dt = {
+ clipboardData: {
+ types: ['text/plain', 'text/html'],
+ getData: (k: string) =>
+ k === 'text/plain' ? payload : k === 'text/html' ? '<ul><li>x</li></ul>' : '',
+ },
+ } as unknown as ClipboardEvent;
+ return createHandlePaste({ mdManager })(editor.view, dt);
+}
+
+/** Doc position of the first char / last char of the nth list item's first
+ * paragraph (0-based, doc order). */
+function itemParaRange(doc: ProseMirrorNode, n: number): { start: number; end: number } {
+ let i = 0;
+ let found: { start: number; end: number } | null = null;
+ doc.descendants((node, pos) => {
+ if (found) return false;
+ if (node.type.name === 'listItem') {
+ if (i === n) {
+ const para = node.firstChild;
+ const start = pos + 2; // listItem open +1 → paragraph, +1 → text
+ found = { start, end: start + (para ? para.content.size : 0) };
+ return false;
+ }
+ i++;
+ }
+ return true;
+ });
+ if (!found) throw new Error(`listItem ${n} not found`);
+ return found;
+}
+
+function setCaret(editor: Editor, pos: number): void {
+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, pos)));
+}
+
+interface ItemShape {
+ checked: boolean | null;
+ text: string;
+ nested: string[];
+}
+
+/** The first top-level list's items as {checked, text, nested-item-texts}. */
+function firstListItems(doc: ProseMirrorNode): ItemShape[] {
+ let list: ProseMirrorNode | null = null;
+ doc.forEach((node) => {
+ if (!list && node.type.name === 'list') list = node;
+ });
+ if (!list) throw new Error('no top-level list');
+ const items: ItemShape[] = [];
+ (list as ProseMirrorNode).forEach((item) => {
+ if (item.type.name !== 'listItem') return;
+ let text: string | null = null;
+ const nested: string[] = [];
+ item.forEach((child) => {
+ if (child.type.name === 'paragraph' && text === null) text = child.textContent;
+ if (child.type.name === 'list') {
+ child.forEach((ni) => {
+ if (ni.type.name === 'listItem') nested.push(ni.textContent);
+ });
+ }
+ });
+ items.push({ checked: item.attrs.checked, text: text ?? '', nested });
+ });
+ return items;
+}
+
+/** Top-level node type names — asserts nothing leaked outside the list. */
+function topLevelTypes(doc: ProseMirrorNode): string[] {
+ const names: string[] = [];
+ doc.forEach((node) => {
+ names.push(node.type.name);
+ });
+ return names;
+}
+
+function serialize(editor: Editor): string {
+ return mdManager.serialize(editor.getJSON() as JSONContent);
+}
+
+/** The orphan byte shapes #609 produces when list content is mis-placed. */
+function hasOrphanShapes(md: string): boolean {
+ return /- \[ \] - \[ \]/.test(md) || /^\s*\\- /m.test(md) || /- - /.test(md);
+}
+
+const TASK_SEED = ['- [ ] alpha', '- [ ] bravo', '- [x] charlie', '- [ ] delta', '- [ ] echo'].join(
+ '\n',
+);
+
+describe('list paste placement — tracer: full copy→paste round trip', () => {
+ test('copying a real item and pasting it at another item start splices a sibling above', () => {
+ // Copy item "bravo" through the REAL clipboard text serializer (the exact
+ // text/plain an OK copy writes), then paste at the start of "delta".
+ const source = mountEditor(TASK_SEED);
+ const bravo = itemParaRange(source.state.doc, 1);
+ source.view.dispatch(
+ source.state.tr.setSelection(TextSelection.create(source.state.doc, bravo.start, bravo.end)),
+ );
+ const payload = createClipboardTextSerializer({ mdManager })(
+ source.state.selection.content(),
+ source.view,
+ );
+ expect(payload).toBe('- [ ] bravo\n');
+
+ const target = mountEditor(TASK_SEED);
+ setCaret(target, itemParaRange(target.state.doc, 3).start);
+ expect(pasteMarkdown(target, payload)).toBe(true);
+
+ expect(firstListItems(target.state.doc).map((i) => i.text)).toEqual([
+ 'alpha',
+ 'bravo',
+ 'charlie',
+ 'bravo',
+ 'delta',
+ 'echo',
+ ]);
+ expect(hasOrphanShapes(serialize(target))).toBe(false);
+ });
+});
+
+describe('list paste placement — caret at item start (siblings above)', () => {
+ test('single task item pastes as a sibling above the intact target, no orphan shape', () => {
+ const editor = mountEditor(TASK_SEED);
+ setCaret(editor, itemParaRange(editor.state.doc, 3).start); // start of "delta"
+
+ expect(pasteMarkdown(editor, '- [ ] bravo\n')).toBe(true);
+
+ const items = firstListItems(editor.state.doc);
+ expect(items.map((i) => i.text)).toEqual([
+ 'alpha',
+ 'bravo',
+ 'charlie',
+ 'bravo',
+ 'delta',
+ 'echo',
+ ]);
+ // The pasted item is a full sibling (its own item, not nested); the target
+ // "delta" is intact and unchecked; no item carries an empty leading para.
+ expect(items[3]).toEqual({ checked: false, text: 'bravo', nested: [] });
+ expect(items[4]).toEqual({ checked: false, text: 'delta', nested: [] });
+ expect(items.every((i) => i.text.length > 0)).toBe(true);
+
+ const md = serialize(editor);
+ expect(md).toContain('- [ ] bravo\n- [ ] delta\n');
+ expect(hasOrphanShapes(md)).toBe(false);
+ });
+
+ test('two copied items paste above the first item preserving order', () => {
+ const editor = mountEditor(TASK_SEED);
+ setCaret(editor, itemParaRange(editor.state.doc, 0).start); // start of "alpha"
+
+ expect(pasteMarkdown(editor, '- [ ] bravo\n- [x] charlie\n')).toBe(true);
+
+ const items = firstListItems(editor.state.doc);
+ expect(items.map((i) => i.text)).toEqual([
+ 'bravo',
+ 'charlie',
+ 'alpha',
+ 'bravo',
+ 'charlie',
+ 'delta',
+ 'echo',
+ ]);
+ // Pasted checked state rides along: charlie stays checked.
+ expect(items[1]).toEqual({ checked: true, text: 'charlie', nested: [] });
+ expect(hasOrphanShapes(serialize(editor))).toBe(false);
+ });
+});
+
+describe('list paste placement — caret at item end (siblings below, not children)', () => {
+ test('single item pastes as a sibling below the target, never nested as a child', () => {
+ const editor = mountEditor(TASK_SEED);
+ setCaret(editor, itemParaRange(editor.state.doc, 3).end); // end of "delta"
+
+ expect(pasteMarkdown(editor, '- [ ] bravo\n')).toBe(true);
+
+ const items = firstListItems(editor.state.doc);
+ expect(items.map((i) => i.text)).toEqual([
+ 'alpha',
+ 'bravo',
+ 'charlie',
+ 'delta',
+ 'bravo',
+ 'echo',
+ ]);
+ // "delta" keeps no nested list — the pasted item is its sibling below.
+ expect(items[3]).toEqual({ checked: false, text: 'delta', nested: [] });
+ expect(items[4]).toEqual({ checked: false, text: 'bravo', nested: [] });
+
+ const md = serialize(editor);
+ expect(md).toContain('- [ ] delta\n- [ ] bravo\n');
+ expect(hasOrphanShapes(md)).toBe(false);
+ });
+
+ test('two copied items paste below the target as siblings', () => {
+ const editor = mountEditor(TASK_SEED);
+ setCaret(editor, itemParaRange(editor.state.doc, 4).end); // end of "echo"
+
+ expect(pasteMarkdown(editor, '- [ ] bravo\n- [x] charlie\n')).toBe(true);
+
+ expect(firstListItems(editor.state.doc).map((i) => i.text)).toEqual([
+ 'alpha',
+ 'bravo',
+ 'charlie',
+ 'delta',
+ 'echo',
+ 'bravo',
+ 'charlie',
+ ]);
+ expect(firstListItems(editor.state.doc).every((i) => i.nested.length === 0)).toBe(true);
+ expect(hasOrphanShapes(serialize(editor))).toBe(false);
+ });
+});
+
+describe('list paste placement — caret mid-item (split at caret)', () => {
+ test('mid-item paste splits the item: text-before stays, pasted follows, text-after trails', () => {
+ const editor = mountEditor(TASK_SEED);
+ setCaret(editor, itemParaRange(editor.state.doc, 3).start + 2); // "de|lta"
+
+ expect(pasteMarkdown(editor, '- [ ] bravo\n')).toBe(true);
+
+ const items = firstListItems(editor.state.doc);
+ expect(items.map((i) => i.text)).toEqual([
+ 'alpha',
+ 'bravo',
+ 'charlie',
+ 'de',
+ 'bravo',
+ 'lta',
+ 'echo',
+ ]);
+ // Both split halves are their own siblings; neither nests the pasted item.
+ expect(items[3]).toEqual({ checked: false, text: 'de', nested: [] });
+ expect(items[5]).toEqual({ checked: false, text: 'lta', nested: [] });
+ expect(hasOrphanShapes(serialize(editor))).toBe(false);
+ });
+});
+
+describe('list paste placement — nested lists, ordered, plain-bullet uniformity', () => {
+ test('a pasted item keeps its own nested list as a child (nested lists preserved)', () => {
+ const editor = mountEditor(TASK_SEED);
+ setCaret(editor, itemParaRange(editor.state.doc, 4).end); // end of "echo"
+
+ expect(pasteMarkdown(editor, '- [ ] parent\n - [ ] child-a\n - [ ] child-b\n')).toBe(true);
+
+ const items = firstListItems(editor.state.doc);
+ expect(items.map((i) => i.text)).toEqual([
+ 'alpha',
+ 'bravo',
+ 'charlie',
+ 'delta',
+ 'echo',
+ 'parent',
+ ]);
+ // The pasted "parent" item carries its own child list — opened at the
+ // sibling boundary only, never into the item's interior.
+ expect(items[5]).toEqual({ checked: false, text: 'parent', nested: ['child-a', 'child-b'] });
+ expect(hasOrphanShapes(serialize(editor))).toBe(false);
+ });
+
+ test('plain-bullet paste at item start splices siblings with no orphan (OP16 control)', () => {
+ const editor = mountEditor('- alpha\n- bravo\n- charlie');
+ setCaret(editor, itemParaRange(editor.state.doc, 2).start); // start of "charlie"
+
+ expect(pasteMarkdown(editor, '- bravo\n')).toBe(true);
+
+ const items = firstListItems(editor.state.doc);
+ expect(items.map((i) => i.text)).toEqual(['alpha', 'bravo', 'bravo', 'charlie']);
+ // Plain bullets carry a null checked attr — no task-marker leaks in.
+ expect(items.every((i) => i.checked === null)).toBe(true);
+
+ const md = serialize(editor);
+ expect(md).toContain('- bravo\n- charlie\n');
+ expect(hasOrphanShapes(md)).toBe(false);
+ });
+
+ test('ordered-list items pasted into a bullet list adopt the target level', () => {
+ const editor = mountEditor('- alpha\n- bravo\n- charlie');
+ setCaret(editor, itemParaRange(editor.state.doc, 2).end); // end of "charlie"
+
+ expect(pasteMarkdown(editor, '1. one\n2. two\n')).toBe(true);
+
+ expect(firstListItems(editor.state.doc).map((i) => i.text)).toEqual([
+ 'alpha',
+ 'bravo',
+ 'charlie',
+ 'one',
+ 'two',
+ ]);
+ expect(topLevelTypes(editor.state.doc).filter((t) => t === 'list')).toHaveLength(1);
+ expect(hasOrphanShapes(serialize(editor))).toBe(false);
+ });
+});
+
+describe('list paste placement — caret lands after pasted content', () => {
+ test('the caret ends inside the last pasted item at its text end', () => {
+ const editor = mountEditor(TASK_SEED);
+ setCaret(editor, itemParaRange(editor.state.doc, 3).start); // start of "delta"
+
+ pasteMarkdown(editor, '- [ ] bravo\n- [x] charlie\n');
+
+ const { $from } = editor.state.selection;
+ expect($from.parent.textContent).toBe('charlie');
+ expect($from.parentOffset).toBe($from.parent.content.size); // at the end
+ });
+});
+
+describe('list paste placement — closed-slice path preserved for non-list / non-list-caret', () => {
+ test('list content pasted outside any list keeps the closed-slice behavior', () => {
+ const editor = mountEditor('<p>plain paragraph</p>');
+ setCaret(editor, 1); // inside the paragraph, not in a list
+
+ expect(pasteMarkdown(editor, '- [ ] one\n- [ ] two\n')).toBe(true);
+
+ // A list still lands (closed slice), but there is no list-item context to
+ // splice into — the fix must not touch this path.
+ expect(firstListItems(editor.state.doc).map((i) => i.text)).toEqual(['one', 'two']);
+ expect(hasOrphanShapes(serialize(editor))).toBe(false);
+ });
+});
+
+describe('list paste placement — containers never opened (FR5 / QA-006)', () => {
+ test('a copied block component pasted at a paragraph caret preserves descriptor identity', () => {
+ const editor = mountEditor('<p>before</p>');
+ setCaret(editor, 3); // inside "before"
+
+ expect(pasteMarkdown(editor, '<Callout>\n\nnote\n\n</Callout>\n')).toBe(true);
+
+ let component: ProseMirrorNode | null = null;
+ editor.state.doc.descendants((node) => {
+ if (node.type.name === 'jsxComponent') component = node;
+ return true;
+ });
+ expect(component).not.toBeNull();
+ // Descriptor identity survives byte-exactly: the placement fix never opens
+ // a non-list container, so the Callout round-trips whole.
+ expect(serialize(editor)).toContain('<Callout>');
+ expect((component as unknown as ProseMirrorNode).attrs.componentName).toBe('Callout');
+ });
+
+ test('a copied component with the caret in a list item does not trigger the list splice', () => {
+ const editor = mountEditor(TASK_SEED);
+ setCaret(editor, itemParaRange(editor.state.doc, 3).start); // start of "delta"
+
+ // Payload is a component (not all-lists) → the splice guard's payload
+ // dimension must reject it; the closed-slice path handles it and the
+ // descriptor is preserved whole (never opened).
+ expect(pasteMarkdown(editor, '<Callout>\n\nnote\n\n</Callout>\n')).toBe(true);
+
+ let component: ProseMirrorNode | null = null;
+ editor.state.doc.descendants((node) => {
+ if (node.type.name === 'jsxComponent') component = node;
+ return true;
+ });
+ expect(component).not.toBeNull();
+ expect((component as unknown as ProseMirrorNode).attrs.componentName).toBe('Callout');
+ });
+});
+
+describe('list paste placement — payload and guard edges', () => {
+ test('a payload of two separate lists splices every item as a sibling, in payload order', () => {
+ const editor = mountEditor(TASK_SEED);
+ setCaret(editor, itemParaRange(editor.state.doc, 3).start); // start of "delta"
+
+ // A task list AND an ordered list in one payload: the splice collects the
+ // items across both lists rather than nesting either list whole.
+ expect(pasteMarkdown(editor, '- [ ] one\n\n1. two\n')).toBe(true);
+
+ const items = firstListItems(editor.state.doc);
+ expect(items.map((i) => i.text)).toEqual([
+ 'alpha',
+ 'bravo',
+ 'charlie',
+ 'one',
+ 'two',
+ 'delta',
+ 'echo',
+ ]);
+ expect(items[3]?.checked).toBe(false);
+ expect(items[4]?.checked).toBeNull();
+ expect(topLevelTypes(editor.state.doc).filter((t) => t === 'list')).toHaveLength(1);
+ expect(hasOrphanShapes(serialize(editor))).toBe(false);
+ });
+
+ test('paste at the start of a nested item splices siblings at the nested level', () => {
+ const editor = mountEditor('- [ ] parent\n - [ ] childA\n - [ ] childB');
+ // Doc-order listItems: 0=parent, 1=childA, 2=childB.
+ setCaret(editor, itemParaRange(editor.state.doc, 2).start);
+
+ expect(pasteMarkdown(editor, '- [ ] new\n')).toBe(true);
+
+ const items = firstListItems(editor.state.doc);
+ expect(items.map((i) => i.text.startsWith('parent'))).toEqual([true]);
+ expect(items[0]?.nested).toEqual(['childA', 'new', 'childB']);
+ expect(hasOrphanShapes(serialize(editor))).toBe(false);
+ });
+
+ test('a ranged selection inside a list item falls back to the closed-slice path', () => {
+ const payload = '- [ ] pasted\n';
+ const editor = mountEditor(TASK_SEED);
+ const range = itemParaRange(editor.state.doc, 3); // "delta"
+ editor.view.dispatch(
+ editor.state.tr.setSelection(TextSelection.create(editor.state.doc, range.start, range.end)),
+ );
+
+ // Control: the identical seed + selection, with the pre-existing
+ // closed-slice insertion applied directly. The dispatcher outcome must
+ // equal it — proving the splice declined the ranged selection rather than
+ // producing its own placement.
+ const control = mountEditor(TASK_SEED);
+ const controlRange = itemParaRange(control.state.doc, 3);
+ control.view.dispatch(
+ control.state.tr.setSelection(
+ TextSelection.create(control.state.doc, controlRange.start, controlRange.end),
+ ),
+ );
+ const node = control.state.schema.nodeFromJSON(mdManager.parse(payload) as JSONContent);
+ control.view.dispatch(control.state.tr.replaceSelection(node.slice(0, node.content.size)));
+
+ expect(pasteMarkdown(editor, payload)).toBe(true);
+ // Structural-JSON oracle rather than doc.eq: eq() trips over an
+ // undefined-vs-absent attr artifact between independently parsed seeds;
+ // the JSON form captures every attr the serializer consumes.
+ expect(JSON.stringify(editor.state.doc.toJSON())).toBe(
+ JSON.stringify(control.state.doc.toJSON()),
+ );
+ });
+});
diff --git a/packages/app/src/editor/clipboard/handle-paste.test.ts b/packages/app/src/editor/clipboard/handle-paste.test.ts
index 03e885ce9..10c0a2570 100644
--- a/packages/app/src/editor/clipboard/handle-paste.test.ts
+++ b/packages/app/src/editor/clipboard/handle-paste.test.ts
@@ -90,7 +90,15 @@ function fakeView(opts: { inCodeBlock?: boolean } = {}): any {
// biome-ignore lint/suspicious/noExplicitAny: fake schema for unit test
nodeFromJSON: (json: any) => ({
slice: (_f: number, _t: number) => ({ json, size: 10, content: { size: 10 } }),
- content: { size: 10 },
+ // fakeMdManager parses to a single non-list block; model the fragment
+ // shape applyJsonSlice's list-splice check reads (childCount + forEach)
+ // so it recognizes "not all lists" and takes the closed-slice path.
+ content: {
+ size: 10,
+ childCount: 1,
+ // biome-ignore lint/suspicious/noExplicitAny: fake fragment child
+ forEach: (fn: (child: any) => void) => fn({ type: { name: 'paragraph' } }),
+ },
}),
},
tr: {
diff --git a/packages/app/src/editor/clipboard/handle-paste.ts b/packages/app/src/editor/clipboard/handle-paste.ts
index 748d7202f..8bcd16527 100644
--- a/packages/app/src/editor/clipboard/handle-paste.ts
+++ b/packages/app/src/editor/clipboard/handle-paste.ts
@@ -20,6 +20,12 @@
* Branch E: text/plain only → markdown-first if isMarkdown threshold hit;
* else verbatim plain-text insert.
*
+ * Placement: the markdown branches insert the re-parsed JSON as a closed
+ * slice, EXCEPT when the caret is inside a list item and the pasted content
+ * is entirely lists — then `buildListSiblingSpliceTr` splices the pasted
+ * items as siblings at the caret's list level instead of letting the fitter
+ * nest or orphan them (issue #609).
+ *
* codeBlock short-circuit: cursor inside a codeBlock → skip all branches,
* insert text/plain verbatim.
*
@@ -60,7 +66,8 @@
import type { MarkdownManager } from '@inkeep/open-knowledge-core';
import { htmlToMdast, mdastToMarkdown } from '@inkeep/open-knowledge-core';
import type { JSONContent } from '@tiptap/core';
-import { TextSelection } from '@tiptap/pm/state';
+import { Fragment, type Node as ProseMirrorNode } from '@tiptap/pm/model';
+import { type EditorState, TextSelection, type Transaction } from '@tiptap/pm/state';
import type { EditorView } from '@tiptap/pm/view';
import { PREVENT_AUTOLINK_META } from '../gfm-autolink-plugin.ts';
import { type ClipboardSource, detectSource } from './detect-source.ts';
@@ -447,6 +454,97 @@ function tryBranchHtml(
return applyJsonSlice(view, json, source, 'D', html.length);
}
+/**
+ * A list item is "blank" when it holds only empty paragraphs — no text, no
+ * nested list, no other block. Splitting a target item at a caret sitting at
+ * its very start or end yields one such blank half; the splice drops those so
+ * no empty item is minted.
+ */
+function isBlankListItem(item: ProseMirrorNode): boolean {
+ if (item.textContent.length > 0) return false;
+ let onlyEmptyParagraphs = true;
+ item.forEach((child) => {
+ if (child.type.name !== 'paragraph' || child.content.size > 0) onlyEmptyParagraphs = false;
+ });
+ return onlyEmptyParagraphs;
+}
+
+/**
+ * List-aware placement for OK→OK paste (#609 cause 1).
+ *
+ * `applyJsonSlice` normally inserts the re-parsed markdown as a CLOSED slice.
+ * When the caret sits inside a list item and the pasted content is entirely
+ * lists, that closed slice makes ProseMirror's fitter nest the pasted list as
+ * a child of the target item (caret at item end) or mint a degenerate
+ * empty-leading-paragraph + nested-list shape (caret at item start) — the
+ * mis-placement users see as orphaned todo rows.
+ *
+ * Instead, split the target item at the caret and splice the pasted items in
+ * between as SIBLINGS at the target item's own list level:
+ * `[before-caret item if non-empty] + pasted items + [after-caret item if
+ * non-empty]`. Whole list items are moved verbatim, so a pasted item's own
+ * nested list rides along as its child and any container it holds (component,
+ * table) is never opened.
+ *
+ * Returns a built transaction, or null to fall back to the closed-slice path:
+ * a ranged (non-collapsed) selection, a caret not inside a list-item textblock,
+ * or pasted content that is not purely lists all keep current behavior.
+ */
+function buildListSiblingSpliceTr(
+ state: EditorState,
+ docNode: ProseMirrorNode,
+): Transaction | null {
+ const { selection } = state;
+ if (!selection.empty) return null;
+
+ // Payload gate first (reads only the pasted doc): every top-level node must
+ // be a list, else this is not the list-splice case.
+ const pastedItems: ProseMirrorNode[] = [];
+ let allLists = docNode.content.childCount > 0;
+ docNode.content.forEach((child) => {
+ if (child.type.name !== 'list') {
+ allLists = false;
+ return;
+ }
+ child.forEach((item) => {
+ if (item.type.name === 'listItem') pastedItems.push(item);
+ });
+ });
+ if (!allLists || pastedItems.length === 0) return null;
+
+ const { $from } = selection;
+ let itemDepth = -1;
+ for (let depth = $from.depth; depth > 0; depth--) {
+ if ($from.node(depth).type.name === 'listItem') {
+ itemDepth = depth;
+ break;
+ }
+ }
+ if (itemDepth < 0) return null;
+ // A gap cursor (also "empty") can sit between blocks where the parent is the
+ // list itself; the split math below assumes a caret inside the item's text.
+ if (!$from.parent.isTextblock) return null;
+
+ const targetItem = $from.node(itemDepth);
+ const itemStart = $from.before(itemDepth);
+ const itemEnd = $from.after(itemDepth);
+ const caretOffset = $from.pos - $from.start(itemDepth);
+ const beforeItem = targetItem.cut(0, caretOffset);
+ const afterItem = targetItem.cut(caretOffset);
+
+ const replacement: ProseMirrorNode[] = [];
+ const keepBefore = !isBlankListItem(beforeItem);
+ if (keepBefore) replacement.push(beforeItem);
+ replacement.push(...pastedItems);
+ if (!isBlankListItem(afterItem)) replacement.push(afterItem);
+
+ const tr = state.tr.replaceWith(itemStart, itemEnd, Fragment.fromArray(replacement));
+ let caretPos = itemStart + (keepBefore ? beforeItem.nodeSize : 0);
+ for (const item of pastedItems) caretPos += item.nodeSize;
+ tr.setSelection(TextSelection.near(tr.doc.resolve(Math.min(caretPos, tr.doc.content.size)), -1));
+ return tr;
+}
+
function applyJsonSlice(
view: EditorView,
json: JSONContent,
@@ -456,12 +554,18 @@ function applyJsonSlice(
): boolean {
try {
const node = view.state.schema.nodeFromJSON(json);
- view.dispatch(
- view.state.tr
- .replaceSelection(node.slice(0, node.content.size))
- .setMeta(PREVENT_AUTOLINK_META, true)
- .scrollIntoView(),
- );
+ // Scope the splice attempt so a throw in its position math degrades to the
+ // proven closed-slice path below, not to the outer catch — which would
+ // toast a degradation and hand the paste to PM's native fallthrough even
+ // though the closed slice could have delivered it.
+ let spliceTr: Transaction | null = null;
+ try {
+ spliceTr = buildListSiblingSpliceTr(view.state, node);
+ } catch {
+ spliceTr = null;
+ }
+ const tr = spliceTr ?? view.state.tr.replaceSelection(node.slice(0, node.content.size));
+ view.dispatch(tr.setMeta(PREVENT_AUTOLINK_META, true).scrollIntoView());
return true;
} catch (err) {
logConversionFail({
diff --git a/packages/app/src/editor/extensions/cell-insertion-gate.test.ts b/packages/app/src/editor/extensions/cell-insertion-gate.test.ts
new file mode 100644
index 000000000..c7b852356
--- /dev/null
+++ b/packages/app/src/editor/extensions/cell-insertion-gate.test.ts
@@ -0,0 +1,448 @@
+/**
+ * Cell-insertion gate — refuses a block jsxComponent inside a GFM table cell at
+ * the owned insertion routes (command tier, real paste dispatcher, PM-native
+ * drop, and the nested table-wrapping-a-component shape), exempts CRDT-origin
+ * transactions, and leaves edits inside an existing (un-owned-surface)
+ * component-in-cell untouched.
+ *
+ * Real ProseMirror EditorViews over jsdom globals (installDomGlobals from the
+ * shared walk-currency harness) with the real core schema (jsxComponent +
+ * table), the real MarkdownManager, and the real createHandlePaste dispatcher,
+ * so every route runs its production code path into the gate's
+ * filterTransaction. A filtered transaction is a silent no-op: the paste
+ * dispatcher still claims the event (returns true) rather than falling through
+ * to a branch that would re-insert the refused content elsewhere.
+ */
+
+import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
+import { sharedExtensions as coreExtensions, MarkdownManager } from '@inkeep/open-knowledge-core';
+import { Editor, type JSONContent } from '@tiptap/core';
+import { Fragment, type Node as ProseMirrorNode, Slice } from '@tiptap/pm/model';
+import { dropPoint, ReplaceAroundStep } from '@tiptap/pm/transform';
+import { ySyncPluginKey } from '@tiptap/y-tiptap';
+import * as actualSonner from 'sonner';
+import { createHandlePaste } from '../clipboard/handle-paste';
+import { installDomGlobals } from '../walk-currency-test-harness';
+import { CellInsertionGate } from './cell-insertion-gate';
+
+// The paste dispatcher pulls the degrade-path toast (sonner) into its import
+// graph; stub it so module load stays inert in the jsdom env. The gate's no-op
+// path never degrades, so the stub is never invoked.
+mock.module('sonner', () => ({ ...actualSonner, toast: { error: mock(() => {}) } }));
+
+const mdManager = new MarkdownManager({ extensions: coreExtensions });
+
+/** A ClipboardEvent whose clipboardData serves the given MIME map. */
+function fakeDT(data: Record<string, string>): ClipboardEvent {
+ return {
+ clipboardData: { types: Object.keys(data), getData: (k: string) => data[k] ?? '' },
+ } as unknown as ClipboardEvent;
+}
+
+/** Run the real WYSIWYG paste dispatcher against a mounted editor's view. */
+function pasteInto(editor: Editor, data: Record<string, string>): boolean {
+ return createHandlePaste({ mdManager })(editor.view, fakeDT(data));
+}
+
+/** A 2x2 GFM table: header row (a,b), one data row (c,d). */
+const TABLE_MD = '| a | b |\n| - | - |\n| c | d |\n';
+
+const CELL_NODES = new Set(['tableCell', 'tableHeader']);
+
+let restoreDomGlobals: (() => void) | null = null;
+const editors: Editor[] = [];
+
+beforeAll(() => {
+ restoreDomGlobals = installDomGlobals();
+});
+
+afterAll(() => {
+ restoreDomGlobals?.();
+ restoreDomGlobals = null;
+});
+
+afterEach(() => {
+ while (editors.length > 0) editors.pop()?.destroy();
+});
+
+function mountGateEditor(content?: string | JSONContent): Editor {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const editor = new Editor({
+ element: host,
+ content,
+ extensions: [...coreExtensions, CellInsertionGate],
+ });
+ editors.push(editor);
+ return editor;
+}
+
+/** Gate-less mount — fixture control proving a refused step is otherwise valid. */
+function mountEditor(content?: string | JSONContent): Editor {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const editor = new Editor({ element: host, content, extensions: [...coreExtensions] });
+ editors.push(editor);
+ return editor;
+}
+
+/** A fresh block-component JSON (Callout wrapping one paragraph). */
+function componentJSON(): JSONContent {
+ return {
+ type: 'jsxComponent',
+ attrs: { componentName: 'Callout', sourceRaw: '<Callout>note</Callout>' },
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'note' }] }],
+ };
+}
+
+/** Caret position inside the first data cell's paragraph text. */
+function firstDataCellCaret(editor: Editor): number {
+ let cellPos = -1;
+ editor.state.doc.descendants((node, pos) => {
+ if (cellPos === -1 && node.type.name === 'tableCell') {
+ cellPos = pos;
+ return false;
+ }
+ return true;
+ });
+ if (cellPos < 0) throw new Error('seed table has no tableCell');
+ const caret = cellPos + 2; // cell open +1 → paragraph, +2 → paragraph text
+ expect(editor.state.doc.resolve(caret).parent.type.name).toBe('paragraph');
+ return caret;
+}
+
+/** Whether any jsxComponent in `doc` has a table-cell ancestor. */
+function hasComponentInCell(doc: ProseMirrorNode): boolean {
+ let found = false;
+ doc.descendants((node, pos) => {
+ if (found) return false;
+ if (node.type.name === 'jsxComponent') {
+ const $pos = doc.resolve(pos);
+ for (let depth = $pos.depth; depth > 0; depth--) {
+ if (CELL_NODES.has($pos.node(depth).type.name)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ return !found;
+ });
+ return found;
+}
+
+function countJsxComponents(doc: ProseMirrorNode): number {
+ let count = 0;
+ doc.descendants((node) => {
+ if (node.type.name === 'jsxComponent') count += 1;
+ return true;
+ });
+ return count;
+}
+
+/** Table JSON whose first data cell already holds a component (un-owned state). */
+function tableJsonWithComponentInCell(): JSONContent {
+ const json = mdManager.parse(TABLE_MD) as JSONContent;
+ const inject = (node: JSONContent): boolean => {
+ if (node.type === 'tableCell') {
+ node.content = [componentJSON()];
+ return true;
+ }
+ if (node.content) {
+ for (const child of node.content) if (inject(child)) return true;
+ }
+ return false;
+ };
+ if (!inject(json)) throw new Error('failed to inject component into a cell');
+ return json;
+}
+
+describe('cell-insertion gate — command routes refuse component-into-cell', () => {
+ test('insertContent of a component with the caret in a cell leaves the doc unchanged', () => {
+ const editor = mountGateEditor(mdManager.parse(TABLE_MD) as JSONContent);
+ const before = editor.state.doc;
+
+ editor
+ .chain()
+ .setTextSelection(firstDataCellCaret(editor))
+ .insertContent(componentJSON())
+ .run();
+
+ expect(editor.state.doc.eq(before)).toBe(true);
+ expect(hasComponentInCell(editor.state.doc)).toBe(false);
+ });
+
+ test('insertContentAt targeting a cell position leaves the doc unchanged', () => {
+ const editor = mountGateEditor(mdManager.parse(TABLE_MD) as JSONContent);
+ const before = editor.state.doc;
+
+ editor.commands.insertContentAt(firstDataCellCaret(editor), componentJSON());
+
+ expect(editor.state.doc.eq(before)).toBe(true);
+ expect(hasComponentInCell(editor.state.doc)).toBe(false);
+ });
+
+ test('insertJsxComponent with the caret in a cell leaves the doc unchanged', () => {
+ const editor = mountGateEditor(mdManager.parse(TABLE_MD) as JSONContent);
+ const before = editor.state.doc;
+
+ editor
+ .chain()
+ .setTextSelection(firstDataCellCaret(editor))
+ .insertJsxComponent('<Callout>note</Callout>')
+ .run();
+
+ expect(editor.state.doc.eq(before)).toBe(true);
+ expect(hasComponentInCell(editor.state.doc)).toBe(false);
+ });
+});
+
+describe('cell-insertion gate — permitted transactions', () => {
+ test('the same component inserts normally at a top-level caret (control)', () => {
+ const editor = mountGateEditor('<p>hello</p>');
+
+ editor.chain().setTextSelection(1).insertContent(componentJSON()).run();
+
+ expect(countJsxComponents(editor.state.doc)).toBe(1);
+ expect(hasComponentInCell(editor.state.doc)).toBe(false);
+ });
+
+ test('ordinary text typing at a top-level caret is never filtered', () => {
+ const editor = mountGateEditor('<p>hello</p>');
+ const before = editor.state.doc;
+
+ editor.chain().setTextSelection(3).insertContent('X').run();
+
+ expect(editor.state.doc.eq(before)).toBe(false);
+ expect(editor.state.doc.textContent).toContain('X');
+ });
+
+ test('a component-into-cell transaction carrying ySync meta is applied, not filtered', () => {
+ // The exact insertContent transaction route 1 blocks, tagged as if it
+ // arrived from the y-sync plugin (remote peer / y-undo replay). The gate
+ // must let it through or this client's PM view desyncs from the Y.Doc.
+ const editor = mountGateEditor(mdManager.parse(TABLE_MD) as JSONContent);
+
+ editor
+ .chain()
+ .setTextSelection(firstDataCellCaret(editor))
+ .insertContent(componentJSON())
+ .command(({ tr }) => {
+ tr.setMeta(ySyncPluginKey, { isChangeOrigin: true });
+ return true;
+ })
+ .run();
+
+ expect(hasComponentInCell(editor.state.doc)).toBe(true);
+ });
+
+ test('typing inside an existing component-in-cell (legacy state) is not filtered', () => {
+ const editor = mountGateEditor(tableJsonWithComponentInCell());
+ expect(hasComponentInCell(editor.state.doc)).toBe(true);
+ const before = editor.state.doc;
+
+ let componentPos = -1;
+ editor.state.doc.descendants((node, pos) => {
+ if (componentPos === -1 && node.type.name === 'jsxComponent') {
+ componentPos = pos;
+ return false;
+ }
+ return true;
+ });
+ const interiorCaret = componentPos + 2; // component open +1 → paragraph, +2 → text
+
+ editor.chain().setTextSelection(interiorCaret).insertContent('Z').run();
+
+ expect(editor.state.doc.eq(before)).toBe(false);
+ expect(editor.state.doc.textContent).toContain('Z');
+ expect(hasComponentInCell(editor.state.doc)).toBe(true);
+ });
+});
+
+describe('cell-insertion gate — paste route refuses component-into-cell', () => {
+ // An OK→OK copy of one block component carries both text/plain (canonical
+ // markdown) and text/html (PM slice), so the dispatcher's markdown-first
+ // tiebreak parses it through MarkdownManager into a jsxComponent. The
+ // blank-line-wrapped form is what parses to a block (flow) element; the
+ // inline `<Callout>note</Callout>` form parses to a paragraph instead.
+ const COMPONENT_CLIPBOARD = {
+ 'text/plain': '<Callout>\n\nnote\n\n</Callout>\n',
+ 'text/html':
+ '<div data-pm-slice="0 0 paragraph"><p>&lt;Callout&gt;note&lt;/Callout&gt;</p></div>',
+ };
+
+ test('pasting a block component with the caret in a cell claims the event and leaves the doc unchanged', () => {
+ const editor = mountGateEditor(mdManager.parse(TABLE_MD) as JSONContent);
+ editor.commands.setTextSelection(firstDataCellCaret(editor));
+ // Baseline captured after the caret lands: placing a selection after a
+ // trailing table appends the schema's required trailing paragraph in its
+ // own transaction, and that normalization is not what this test measures.
+ const before = editor.state.doc;
+
+ const handled = pasteInto(editor, COMPONENT_CLIPBOARD);
+
+ // The dispatcher claims the paste (true) so no later branch re-inserts the
+ // content; the gate filtered the applyJsonSlice dispatch, so the doc — and
+ // the component count anywhere in it — is untouched.
+ expect(handled).toBe(true);
+ expect(editor.state.doc.eq(before)).toBe(true);
+ expect(countJsxComponents(editor.state.doc)).toBe(0);
+ });
+
+ test('a mixed paste (component plus surrounding markdown) at a cell caret is refused whole', () => {
+ const editor = mountGateEditor(mdManager.parse(TABLE_MD) as JSONContent);
+ editor.commands.setTextSelection(firstDataCellCaret(editor));
+ const before = editor.state.doc;
+
+ // Markdown-shaped payload (heading + list around the component) so the
+ // markdown-first tiebreak parses it into blocks rather than falling to
+ // the verbatim plain-text branch.
+ const handled = pasteInto(editor, {
+ 'text/plain': '# heading before\n\n<Callout>\n\nnote\n\n</Callout>\n\n- item after\n',
+ 'text/html': '<div data-pm-slice="0 0 paragraph"><p>mixed</p></div>',
+ });
+
+ // Refusal is whole-transaction: no partial delivery of the blocks around
+ // the component — silently delivering a subset would fabricate a state
+ // the user never authored.
+ expect(handled).toBe(true);
+ expect(editor.state.doc.eq(before)).toBe(true);
+ expect(editor.state.doc.textContent).not.toContain('heading before');
+ expect(editor.state.doc.textContent).not.toContain('item after');
+ });
+
+ test('the same component paste at a top-level caret inserts normally (control)', () => {
+ const editor = mountGateEditor('<p></p>');
+ editor.commands.setTextSelection(1);
+
+ const handled = pasteInto(editor, COMPONENT_CLIPBOARD);
+
+ expect(handled).toBe(true);
+ expect(countJsxComponents(editor.state.doc)).toBe(1);
+ expect(hasComponentInCell(editor.state.doc)).toBe(false);
+ });
+
+ test('pasting plain multi-block markdown without a component into a cell is not blocked', () => {
+ const editor = mountGateEditor(mdManager.parse(TABLE_MD) as JSONContent);
+ editor.commands.setTextSelection(firstDataCellCaret(editor));
+ const before = editor.state.doc;
+
+ const handled = pasteInto(editor, { 'text/plain': '**bold**\n\nsecond paragraph' });
+
+ // No component in the payload → the gate does not fire; content inserts as
+ // before (the shipped in-cell flatten happens later, on serialize).
+ expect(handled).toBe(true);
+ expect(editor.state.doc.eq(before)).toBe(false);
+ expect(editor.state.doc.textContent).toContain('bold');
+ expect(editor.state.doc.textContent).toContain('second paragraph');
+ expect(countJsxComponents(editor.state.doc)).toBe(0);
+ });
+});
+
+describe('cell-insertion gate — drop and nested-table routes', () => {
+ test('an internal drag-move of a top-level component onto a cell is refused; the component stays at origin', () => {
+ const tableDoc = mdManager.parse(TABLE_MD) as JSONContent;
+ const seed: JSONContent = {
+ type: 'doc',
+ content: [...(tableDoc.content ?? []), componentJSON()],
+ };
+ const editor = mountGateEditor(seed);
+ const before = editor.state.doc;
+ expect(countJsxComponents(before)).toBe(1);
+ expect(hasComponentInCell(before)).toBe(false);
+
+ // Locate the trailing top-level component (doc children are siblings).
+ const comps: Array<{ node: ProseMirrorNode; from: number }> = [];
+ before.forEach((node, offset) => {
+ if (node.type.name === 'jsxComponent') comps.push({ node, from: offset });
+ });
+ const moved = comps[0];
+ if (!moved) throw new Error('seed lost its top-level component');
+ const cellCaret = firstDataCellCaret(editor);
+
+ // Model PM's internal move as one transaction: delete the source, then
+ // dropPoint + replaceRange the component into the cell — the primitive the
+ // drop dispatcher's Branch-C `return false` hands off to PM.
+ const slice = new Slice(Fragment.from(moved.node), 0, 0);
+ const tr = editor.state.tr.delete(moved.from, moved.from + moved.node.nodeSize);
+ const dropPos = dropPoint(tr.doc, tr.mapping.map(cellCaret), slice);
+ if (dropPos == null) throw new Error('dropPoint found no position for the component');
+ // Guard the fixture: the resolved drop must sit inside a cell, else a
+ // non-cell landing would make the "refused" assertion vacuous.
+ const $drop = tr.doc.resolve(dropPos);
+ let dropInCell = false;
+ for (let depth = $drop.depth; depth > 0; depth--) {
+ if (CELL_NODES.has($drop.node(depth).type.name)) dropInCell = true;
+ }
+ expect(dropInCell).toBe(true);
+ tr.replaceRange(dropPos, dropPos, slice);
+ editor.view.dispatch(tr);
+
+ // The whole move is refused: nothing landed in a cell and the component is
+ // still exactly where it started.
+ expect(editor.state.doc.eq(before)).toBe(true);
+ expect(hasComponentInCell(editor.state.doc)).toBe(false);
+ expect(countJsxComponents(editor.state.doc)).toBe(1);
+ });
+
+ test('inserting a table whose cell already holds a component is refused (nested shape)', () => {
+ const editor = mountGateEditor('<p>hi</p>');
+ const before = editor.state.doc;
+
+ editor.chain().setTextSelection(1).insertContent(tableJsonWithComponentInCell()).run();
+
+ expect(editor.state.doc.eq(before)).toBe(true);
+ expect(hasComponentInCell(editor.state.doc)).toBe(false);
+ expect(countJsxComponents(editor.state.doc)).toBe(0);
+ });
+
+ test('wrapping an existing component into a fresh table cell is refused (ReplaceAroundStep)', () => {
+ // No user affordance performs this wrap today (the only table-creation
+ // command inserts a new empty table), but the gate is route-agnostic: a
+ // future command or extension issuing the wrap step must hit the same
+ // refusal. Built as a raw ReplaceAroundStep so the step class itself is
+ // exercised, not just ReplaceStep insertions.
+ const seed: JSONContent = { type: 'doc', content: [componentJSON()] };
+ const buildWrapStep = (doc: ProseMirrorNode) => {
+ const schema = doc.type.schema;
+ let compPos = -1;
+ let compNode: ProseMirrorNode | null = null;
+ doc.forEach((node, offset) => {
+ if (compNode === null && node.type.name === 'jsxComponent') {
+ compPos = offset;
+ compNode = node;
+ }
+ });
+ if (compNode === null) throw new Error('seed lost its component');
+ const cell = schema.nodes.tableCell.create();
+ const row = schema.nodes.tableRow.create(null, cell);
+ const table = schema.nodes.table.create(null, row);
+ const from = compPos;
+ const to = compPos + (compNode as ProseMirrorNode).nodeSize;
+ return new ReplaceAroundStep(
+ from,
+ to,
+ from,
+ to,
+ new Slice(Fragment.from(table), 0, 0),
+ 3,
+ true,
+ );
+ };
+
+ // Fixture guard: without the gate, the identical step applies cleanly and
+ // produces the component-in-cell state — so the refusal below is the
+ // gate's doing, not step invalidity.
+ const control = mountEditor(seed);
+ const controlTr = control.state.tr.step(buildWrapStep(control.state.doc));
+ control.view.dispatch(controlTr);
+ expect(hasComponentInCell(control.state.doc)).toBe(true);
+
+ const editor = mountGateEditor(seed);
+ const before = editor.state.doc;
+ const tr = editor.state.tr.step(buildWrapStep(editor.state.doc));
+ editor.view.dispatch(tr);
+
+ expect(editor.state.doc.eq(before)).toBe(true);
+ expect(hasComponentInCell(editor.state.doc)).toBe(false);
+ });
+});
diff --git a/packages/app/src/editor/extensions/cell-insertion-gate.ts b/packages/app/src/editor/extensions/cell-insertion-gate.ts
new file mode 100644
index 000000000..d09923b16
--- /dev/null
+++ b/packages/app/src/editor/extensions/cell-insertion-gate.ts
@@ -0,0 +1,99 @@
+/**
+ * Cell-insertion gate — refuses placing a block jsxComponent inside a GFM table
+ * cell.
+ *
+ * A cell's PM schema is `block+` and a jsxComponent is `group: block`, so a
+ * component is schema-valid inside a cell and reachable by ordinary single-user
+ * input (slash command, paste, drop, insertContent). But a GFM cell serializes
+ * to one phrasing-only line, so the PM->markdown serializer flattens a cell's
+ * block content and a component (whose name/props/source live outside the
+ * projectable phrasing) is dropped whole — author-invisible content loss. This
+ * gate makes that state unproducible at the owned insertion routes: a refused
+ * insertion is a silent no-op (a filtered transaction never happened).
+ *
+ * The gate is a single `filterTransaction` at the transaction boundary rather
+ * than per-route guards: every owned route (command tier, paste dispatcher,
+ * PM-native drop) converges here, so one count-delta invariant covers all of
+ * them and future routes without per-call-site wrapping.
+ *
+ * App-side only. Server write surfaces route through parse and cannot spell a
+ * block-component-in-cell, so the gate is a client producer-input concern, not
+ * a schema/serialize one — it never joins core `sharedExtensions`.
+ */
+
+import { Extension } from '@tiptap/core';
+import type { Node as ProseMirrorNode, Slice } from '@tiptap/pm/model';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { ReplaceAroundStep, ReplaceStep } from '@tiptap/pm/transform';
+import { ySyncPluginKey } from '@tiptap/y-tiptap';
+import { CELL_NODES } from '../table-cell-context';
+
+const COMPONENT_NODE = 'jsxComponent';
+
+// A step can raise the in-cell component count two ways: it inserts the
+// component directly into a cell, or it inserts a table wrapper that newly
+// encloses content already holding a component (wrap-in-table around a
+// selection). A step whose inserted slice carries none of these nodes cannot
+// change the count, so it skips the doc walk.
+const CANDIDATE_NODES = new Set([COMPONENT_NODE, 'table', 'tableRow', 'tableCell', 'tableHeader']);
+
+/** Count of jsxComponent nodes anywhere beneath a table cell in `doc`. */
+function countComponentsInCells(doc: ProseMirrorNode): number {
+ let count = 0;
+ const walk = (node: ProseMirrorNode, inCell: boolean): void => {
+ node.forEach((child) => {
+ const childInCell = inCell || CELL_NODES.has(child.type.name);
+ if (childInCell && child.type.name === COMPONENT_NODE) count += 1;
+ walk(child, childInCell);
+ });
+ };
+ walk(doc, false);
+ return count;
+}
+
+/** Whether a step's inserted slice contains a component or table wrapper. */
+function sliceHasCandidate(slice: Slice): boolean {
+ let found = false;
+ slice.content.descendants((node) => {
+ if (found) return false;
+ if (CANDIDATE_NODES.has(node.type.name)) {
+ found = true;
+ return false;
+ }
+ return true;
+ });
+ return found;
+}
+
+const cellInsertionGateKey = new PluginKey('cellInsertionGate');
+
+export const CellInsertionGate = Extension.create({
+ name: 'cellInsertionGate',
+
+ addProseMirrorPlugins() {
+ return [
+ new Plugin({
+ key: cellInsertionGateKey,
+ filterTransaction(tr, state) {
+ // CRDT-origin transactions (remote peers, agent writes, disk load,
+ // and y-undo replays) re-enter tagged with ySync meta. Rejecting one
+ // would desync this client's PM view from the shared Y.Doc, so the
+ // gate is producer-side only. Same origin discipline the typed
+ // autolink plugin uses.
+ if (tr.getMeta(ySyncPluginKey)) return true;
+ if (!tr.docChanged) return true;
+ // Pre-check keeps ordinary typing (and editing inside an existing
+ // component-in-cell) off the doc walk: only a step inserting a
+ // component or a table wrapper can raise the in-cell count.
+ const candidate = tr.steps.some(
+ (step) =>
+ (step instanceof ReplaceStep || step instanceof ReplaceAroundStep) &&
+ sliceHasCandidate(step.slice),
+ );
+ if (!candidate) return true;
+ return countComponentsInCells(tr.doc) <= countComponentsInCells(state.doc);
+ },
+ }),
+ ];
+ },
+});
diff --git a/packages/app/src/editor/extensions/shared.ts b/packages/app/src/editor/extensions/shared.ts
index b13cbb0f1..c7e880c5c 100644
--- a/packages/app/src/editor/extensions/shared.ts
+++ b/packages/app/src/editor/extensions/shared.ts
@@ -14,6 +14,7 @@ import { InlineLinkInputRule } from '../inline-link-input-rule';
import { getComponentItems, getInlineComponentItems } from '../slash-command/component-items';
import { getEmbedStarterItems } from '../slash-command/embed-starter-items';
import { getSlashCommandItems } from '../slash-command/items';
+
import { BlockMover } from './block-mover';
// BridgeIdPlugin — SelectionStatePlugin consumes it to resolve stable
// ancestor-chain IDs across PM re-renders (see Precedent "Selection state
@@ -22,6 +23,7 @@ import { BlockMover } from './block-mover';
// Y.XmlElement-keyed IDs. bridge-id-plugin lives on as a standalone
// stable-identity primitive.
import { BridgeIdPlugin } from './bridge-id-plugin';
+import { CellInsertionGate } from './cell-insertion-gate';
import { chunkWrapperDecorationPlugin } from './chunk-wrapper-decoration';
import { CodeBlockFidelity } from './code-block';
import { BlockDragHandle } from './drag-handle';
@@ -43,6 +45,26 @@ import { Tag } from './tag-view';
import { WikiLink } from './wiki-link';
import { WikiLinkEmbed } from './wiki-link-embed';
+/**
+ * The slash menu's wired item sources — the single production list. Coverage
+ * tests import this instead of re-declaring it so a source added here is
+ * automatically inside the "no block component offered in a cell" net.
+ */
+export const SLASH_ITEM_SOURCES = [
+ getSlashCommandItems,
+ getComponentItems,
+ // Themed `html preview` embed starters (chart, stat cards, custom SVG,
+ // interactive control) — the human on-ramp for the embed palette.
+ getEmbedStarterItems,
+ // Inline-atom slash entries (Tag — placeholder pill with inline
+ // input; future inline atoms like mathInline can extend this
+ // list). Kept separate from `getComponentItems` because inline
+ // atoms aren't in the descriptor registry — they map to direct
+ // PM nodes via the `mdxJsxTextElement` short-circuit in
+ // `markdown/index.ts`.
+ getInlineComponentItems,
+] as const;
+
// Replace core extensions that have app-side NodeViews or mark views.
export const sharedExtensions = [
...coreExtensions.map((ext) => {
@@ -68,21 +90,12 @@ export const sharedExtensions = [
if (ext.name === 'codeBlock') return CodeBlockFidelity;
return ext;
}),
+ // Refuse a block jsxComponent inside a table cell at the owned insertion
+ // routes — a component there serializes to zero bytes (GFM cells are
+ // phrasing-only). Client producer-input gate; never in core sharedExtensions.
+ CellInsertionGate,
SlashCommand.configure({
- itemsSources: [
- getSlashCommandItems,
- getComponentItems,
- // Themed `html preview` embed starters (chart, stat cards, custom SVG,
- // interactive control) — the human on-ramp for the embed palette.
- getEmbedStarterItems,
- // Inline-atom slash entries (Tag — placeholder pill with inline
- // input; future inline atoms like mathInline can extend this
- // list). Kept separate from `getComponentItems` because inline
- // atoms aren't in the descriptor registry — they map to direct
- // PM nodes via the `mdxJsxTextElement` short-circuit in
- // `markdown/index.ts`.
- getInlineComponentItems,
- ],
+ itemsSources: [...SLASH_ITEM_SOURCES],
categoryLabels: {
content: 'Components',
layout: 'Layout',
diff --git a/packages/app/src/editor/extensions/slash-command.ts b/packages/app/src/editor/extensions/slash-command.ts
index 4d47ef671..0b17cb5d1 100644
--- a/packages/app/src/editor/extensions/slash-command.ts
+++ b/packages/app/src/editor/extensions/slash-command.ts
@@ -1,9 +1,10 @@
import { Extension } from '@tiptap/core';
-import { PluginKey } from '@tiptap/pm/state';
+import { type EditorState, PluginKey } from '@tiptap/pm/state';
import { ReactRenderer } from '@tiptap/react';
import Suggestion, { type SuggestionKeyDownProps, type SuggestionProps } from '@tiptap/suggestion';
import { filterItems, getSlashCommandItems, type SlashCommandItem } from '../slash-command/items';
import { SlashCommandMenu } from '../slash-command/SlashCommandMenu';
+import { isSelectionInTableCell } from '../table-cell-context';
import { getEditorSourceMode } from './editor-mode-context';
import {
createSuggestionPopup,
@@ -55,6 +56,65 @@ export interface SlashCommandOptions {
categoryLabels: Record<string, string>;
}
+/**
+ * Resolve the item list the slash menu renders: merge every configured source,
+ * warn on duplicate names in dev, category-sort so the flat order matches the
+ * grouped render, drop block-component items when the caret is in a table cell
+ * (they would no-op there — the cell-insertion gate refuses a block component
+ * in a phrasing-only cell), then apply the search query. Exported so tests
+ * exercise the exact transform the extension runs rather than a re-derivation.
+ */
+export function buildSlashMenuItems(options: {
+ sources: (() => SlashCommandItem[])[];
+ categoryOrder: string[];
+ query: string;
+ state: EditorState;
+}): SlashCommandItem[] {
+ const { sources, categoryOrder, query, state } = options;
+ const allItems = sources.flatMap((source) => {
+ try {
+ return source();
+ } catch (err) {
+ console.error('[slash-command] item source threw an error', err);
+ return [];
+ }
+ });
+ if (process.env.NODE_ENV !== 'production') {
+ const seen = new Set<string>();
+ for (const item of allItems) {
+ if (seen.has(item.name)) {
+ console.warn(
+ `[slash-command] duplicate item name "${item.name}" — both will appear in the menu; ensure names are unique across sources`,
+ );
+ }
+ seen.add(item.name);
+ }
+ }
+ // Sort items so source order matches the visual (category-grouped) order the
+ // menu renders. `SlashCommandMenu` groups items into category buckets in
+ // first-appearance order and builds `indexMap` from the flat source array —
+ // if those orders diverge, `selectedIndex` (which advances through the source
+ // array) points to a button whose DOM position differs, so `data-selected`
+ // lands on the wrong visual item. Category order comes from `categoryOrder`
+ // (the `categoryLabels` keys); unknown categories sort last. Stable sort
+ // preserves within-category source order.
+ const indexOfCategory = (cat: string): number => {
+ const i = categoryOrder.indexOf(cat);
+ return i === -1 ? Number.POSITIVE_INFINITY : i;
+ };
+ const sorted = allItems
+ .map((item, i) => ({ item, i }))
+ .sort((a, b) => {
+ const diff = indexOfCategory(a.item.category) - indexOfCategory(b.item.category);
+ return diff !== 0 ? diff : a.i - b.i;
+ })
+ .map((x) => x.item);
+ const offerable = isSelectionInTableCell(state)
+ ? sorted.filter((item) => !item.insertsBlockComponent)
+ : sorted;
+ return filterItems(offerable, query);
+}
+
export const SlashCommand = Extension.create<SlashCommandOptions>({
name: 'slashCommand',
@@ -91,49 +151,13 @@ export const SlashCommand = Extension.create<SlashCommandOptions>({
// non-whitespace character after the trigger. Setting allowedPrefixes to
// null would allow mid-word triggers like "hello/world" (regression).
- items: ({ query }) => {
- const allItems = extension.options.itemsSources.flatMap((source) => {
- try {
- return source();
- } catch (err) {
- console.error('[slash-command] item source threw an error', err);
- return [];
- }
- });
- if (process.env.NODE_ENV !== 'production') {
- const seen = new Set<string>();
- for (const item of allItems) {
- if (seen.has(item.name)) {
- console.warn(
- `[slash-command] duplicate item name "${item.name}" — both will appear in the menu; ensure names are unique across sources`,
- );
- }
- seen.add(item.name);
- }
- }
- // Sort items so source order matches the visual (category-grouped)
- // order the menu renders. `SlashCommandMenu` groups items into
- // category buckets in first-appearance order and builds `indexMap`
- // from the flat source array — if those orders diverge, `selectedIndex`
- // (which advances through the source array) points to a button whose
- // DOM position differs from `selectedIndex`, so `data-selected=true`
- // lands on the wrong visual item. Category order is taken from
- // `categoryLabels` keys (declaration order); unknown categories
- // sort last. Stable sort preserves within-category source order.
- const categoryOrder = Object.keys(extension.options.categoryLabels);
- const indexOfCategory = (cat: string): number => {
- const i = categoryOrder.indexOf(cat);
- return i === -1 ? Number.POSITIVE_INFINITY : i;
- };
- const sorted = allItems
- .map((item, i) => ({ item, i }))
- .sort((a, b) => {
- const diff = indexOfCategory(a.item.category) - indexOfCategory(b.item.category);
- return diff !== 0 ? diff : a.i - b.i;
- })
- .map((x) => x.item);
- return filterItems(sorted, query);
- },
+ items: ({ query, editor }) =>
+ buildSlashMenuItems({
+ sources: extension.options.itemsSources,
+ categoryOrder: Object.keys(extension.options.categoryLabels),
+ query,
+ state: editor.state,
+ }),
command: ({ editor, range, props: item }) => {
try {
diff --git a/packages/app/src/editor/slash-command/cell-context-filter.test.ts b/packages/app/src/editor/slash-command/cell-context-filter.test.ts
new file mode 100644
index 000000000..0e5b4f0a2
--- /dev/null
+++ b/packages/app/src/editor/slash-command/cell-context-filter.test.ts
@@ -0,0 +1,236 @@
+/**
+ * Slash-menu cell-context filtering — inside a GFM table cell the menu must
+ * withhold block-component items (they would no-op there, the cell-insertion
+ * gate refuses them) while keeping every non-component item, and offer the
+ * full set everywhere else.
+ *
+ * Real ProseMirror EditorViews over jsdom globals with the real core schema
+ * (table + jsxComponent), the real item sources wired in `extensions/shared.ts`,
+ * and the exact `buildSlashMenuItems` transform the slash extension runs — so
+ * the predicate, the item flags, and the merge/filter path are all exercised on
+ * production code, not re-implementations.
+ */
+
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { sharedExtensions as coreExtensions, MarkdownManager } from '@inkeep/open-knowledge-core';
+import { Editor, type JSONContent } from '@tiptap/core';
+import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import { CellInsertionGate } from '../extensions/cell-insertion-gate';
+import { SLASH_ITEM_SOURCES } from '../extensions/shared';
+import { buildSlashMenuItems } from '../extensions/slash-command';
+import { isSelectionInTableCell } from '../table-cell-context';
+import { installDomGlobals } from '../walk-currency-test-harness';
+import { getComponentItems, getInlineComponentItems } from './component-items';
+import { getEmbedStarterItems } from './embed-starter-items';
+import { getSlashCommandItems, type SlashCommandItem } from './items';
+
+const mdManager = new MarkdownManager({ extensions: coreExtensions });
+
+/** A 2x2 GFM table: header row (a,b) → tableHeader; data row (c,d) → tableCell. */
+const TABLE_MD = '| a | b |\n| - | - |\n| c | d |\n';
+
+// The production source list itself (not a mirror) — a source added to the
+// wiring is automatically covered here. Category order mirrors the
+// `categoryLabels` keys in `extensions/shared.ts`.
+const SOURCES: (() => SlashCommandItem[])[] = [...SLASH_ITEM_SOURCES];
+const CATEGORY_ORDER = ['content', 'layout', 'media', 'data', 'embed'];
+
+let restoreDomGlobals: (() => void) | null = null;
+const editors: Editor[] = [];
+
+beforeAll(() => {
+ restoreDomGlobals = installDomGlobals();
+});
+
+afterAll(() => {
+ restoreDomGlobals?.();
+ restoreDomGlobals = null;
+});
+
+afterEach(() => {
+ while (editors.length > 0) editors.pop()?.destroy();
+});
+
+function mount(content: string | JSONContent, withGate = false): Editor {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const editor = new Editor({
+ element: host,
+ content,
+ extensions: withGate ? [...coreExtensions, CellInsertionGate] : [...coreExtensions],
+ });
+ editors.push(editor);
+ return editor;
+}
+
+/** Caret inside the first node of the named type (its inner paragraph text). */
+function firstCellCaret(editor: Editor, cellType: 'tableCell' | 'tableHeader'): number {
+ let cellPos = -1;
+ editor.state.doc.descendants((node, pos) => {
+ if (cellPos === -1 && node.type.name === cellType) {
+ cellPos = pos;
+ return false;
+ }
+ return true;
+ });
+ if (cellPos < 0) throw new Error(`seed table has no ${cellType}`);
+ const caret = cellPos + 2; // cell open +1 → paragraph, +2 → paragraph text
+ expect(editor.state.doc.resolve(caret).parent.type.name).toBe('paragraph');
+ return caret;
+}
+
+function names(items: SlashCommandItem[]): string[] {
+ return items.map((i) => i.name);
+}
+
+function countJsxComponents(doc: ProseMirrorNode): number {
+ let count = 0;
+ doc.descendants((node) => {
+ if (node.type.name === 'jsxComponent') count += 1;
+ return true;
+ });
+ return count;
+}
+
+describe('isSelectionInTableCell', () => {
+ test('a caret inside a data cell is in cell context', () => {
+ const editor = mount(mdManager.parse(TABLE_MD) as JSONContent);
+ editor.commands.setTextSelection(firstCellCaret(editor, 'tableCell'));
+ expect(isSelectionInTableCell(editor.state)).toBe(true);
+ });
+
+ test('a caret inside a header cell is in cell context', () => {
+ // Header cells flatten on serialize exactly like data cells, so they must
+ // count as cell context too.
+ const editor = mount(mdManager.parse(TABLE_MD) as JSONContent);
+ editor.commands.setTextSelection(firstCellCaret(editor, 'tableHeader'));
+ expect(isSelectionInTableCell(editor.state)).toBe(true);
+ });
+
+ test('a caret in a top-level paragraph is not in cell context', () => {
+ const editor = mount('<p>hello</p>');
+ editor.commands.setTextSelection(1);
+ expect(isSelectionInTableCell(editor.state)).toBe(false);
+ });
+});
+
+describe('insertsBlockComponent flag on the real item sources', () => {
+ test('every block-component item (descriptors + File) is flagged', () => {
+ const items = getComponentItems();
+ expect(items.length).toBeGreaterThan(0);
+ for (const item of items) {
+ expect(item.insertsBlockComponent).toBe(true);
+ }
+ });
+
+ test('formatting, embed, and inline-atom items are not flagged', () => {
+ // Inline atoms (link, Tag) and codeBlock-based embeds are representable in a
+ // cell, so they must stay offered — only block components are withheld.
+ const unflagged = [
+ ...getSlashCommandItems(),
+ ...getEmbedStarterItems(),
+ ...getInlineComponentItems(),
+ ];
+ expect(unflagged.length).toBeGreaterThan(0);
+ for (const item of unflagged) {
+ expect(item.insertsBlockComponent).toBeFalsy();
+ }
+ });
+});
+
+describe('buildSlashMenuItems — cell-context filtering over the wired sources', () => {
+ function offeredAt(editor: Editor, query = ''): SlashCommandItem[] {
+ return buildSlashMenuItems({
+ sources: SOURCES,
+ categoryOrder: CATEGORY_ORDER,
+ query,
+ state: editor.state,
+ });
+ }
+
+ test('inside a cell, no block-component item is offered but non-component items remain', () => {
+ const editor = mount(mdManager.parse(TABLE_MD) as JSONContent);
+ editor.commands.setTextSelection(firstCellCaret(editor, 'tableCell'));
+
+ const offered = offeredAt(editor);
+ expect(offered.some((i) => i.insertsBlockComponent)).toBe(false);
+ expect(names(offered)).not.toContain('component-Callout');
+ expect(names(offered)).not.toContain('component-File');
+ // Formatting, table, inline atoms, and embeds all survive.
+ expect(names(offered)).toContain('heading1');
+ expect(names(offered)).toContain('table');
+ expect(names(offered)).toContain('link');
+ expect(names(offered)).toContain('component-Tag');
+ expect(names(offered)).toContain('embed-starter-html');
+ });
+
+ test('inside a header cell, block components are withheld too', () => {
+ const editor = mount(mdManager.parse(TABLE_MD) as JSONContent);
+ editor.commands.setTextSelection(firstCellCaret(editor, 'tableHeader'));
+
+ const offered = offeredAt(editor);
+ expect(offered.some((i) => i.insertsBlockComponent)).toBe(false);
+ expect(names(offered)).toContain('heading1');
+ });
+
+ test('outside a cell, block-component items are offered', () => {
+ const editor = mount('<p>hello</p>');
+ editor.commands.setTextSelection(1);
+
+ const offered = offeredAt(editor);
+ expect(names(offered)).toContain('component-Callout');
+ expect(names(offered)).toContain('component-File');
+ // Guard against a false green where nothing is ever flagged/offered.
+ expect(offered.some((i) => i.insertsBlockComponent)).toBe(true);
+ });
+
+ test('the search query narrows within cell context, Callout stays filtered', () => {
+ const editor = mount(mdManager.parse(TABLE_MD) as JSONContent);
+ editor.commands.setTextSelection(firstCellCaret(editor, 'tableCell'));
+
+ expect(names(offeredAt(editor, 'callout'))).not.toContain('component-Callout');
+ expect(names(offeredAt(editor, 'heading'))).toContain('heading1');
+ });
+
+ test('the same query at a top-level caret surfaces Callout (control)', () => {
+ const editor = mount('<p>hello</p>');
+ editor.commands.setTextSelection(1);
+ expect(names(offeredAt(editor, 'callout'))).toContain('component-Callout');
+ });
+});
+
+describe('component item command with a cell caret no-ops via the gate', () => {
+ function calloutItem(): SlashCommandItem {
+ const item = getComponentItems().find((i) => i.name === 'component-Callout');
+ if (!item) throw new Error('Callout slash item missing');
+ return item;
+ }
+
+ test('running the Callout command inside a cell leaves the doc unchanged', () => {
+ const editor = mount(mdManager.parse(TABLE_MD) as JSONContent, true);
+ editor.commands.setTextSelection(firstCellCaret(editor, 'tableCell'));
+ const before = editor.state.doc;
+
+ calloutItem().command(editor);
+
+ expect(editor.state.doc.eq(before)).toBe(true);
+ expect(countJsxComponents(editor.state.doc)).toBe(0);
+ });
+
+ test('the same command at a top-level caret inserts a component (control)', () => {
+ const editor = mount('<p></p>', true);
+ editor.commands.setTextSelection(1);
+
+ // Auto-open (focusInsertedComponent → rAF → setNodeSelection) is out of
+ // scope here; stub rAF so the deferred selection can't fire against the
+ // editor after afterEach tears it down.
+ const originalRaf = globalThis.requestAnimationFrame;
+ globalThis.requestAnimationFrame = (() => 0) as typeof globalThis.requestAnimationFrame;
+ try {
+ calloutItem().command(editor);
+ expect(countJsxComponents(editor.state.doc)).toBe(1);
+ } finally {
+ globalThis.requestAnimationFrame = originalRaf;
+ }
+ });
+});
diff --git a/packages/app/src/editor/slash-command/component-items.tsx b/packages/app/src/editor/slash-command/component-items.tsx
index e7dbb97d9..16881ce6b 100644
--- a/packages/app/src/editor/slash-command/component-items.tsx
+++ b/packages/app/src/editor/slash-command/component-items.tsx
@@ -563,6 +563,8 @@ function getCustomBlockComponentItems(): SlashCommandItem[] {
category: 'media',
aliases: ['file', 'attachment', 'download', 'upload', 'document', 'doc', 'docx', 'zip'],
description: 'Attach a downloadable file (`.pdf` / `.docx` / `.zip` / …)',
+ // Inserts a WikiEmbedFile jsxComponent block — refused in a table cell.
+ insertsBlockComponent: true,
command: openFilePickerAndUpload,
preview: {
description: t`Notion-style inline row for a downloadable file. Drag-drop also works.`,
@@ -611,6 +613,9 @@ export function getComponentItems(): SlashCommandItem[] {
command: createInsertCommand(desc),
aliases: desc.searchTerms,
description: desc.description,
+ // Every registered descriptor here is a block jsxComponent — refused in a
+ // table cell, so the slash menu withholds it there.
+ insertsBlockComponent: true,
preview,
};
});
diff --git a/packages/app/src/editor/slash-command/items.tsx b/packages/app/src/editor/slash-command/items.tsx
index 76e0f98b5..614c5930a 100644
--- a/packages/app/src/editor/slash-command/items.tsx
+++ b/packages/app/src/editor/slash-command/items.tsx
@@ -63,6 +63,14 @@ export interface SlashCommandItem {
*/
description?: string;
+ /**
+ * True when selecting this item inserts a block `jsxComponent`. A GFM table
+ * cell is phrasing-only, so the cell-insertion gate refuses that placement;
+ * the menu withholds these items when the caret is in a cell rather than
+ * offer an affordance that would silently no-op.
+ */
+ insertsBlockComponent?: boolean;
+
/**
* Optional hover preview shown alongside the menu when this item is selected
* (via mouse hover or keyboard navigation). Items without a preview cause the
diff --git a/packages/app/src/editor/table-cell-context.ts b/packages/app/src/editor/table-cell-context.ts
new file mode 100644
index 000000000..7789c656c
--- /dev/null
+++ b/packages/app/src/editor/table-cell-context.ts
@@ -0,0 +1,30 @@
+/**
+ * Table-cell context — the shared cell-node set and selection predicate for
+ * the surfaces that must treat a GFM table cell specially.
+ *
+ * A GFM cell serializes to a single phrasing-only line, so a block component
+ * placed in one is dropped whole on serialize. The cell-insertion gate refuses
+ * that placement and the slash menu withholds the affordance; both key off the
+ * same cell definition here so they can never diverge (a header cell flattens
+ * exactly like a data cell — guarding only `tableCell` would leave a silent gap
+ * for `tableHeader`).
+ */
+
+import type { EditorState } from '@tiptap/pm/state';
+
+// Both cell kinds serialize to one phrasing-only line, so a block component in
+// either is lost on serialize. Treat both as cell context.
+export const CELL_NODES: ReadonlySet<string> = new Set(['tableCell', 'tableHeader']);
+
+/**
+ * Whether the current selection sits inside a GFM table cell (data or header).
+ * Walks the resolved caret's ancestors, so it holds for a collapsed caret or a
+ * range fully inside a cell.
+ */
+export function isSelectionInTableCell(state: EditorState): boolean {
+ const { $from } = state.selection;
+ for (let depth = $from.depth; depth > 0; depth--) {
+ if (CELL_NODES.has($from.node(depth).type.name)) return true;
+ }
+ return false;
+}
diff --git a/packages/app/tests/integration/jsx-unregistered-cell-flatten-loss.test.ts b/packages/app/tests/integration/jsx-unregistered-cell-flatten-loss.test.ts
index 70aed9bb8..5823076dd 100644
--- a/packages/app/tests/integration/jsx-unregistered-cell-flatten-loss.test.ts
+++ b/packages/app/tests/integration/jsx-unregistered-cell-flatten-loss.test.ts
@@ -1,96 +1,110 @@
/**
- * Unregistered component in a table cell — the confirmed-lossy serialize path.
+ * A block jsxComponent inside a table cell — the confirmed-lossy serialize path,
+ * plus the insert-time gate that now keeps this client's owned routes from
+ * producing it.
*
- * A table cell's PM schema is `block+` and a jsxComponent is `group: block`, so
- * an unregistered component is schema-valid inside a cell and reaches one through
- * the ordinary WYSIWYG paste route with no insert-time guard. But a GFM cell is
- * phrasing-only on one physical line, so the PM→markdown serializer flattens a
- * cell's block content (`flattenCellBlocks`, packages/core/src/markdown/
- * table-cell-flatten.ts). A jsxComponent's mdast form is an `mdxJsxFlowElement`
- * whose name, props, and source spelling live outside the `children`/`value`
- * the flattener can project, so a component in a cell is dropped whole and only
- * a `table-cell-flatten-dropped-block` diagnostic marks the loss.
+ * A cell's PM schema is `block+` and a jsxComponent is `group: block`, so a
+ * component is schema-valid inside a cell. But a GFM cell is phrasing-only on one
+ * physical line, so the PM->markdown serializer flattens a cell's block content
+ * (`flattenCellBlocks`, packages/core/src/markdown/table-cell-flatten.ts). A
+ * jsxComponent's mdast form is an `mdxJsxFlowElement` whose name, props, and
+ * source spelling live outside the `children`/`value` the flattener can project,
+ * so a component in a cell is dropped whole and only a
+ * `table-cell-flatten-dropped-block` diagnostic marks the loss.
*
- * These tests PIN that current lossy behavior end to end — real paste dispatcher
- * places the component, real serializer drops it. This is a characterization of
- * reality, not a target. The loss is component-general (a registered component
- * flattens the same way); the unregistered slice is pinned here. Preserving a
- * component's source spelling in a cell instead of dropping it is a
- * serialize-time product decision; if that fix lands these expectations flip and
- * must be updated.
+ * The first block PINS that serialize-side drop end to end on a component-in-cell
+ * doc built directly. Direct construction is deliberate: the owned insertion
+ * routes (paste, slash, drop, insertContent) now refuse this state at the
+ * transaction boundary, so paste can no longer reach it. The state stays
+ * reachable from an un-owned surface — a remote peer whose raw CRDT update spells
+ * a component in a cell — which the gate deliberately exempts (rejecting a
+ * CRDT-origin transaction would desync this client's view from the shared doc).
+ * That peer's state still flows through this serializer, so the drop
+ * characterization still matters. It is a characterization of reality, not a
+ * target; preserving a component's source spelling in a cell instead of dropping
+ * it is a serialize-time product decision, and if that fix lands these
+ * expectations flip.
*
- * No DOM: the dispatcher only touches `view.state`/`view.dispatch`, so a plain
- * object over a real EditorState reaches the production paste path.
+ * The second block pins the reachability change itself: pasting a component at a
+ * cell caret through the real gated editor leaves the doc unchanged.
+ *
+ * The serialize pins need no editor — they build the doc and call the serializer
+ * directly. The gate assertion mounts a real TipTap editor over jsdom globals so
+ * the paste runs the production dispatcher into the gate's filterTransaction.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { sharedExtensions } from '@inkeep/open-knowledge-core';
+import { Editor, type JSONContent } from '@tiptap/core';
import type { Node as PmNode } from '@tiptap/pm/model';
-import { EditorState, TextSelection, type Transaction } from '@tiptap/pm/state';
+import { createHandlePaste } from '../../src/editor/clipboard/handle-paste';
+import { CellInsertionGate } from '../../src/editor/extensions/cell-insertion-gate';
+import { installDomGlobals } from '../../src/editor/walk-currency-test-harness';
+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { mdManager, schema } from './test-harness';
-// paste-failure-toast pulls in sonner; stub it so module load stays inert.
+// The paste dispatcher pulls the degrade-path toast (sonner) into its import
+// graph; stub it so module load stays inert in the jsdom env. The gate's no-op
+// path never degrades, so the stub is never invoked.
mock.module('sonner', () => ({ toast: { error: mock(() => {}) } }));
-let createHandlePaste: typeof import('../../src/editor/clipboard/handle-paste.ts').createHandlePaste;
-beforeEach(async () => {
- ({ createHandlePaste } = await import('../../src/editor/clipboard/handle-paste.ts'));
-});
-
/** The structured diagnostic `flattenCellBlocks` emits for a content-losing drop. */
const DROP_EVENT = 'table-cell-flatten-dropped-block';
-/** A 2x2 GFM table; the caret seeds into the first data cell (text "c"). */
+/** A 2x2 GFM table: header row (a,b), one data row (c,d). */
const TABLE_MD = '| a | b |\n| - | - |\n| c | d |\n';
+/** Self-closing component: schema-valid in a cell, childless, carries a prop. */
+const SELF_CLOSING_COMPONENT_MD = '<CustomWidget foo="bar" />';
+/** Component with an interior body — blank-line-wrapped so it parses to a block. */
+const INTERIOR_COMPONENT_MD = '<CustomWidget>\n\ninside\n\n</CustomWidget>\n';
+
function fakeDT(data: Record<string, string>): ClipboardEvent {
return {
clipboardData: { types: Object.keys(data), getData: (k: string) => data[k] ?? '' },
} as unknown as ClipboardEvent;
}
-/** A view whose state is a real EditorState — dispatch applies for real, so the
- * paste's `replaceSelection` runs PM's actual slice-fitting into the cell. */
-function realStateView(initial: EditorState) {
- let state = initial;
- return {
- get state() {
- return state;
- },
- dispatch(tr: Transaction) {
- state = state.apply(tr);
- },
- current: () => state,
+/** The single jsxComponent node in `md`'s parse, as JSON (throws if absent). */
+function parseComponentJson(md: string): JSONContent {
+ const parsed = mdManager.parse(md) as JSONContent;
+ let found: JSONContent | null = null;
+ const walk = (node: JSONContent): void => {
+ if (found) return;
+ if (node.type === 'jsxComponent') {
+ found = node;
+ return;
+ }
+ node.content?.forEach(walk);
};
+ walk(parsed);
+ if (!found) throw new Error(`no jsxComponent parsed from markdown: ${md}`);
+ return found;
}
-/** Seed the table doc with a collapsed caret inside the first data cell's text. */
-function seedWithCellCaret(): EditorState {
- const doc = schema.nodeFromJSON(mdManager.parse(TABLE_MD));
- const base = EditorState.create({ doc, schema });
- let cellPos = -1;
- base.doc.descendants((node, pos) => {
- if (cellPos === -1 && node.type.name === 'tableCell') {
- cellPos = pos;
- return false;
+/**
+ * Build the table doc with `componentMd`'s component appended into the first data
+ * cell (after the intact "c" paragraph), directly — the un-owned-surface state a
+ * remote peer's raw CRDT update can still spell. Preserving the "c" phrasing lets
+ * the serialize oracle stay "component contributed zero bytes → output === the
+ * untouched table".
+ */
+function tableDocWithComponentInFirstCell(componentMd: string): PmNode {
+ const json = mdManager.parse(TABLE_MD) as JSONContent;
+ const component = parseComponentJson(componentMd);
+ let injected = false;
+ const walk = (node: JSONContent): void => {
+ if (injected) return;
+ if (node.type === 'tableCell') {
+ node.content = [...(node.content ?? []), component];
+ injected = true;
+ return;
}
- return true;
- });
- expect(cellPos).toBeGreaterThanOrEqual(0);
- // cellPos = cell open; +1 enters the cell paragraph; +2 lands in its text.
- const caret = cellPos + 2;
- expect(base.doc.resolve(caret).parent.type.name).toBe('paragraph');
- return base.apply(base.tr.setSelection(TextSelection.create(base.doc, caret)));
-}
-
-/** Paste `payload` (text/plain markdown) into the cell caret; return the doc. */
-function pasteIntoCell(payload: string): PmNode {
- const view = realStateView(seedWithCellCaret());
- const handled = createHandlePaste({ mdManager })(
- view as never,
- fakeDT({ 'text/plain': payload }),
- );
- expect(handled).toBe(true);
- return view.current().doc;
+ node.content?.forEach(walk);
+ };
+ walk(json);
+ if (!injected) throw new Error('parsed table had no tableCell to inject into');
+ return schema.nodeFromJSON(json);
}
/** The first jsxComponent that is a descendant of a tableCell, or null. */
@@ -107,6 +121,16 @@ function componentInCell(doc: PmNode): PmNode | null {
return found;
}
+/** Count of jsxComponent nodes anywhere in `doc`. */
+function countComponentsAnywhere(doc: PmNode): number {
+ let count = 0;
+ doc.descendants((node) => {
+ if (node.type.name === 'jsxComponent') count += 1;
+ return true;
+ });
+ return count;
+}
+
/** Serialize `doc`, capturing every `console.warn` line emitted during the run. */
function serializeCapturingWarns(doc: PmNode): { md: string; warns: string[] } {
const warns: string[] = [];
@@ -121,24 +145,71 @@ function serializeCapturingWarns(doc: PmNode): { md: string; warns: string[] } {
}
}
+// ─── Gated-editor helpers (second block) ───
+
+const editors: Editor[] = [];
+let restoreDomGlobals: (() => void) | null = null;
+
+/** Mount a real editor carrying the app's insertion gate over the core schema. */
+function mountGatedEditor(content: string | JSONContent): Editor {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const editor = new Editor({
+ element: host,
+ content,
+ extensions: [...sharedExtensions, CellInsertionGate],
+ });
+ editors.push(editor);
+ return editor;
+}
+
+/** Run the real WYSIWYG paste dispatcher against a mounted editor's view. */
+function pasteInto(editor: Editor, data: Record<string, string>): boolean {
+ return createHandlePaste({ mdManager })(editor.view, fakeDT(data));
+}
+
+/** Caret position inside the first data cell's paragraph text. */
+function firstDataCellCaret(editor: Editor): number {
+ let cellPos = -1;
+ editor.state.doc.descendants((node, pos) => {
+ if (cellPos === -1 && node.type.name === 'tableCell') {
+ cellPos = pos;
+ return false;
+ }
+ return true;
+ });
+ if (cellPos < 0) throw new Error('seed table has no tableCell');
+ const caret = cellPos + 2; // cell open +1 → paragraph, +2 → paragraph text
+ expect(editor.state.doc.resolve(caret).parent.type.name).toBe('paragraph');
+ return caret;
+}
+
let origWarn: typeof console.warn;
+beforeAll(() => {
+ restoreDomGlobals = installDomGlobals();
+}, HARNESS_BOOT_TIMEOUT_MS);
+afterAll(() => {
+ restoreDomGlobals?.();
+ restoreDomGlobals = null;
+});
beforeEach(() => {
origWarn = console.warn;
});
afterEach(() => {
console.warn = origWarn;
+ while (editors.length > 0) editors.pop()?.destroy();
});
-describe('unregistered component in a table cell drops on serialize', () => {
+describe('a component in a table cell drops on serialize', () => {
// Serializing the untouched table is the oracle for "the component
- // contributed nothing": a total drop makes the pasted-doc output
+ // contributed nothing": a total drop makes the built-doc output
// byte-identical to this, independent of table formatting details.
const baselineMd = mdManager.serialize(schema.nodeFromJSON(mdManager.parse(TABLE_MD)).toJSON());
- test('a self-closing component pastes into a cell then serializes to nothing + a drop warn', () => {
- const doc = pasteIntoCell('<CustomWidget foo="bar" />');
+ test('a self-closing component in a cell serializes to nothing plus a drop warn', () => {
+ const doc = tableDocWithComponentInFirstCell(SELF_CLOSING_COMPONENT_MD);
- // Reachability: the component genuinely reached the cell (no insert guard).
+ // Reachability: the component genuinely sits inside the cell.
const comp = componentInCell(doc);
expect(comp?.attrs.componentName).toBe('CustomWidget');
expect(comp?.childCount).toBe(0);
@@ -157,8 +228,8 @@ describe('unregistered component in a table cell drops on serialize', () => {
expect(drops).toContainEqual({ event: DROP_EVENT, nodeType: 'mdxJsxFlowElement' });
});
- test('a component WITH interior content in a cell drops the interior too', () => {
- const doc = pasteIntoCell('<CustomWidget>\n\ninside\n\n</CustomWidget>\n');
+ test('a component with interior content in a cell drops the interior too', () => {
+ const doc = tableDocWithComponentInFirstCell(INTERIOR_COMPONENT_MD);
const comp = componentInCell(doc);
expect(comp?.attrs.componentName).toBe('CustomWidget');
@@ -178,6 +249,26 @@ describe('unregistered component in a table cell drops on serialize', () => {
});
});
+describe('the owned WYSIWYG paste route refuses a component at a cell caret', () => {
+ test('pasting a block component with the caret in a cell leaves the doc unchanged', () => {
+ const editor = mountGatedEditor(mdManager.parse(TABLE_MD) as JSONContent);
+ editor.commands.setTextSelection(firstDataCellCaret(editor));
+ // Baseline captured after the caret lands: seating a selection after a
+ // trailing table appends the schema's trailing paragraph in its own
+ // (unfiltered) transaction, which is not what this assertion measures.
+ const before = editor.state.doc;
+
+ const handled = pasteInto(editor, { 'text/plain': SELF_CLOSING_COMPONENT_MD });
+
+ // The dispatcher claims the paste (true) so no later branch re-inserts the
+ // content; the gate filtered the insertion, so the doc is byte-identical and
+ // no component landed anywhere.
+ expect(handled).toBe(true);
+ expect(editor.state.doc.eq(before)).toBe(true);
+ expect(countComponentsAnywhere(editor.state.doc)).toBe(0);
+ });
+});
+
interface DropWarn {
event: string;
nodeType: string;
diff --git a/packages/app/tests/stress/paste-fidelity.e2e.ts b/packages/app/tests/stress/paste-fidelity.e2e.ts
index 1aa066111..49cabcc8b 100644
--- a/packages/app/tests/stress/paste-fidelity.e2e.ts
+++ b/packages/app/tests/stress/paste-fidelity.e2e.ts
@@ -28,6 +28,7 @@ import {
simulateCopyAndRead,
simulateCutAndRead,
test,
+ waitForPmSelectionInNode,
waitForActiveProviderSynced as waitForProvider,
} from './_helpers';
@@ -1702,3 +1703,246 @@ test.describe('Clipboard component contract — drag-and-drop (US-009)', () => {
expect(out.html).toContain('ℹ');
});
});
+
+// ─── Insertion-route correctness: #609 list placement + cell gate (persisted bytes) ───
+//
+// Both diagnoses behind this batch lived at the client→server persistence
+// boundary: #609 mis-placed pasted list items (nested-as-child or orphan
+// shapes) and a block component dropped into a table cell projected to zero
+// persisted bytes. Mounted-editor Bun tests prove the in-process transaction;
+// only a real browser paste round-tripped through the server proves the
+// PERSISTED Y.Text bytes these scenarios assert.
+
+const TASK_SEED = '- [ ] alpha\n- [ ] bravo\n- [x] charlie\n- [ ] delta\n- [ ] echo\n';
+const TABLE_SEED = '| a | b |\n| --- | --- |\n| c | d |\n';
+
+/**
+ * Minimal structural view of the DEV-only `window.__activeEditor` (a TipTap
+ * `Editor`) these scenarios drive from inside `page.evaluate` — enough to walk
+ * the doc, place a selection, and reach the PM view DOM. A structural cast
+ * avoids `any` while keeping the e2e file free of ProseMirror type imports.
+ */
+type DevPmNode = { type: { name: string }; firstChild: { content: { size: number } } | null };
+interface DevEditorHandle {
+ state: {
+ doc: { descendants: (fn: (node: DevPmNode, pos: number) => boolean | undefined) => void };
+ };
+ commands: { setTextSelection: (pos: number | { from: number; to: number }) => boolean };
+ view: { dom: HTMLElement };
+}
+
+/**
+ * Copy the nth (0-based) top-level list item through the real clipboard hooks
+ * and return the captured MIME map — the exact payload an OK→OK copy carries.
+ * Selecting the item's paragraph text is enough for the serializer to emit the
+ * full `- [ ] text` line: the list marker rides the open slice's context.
+ * `pos + 2` steps over the listItem-open and paragraph-open tokens.
+ */
+async function copyListItem(
+ page: Page,
+ itemIndex: number,
+): Promise<{ plain: string; html: string }> {
+ return page.evaluate((n) => {
+ const editor = (window as unknown as { __activeEditor?: DevEditorHandle }).__activeEditor;
+ if (!editor) throw new Error('copyListItem: no active editor');
+ let from = -1;
+ let to = -1;
+ let i = 0;
+ editor.state.doc.descendants((node, pos) => {
+ if (from !== -1) return false;
+ if (node.type.name === 'listItem') {
+ if (i === n) {
+ from = pos + 2;
+ to = from + (node.firstChild ? node.firstChild.content.size : 0);
+ return false;
+ }
+ i++;
+ }
+ return true;
+ });
+ if (from === -1) throw new Error(`copyListItem: listItem ${n} not found`);
+ editor.commands.setTextSelection({ from, to });
+ const captured: Record<string, string> = {};
+ const dt = new DataTransfer();
+ const orig = dt.setData.bind(dt);
+ dt.setData = (k: string, v: string): void => {
+ captured[k] = v;
+ orig(k, v);
+ };
+ editor.view.dom.dispatchEvent(
+ new ClipboardEvent('copy', { clipboardData: dt, bubbles: true, cancelable: true }),
+ );
+ return { plain: captured['text/plain'] ?? '', html: captured['text/html'] ?? '' };
+ }, itemIndex);
+}
+
+/** Collapse the caret at the start or end of the nth list item's text. */
+async function setListItemCaret(
+ page: Page,
+ itemIndex: number,
+ where: 'start' | 'end',
+): Promise<void> {
+ await page.evaluate(
+ ({ n, edge }) => {
+ const editor = (window as unknown as { __activeEditor?: DevEditorHandle }).__activeEditor;
+ if (!editor) throw new Error('setListItemCaret: no active editor');
+ let start = -1;
+ let end = -1;
+ let i = 0;
+ editor.state.doc.descendants((node, pos) => {
+ if (start !== -1) return false;
+ if (node.type.name === 'listItem') {
+ if (i === n) {
+ start = pos + 2;
+ end = start + (node.firstChild ? node.firstChild.content.size : 0);
+ return false;
+ }
+ i++;
+ }
+ return true;
+ });
+ if (start === -1) throw new Error(`setListItemCaret: listItem ${n} not found`);
+ editor.commands.setTextSelection(edge === 'end' ? end : start);
+ },
+ { n: itemIndex, edge: where },
+ );
+ await waitForPmSelectionInNode(page, 'listItem');
+}
+
+/** Collapse the caret inside the first table data cell. */
+async function setFirstCellCaret(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const editor = (window as unknown as { __activeEditor?: DevEditorHandle }).__activeEditor;
+ if (!editor) throw new Error('setFirstCellCaret: no active editor');
+ let caret = -1;
+ editor.state.doc.descendants((node, pos) => {
+ if (caret !== -1) return false;
+ if (node.type.name === 'tableCell') {
+ caret = pos + 2;
+ return false;
+ }
+ return true;
+ });
+ if (caret === -1) throw new Error('setFirstCellCaret: no tableCell found');
+ editor.commands.setTextSelection(caret);
+ });
+ await waitForPmSelectionInNode(page, 'tableCell');
+}
+
+/** Count jsxComponent nodes in the live editor doc. */
+async function countComponentsInDoc(page: Page): Promise<number> {
+ return page.evaluate(() => {
+ const editor = (window as unknown as { __activeEditor?: DevEditorHandle }).__activeEditor;
+ if (!editor) throw new Error('countComponentsInDoc: no active editor');
+ let n = 0;
+ editor.state.doc.descendants((node) => {
+ if (node.type.name === 'jsxComponent') n++;
+ return true;
+ });
+ return n;
+ });
+}
+
+test.describe('#609 sibling-item list paste placement (persisted bytes)', () => {
+ let docName: string;
+
+ test.beforeEach(async ({ page, api }) => {
+ docName = `test-paste-609-${randomUUID().slice(0, 8)}`;
+ await api.createPage(`${docName}.md`);
+ await page.goto(`/#/${docName}`);
+ await waitForProvider(page);
+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');
+ await api.replaceDoc(docName, TASK_SEED);
+ await expect.poll(() => getYText(page), { timeout: 5_000 }).toContain('echo');
+ await page.click('.ProseMirror:not(.composer-prosemirror)');
+ });
+
+ test('copied task item pasted at item-start lands as a sibling above with no orphan bytes', async ({
+ page,
+ }) => {
+ const payload = await copyListItem(page, 1); // "bravo"
+ expect(payload.plain).toContain('- [ ] bravo');
+
+ await setListItemCaret(page, 3, 'start'); // start of "delta"
+ await pasteWithMimes(page, { 'text/plain': payload.plain, 'text/html': payload.html });
+
+ await expect(async () => {
+ const content = await getYText(page);
+ // The pasted item is a full sibling immediately above the intact target.
+ expect(content).toContain('- [ ] bravo\n- [ ] delta');
+ // The item that was above delta keeps its own line and checked state.
+ expect(content).toContain('- [x] charlie');
+ // None of the #609 orphan byte shapes are minted.
+ expect(content).not.toMatch(/- \[ \] - \[ \]/);
+ expect(content).not.toMatch(/^\s*\\- /m);
+ expect(content).not.toMatch(/- - /);
+ }).toPass({ timeout: 8_000 });
+ });
+
+ test('copied task item pasted at item-end lands as a sibling below, never a child', async ({
+ page,
+ }) => {
+ const payload = await copyListItem(page, 1); // "bravo"
+ expect(payload.plain).toContain('- [ ] bravo');
+
+ await setListItemCaret(page, 3, 'end'); // end of "delta"
+ await pasteWithMimes(page, { 'text/plain': payload.plain, 'text/html': payload.html });
+
+ await expect(async () => {
+ const content = await getYText(page);
+ // delta → pasted bravo → echo, all siblings at the same list level.
+ expect(content).toContain('- [ ] delta\n- [ ] bravo\n- [ ] echo');
+ // A child sublist would indent the pasted item — assert it never does.
+ expect(content).not.toMatch(/\n[ \t]+- \[ \] bravo/);
+ expect(content).not.toMatch(/- \[ \] - \[ \]/);
+ expect(content).not.toMatch(/^\s*\\- /m);
+ }).toPass({ timeout: 8_000 });
+ });
+});
+
+test.describe('cell-insertion gate — component paste into a table cell (persisted bytes)', () => {
+ let docName: string;
+
+ test.beforeEach(async ({ page, api }) => {
+ docName = `test-paste-cell-gate-${randomUUID().slice(0, 8)}`;
+ await api.createPage(`${docName}.md`);
+ await page.goto(`/#/${docName}`);
+ await waitForProvider(page);
+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');
+ await api.replaceDoc(docName, TABLE_SEED);
+ await expect(async () => {
+ expect(await getYText(page)).toMatch(/\|\s*c\s*\|\s*d\s*\|/);
+ }).toPass({ timeout: 5_000 });
+ await page.click('.ProseMirror:not(.composer-prosemirror)');
+ });
+
+ test('pasting a block component with the caret in a cell leaves the document bytes unchanged', async ({
+ page,
+ }) => {
+ await setFirstCellCaret(page);
+ const baseline = await getYText(page);
+ expect(baseline).toMatch(/\|\s*c\s*\|\s*d\s*\|/);
+
+ await pasteWithMimes(page, {
+ 'text/plain': '<Callout>\n\nnote\n\n</Callout>\n',
+ 'text/html':
+ '<div data-pm-slice="0 0 paragraph"><p>&lt;Callout&gt;note&lt;/Callout&gt;</p></div>',
+ });
+
+ // The gate rejects the transaction synchronously — the live doc gains no
+ // component from any branch (no fall-through re-insert).
+ expect(await countComponentsInDoc(page)).toBe(0);
+
+ // Give any propagation two frames, then assert the persisted bytes are
+ // byte-identical to the pre-paste baseline and never carry the component.
+ await page.evaluate(
+ () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ }),
+ );
+ const after = await getYText(page);
+ expect(after).toBe(baseline);
+ expect(after).not.toContain('Callout');
+ });
+});
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index 8f9d95287..c014b1413 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,4 +1,3 @@
-
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 8bfdb40cd..005627195 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,4 +1,3 @@
-
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index c18c086d5..8890f6739 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,4 +1,3 @@
-
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 463e89595..9d9c244b0 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,4 +1,3 @@
-
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index 3c927eb47..3ab9cc6ef 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -38,7 +38,6 @@ function mergeThreeWayImpl(baseline: string, userText: string, agentText: string
return parts.join('\n');
}
-
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index 592f0b956..e67f33b40 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,4 +1,3 @@
-
const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;
const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 0be5203e4..754dc5cc2 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,7 +32,6 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
-
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -128,7 +127,6 @@ export interface ComparePmStructuralOptions {
ignoreAttrs?: (attrKey: string) => boolean;
}
-
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -250,7 +248,6 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
-
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index dca644141..af20de1e2 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,4 +1,3 @@
-
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index a363dfd54..83d47404a 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,4 +1,3 @@
-
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 47f0d07e4..193e286b0 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index b6299a948..ece5c02a1 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,4 +1,3 @@
-
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index acd398aa6..54774764a 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index fb5ac8e8a..c7518d614 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,4 +1,3 @@
-
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 6931623c7..00f5771ee 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,4 +1,3 @@
-
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
-
interface GfmExample {
section: string;
markdown: string;
@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
-
interface MdxCrashEntry {
id: string;
input: string;
@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
-
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
-
export interface NgPinnedCase {
id: string;
name: string;
@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
-
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index daa3ef82b..8b1eb8519 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,4 +1,3 @@
-
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
-
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
-
const WORDS = [
'lorem',
'ipsum',
@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
-
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
-
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 32c055c5b..420dc0fe5 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,7 +7,6 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
-
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 283913255..2653473da 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,4 +1,3 @@
-
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index 7a22e8016..f758cf737 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 2f082e6d0..78fdfeb02 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,4 +1,3 @@
-
import type { Root as HastRoot } from 'hast';
import type { Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -76,8 +75,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified()
- .use(rehypeParse, { fragment: true });
+ const processor = unified().use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 994eb6917..706fa9afb 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index c58d0847d..58be35302 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -197,7 +196,6 @@ export class MarkdownManager {
}
}
-
const registry = createRegistry();
function destructureAttrs(
@@ -246,7 +244,6 @@ function destructureAttrs(
return result;
}
-
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -266,7 +263,6 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
-
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -335,7 +331,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
-
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -585,7 +580,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -665,7 +659,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -944,7 +937,6 @@ function buildMdastToPmHandlers(
};
}
-
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1070,7 +1062,6 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
-
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index bd79424c7..a5b511f25 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index f84967798..679c72ef7 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index df788a80d..8ce2b2492 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index a58f8c720..35d74b85e 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 17ed2b829..1a897fca8 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index 7e4a9a48b..9864b3b60 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,7 +168,6 @@ export function parseRecursive(
}
}
-
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
-
interface Region {
start: number;
end: number;
@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
-
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
-
interface SourceBlock {
src: string;
start: number;
@@ -456,7 +452,6 @@ function tryPerBlockFallback(
};
}
-
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index 43d420187..e6ab4fd57 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,4 +1,3 @@
-
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 5b9550e90..5d6db7aa8 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index 4ac5731e7..248685cfe 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,4 +1,3 @@
-
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index 240be90e6..50a193a16 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -467,8 +466,7 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- }
- else if (first === '[') {
+ } else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index ca225ce9b..db10fa54b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 3a2524a9a..34068d103 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 2279a0189..93151d43b 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index a0f467c42..188f02d83 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4e8542a21..4ba2c3418 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index a3c96b24a..1a74b1272 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index e95cf43d6..de35e7b79 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index ffdb4d5b5..b4be1b2ea 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index e2a96d1a7..3c8d88b7c 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index 0389575ac..cf2c9da8e 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,4 +1,3 @@
-
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 8be632ba4..4d3250d3a 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,4 +1,3 @@
-
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 542204403..46cc6a074 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,4 +1,3 @@
-
import type { Node as PmNode } from '@tiptap/pm/model';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { PropDef, SerializeContext } from '../registry/types.ts';
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index fe73659e6..be97d4d62 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index f91cd591f..cba68fb3a 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index c5bfd2386..cd245c38c 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,4 +1,3 @@
-
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index 1b75ba564..a100cad76 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,4 +1,3 @@
-
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index afd9936fe..6dad26200 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {
}
}
-
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {
};
}
-
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
-
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index e5bb4656d..af4d7deae 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -1993,10 +1993,12 @@ export function createServer(options: ServerOptions): ServerInstance {
const isDirty = ours !== base;
if (isDirty && shadowRef.current) {
- // Silent rescue checkpoint — preserve in-memory
- // content on a timeline ref so TimelinePanel renders it as an
- // 'external-change-rescue' row. Fire-and-forget; failures warn
- // but don't block the delete lifecycle.
+ // Silent rescue checkpoint — preserve the dirty in-memory
+ // content on a checkpoint ref so it survives this external
+ // delete and stays recoverable via GET /api/rescue. It does
+ // NOT appear in the human timeline: TimelinePanel drops all
+ // checkpoint-type rows. Fire-and-forget; failures warn but
+ // don't block the delete lifecycle.
const shadowForCheckpoint = shadowRef.current;
const branch = headWatcher?.getLastKnownBranch() ?? 'main';
queueMicrotask(() => {