Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): atomic slash-command insert + de-flake auto-open e2e (#2945)
Nick Gomez0e83fcf3d454
diff --git a/.changeset/slash-menu-single-transaction-insert.md b/.changeset/slash-menu-single-transaction-insert.mdnew file mode 100644index 000000000..e4959cd1c--- /dev/null+++ b/.changeset/slash-menu-single-transaction-insert.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge": patch+---++Stop the slash menu from silently replacing an adjacent image or component on insert.++Picking a slash-menu item used to delete the typed `/trigger` in one editor transaction and run the item's insert in a second. Under load, a transaction fired during the delete (for example the collaboration layer reacting to it) could move the selection onto a neighboring selectable block, and the insert would then overwrite that block instead of inserting at the caret: the user typed `/image`, pressed Enter, and a previous image vanished with no error and no useful undo trail. The trigger delete and the item insert now land as one transaction, so nothing can divert the insert onto existing content. The other insertion menus (`#` tags, `[[` wiki links, `@` mentions in the Ask AI composer) already inserted atomically and are now guarded by a lint rule and regression tests so none of them can regress to the split form.diff --git a/biome-plugins/README.md b/biome-plugins/README.mdindex 92d54dad0..23e8dc2c7 100644--- a/biome-plugins/README.md+++ b/biome-plugins/README.md@@ -67,6 +67,25 @@ Detection patterns (call expressions only — type-declarations are naturally exTest: [`packages/desktop/tests/integration/no-resolved-value-theme-source.test.ts`](../packages/desktop/tests/integration/no-resolved-value-theme-source.test.ts).+### `no-split-suggestion-dispatch.grit`++One-transaction suggestion insertion ([PRECEDENTS.md #58](../PRECEDENTS.md#one-transaction-menu-insertions-precedent-58)). Inside a `@tiptap/suggestion` `Suggestion({ ... })` config, a trigger-range delete dispatched on its own (separate from the content insert) opens a re-entrant-dispatch window: anything fired synchronously during the delete's own `updateState` (a plugin `appendTransaction`, a view/NodeView update, the y-prosemirror binding reacting to the delete) can remap the selection onto an adjacent `selectable: true` node, and the follow-up insert then silently REPLACES that node. The fix is one chain (`.deleteRange(range).insertContent(...).run()`) or an `applySlashCommandItem`-style boundary (`packages/app/src/editor/slash-command/apply-item.ts`) for items needing post-commit work.++Detection patterns (scoped to `Suggestion($config)` call sites, so delete-only surfaces outside suggestion configs — e.g. a mention chip's remove button — never fire):+- a chain whose `.run()` receiver is the `deleteRange(...)` call itself (`....deleteRange(range).run()` — a compliant atomic chain always continues past the delete before `.run()`)+- `$editor.commands.deleteRange($range)` — the `commands.*` form dispatches immediately, always a standalone delete transaction++**Registered at root `plugins[]`** (workspace-wide, like `microcopy-ellipsis`): the pattern self-scopes to `Suggestion(...)` calls, and a future suggestion surface in any package must be covered without a biome.jsonc edit.++The rule does NOT catch:+- a split whose delete chain carries a non-content step after `deleteRange` and before `.run()` (e.g. `.deleteRange(r).focus().run()`) — the `.run()` receiver is then not the `deleteRange` call+- a second dispatch made inside a delegated item body (`item.command(editor)` running its own `editor.chain().run()`) — lint can't see through delegation+- raw `view.dispatch(tr.delete(...))` inside a Suggestion config — no occurrence today++Runtime complement: `packages/app/src/editor/extensions/suggestion-atomicity.dom.test.tsx` + `slash-command-atomicity.dom.test.tsx` drive every registered suggestion surface through a real Enter and assert exactly one doc-changing transaction — they catch the delegated-dispatch shapes the lint can't.++Plugin: [`biome-plugins/no-split-suggestion-dispatch.grit`](no-split-suggestion-dispatch.grit). Fixture: [`biome-plugins/__fixtures__/no-split-suggestion-dispatch.fixture.tsx`](__fixtures__/no-split-suggestion-dispatch.fixture.tsx). Test: [`packages/app/tests/lint-plugins/no-split-suggestion-dispatch.test.ts`](../packages/app/tests/lint-plugins/no-split-suggestion-dispatch.test.ts).+### `no-unportaled-editor-content.grit`H6 cross-doc DOM bleed contract. `@tiptap/react`'s `PureEditorContent.componentDidMount` runs `element.append(...editor.view.dom.parentNode.childNodes)` — a sibling-vacuum primitive. When `view.dom` shares a parent with another editor's `view.dom` (e.g., V2 cache parked nodes, cross-Activity reconciliation transitions), the vacuum drags foreign content into the active wrapper. The structural fix is to render every `<EditorContent>` via `React.createPortal` into a per-Activity exclusively-owned DOM target, so `view.dom`'s parent only ever contains THIS editor's nodes.diff --git a/biome-plugins/__fixtures__/no-split-suggestion-dispatch.fixture.tsx b/biome-plugins/__fixtures__/no-split-suggestion-dispatch.fixture.tsxnew file mode 100644index 000000000..47f58015d--- /dev/null+++ b/biome-plugins/__fixtures__/no-split-suggestion-dispatch.fixture.tsx@@ -0,0 +1,105 @@+/**+ * Fixture for `no-split-suggestion-dispatch.grit` (precedent #58).+ *+ * 3 positive cases (MUST each fire exactly once):+ * P1 — bare trigger-delete chain dispatch inside a Suggestion config+ * (`.focus().deleteRange(range).run()` — the pre-fix slash-command shape).+ * P2 — bare delete chain without `.focus()` (`.deleteRange(range).run()`).+ * P3 — `commands.deleteRange(range)` immediate dispatch inside a Suggestion+ * config.+ *+ * 4 negative cases (MUST NOT fire):+ * N1 — atomic single chain: `.deleteRange(range).insertContent(...).run()`+ * (the tag/wiki-link/composer-mention shape).+ * N2 — boundary composition: `.deleteRange(range).command(...).run()`+ * (the applySlashCommandItem shape).+ * N3 — delegation to a boundary function (the fixed slash-command shape).+ * N4 — a bare `deleteRange(...).run()` chain OUTSIDE any Suggestion config+ * (delete-only surfaces like a chip's remove button are legitimate).+ *+ * The paired test asserts the plugin fires exactly 3 times on this file.+ */++// Minimal stand-ins — the rule matches call shapes, not imports.+declare function Suggestion(config: Record<string, unknown>): unknown;+declare const applySlashCommandItem: (args: Record<string, unknown>) => void;++interface FixtureEditor {+ chain(): FixtureChain;+ commands: { deleteRange(range: FixtureRange): boolean };+}+interface FixtureChain {+ focus(): FixtureChain;+ deleteRange(range: FixtureRange): FixtureChain;+ insertContent(content: unknown): FixtureChain;+ command(fn: (props: unknown) => boolean): FixtureChain;+ run(): boolean;+}+interface FixtureRange {+ from: number;+ to: number;+}+interface FixtureCommandProps {+ editor: FixtureEditor;+ range: FixtureRange;+ props: { command: (editor: FixtureEditor) => void };+}++// P1 — the pre-fix slash-command bug: delete dispatched alone, item dispatches+// its own transaction afterward.+export const positiveSplitWithFocus = Suggestion({+ command: ({ editor, range, props: item }: FixtureCommandProps) => {+ editor.chain().focus().deleteRange(range).run();+ item.command(editor);+ },+});++// P2 — same split without the focus() step.+export const positiveSplitBare = Suggestion({+ command: ({ editor, range, props: item }: FixtureCommandProps) => {+ editor.chain().deleteRange(range).run();+ item.command(editor);+ },+});++// P3 — commands.* form dispatches immediately: a standalone delete transaction.+export const positiveCommandsForm = Suggestion({+ command: ({ editor, range, props: item }: FixtureCommandProps) => {+ editor.commands.deleteRange(range);+ item.command(editor);+ },+});++// N1 — atomic single chain (tag / wiki-link / composer-mention shape).+export const negativeAtomicChain = Suggestion({+ command: ({ editor, range }: FixtureCommandProps) => {+ editor.chain().focus().deleteRange(range).insertContent({ type: 'tag' }).run();+ },+});++// N2 — boundary composition: the item contributes steps via `.command()`.+export const negativeBoundaryComposition = Suggestion({+ command: ({ editor, range, props: item }: FixtureCommandProps) => {+ editor+ .chain()+ .focus()+ .deleteRange(range)+ .command(() => {+ item.command(editor);+ return true;+ })+ .run();+ },+});++// N3 — delegation to the sanctioned boundary (the fixed slash-command shape).+export const negativeDelegation = Suggestion({+ command: ({ editor, range, props: item }: FixtureCommandProps) =>+ applySlashCommandItem({ editor, item, range }),+});++// N4 — delete-only dispatch OUTSIDE a Suggestion config (e.g. a mention chip's+// remove button). Legitimate: there is no follow-up insert to split from.+export function negativeOutsideSuggestion(editor: FixtureEditor, range: FixtureRange): void {+ editor.chain().focus().deleteRange(range).run();+}diff --git a/biome-plugins/no-split-suggestion-dispatch.grit b/biome-plugins/no-split-suggestion-dispatch.gritnew file mode 100644index 000000000..aef4c7c87--- /dev/null+++ b/biome-plugins/no-split-suggestion-dispatch.grit@@ -0,0 +1,64 @@+// no-split-suggestion-dispatch — one-transaction suggestion insertion (precedent #58).+//+// A `@tiptap/suggestion` surface that deletes its trigger range and then+// inserts content MUST land both in ONE dispatched transaction. Dispatching+// the trigger-delete on its own opens a window: `view.dispatch` runs+// `updateState` synchronously, and anything it fires re-entrantly during the+// delete's own dispatch (a plugin `appendTransaction`, a plugin-view or+// NodeView update, an `editor.on('transaction')` listener, or the+// y-prosemirror binding reacting to the just-applied delete) can dispatch a+// transaction that remaps the selection onto an adjacent `selectable: true`+// node — the follow-up insert then REPLACES that node. Silent data loss, no+// error, load-dependent (reads as e2e flake).+//+// The rule fires INSIDE a `Suggestion({ ... })` config on the two+// bare-trigger-delete dispatch shapes:+//+// 1. `....deleteRange(range).run()` — a chain whose FINAL step before+// `.run()` is the delete. A compliant atomic chain always continues past+// the delete (`.deleteRange(range).insertContent(...).run()`, or the+// slash boundary's `.deleteRange(range).command(...).run()`), so the+// receiver of its `.run()` is never the `deleteRange` call itself.+// 2. `editor.commands.deleteRange(range)` — the `commands.*` form always+// dispatches immediately, so inside a suggestion `command` it is a+// standalone trigger-delete transaction by construction.+//+// Fix: compose delete + insert into one chain, or route through a boundary+// like `applySlashCommandItem` (`packages/app/src/editor/slash-command/+// apply-item.ts`) when items need post-commit work (`afterCommit`).+//+// Does NOT catch (documented honestly):+// - A split where the delete chain carries an unrelated non-content step+// before `.run()` (e.g. `.deleteRange(r).focus().run()`) — the receiver+// of `.run()` is then not the `deleteRange` call. Focus-first ordering+// (`.focus().deleteRange(r).run()`) IS caught (shape 1).+// - A second dispatch made by the ITEM the command delegates to (an+// `item.command(editor)` that runs its own `editor.chain().run()`).+// Lint can't see through the delegation; the runtime pins in+// `suggestion-atomicity.dom.test.tsx` + `slash-command-atomicity.dom.test.tsx`+// assert the exactly-one-doc-changing-transaction invariant end to end.+// - A raw `view.dispatch(tr.delete(...))` inside a Suggestion config —+// no occurrence today; add a shape if one appears.+//+// Suppress a legitimate exception (a Suggestion surface that deletes its+// trigger WITHOUT ever inserting — none exists today) with:+// // biome-ignore lint/plugin/no-split-suggestion-dispatch: <reason>++language js++or {+ `Suggestion($config)` where {+ $config <: contains `$chain.deleteRange($range).run()` as $bare,+ register_diagnostic(+ span = $bare,+ message = "Split suggestion dispatch: this chain dispatches the trigger-range delete on its own. Compose the delete and the insert into ONE chain (`.deleteRange(range).insertContent(...).run()`) or route through an applySlashCommandItem-style boundary so the item contributes steps to the same transaction (precedent #58). A separately dispatched delete lets a re-entrant transaction remap the selection and the follow-up insert silently replace an adjacent node. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-split-suggestion-dispatchgrit"+ )+ },+ `Suggestion($config)` where {+ $config <: contains `$editor.commands.deleteRange($range)` as $cmd,+ register_diagnostic(+ span = $cmd,+ message = "Split suggestion dispatch: `commands.deleteRange` dispatches the trigger-range delete immediately as its own transaction. Compose the delete and the insert into ONE chain (`.deleteRange(range).insertContent(...).run()`) or route through an applySlashCommandItem-style boundary so the item contributes steps to the same transaction (precedent #58). See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-split-suggestion-dispatchgrit"+ )+ }+}diff --git a/biome.jsonc b/biome.jsoncindex b4430adb2..9d533b34c 100644--- a/biome.jsonc+++ b/biome.jsonc@@ -4,6 +4,7 @@"./biome-plugins/microcopy-ellipsis.grit","./biome-plugins/no-loosely-typed-webcontents-ipc.grit","./biome-plugins/no-resolved-value-theme-source.grit",+ "./biome-plugins/no-split-suggestion-dispatch.grit","./biome-plugins/no-unportaled-editor-content.grit"],"assist": { "actions": { "source": { "organizeImports": "on" } } },diff --git a/packages/app/src/editor/extensions/slash-command-atomicity.dom.test.tsx b/packages/app/src/editor/extensions/slash-command-atomicity.dom.test.tsxnew file mode 100644index 000000000..034865ea5--- /dev/null+++ b/packages/app/src/editor/extensions/slash-command-atomicity.dom.test.tsx@@ -0,0 +1,217 @@+/**+ * Pin the atomicity invariant of the slash-command suggestion handler:+ *+ * A suggestion command's trigger-range delete and its content insert must+ * land as ONE transaction. If they land as two, any transaction dispatched+ * in between can move the selection, and the insert then applies to+ * whatever the selection became — replacing a pre-existing node instead of+ * inserting a new one.+ *+ * The window is not hypothetical, and it is not an async gap between two+ * statements: `view.dispatch` runs `updateState` synchronously, and anything+ * it fires re-entrantly during the delete's own dispatch (a plugin+ * `appendTransaction`, a plugin-view or NodeView update, an+ * `editor.on('transaction')` listener, or the y-prosemirror binding reacting+ * to the just-applied delete) can dispatch its own transaction before+ * control reaches the insert. ProseMirror's selection remapping then settles+ * on the nearest selectable node, and a block `jsxComponent`+ * (`selectable: true`) adjacent to the trigger is exactly such a node. The+ * next `insertContent` targets a NodeSelection and REPLACES it, so the+ * document ends with the same node count it started with: the user typed+ * `/image`, pressed Enter, and their previous image vanished.+ *+ * The sibling suggestion extensions (`wiki-link-suggestion.ts`,+ * `tag-suggestion.ts`) already chain delete and insert into a single+ * transaction, which is why only the slash menu exhibits this.+ *+ * Two complementary assertions:+ *+ * 1. The direct oracle — exactly one doc-changing transaction per+ * slash-command invocation. This is the invariant itself, independent+ * of any particular interleaving.+ * 2. The consequence — with a selection-only transaction interleaved at+ * the first doc-changing transaction, both the pre-existing component+ * and the newly inserted one must survive. Under an atomic+ * implementation the interleaved transaction cannot land mid-command,+ * so the diverted selection is harmless.+ *+ * Tier: `.dom.test.tsx` (jsdom). TipTap's `new Editor({ ... })` needs+ * `document`/`window`, and the product `command` callback is reachable only+ * through `@tiptap/suggestion`'s renderer (`props.command` is closure-held),+ * so the test drives a real Enter keydown through the mounted plugin rather+ * than calling the callback directly.+ *+ * Contention-level coverage for the same invariant lives in+ * `tests/stress/slash-command-auto-open.e2e.ts`; this file is the+ * deterministic, contention-free tier.+ */++// `cleanup` satisfies the Tier-3 filename contract (every `*.dom.test.tsx`+// must value-import from `@testing-library/react`). The suite constructs the+// Editor directly rather than rendering through RTL; `cleanup` runs in+// `afterEach` so any future RTL render is torn down between tests.+import { cleanup } from '@testing-library/react';+import { Editor } from '@tiptap/core';+import { NodeSelection } from '@tiptap/pm/state';+import { afterEach, describe, expect, test } from 'vitest';+import { sharedExtensions } from './shared';++/** Byte-identifying attr of the component that must survive the slash insert. */+const PRIOR_SOURCE_RAW = '<img src="prior-marker.png" />';++/** Document position of the pre-existing `jsxComponent` (first top-level node). */+const PRIOR_POS = 0;++interface SuggestionPluginState {+ active: boolean;+}++/**+ * Locate the slash-command Suggestion plugin by plugin-key prefix.+ * `new PluginKey('slashCommand')` synthesizes a unique suffix, and+ * `slashCommandKey` is not exported from `slash-command.ts` — matching the+ * prefix avoids widening the production surface for a test.+ */+function getSlashState(editor: Editor): SuggestionPluginState | null {+ const plugin = editor.state.plugins.find((p) => {+ const keyName = (p as { spec?: { key?: { key?: string } } }).spec?.key?.key;+ return typeof keyName === 'string' && keyName.startsWith('slashCommand');+ });+ return (plugin?.getState(editor.state) as SuggestionPluginState | undefined) ?? null;+}++function mountEditorWithPriorComponent(): { editor: Editor; container: HTMLDivElement } {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const editor = new Editor({+ element: container,+ extensions: sharedExtensions,+ editable: true,+ content: {+ type: 'doc',+ content: [+ {+ type: 'jsxComponent',+ attrs: {+ componentName: 'img',+ kind: 'element',+ attributes: [],+ sourceRaw: PRIOR_SOURCE_RAW,+ sourceDirty: false,+ props: { src: 'prior-marker.png' },+ },+ },+ { type: 'paragraph' },+ ],+ },+ });+ return { editor, container };+}++function teardown(editor: Editor, container: HTMLDivElement): void {+ editor.destroy();+ container.remove();+ // Suggestion popups are appended to `document.body`, not to the editor+ // container; clear any that outlived destroy() so the next test starts clean.+ for (const node of Array.from(document.body.children)) {+ if (node !== container) node.remove();+ }+}++/**+ * The Suggestion plugin's `view.update()` runs synchronously on dispatch and+ * may call `onStart`, which mounts a ReactRenderer. React 19 commits+ * concurrently — yield to the microtask queue twice so the popup is live+ * before the keydown is delivered.+ */+async function flush(): Promise<void> {+ await Promise.resolve();+ await Promise.resolve();+}++/** Type `/image` in the trailing paragraph and assert the menu is open. */+async function openSlashMenu(editor: Editor): Promise<void> {+ editor.commands.focus('end');+ editor.commands.insertContent('/image');+ await flush();+ // Precondition, not the assertion under test: if the menu never opened the+ // failures below would be about a command that never ran.+ expect(getSlashState(editor)?.active).toBe(true);+}++/**+ * Deliver Enter the way ProseMirror does — `view.someProp('handleKeyDown')` —+ * so the real `render().onKeyDown` handler selects the highlighted item and+ * invokes the production `command` callback.+ */+function pressEnter(editor: Editor): boolean {+ const event = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true });+ return editor.view.someProp('handleKeyDown', (f) => f(editor.view, event)) === true;+}++function jsxComponentSourceRaws(editor: Editor): string[] {+ const out: string[] = [];+ editor.state.doc.descendants((node) => {+ if (node.type.name === 'jsxComponent') out.push(String(node.attrs.sourceRaw));+ });+ return out;+}++describe('Slash-command insertion is a single transaction', () => {+ afterEach(() => {+ cleanup();+ });++ test('running a slash-command item dispatches exactly one doc-changing transaction', async () => {+ const { editor, container } = mountEditorWithPriorComponent();+ try {+ await openSlashMenu(editor);++ let docChangingCount = 0;+ editor.on('transaction', ({ transaction }) => {+ if (transaction.docChanged) docChangingCount += 1;+ });++ expect(pressEnter(editor)).toBe(true);+ await flush();++ // The insert landed (guards against a vacuous zero-transaction pass).+ expect(jsxComponentSourceRaws(editor)).toHaveLength(2);++ expect(docChangingCount).toBe(1);+ } finally {+ teardown(editor, container);+ }+ });++ test('a transaction interleaved mid-command cannot divert the insert onto a prior node', async () => {+ const { editor, container } = mountEditorWithPriorComponent();+ try {+ await openSlashMenu(editor);++ // Model the CRDT-remap window: on the first doc-changing transaction of+ // the command, move the selection onto the pre-existing component. This+ // is selection-only — it changes no content, so any change in component+ // count is attributable solely to where the insert landed.+ let interleaved = false;+ editor.on('transaction', ({ transaction }) => {+ if (interleaved || !transaction.docChanged) return;+ interleaved = true;+ const { state, dispatch } = editor.view;+ dispatch(state.tr.setSelection(NodeSelection.create(state.doc, PRIOR_POS)));+ });++ expect(pressEnter(editor)).toBe(true);+ await flush();++ // Precondition: the interleaving actually happened.+ expect(interleaved).toBe(true);++ const sourceRaws = jsxComponentSourceRaws(editor);+ expect(sourceRaws).toHaveLength(2);+ expect(sourceRaws).toContain(PRIOR_SOURCE_RAW);+ } finally {+ teardown(editor, container);+ }+ });+});diff --git a/packages/app/src/editor/extensions/slash-command.ts b/packages/app/src/editor/extensions/slash-command.tsindex 0b17cb5d1..6b0ebd0c2 100644--- a/packages/app/src/editor/extensions/slash-command.ts+++ b/packages/app/src/editor/extensions/slash-command.ts@@ -2,6 +2,7 @@ import { Extension } from '@tiptap/core';import { type EditorState, PluginKey } from '@tiptap/pm/state';import { ReactRenderer } from '@tiptap/react';import Suggestion, { type SuggestionKeyDownProps, type SuggestionProps } from '@tiptap/suggestion';+import { applySlashCommandItem } from '../slash-command/apply-item';import { filterItems, getSlashCommandItems, type SlashCommandItem } from '../slash-command/items';import { SlashCommandMenu } from '../slash-command/SlashCommandMenu';import { isSelectionInTableCell } from '../table-cell-context';@@ -159,19 +160,7 @@ export const SlashCommand = Extension.create<SlashCommandOptions>({state: editor.state,}),- command: ({ editor, range, props: item }) => {- try {- editor.chain().focus().deleteRange(range).run();- } catch (err) {- console.error(`[slash-command] deleteRange failed for "${item.name}"`, err);- return;- }- try {- item.command(editor);- } catch (err) {- console.error(`[slash-command] command "${item.name}" threw an error`, err);- }- },+ command: ({ editor, range, props: item }) => applySlashCommandItem({ editor, item, range }),render: () => {let renderer: ReactRenderer<typeof SlashCommandMenu> | null = null;diff --git a/packages/app/src/editor/extensions/suggestion-atomicity.dom.test.tsx b/packages/app/src/editor/extensions/suggestion-atomicity.dom.test.tsxnew file mode 100644index 000000000..ebb1206bf--- /dev/null+++ b/packages/app/src/editor/extensions/suggestion-atomicity.dom.test.tsx@@ -0,0 +1,216 @@+/**+ * Generalized one-transaction pin for every non-slash `@tiptap/suggestion`+ * surface (precedent #58): tag (`#`), wiki-link (`[[`), and the Ask-AI+ * composer's `@`-mention. The slash menu has its own pin with an+ * interleaved-transaction consequence test in+ * `slash-command-atomicity.dom.test.tsx`.+ *+ * The invariant: selecting a suggestion item must land the trigger-range+ * delete and the content insert as ONE doc-changing transaction. If they land+ * as two, a transaction dispatched re-entrantly during the delete's own+ * dispatch (a plugin `appendTransaction`, a view update, or the y-prosemirror+ * binding reacting to the delete) can remap the selection onto an adjacent+ * `selectable: true` node, and the insert then REPLACES that node — silent+ * data loss.+ *+ * This is the runtime complement to the `no-split-suggestion-dispatch`+ * GritQL rule: the lint catches a bare trigger-delete dispatch statically;+ * this test drives each surface through a real Enter keydown (the production+ * `command` callbacks are closure-held inside the Suggestion plugins, so the+ * keydown path is the only way to run them) and asserts the+ * exactly-one-doc-changing-transaction oracle end to end — including any+ * second dispatch the lint cannot see.+ *+ * Corpus fetches (`/api/tags`, `/api/pages`) are stubbed at `global.fetch`;+ * every other endpoint returns a non-ok response, which each surface+ * tolerates by design (ranking context and asset lists degrade to empty).+ */++// `cleanup` satisfies the Tier-3 filename contract (every `*.dom.test.tsx`+// must value-import from `@testing-library/react`). The suite constructs the+// Editor directly rather than rendering through RTL; `cleanup` runs in+// `afterEach` so any future RTL render is torn down between tests.+import { cleanup } from '@testing-library/react';+import type { Extensions } from '@tiptap/core';+import { Editor } from '@tiptap/core';+import type { PluginKey } from '@tiptap/pm/state';+import { afterEach, describe, expect, test, vi } from 'vitest';+import {+ composerMentionExtensions,+ composerMentionSuggestionKey,+} from '../composer-mention/composer-mention';+import { sharedExtensions } from './shared';+import { tagSuggestionKey } from './tag-suggestion';+import { wikiLinkSuggestionKey } from './wiki-link-suggestion';++/** Minimal `fetch` response shim — the corpus fetchers only touch `ok`,+ * `status`, and `json()`. */+function fetchResponse(status: number, body: unknown): unknown {+ return { ok: status >= 200 && status < 300, status, json: async () => body };+}++/**+ * Stub the corpus endpoints. One page ("alpha") and one tag ("alpha") are+ * enough for every surface to produce a selectable first item for the query+ * `alp`. Unknown endpoints 404 — the fetchers degrade to empty asset lists /+ * empty ranking context without rejecting the picker.+ */+function stubCorpusFetch(): void {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: unknown) => {+ const url = String(input);+ if (url.includes('/api/tags')) {+ return fetchResponse(200, { tags: [{ name: 'alpha', count: 3, isLeaf: true }] });+ }+ if (url.includes('/api/pages')) {+ return fetchResponse(200, {+ pages: [+ {+ docName: 'alpha',+ title: 'Alpha',+ docExt: '.md',+ size: 1,+ modified: '2026-01-01T00:00:00.000Z',+ },+ ],+ });+ }+ return fetchResponse(404, {});+ }),+ );+}++function mountEditor(extensions: Extensions): { editor: Editor; container: HTMLDivElement } {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const editor = new Editor({+ element: container,+ extensions,+ editable: true,+ content: { type: 'doc', content: [{ type: 'paragraph' }] },+ });+ return { editor, container };+}++function teardown(editor: Editor, container: HTMLDivElement): void {+ editor.destroy();+ container.remove();+ // Suggestion popups are appended to `document.body`, not to the editor+ // container; clear any that outlived destroy() so the next test starts clean.+ for (const node of Array.from(document.body.children)) {+ if (node !== container) node.remove();+ }+}++/**+ * Deliver Enter to the surface's own Suggestion plugin `handleKeyDown` prop —+ * the same entry point ProseMirror's keydown dispatch uses — so the real+ * `render().onKeyDown` handler selects the highlighted item and invokes the+ * production `command` callback. Scoping to the one plugin (instead of+ * `view.someProp`) keeps a not-yet-populated menu from falling through to the+ * editor's base Enter binding, which would split the paragraph and end the+ * poll below with a false positive.+ */+function pressEnterOnSuggestion(editor: Editor, pluginKey: PluginKey): boolean {+ const plugin = pluginKey.get(editor.state);+ const handleKeyDown = plugin?.props.handleKeyDown;+ if (!plugin || !handleKeyDown) return false;+ const event = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true });+ return handleKeyDown.call(plugin, editor.view, event) === true;+}++/**+ * The corpus loads through async `items()` (stubbed fetch + schema parse), so+ * the menu is not selectable on the first microtask: the suggestion handler+ * returns false while its item list is still empty, dispatching nothing. Poll+ * a real macrotask tick until Enter is handled.+ */+async function pressEnterOnceItemsLoad(editor: Editor, pluginKey: PluginKey): Promise<boolean> {+ for (let i = 0; i < 50; i++) {+ if (pressEnterOnSuggestion(editor, pluginKey)) return true;+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ return false;+}++interface SurfaceCase {+ name: string;+ extensions: () => Extensions;+ pluginKey: PluginKey;+ /** Typed at the head of the empty paragraph to open the menu. */+ trigger: string;+ /** Node type the selected item must have inserted. */+ insertedNodeType: string;+}++const SURFACES: SurfaceCase[] = [+ {+ name: 'tag suggestion (#)',+ extensions: () => sharedExtensions,+ pluginKey: tagSuggestionKey,+ trigger: '#alp',+ insertedNodeType: 'tag',+ },+ {+ name: 'wiki-link suggestion ([[)',+ extensions: () => sharedExtensions,+ pluginKey: wikiLinkSuggestionKey,+ trigger: '[[alp',+ insertedNodeType: 'wikiLink',+ },+ {+ name: 'composer mention (@)',+ extensions: () => composerMentionExtensions(),+ pluginKey: composerMentionSuggestionKey,+ trigger: '@alp',+ insertedNodeType: 'composerMention',+ },+];++function countNodesOfType(editor: Editor, typeName: string): number {+ let count = 0;+ editor.state.doc.descendants((node) => {+ if (node.type.name === typeName) count += 1;+ });+ return count;+}++describe('Suggestion-surface insertion is a single transaction', () => {+ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ for (const surface of SURFACES) {+ test(`${surface.name}: selecting an item dispatches exactly one doc-changing transaction`, async () => {+ stubCorpusFetch();+ const { editor, container } = mountEditor(surface.extensions());+ try {+ editor.commands.focus('end');+ editor.commands.insertContent(surface.trigger);++ let docChangingCount = 0;+ editor.on('transaction', ({ transaction }) => {+ if (transaction.docChanged) docChangingCount += 1;+ });++ // Precondition, not the assertion under test: if the menu never+ // became selectable the invariant below would pass vacuously.+ expect(await pressEnterOnceItemsLoad(editor, surface.pluginKey)).toBe(true);+ // Drain any deferred post-commit work (selection moves are+ // selection-only and must not add a doc-changing transaction).+ await new Promise((resolve) => setTimeout(resolve, 0));++ // The insert landed in place of the trigger (guards against a+ // vacuous pass where Enter was handled but no item command ran).+ expect(countNodesOfType(editor, surface.insertedNodeType)).toBe(1);+ expect(editor.state.doc.textContent).not.toContain(surface.trigger);++ expect(docChangingCount).toBe(1);+ } finally {+ teardown(editor, container);+ }+ });+ }+});diff --git a/packages/app/src/editor/slash-command/apply-item.dom.test.tsx b/packages/app/src/editor/slash-command/apply-item.dom.test.tsxnew file mode 100644index 000000000..020892152--- /dev/null+++ b/packages/app/src/editor/slash-command/apply-item.dom.test.tsx@@ -0,0 +1,230 @@+/**+ * Error-path pins for `applySlashCommandItem` (precedent #58 boundary).+ *+ * The happy-path single-transaction semantics are pinned in+ * `../extensions/slash-command-atomicity.dom.test.tsx`; this file pins the+ * three deliberate failure-mode behaviors of the boundary:+ *+ * 1. An item whose `command` throws must NOT roll back the trigger-range+ * delete — the chain's `.command()` step returns true unconditionally so+ * the user's `/query` text does not survive a broken item. The failure+ * is surfaced via `console.error` after the dispatch.+ * 2. A throwing `afterCommit` callback must not starve the remaining+ * deferred callbacks, and its log message must be distinguishable from+ * an item-command failure (the two share a catch-shaped code path but+ * mean different things when debugging).+ * 3. A throwing item must not poison the dispatch: the delete still lands+ * as a doc-changing transaction and the editor stays usable.+ *+ * Tier: `.dom.test.tsx` (jsdom) — `applySlashCommandItem` drives a real+ * `editor.chain()`, so it needs a mounted TipTap Editor.+ */++// `cleanup` satisfies the Tier-3 filename contract (every `*.dom.test.tsx`+// must value-import from `@testing-library/react`). The suite constructs the+// Editor directly rather than rendering through RTL; `cleanup` runs in+// `afterEach` so any future RTL render is torn down between tests.+import { cleanup } from '@testing-library/react';+import { Editor } from '@tiptap/core';+import { Zap } from 'lucide-react';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { sharedExtensions } from '../extensions/shared';+import { applySlashCommandItem } from './apply-item';+import type { SlashCommandItem } from './items';++function mountEditor(): { editor: Editor; container: HTMLDivElement } {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const editor = new Editor({+ element: container,+ extensions: sharedExtensions,+ editable: true,+ content: { type: 'doc', content: [{ type: 'paragraph' }] },+ });+ return { editor, container };+}++function teardown(editor: Editor, container: HTMLDivElement): void {+ editor.destroy();+ container.remove();+}++function makeItem(overrides: Partial<SlashCommandItem>): SlashCommandItem {+ return {+ name: 'test-item',+ label: 'Test item',+ icon: Zap,+ category: 'basic',+ command: () => {},+ ...overrides,+ };+}++/**+ * Type stand-in trigger text and return the range the suggestion would hand+ * over. Deliberately NOT slash-prefixed: `applySlashCommandItem` only sees a+ * positional range, and real trigger text would open the live suggestion+ * popup, whose async floating-ui positioning outlives the test's teardown.+ */+function typeTrigger(editor: Editor, text: string): { from: number; to: number } {+ editor.commands.focus('end');+ const from = editor.state.selection.from;+ editor.commands.insertContent(text);+ return { from, to: editor.state.selection.from };+}++describe('applySlashCommandItem error paths', () => {+ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });++ test('a throwing item command does not roll back the trigger-range delete', () => {+ const { editor, container } = mountEditor();+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ const range = typeTrigger(editor, 'xboom');+ const itemFailure = new Error('item exploded');+ const item = makeItem({+ name: 'boom',+ command: () => {+ throw itemFailure;+ },+ });++ let docChangingCount = 0;+ editor.on('transaction', ({ transaction }) => {+ if (transaction.docChanged) docChangingCount += 1;+ });++ applySlashCommandItem({ editor, item, range });++ // The user's trigger text must not survive the broken item.+ expect(editor.state.doc.textContent).not.toContain('xboom');+ // The delete still landed as a normal dispatch, not a rollback.+ expect(docChangingCount).toBe(1);+ // The failure is surfaced, attributed to the item command.+ expect(consoleError).toHaveBeenCalledWith(+ '[slash-command] command "boom" threw an error',+ itemFailure,+ );+ // The editor is still usable after the failure.+ expect(editor.commands.insertContent('still alive')).toBe(true);+ expect(editor.state.doc.textContent).toContain('still alive');+ } finally {+ teardown(editor, container);+ }+ });++ test('a throwing afterCommit callback does not starve later callbacks and logs distinguishably', () => {+ const { editor, container } = mountEditor();+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ const range = typeTrigger(editor, 'xdefer');+ const deferredFailure = new Error('deferred exploded');+ const secondCallback = vi.fn();+ const item = makeItem({+ name: 'defer',+ command: ({ chain, afterCommit }) => {+ chain().insertContent('inserted').run();+ afterCommit(() => {+ throw deferredFailure;+ });+ afterCommit(secondCallback);+ },+ });++ applySlashCommandItem({ editor, item, range });++ // The insert committed and the trigger is gone.+ expect(editor.state.doc.textContent).toContain('inserted');+ expect(editor.state.doc.textContent).not.toContain('xdefer');+ // The second deferred callback still ran despite the first throwing.+ expect(secondCallback).toHaveBeenCalledTimes(1);+ // The message names the afterCommit path, not the item-command path —+ // the two failure modes must stay distinguishable in logs.+ expect(consoleError).toHaveBeenCalledWith(+ '[slash-command] afterCommit callback for "defer" threw an error',+ deferredFailure,+ );+ expect(consoleError).not.toHaveBeenCalledWith(+ '[slash-command] command "defer" threw an error',+ deferredFailure,+ );+ } finally {+ teardown(editor, container);+ }+ });++ test('a dispatch failure surfaces a preceding item failure instead of swallowing it', () => {+ // Editor double: the chain invokes the boundary's `.command()` wrapper+ // (so `item.command` runs and its throw is captured as `itemError`), then+ // `.run()` itself throws — the dual-failure case. A real TipTap chain+ // can't be made to throw at dispatch without patching internals, so the+ // double stands in for the chain contract only.+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const dispatchFailure = new Error('dispatch exploded');+ const itemFailure = new Error('item exploded');+ type CommandFn = (props: { chain: unknown; state: unknown }) => boolean;+ let commandFn: CommandFn | null = null;+ const chainDouble = {+ focus: () => chainDouble,+ deleteRange: () => chainDouble,+ command: (fn: CommandFn) => {+ commandFn = fn;+ return chainDouble;+ },+ run: () => {+ commandFn?.({ chain: undefined, state: undefined });+ throw dispatchFailure;+ },+ };+ const editorDouble = { chain: () => chainDouble } as unknown as Editor;+ const item = makeItem({+ name: 'dual',+ command: () => {+ throw itemFailure;+ },+ });++ applySlashCommandItem({ editor: editorDouble, item, range: { from: 0, to: 1 } });++ expect(consoleError).toHaveBeenCalledWith(+ '[slash-command] deleteRange failed for "dual"',+ dispatchFailure,+ );+ expect(consoleError).toHaveBeenCalledWith(+ '[slash-command] command "dual" threw an error',+ itemFailure,+ );+ });++ test('a throwing item still commits the delete in the same single transaction as a working item would', () => {+ const { editor, container } = mountEditor();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ const range = typeTrigger(editor, 'xpartial');+ const item = makeItem({+ name: 'partial',+ command: ({ chain }) => {+ chain().insertContent('kept').run();+ throw new Error('after contributing steps');+ },+ });++ let docChangingCount = 0;+ editor.on('transaction', ({ transaction }) => {+ if (transaction.docChanged) docChangingCount += 1;+ });++ applySlashCommandItem({ editor, item, range });++ // Steps contributed before the throw ride the same single dispatch.+ expect(docChangingCount).toBe(1);+ expect(editor.state.doc.textContent).toContain('kept');+ expect(editor.state.doc.textContent).not.toContain('xpartial');+ } finally {+ teardown(editor, container);+ }+ });+});diff --git a/packages/app/src/editor/slash-command/apply-item.ts b/packages/app/src/editor/slash-command/apply-item.tsnew file mode 100644index 000000000..2c3053ba7--- /dev/null+++ b/packages/app/src/editor/slash-command/apply-item.ts@@ -0,0 +1,74 @@+import type { Editor, Range } from '@tiptap/react';+import type { SlashCommandItem } from './items';++interface ApplySlashCommandItemArgs {+ editor: Editor;+ item: SlashCommandItem;+ range: Range;+}++/**+ * Run a slash-command item's insert in the same transaction as the+ * trigger-range delete.+ *+ * The composition is the whole point. `.command()` hands the item a chain+ * seeded with the outer transaction, so the item's `.run()` appends steps+ * rather than dispatching; the single `.run()` below is the only dispatch.+ * A second transaction would open a window in which a transaction dispatched+ * re-entrantly during the delete's own dispatch — a plugin `appendTransaction`,+ * a view update, or the collab binding reacting to the just-applied delete —+ * can remap the selection onto an adjacent selectable node, and the item's+ * insert would then replace that node.+ *+ * Two shapes deliberately avoided: handing the item this function's own chain+ * object (its `.run()` would dispatch the shared transaction a second time),+ * and calling `item.command` with an `editor` it can chain off (`editor.chain()`+ * reads `editor.state`, which is still the pre-deleteRange document).+ */+export function applySlashCommandItem({ editor, item, range }: ApplySlashCommandItemArgs): void {+ const deferred: Array<() => void> = [];+ let itemError: unknown;++ try {+ editor+ .chain()+ .focus()+ .deleteRange(range)+ .command((props) => {+ try {+ item.command({+ editor,+ chain: props.chain,+ state: props.state,+ afterCommit: (fn) => deferred.push(fn),+ });+ } catch (err) {+ itemError = err;+ }+ // An item failure must not roll back the trigger-range delete: the+ // chain aborts on a false return and the user's "/query" text would+ // survive with no insert, which is not today's behaviour.+ return true;+ })+ .run();+ } catch (err) {+ console.error(`[slash-command] deleteRange failed for "${item.name}"`, err);+ // A dispatch failure must not swallow an item failure that preceded it —+ // both throws are needed to trace the dual-failure case.+ if (itemError !== undefined) {+ console.error(`[slash-command] command "${item.name}" threw an error`, itemError);+ }+ return;+ }++ if (itemError !== undefined) {+ console.error(`[slash-command] command "${item.name}" threw an error`, itemError);+ }+ for (const fn of deferred) {+ try {+ fn();+ } catch (err) {+ console.error(`[slash-command] afterCommit callback for "${item.name}" threw an error`, err);+ }+ }+}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.tsindex 693c1e83e..496daa64a 100644--- a/packages/app/src/editor/slash-command/cell-context-filter.test.ts+++ b/packages/app/src/editor/slash-command/cell-context-filter.test.ts@@ -20,6 +20,7 @@ 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 { applySlashCommandItem } from './apply-item';import { getComponentItems, getInlineComponentItems } from './component-items';import { getEmbedStarterItems } from './embed-starter-items';import { getSlashCommandItems, type SlashCommandItem } from './items';@@ -206,12 +207,22 @@ describe('component item command with a cell caret no-ops via the gate', () => {return item;}+ /**+ * Run an item the way the slash extension does. The range is zero-width at+ * the caret so the trigger-range delete is a no-op and the only document+ * change under test is the item's own insert.+ */+ function runItem(editor: Editor, item: SlashCommandItem): void {+ const { from } = editor.state.selection;+ applySlashCommandItem({ editor, item, range: { from, to: from } });+ }+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);+ runItem(editor, calloutItem());expect(editor.state.doc.eq(before)).toBe(true);expect(countJsxComponents(editor.state.doc)).toBe(0);@@ -227,7 +238,7 @@ describe('component item command with a cell caret no-ops via the gate', () => {const originalRaf = globalThis.requestAnimationFrame;globalThis.requestAnimationFrame = (() => 0) as typeof globalThis.requestAnimationFrame;try {- calloutItem().command(editor);+ runItem(editor, calloutItem());expect(countJsxComponents(editor.state.doc)).toBe(1);} finally {globalThis.requestAnimationFrame = originalRaf;diff --git a/packages/app/src/editor/slash-command/component-items.test.ts b/packages/app/src/editor/slash-command/component-items.test.tsindex 47036cd36..aa7f1305f 100644--- a/packages/app/src/editor/slash-command/component-items.test.ts+++ b/packages/app/src/editor/slash-command/component-items.test.ts@@ -331,21 +331,22 @@ describe('getInlineComponentItems — inline-atom slash entries', () => {}) as typeof globalThis.requestAnimationFrame;try {- const editor = {+ const state = { selection: { from: 1 } };+ const ctx = {// No markIdentity plugin in this mock → getState() returns undefined,// so the command inserts the chip then returns before scheduling rAF.- state: { selection: { from: 1 } },+ state,+ editor: { state },+ afterCommit: (fn: () => void) => fn(),chain: () => ({- focus: () => ({- insertContent: (content: typeof insertedContent) => ({- run: () => {- insertedContent = content;- },- }),+ insertContent: (content: typeof insertedContent) => ({+ run: () => {+ insertedContent = content;+ },}),}),};- link.command(editor as never);+ link.command(ctx as never);expect(insertedContent?.type).toBe('text');expect(insertedContent?.text).toBe('link');expect(insertedContent?.marks).toEqual([{ type: 'link', attrs: { href: '' } }]);@@ -381,15 +382,16 @@ describe('getInlineComponentItems — inline-atom slash entries', () => {}) as typeof globalThis.requestAnimationFrame;try {- const editor = {- state: { selection: { from: 1 } },+ const state = { selection: { from: 1 } };+ const ctx = {+ state,+ editor: { state },+ afterCommit: (fn: () => void) => fn(),chain: () => ({- focus: () => ({- insertContent: () => ({ run: () => {} }),- }),+ insertContent: () => ({ run: () => {} }),}),};- link.command(editor as never);+ link.command(ctx as never);// findLinkMarkIdAt resolved 'm7' and the command flagged it for// auto-edit — consume confirms the flag is present (and drains it).@@ -413,7 +415,7 @@ describe('getInlineComponentItems — inline-atom slash entries', () => {let chainFocusCalled = false;let inserted = false;let insertedValue: string | undefined;- const editor = {+ const ctx = {chain: () => ({focus: () => {chainFocusCalled = true;@@ -436,7 +438,7 @@ describe('getInlineComponentItems — inline-atom slash entries', () => {};const tag = getInlineComponentItems().find((item) => item.name === 'component-Tag');if (!tag) throw new Error('Tag entry missing');- tag.command(editor as never);+ tag.command(ctx as never);expect(inserted).toBe(true);expect(insertedValue).toBe('');// Pin the no-leading-focus invariant: the slash command must NOTdiff --git a/packages/app/src/editor/slash-command/component-items.tsx b/packages/app/src/editor/slash-command/component-items.tsxindex e14ff5281..7b0a2c4eb 100644--- a/packages/app/src/editor/slash-command/component-items.tsx+++ b/packages/app/src/editor/slash-command/component-items.tsx@@ -29,7 +29,7 @@ import { getInteractionLayer } from '../interaction-layer-host';import { resolveIcon } from '../registry/icons.ts';import { getDescriptor, getRegisteredDescriptors } from '../registry/index.ts';import type { JsxComponentDescriptor } from '../registry/types.ts';-import type { SlashCommandItem } from './items';+import type { SlashCommandContext, SlashCommandItem } from './items';import imagePreview from './preview-assets/image-preview.png';import videoPreview from './preview-assets/video-preview.png';@@ -473,8 +473,10 @@ export function focusInsertedComponent(* Inserts a jsxComponent PM node with structured attrs + default props.* Post-insert: auto-opens PropPanel (editable props) or focuses children.*/-function createInsertCommand(descriptor: JsxComponentDescriptor): (editor: Editor) => void {- return (editor: Editor) => {+function createInsertCommand(+ descriptor: JsxComponentDescriptor,+): (ctx: SlashCommandContext) => void {+ return ({ chain, state, editor, afterCommit }: SlashCommandContext) => {// Snapshot existing matching jsxComponent node references. ProseMirror// preserves node identity for nodes unchanged by a transaction, so the// matching node in the new doc whose reference is NOT in this set is@@ -488,7 +490,7 @@ function createInsertCommand(descriptor: JsxComponentDescriptor): (editor: Edito// a NodeSelection target — and the consumer's consumeAutoOpen(getPos())// keys off the boundary position regardless.const beforeRefs = new WeakSet<object>();- editor.state.doc.descendants((node) => {+ state.doc.descendants((node) => {if (node.type.name === 'jsxComponent' && node.attrs.componentName === descriptor.name) {beforeRefs.add(node);}@@ -513,22 +515,24 @@ function createInsertCommand(descriptor: JsxComponentDescriptor): (editor: Editotab2Attrs.props = { ...(tab2Attrs.props as Record<string, unknown>), label: 'Tab 2' };(inserted as Record<string, unknown>).content = [tab1, tab2];}- editor.chain().focus().insertContent(inserted).run();+ chain().insertContent(inserted).run();- let insertPos = -1;- editor.state.doc.descendants((node, pos) => {- if (insertPos >= 0) return false;- if (- node.type.name === 'jsxComponent' &&- node.attrs.componentName === descriptor.name &&- !beforeRefs.has(node)- ) {- insertPos = pos;- }- });+ afterCommit(() => {+ let insertPos = -1;+ editor.state.doc.descendants((node, pos) => {+ if (insertPos >= 0) return false;+ if (+ node.type.name === 'jsxComponent' &&+ node.attrs.componentName === descriptor.name &&+ !beforeRefs.has(node)+ ) {+ insertPos = pos;+ }+ });- if (insertPos < 0) return;- focusInsertedComponent(editor, insertPos, descriptor);+ if (insertPos < 0) return;+ focusInsertedComponent(editor, insertPos, descriptor);+ });};}@@ -647,8 +651,12 @@ export function getComponentItems(): SlashCommandItem[] {* The picker's `accept` attribute is set to all-types (matching `File`'s* descriptor `accept`) so the OS dialog shows every file. The uploaded* asset is inserted at the cursor's current position.+ *+ * The insert happens asynchronously, after the user picks a file, so there+ * is nothing to contribute to the slash-command transaction — the item takes+ * the editor and leaves `chain` untouched.*/-function openFilePickerAndUpload(editor: Editor): void {+function openFilePickerAndUpload({ editor }: SlashCommandContext): void {const input = document.createElement('input');input.type = 'file';input.accept = '*/*';@@ -733,11 +741,9 @@ export function getInlineComponentItems(): SlashCommandItem[] {</p>),},- command: (editor: Editor) => {- const insertPos = editor.state.selection.from;- editor- .chain()- .focus()+ command: ({ chain, state, editor, afterCommit }) => {+ const insertPos = state.selection.from;+ chain().insertContent({type: 'text',text: 'link',@@ -745,11 +751,16 @@ export function getInlineComponentItems(): SlashCommandItem[] {}).run();- const markId = findMarkIdAt(editor.state, insertPos, 'link');- if (!markId) return;- setPendingLinkEdit(markId);- requestAnimationFrame(() => {- getInteractionLayer(editor).setActiveNode(markId);+ // Mark ids are assigned by the mark-identity plugin's+ // `appendTransaction`, so the id only exists once the insert has+ // been committed and that plugin has run.+ afterCommit(() => {+ const markId = findMarkIdAt(editor.state, insertPos, 'link');+ if (!markId) return;+ setPendingLinkEdit(markId);+ requestAnimationFrame(() => {+ getInteractionLayer(editor).setActiveNode(markId);+ });});},},@@ -777,15 +788,15 @@ export function getInlineComponentItems(): SlashCommandItem[] {</p>),},- command: (editor: Editor) => {- // Insert an empty `tag` atom WITHOUT a leading `chain().focus()`.+ command: ({ chain }) => {+ // Insert an empty `tag` atom WITHOUT a leading `focus()`.// The NodeView's mount effect (deferred via rAF) pulls focus// into the placeholder's inline input on the next frame; an// explicit editor-focus here would race with that and leave// the cursor past the atom instead. Insertion proceeds even// without the explicit focus because PM's selection is still// valid from the slash command's own match range.- editor.chain().insertTag('').run();+ chain().insertTag('').run();},},];diff --git a/packages/app/src/editor/slash-command/embed-starter-items.test.ts b/packages/app/src/editor/slash-command/embed-starter-items.test.tsindex 6279bfc89..502db0a0d 100644--- a/packages/app/src/editor/slash-command/embed-starter-items.test.ts+++ b/packages/app/src/editor/slash-command/embed-starter-items.test.ts@@ -9,9 +9,9 @@*/import { PREVIEW_EMBED_STARTERS } from '@inkeep/open-knowledge-core';-import type { Editor } from '@tiptap/react';import { describe, expect, test } from 'vitest';import { getEmbedStarterItems } from './embed-starter-items';+import type { SlashCommandContext } from './items';interface InsertedNode {type: string;@@ -19,11 +19,10 @@ interface InsertedNode {content: Array<{ type: string; text: string }>;}-/** Minimal editor double that captures the `insertContent` payload. */-function makeEditor(): { editor: Editor; getInserted: () => InsertedNode | undefined } {+/** Minimal command-context double that captures the `insertContent` payload. */+function makeContext(): { ctx: SlashCommandContext; getInserted: () => InsertedNode | undefined } {let inserted: InsertedNode | undefined;const chain = {- focus: () => chain,insertContent: (node: InsertedNode) => {inserted = node;return chain;@@ -31,7 +30,7 @@ function makeEditor(): { editor: Editor; getInserted: () => InsertedNode | undefrun: () => true,};return {- editor: { chain: () => chain } as unknown as Editor,+ ctx: { chain: () => chain } as unknown as SlashCommandContext,getInserted: () => inserted,};}@@ -58,8 +57,8 @@ describe('getEmbedStarterItems', () => {test('every command inserts a code block that opens in HTML preview mode', () => {for (const item of getEmbedStarterItems()) {- const { editor, getInserted } = makeEditor();- item.command(editor);+ const { ctx, getInserted } = makeContext();+ item.command(ctx);const node = getInserted();expect(node?.type).toBe('codeBlock');expect(node?.attrs).toEqual({ language: 'html', meta: 'preview' });@@ -74,8 +73,8 @@ describe('getEmbedStarterItems', () => {const items = getEmbedStarterItems();for (const starter of PREVIEW_EMBED_STARTERS) {const item = items.find((i) => i.name === `embed-starter-${starter.id}`);- const { editor, getInserted } = makeEditor();- item?.command(editor);+ const { ctx, getInserted } = makeContext();+ item?.command(ctx);expect(getInserted()?.content[0]?.text).toBe(starter.html);}});@@ -83,8 +82,8 @@ describe('getEmbedStarterItems', () => {test('blank-HTML inserts a seeded Hello-world body so the preview shows something on first paint', () => {const blank = getEmbedStarterItems().find((i) => i.name === 'embed-starter-html');expect(blank).toBeDefined();- const { editor, getInserted } = makeEditor();- blank?.command(editor);+ const { ctx, getInserted } = makeContext();+ blank?.command(ctx);const text = getInserted()?.content[0]?.text ?? '';expect(text).toContain('Hello, world!');// The seed nudges the author toward editing — without it the iframediff --git a/packages/app/src/editor/slash-command/embed-starter-items.tsx b/packages/app/src/editor/slash-command/embed-starter-items.tsxindex 8ff1a8d53..156f61392 100644--- a/packages/app/src/editor/slash-command/embed-starter-items.tsx+++ b/packages/app/src/editor/slash-command/embed-starter-items.tsx@@ -26,10 +26,9 @@import { PREVIEW_EMBED_STARTERS, type PreviewEmbedStarter } from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';import { Trans } from '@lingui/react/macro';-import type { Editor } from '@tiptap/react';import { BarChart3, Code, LayoutGrid, Shapes, SlidersHorizontal } from 'lucide-react';import type { ReactNode } from 'react';-import type { SlashCommandItem } from './items';+import type { SlashCommandContext, SlashCommandItem } from './items';/*** Insert an `html preview` code block at the current selection. Single@@ -37,10 +36,8 @@ import type { SlashCommandItem } from './items';* themed starters both call through here so the (codeBlock + language=html* + meta=preview) shape stays in one place.*/-function insertHtmlPreview(editor: Editor, html: string): void {- editor- .chain()- .focus()+function insertHtmlPreview(chain: SlashCommandContext['chain'], html: string): void {+ chain().insertContent({type: 'codeBlock',attrs: { language: 'html', meta: 'preview' },@@ -163,7 +160,7 @@ function getBlankHtmlEmbedItem(): SlashCommandItem {category: 'embed',aliases: ['html', 'embed', 'preview', 'iframe', 'sandbox', 'web', 'snippet'],description: t`Sandboxed HTML embed — write HTML, see the rendered preview live.`,- command: (editor: Editor) => insertHtmlPreview(editor, BLANK_HTML_BODY),+ command: ({ chain }) => insertHtmlPreview(chain, BLANK_HTML_BODY),preview: {description: t`Custom HTML with a live preview pane (sandboxed iframe).`,// Hand-built browser-pane mockup matching the `Embed` jsx component's@@ -207,7 +204,7 @@ export function getEmbedStarterItems(): SlashCommandItem[] {label: starter.title,icon: ui.icon,category: 'embed',- command: (editor: Editor) => insertHtmlPreview(editor, starter.html),+ command: ({ chain }) => insertHtmlPreview(chain, starter.html),aliases: ui.aliases,description: starter.description,preview: {diff --git a/packages/app/src/editor/slash-command/items.test.ts b/packages/app/src/editor/slash-command/items.test.tsindex dc3c11220..fb21ecee0 100644--- a/packages/app/src/editor/slash-command/items.test.ts+++ b/packages/app/src/editor/slash-command/items.test.ts@@ -1,5 +1,11 @@-import { describe, expect, test } from 'vitest';-import { filterItems, getSlashCommandItems, type SlashCommandItem } from './items';+import { afterEach, describe, expect, test } from 'vitest';+import { _resetPendingAutoOpenForTest, consumeAutoOpen } from './component-items';+import {+ filterItems,+ getSlashCommandItems,+ type SlashCommandContext,+ type SlashCommandItem,+} from './items';describe('filterItems', () => {test('empty query returns all provided items', () => {@@ -108,3 +114,95 @@ describe('built-in slash command items', () => {expect(items.some((i) => i.aliases?.includes('img'))).toBe(false);});});++describe('Inline Math item composes into the slash-command transaction', () => {+ afterEach(() => {+ _resetPendingAutoOpenForTest();+ });++ function inlineMathItem(): SlashCommandItem {+ const item = getSlashCommandItems().find((i) => i.name === 'inlineMath');+ if (!item) throw new Error('Inline Math slash item missing');+ return item;+ }++ /**+ * Context double standing in for what `applySlashCommandItem` passes: a+ * chain that only records (a real one would append steps to the handler's+ * transaction), the pre-insert selection, and a manually drained+ * `afterCommit` queue so the split between in-transaction and post-commit+ * work is observable.+ */+ function makeContext(caret: number): {+ ctx: SlashCommandContext;+ getInsertedFormula: () => string | undefined;+ getSelectedPositions: () => number[];+ drainDeferred: () => void;+ } {+ let insertedFormula: string | undefined;+ const selectedPositions: number[] = [];+ const deferred: Array<() => void> = [];+ const chain = {+ insertMathInline: (formula: string) => {+ insertedFormula = formula;+ return chain;+ },+ run: () => true,+ };+ const ctx = {+ chain: () => chain,+ state: { selection: { from: caret } },+ editor: {+ commands: {+ setNodeSelection: (pos: number) => {+ selectedPositions.push(pos);+ return true;+ },+ },+ },+ afterCommit: (fn: () => void) => deferred.push(fn),+ } as unknown as SlashCommandContext;+ return {+ ctx,+ getInsertedFormula: () => insertedFormula,+ getSelectedPositions: () => selectedPositions,+ drainDeferred: () => {+ for (const fn of deferred) fn();+ },+ };+ }++ test('the insert lands on the passed chain and the selection move waits for the commit', () => {+ const caret = 12;+ const { ctx, getInsertedFormula, getSelectedPositions, drainDeferred } = makeContext(caret);++ const rafQueue: FrameRequestCallback[] = [];+ const originalRaf = globalThis.requestAnimationFrame;+ globalThis.requestAnimationFrame = ((fn: FrameRequestCallback) => {+ rafQueue.push(fn);+ return rafQueue.length;+ }) as typeof globalThis.requestAnimationFrame;++ try {+ inlineMathItem().command(ctx);++ // The atom insert is the item's only contribution to the transaction.+ expect(getInsertedFormula()).toBe('');+ // Nothing post-insert may run inside the chain: at that point the+ // insert has not been applied to the editor, so a NodeSelection on the+ // atom would target a position that does not exist yet.+ expect(rafQueue).toHaveLength(0);+ expect(consumeAutoOpen(caret)).toBe(false);++ drainDeferred();++ // Once committed, the auto-open handshake runs against the real editor.+ expect(consumeAutoOpen(caret)).toBe(true);+ expect(rafQueue).toHaveLength(1);+ rafQueue[0]?.(0);+ expect(getSelectedPositions()).toEqual([caret]);+ } finally {+ globalThis.requestAnimationFrame = originalRaf;+ }+ });+});diff --git a/packages/app/src/editor/slash-command/items.tsx b/packages/app/src/editor/slash-command/items.tsxindex 614c5930a..7dc6311b9 100644--- a/packages/app/src/editor/slash-command/items.tsx+++ b/packages/app/src/editor/slash-command/items.tsx@@ -5,7 +5,8 @@ import {} from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';import { Trans } from '@lingui/react/macro';-import type { Editor } from '@tiptap/react';+import type { EditorState } from '@tiptap/pm/state';+import type { ChainedCommands, Editor } from '@tiptap/react';import {Code2,Heading1,@@ -23,6 +24,53 @@ import {import type { ReactNode } from 'react';import { setPendingAutoOpen } from './component-items';+/**+ * What an item's `command` receives when the slash menu runs it.+ *+ * The trigger-range delete and the item's insert must land as ONE+ * transaction. If they land as two, a transaction dispatched re-entrantly+ * during the delete's own dispatch (a plugin `appendTransaction`, a view+ * update, or the collab binding reacting to the delete) can move the+ * selection onto an adjacent selectable node, and the insert then replaces+ * that node instead of inserting a new one — the user's existing content+ * silently vanishes.+ *+ * So an item must build its steps on `chain()` and read pre-insert document+ * state from `state`, never from `editor.chain()` / `editor.state`: the+ * former dispatches a second transaction, the latter is the stale+ * pre-deleteRange document.+ *+ * Caveat on "one transaction": an item whose insert triggers a plugin+ * `appendTransaction` (mark identity, autolinking) still produces a follow-on+ * transaction from that plugin. The contract is that the item contributes no+ * dispatch of its own, not that the editor sees exactly one transaction for+ * every item.+ */+export interface SlashCommandContext {+ /**+ * Builds the item's insert. Non-dispatching — its `.run()` commits nothing+ * on its own; the steps join the handler's single transaction.+ */+ chain: () => ChainedCommands;++ /**+ * Chainable state: the document AFTER the trigger-range delete and BEFORE+ * the item's own steps. This is what pre-insert reads (positions, sibling+ * scans) must be computed against.+ */+ state: EditorState;++ /** For non-transactional needs: plugin state, side-channel setters, DOM. */+ editor: Editor;++ /**+ * Schedules work to run once the transaction has committed, against the+ * live `editor.state`. Post-insert node lookups and selection moves belong+ * here — inside the chain the insert has not been applied to the editor yet.+ */+ afterCommit: (fn: () => void) => void;+}+/*** A slash command menu item.*@@ -48,11 +96,12 @@ export interface SlashCommandItem {category: string;/**- * Command to execute when the item is selected. The extension deletes- * the trigger range (`/query`) before calling this, so commands can- * directly insert or toggle content without worrying about cleanup.+ * Command to execute when the item is selected. The extension deletes the+ * trigger range (`/query`) before calling this, so commands can directly+ * insert or toggle content without worrying about cleanup — but they must+ * build on `ctx.chain()` so the delete and the insert stay atomic.*/- command: (editor: Editor) => void;+ command: (ctx: SlashCommandContext) => void;/** Alternative search terms (e.g., `['h1']` for "Heading 1") */aliases?: string[];@@ -97,7 +146,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {label: t`Heading 1`,icon: Heading1,category: 'basic',- command: (editor) => editor.chain().focus().toggleHeading({ level: 1 }).run(),+ command: ({ chain }) => chain().toggleHeading({ level: 1 }).run(),aliases: ['h1'],preview: {description: t`Big section heading.`,@@ -113,7 +162,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {label: t`Heading 2`,icon: Heading2,category: 'basic',- command: (editor) => editor.chain().focus().toggleHeading({ level: 2 }).run(),+ command: ({ chain }) => chain().toggleHeading({ level: 2 }).run(),aliases: ['h2'],preview: {description: t`Medium section heading.`,@@ -129,7 +178,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {label: t`Heading 3`,icon: Heading3,category: 'basic',- command: (editor) => editor.chain().focus().toggleHeading({ level: 3 }).run(),+ command: ({ chain }) => chain().toggleHeading({ level: 3 }).run(),aliases: ['h3'],preview: {description: t`Small section heading.`,@@ -145,7 +194,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {label: t`Bullet List`,icon: List,category: 'basic',- command: (editor) => editor.chain().focus().toggleBulletList().run(),+ command: ({ chain }) => chain().toggleBulletList().run(),aliases: ['ul', 'unordered'],preview: {description: t`Unordered list of items.`,@@ -166,7 +215,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {label: t`Ordered List`,icon: ListOrdered,category: 'basic',- command: (editor) => editor.chain().focus().toggleOrderedList().run(),+ command: ({ chain }) => chain().toggleOrderedList().run(),aliases: ['ol', 'numbered'],preview: {description: t`Numbered list of items.`,@@ -187,7 +236,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {label: t`Task List`,icon: ListTodo,category: 'basic',- command: (editor) => editor.chain().focus().toggleTaskList().run(),+ command: ({ chain }) => chain().toggleTaskList().run(),aliases: ['todo', 'checklist', 'checkbox'],preview: {description: t`Checklist with checkboxes.`,@@ -214,7 +263,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {label: t`Quote`,icon: Quote,category: 'basic',- command: (editor) => editor.chain().focus().toggleBlockquote().run(),+ command: ({ chain }) => chain().toggleBlockquote().run(),aliases: ['quote'],preview: {description: t`Indented blockquote for citations.`,@@ -236,7 +285,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {// schema default — the y-tiptap bridge would otherwise migrate// parsed-from-disk bare fences. See `extensions/code-block.ts`'s// top-of-file comment for the bridge mechanics.- command: (editor) => editor.chain().focus().toggleCodeBlock({ language: 'js' }).run(),+ command: ({ chain }) => chain().toggleCodeBlock({ language: 'js' }).run(),aliases: ['code', 'fence'],preview: {description: t`Fenced code block with monospace text.`,@@ -253,8 +302,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {label: t`Table`,icon: Table2,category: 'insert',- command: (editor) =>- editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),+ command: ({ chain }) => chain().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),aliases: ['grid'],preview: {description: t`Grid of rows and columns with a header row.`,@@ -291,7 +339,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {label: t`Separator`,icon: Minus,category: 'insert',- command: (editor) => editor.chain().focus().setHorizontalRule().run(),+ command: ({ chain }) => chain().setHorizontalRule().run(),aliases: ['hr', 'divider', 'rule'],preview: {description: t`Horizontal rule that divides sections.`,@@ -322,7 +370,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {// wrong direction.icon: Superscript,category: 'insert',- command: (editor) => {+ command: ({ chain, state }) => {// Identifier allocation: max existing integer identifier + 1.// Shared with the bubble-menu Footnote entry (see// `bubble-menu/FootnoteBubbleButton.tsx`) — both surfaces collect@@ -330,7 +378,7 @@ export function getSlashCommandItems(): SlashCommandItem[] {// pick the next ID via the same `nextFootnoteIdentifier` rule, so// they produce the same auto-numbering sequence. Non-integer// existing IDs (e.g. `[^note]`) are ignored.- const next = nextFootnoteIdentifier(collectFootnoteIdentifiers(editor.state.doc));+ const next = nextFootnoteIdentifier(collectFootnoteIdentifiers(state.doc));// Single chain so a single Ctrl+Z undoes both insertions atomically.// Targeting: insert AFTER any existing `footnoteDefinition` blocks// via the shared helper. Without this, each `/footnote` invocation@@ -340,10 +388,8 @@ export function getSlashCommandItems(): SlashCommandItem[] {// the serialized markdown. The reference is an inline atom// (nodeSize = 1), so step 2 shifts the helper's pre-chain anchor// by +1.- const insertAt = findFootnoteDefinitionInsertPos(editor.state.doc) + 1;- editor- .chain()- .focus()+ const insertAt = findFootnoteDefinitionInsertPos(state.doc) + 1;+ chain().insertFootnoteReference(next).insertContentAt(insertAt, {type: 'footnoteDefinition',@@ -391,12 +437,14 @@ export function getSlashCommandItems(): SlashCommandItem[] {label: t`Inline Math`,icon: Sigma,category: 'insert',- command: (editor) => {- const insertPos = editor.state.selection.from;- editor.chain().focus().insertMathInline('').run();- setPendingAutoOpen(insertPos);- requestAnimationFrame(() => {- editor.commands.setNodeSelection(insertPos);+ command: ({ chain, state, editor, afterCommit }) => {+ const insertPos = state.selection.from;+ chain().insertMathInline('').run();+ afterCommit(() => {+ setPendingAutoOpen(insertPos);+ requestAnimationFrame(() => {+ editor.commands.setNodeSelection(insertPos);+ });});},aliases: ['math', 'latex', 'equation', 'formula', 'katex', 'inlinemath'],diff --git a/packages/app/tests/lint-plugins/no-split-suggestion-dispatch.test.ts b/packages/app/tests/lint-plugins/no-split-suggestion-dispatch.test.tsnew file mode 100644index 000000000..82846a9a7--- /dev/null+++ b/packages/app/tests/lint-plugins/no-split-suggestion-dispatch.test.ts@@ -0,0 +1,62 @@+/**+ * One-transaction suggestion insertion enforcement — `no-split-suggestion-dispatch`+ * GritQL plugin (precedent #58).+ *+ * Plugin: `biome-plugins/no-split-suggestion-dispatch.grit`+ * Fixture: `biome-plugins/__fixtures__/no-split-suggestion-dispatch.fixture.tsx`+ *+ * The fixture pairs 3 positive cases (bare trigger-delete chain dispatch with+ * and without `.focus()`, plus the immediately-dispatching `commands.deleteRange`+ * form — all inside a `Suggestion({ ... })` config) with 4 negative cases (the+ * atomic single chain, the `.command()` boundary composition, delegation to+ * `applySlashCommandItem`, and a delete-only chain outside any Suggestion+ * config). The test asserts the plugin fires exactly 3 times.+ *+ * Exact equality (`toBe(3)`) catches drift in both directions:+ * - false-negative: a weakened pattern drops below 3 → fails+ * - false-positive: a widened pattern fires on a negative case → above 3 → fails+ *+ * The runtime complement lives in `suggestion-atomicity.dom.test.tsx` and+ * `slash-command-atomicity.dom.test.tsx`, which drive the real surfaces through+ * a real Enter and assert exactly one doc-changing transaction — the lint rule+ * catches the bare-delete dispatch shape statically; the dom tests catch any+ * second dispatch the lint can't see (e.g. inside a delegated item).+ */++import { spawnSync } from 'node:child_process';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';+import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper';++// __dirname → packages/app/tests/lint-plugins/. Repo root is 4 levels up.+const REPO_ROOT = join(__dirname, '..', '..', '..', '..');+const FIXTURE_REL = 'biome-plugins/__fixtures__/no-split-suggestion-dispatch.fixture.tsx';++describe('no-split-suggestion-dispatch GritQL plugin', () => {+ test('fires on exactly 3 positive cases (and on no negative case)', () => {+ const result = spawnSync('pnpm', ['exec', 'biome', 'check', FIXTURE_REL], {+ cwd: REPO_ROOT,+ encoding: 'utf-8',+ });+ expect(result.status).not.toBe(0);+ const output = `${result.stdout}\n${result.stderr}`;+ const fires = (output.match(/Split suggestion dispatch/g) ?? []).length;+ expect(fires).toBe(3);+ // Diagnostic message names the fix (action verb-phrase substring).+ expect(output).toContain('Compose the delete and the insert into ONE chain');+ // Diagnostic message appends a docs URL — generic URL regex + anchor+ // substring. The anchor check keeps the regex from being vacuously+ // satisfied by an unrelated URL biome might surface elsewhere.+ expect(output).toMatch(/https?:\/\/[^\s]+/);+ expect(output).toContain('biome-plugins/README.md#no-split-suggestion-dispatchgrit');+ });++ test('plugin is registered in biome.jsonc at root plugins (workspace-wide)', () => {+ // Root registration is load-bearing: the pattern self-scopes to+ // `Suggestion({ ... })` call sites, and a FUTURE suggestion surface in any+ // package must be covered without a biome.jsonc edit.+ const config = readBiomeConfig(REPO_ROOT);+ const plugins = config.plugins ?? [];+ expect(plugins).toContain('./biome-plugins/no-split-suggestion-dispatch.grit');+ });+});diff --git a/packages/app/tests/stress/slash-command-auto-open.e2e.ts b/packages/app/tests/stress/slash-command-auto-open.e2e.tsindex 8d859e88d..635e532b2 100644--- a/packages/app/tests/stress/slash-command-auto-open.e2e.ts+++ b/packages/app/tests/stress/slash-command-auto-open.e2e.ts@@ -16,13 +16,13 @@* surfaces.*/-import { expect, test, waitForActiveProviderSynced, waitForSlashMenuFirstOption } from './_helpers';--// ----------------------------------------------------------------------------// Helpers-// -----------------------------------------------------------------------------const PROP_PANEL_TIMEOUT = 1_000;+import {+ expect,+ focusEditor,+ test,+ waitForActiveProviderSynced,+ waitForSlashMenuFirstOption,+} from './_helpers';// ---------------------------------------------------------------------------// Tests@@ -45,7 +45,7 @@ test('SLASH-AUTOOPEN-IMG: slash-inserting Image auto-opens its PropPanel', async// `[data-prop-panel]` is rendered only when the Popover's `open` state is true,// which the consumer toggles via the auto-open useEffect in JsxComponentView.- await expect(page.locator('[data-prop-panel]')).toBeVisible({ timeout: PROP_PANEL_TIMEOUT });+ await expect(page.locator('[data-prop-panel]')).toBeVisible();});test('SLASH-AUTOOPEN-VIDEO: slash-inserting Video auto-opens its PropPanel', async ({@@ -63,7 +63,7 @@ test('SLASH-AUTOOPEN-VIDEO: slash-inserting Video auto-opens its PropPanel', asyawait waitForSlashMenuFirstOption(page, 'video');await page.keyboard.press('Enter');- await expect(page.locator('[data-prop-panel]')).toBeVisible({ timeout: PROP_PANEL_TIMEOUT });+ await expect(page.locator('[data-prop-panel]')).toBeVisible();});test('SLASH-AUTOOPEN-CALLOUT: slash-inserting Callout auto-opens its PropPanel', async ({@@ -84,7 +84,7 @@ test('SLASH-AUTOOPEN-CALLOUT: slash-inserting Callout auto-opens its PropPanel',await waitForSlashMenuFirstOption(page, 'callout');await page.keyboard.press('Enter');- await expect(page.locator('[data-prop-panel]')).toBeVisible({ timeout: PROP_PANEL_TIMEOUT });+ await expect(page.locator('[data-prop-panel]')).toBeVisible();});test('SLASH-AUTOOPEN-IMG-MULTI: slash-inserting Image with a prior Image auto-opens the NEW one', async ({@@ -105,37 +105,86 @@ test('SLASH-AUTOOPEN-IMG-MULTI: slash-inserting Image with a prior Image auto-op// Wait for the seeded img NodeView to mount.await expect(page.locator('[data-jsx-component]')).toHaveCount(1);- // Land cursor at end of doc (in the trailing empty paragraph).+ // Land cursor at end of doc (in the trailing empty paragraph). Typing the+ // trigger before the caret has actually moved there types '/image' at a stale+ // position, where the suggestion never matches — prove the move landed first.await page.click('.ProseMirror:not(.composer-prosemirror)');await page.keyboard.press('ControlOrMeta+End');+ await focusEditor(page);+ await expect+ .poll(() =>+ page.evaluate(() => {+ interface WindowEditor {+ state: {+ doc: { childCount: number };+ selection: { $from: { depth: number; index: (depth: number) => number } };+ };+ }+ const ed = (window as unknown as { __activeEditor?: WindowEditor }).__activeEditor;+ if (!ed) return false;+ const { $from } = ed.state.selection;+ return $from.depth >= 1 && $from.index(0) === ed.state.doc.childCount - 1;+ }),+ )+ .toBe(true);await page.keyboard.type('/image');await waitForSlashMenuFirstOption(page, 'image');await page.keyboard.press('Enter');await expect(page.locator('[data-jsx-component]')).toHaveCount(2);- await expect(page.locator('[data-prop-panel]')).toBeVisible({ timeout: PROP_PANEL_TIMEOUT });+ // The insert must ADD a node, never replace the one already in the document.+ // The count above catches destruction only by arithmetic; this names it.+ await expect+ .poll(+ () =>+ page.evaluate(() => {+ interface PmNode {+ type: { name: string };+ attrs: { componentName?: string; props?: Record<string, unknown> };+ }+ interface WindowEditor {+ state: { doc: { descendants: (cb: (n: PmNode) => boolean | undefined) => void } };+ }+ const ed = (window as unknown as { __activeEditor?: WindowEditor }).__activeEditor;+ if (!ed) return null;+ const srcs: unknown[] = [];+ ed.state.doc.descendants((n) => {+ if (n.type.name === 'jsxComponent' && n.attrs.componentName === 'img') {+ srcs.push(n.attrs.props?.src ?? null);+ }+ return true;+ });+ return srcs;+ }),+ {+ message:+ 'the pre-existing image node was destroyed by the slash insert (its src is no longer in the document)',+ },+ )+ .toContain('prior-marker.png');+ await expect(page.locator('[data-prop-panel]')).toBeVisible();// The selected (and thus auto-opened) node must be the NEW img — not the// pre-existing one. Read the PM NodeSelection's node attrs directly: the// new img has default props (empty src), the prior has 'prior-marker.png'.- const selectedSrc = await page.evaluate(() => {- const ed = (window as unknown as { __activeEditor?: { state: { selection: unknown } } })- .__activeEditor;- if (!ed) return null;- const sel = ed.state.selection as {- node?: { attrs: { componentName?: string; props?: Record<string, unknown> } };- };- if (!sel.node) return null;- return {- componentName: sel.node.attrs.componentName,- src: sel.node.attrs.props?.src ?? null,- };- });-- expect(selectedSrc).not.toBeNull();- expect(selectedSrc?.componentName).toBe('img');- expect(selectedSrc?.src).not.toBe('prior-marker.png');+ await expect+ .poll(() =>+ page.evaluate(() => {+ const ed = (window as unknown as { __activeEditor?: { state: { selection: unknown } } })+ .__activeEditor;+ if (!ed) return null;+ const sel = ed.state.selection as {+ node?: { attrs: { componentName?: string; props?: Record<string, unknown> } };+ };+ if (!sel.node) return null;+ return {+ componentName: sel.node.attrs.componentName,+ isPriorImage: sel.node.attrs.props?.src === 'prior-marker.png',+ };+ }),+ )+ .toEqual({ componentName: 'img', isPriorImage: false });});test('PLACEHOLDER-RENDERS-FRESH: slash-inserted img shows placeholder + auto-opens panel', async ({@@ -157,10 +206,8 @@ test('PLACEHOLDER-RENDERS-FRESH: slash-inserted img shows placeholder + auto-opeawait waitForSlashMenuFirstOption(page, 'image');await page.keyboard.press('Enter');- await expect(page.locator('[data-descriptor-placeholder]')).toBeVisible({- timeout: PROP_PANEL_TIMEOUT,- });- await expect(page.locator('[data-prop-panel]')).toBeVisible({ timeout: PROP_PANEL_TIMEOUT });+ await expect(page.locator('[data-descriptor-placeholder]')).toBeVisible();+ await expect(page.locator('[data-prop-panel]')).toBeVisible();});test('PLACEHOLDER-CLICK-OPENS-PANEL: clicking placeholder NodeSelects + reopens PropPanel', async ({@@ -181,26 +228,31 @@ test('PLACEHOLDER-CLICK-OPENS-PANEL: clicking placeholder NodeSelects + reopensawait waitForSlashMenuFirstOption(page, 'image');await page.keyboard.press('Enter');- await expect(page.locator('[data-prop-panel]')).toBeVisible({ timeout: PROP_PANEL_TIMEOUT });+ await expect(page.locator('[data-prop-panel]')).toBeVisible();await page.keyboard.press('Escape');- await expect(page.locator('[data-prop-panel]')).toBeHidden({ timeout: PROP_PANEL_TIMEOUT });+ await expect(page.locator('[data-prop-panel]')).toBeHidden();await expect(page.locator('[data-descriptor-placeholder]')).toBeVisible();await page.locator('[data-descriptor-placeholder]').click();- await expect(page.locator('[data-prop-panel]')).toBeVisible({ timeout: PROP_PANEL_TIMEOUT });-- // Verify PM selection is now a NodeSelection on the img specifically.- const selected = await page.evaluate(() => {- const ed = (window as unknown as { __activeEditor?: { state: { selection: unknown } } })- .__activeEditor;- if (!ed) return null;- const sel = ed.state.selection as {- node?: { attrs: { componentName?: string } };- };- return sel.node?.attrs.componentName ?? null;- });- expect(selected).toBe('img');+ await expect(page.locator('[data-prop-panel]')).toBeVisible();++ // Verify PM selection is now a NodeSelection on the img specifically. The+ // click handler's setNodeSelection and the popover open are separate+ // dispatches, so the panel being visible does not prove the selection landed.+ await expect+ .poll(() =>+ page.evaluate(() => {+ const ed = (window as unknown as { __activeEditor?: { state: { selection: unknown } } })+ .__activeEditor;+ if (!ed) return null;+ const sel = ed.state.selection as {+ node?: { attrs: { componentName?: string } };+ };+ return sel.node?.attrs.componentName ?? null;+ }),+ )+ .toBe('img');});test('PLACEHOLDER-FILL-DISMISSES: filling src dismisses placeholder, real img renders', async ({@@ -221,9 +273,7 @@ test('PLACEHOLDER-FILL-DISMISSES: filling src dismisses placeholder, real img reawait waitForSlashMenuFirstOption(page, 'image');await page.keyboard.press('Enter');- await expect(page.locator('[data-descriptor-placeholder]')).toBeVisible({- timeout: PROP_PANEL_TIMEOUT,- });+ await expect(page.locator('[data-descriptor-placeholder]')).toBeVisible();// The autofocused input is the src field (htmlImgProps[0] has autoFocus: true).const autofocusedInput = page.locator('[data-prop-autofocus]');await expect(autofocusedInput).toBeVisible();@@ -261,9 +311,7 @@ test('PLACEHOLDER-CONTAINER-EXCLUDED: slash-inserting /callout does NOT show pla// Wait for the Callout NodeView to mount before asserting placeholder absence// — without this, the assertion races the slash-insert dispatch.- await expect(page.locator('[data-jsx-component][data-component-type="callout"]')).toBeVisible({- timeout: PROP_PANEL_TIMEOUT,- });+ await expect(page.locator('[data-jsx-component][data-component-type="callout"]')).toBeVisible();await expect(page.locator('[data-descriptor-placeholder]')).toHaveCount(0);});@@ -287,9 +335,7 @@ test('PLACEHOLDER-CHROME-VISIBLE: chrome bar (gear, delete) renders alongside thawait waitForSlashMenuFirstOption(page, 'image');await page.keyboard.press('Enter');- await expect(page.locator('[data-descriptor-placeholder]')).toBeVisible({- timeout: PROP_PANEL_TIMEOUT,- });+ await expect(page.locator('[data-descriptor-placeholder]')).toBeVisible();// Close the auto-opened panel so the chrome bar's gear button isn't hidden by// the popover overlay during the assertion.@@ -325,7 +371,7 @@ test('PLACEHOLDER-DOM-SHAPE: placeholder is a div (not button) and is full-widthawait page.keyboard.press('Enter');const placeholder = page.locator('[data-descriptor-placeholder]');- await expect(placeholder).toBeVisible({ timeout: PROP_PANEL_TIMEOUT });+ await expect(placeholder).toBeVisible();const shape = await placeholder.evaluate((el) => {const wrapper = el.closest('[data-jsx-component]');@@ -376,7 +422,7 @@ test('PLACEHOLDER-CLOSE-ADVANCES-CARET: PM selection lands past the image afterawait waitForSlashMenuFirstOption(page, 'image');await page.keyboard.press('Enter');- await expect(page.locator('[data-prop-panel]')).toBeVisible({ timeout: PROP_PANEL_TIMEOUT });+ await expect(page.locator('[data-prop-panel]')).toBeVisible();// Fill src so the placeholder dismisses to a real <img> element (the path// that handleOpenChange's caret-advance is calibrated for).@@ -386,47 +432,47 @@ test('PLACEHOLDER-CLOSE-ADVANCES-CARET: PM selection lands past the image after// Close the panel via Escape — Radix dispatches onOpenChange(false), our// handleOpenChange schedules the rAF caret-advance.await page.keyboard.press('Escape');- await expect(page.locator('[data-prop-panel]')).toBeHidden({ timeout: PROP_PANEL_TIMEOUT });-- // Wait for the rAF + PM transaction to commit, then read selection state.- // Two frames of slack absorbs Radix's own focus-restore animation frame- // plus our handler's deferred dispatch.- await page.evaluate(- () => new Promise<void>((r) => requestAnimationFrame(() => requestAnimationFrame(() => r()))),- );-- const result = await page.evaluate(() => {- interface PmNode {- type: { name: string };- nodeSize: number;- attrs: { componentName?: string };- }- interface WindowEditor {- state: {- selection: { from: number };- doc: PmNode & {- descendants: (cb: (n: PmNode, p: number) => boolean | undefined) => void;+ await expect(page.locator('[data-prop-panel]')).toBeHidden();++ // Poll the state the deferred dispatch produces rather than counting frames:+ // Radix's focus restore and our handler's rAF both have to land, and how many+ // frames that takes is a property of the machine, not of the contract. The+ // caret must end up AT or PAST the img's end boundary, never inside the img's+ // range [imgPos, imgEnd).+ await expect+ .poll(() =>+ page.evaluate(() => {+ interface PmNode {+ type: { name: string };+ nodeSize: number;+ attrs: { componentName?: string };+ }+ interface WindowEditor {+ state: {+ selection: { from: number };+ doc: PmNode & {+ descendants: (cb: (n: PmNode, p: number) => boolean | undefined) => void;+ };+ };+ }+ const ed = (window as unknown as { __activeEditor?: WindowEditor }).__activeEditor;+ if (!ed) return null;+ let imgPos = -1;+ let imgSize = 0;+ ed.state.doc.descendants((n, p) => {+ if (n.type.name === 'jsxComponent' && n.attrs.componentName === 'img' && imgPos === -1) {+ imgPos = p;+ imgSize = n.nodeSize;+ }+ return true;+ });+ return {+ imgFound: imgPos >= 0,+ caretPastImgEnd: imgPos >= 0 && ed.state.selection.from >= imgPos + imgSize,};- };- }- const ed = (window as unknown as { __activeEditor?: WindowEditor }).__activeEditor;- if (!ed) return null;- let imgPos = -1;- let imgSize = 0;- ed.state.doc.descendants((n, p) => {- if (n.type.name === 'jsxComponent' && n.attrs.componentName === 'img' && imgPos === -1) {- imgPos = p;- imgSize = n.nodeSize;- }- });- return { selectionFrom: ed.state.selection.from, imgPos, imgEnd: imgPos + imgSize };- });-- expect(result).not.toBeNull();- expect(result?.imgPos).toBeGreaterThanOrEqual(0);- // Caret should be AT or PAST the img's end boundary — not inside the- // img's range [imgPos, imgEnd).- expect(result?.selectionFrom).toBeGreaterThanOrEqual(result?.imgEnd ?? 0);+ }),+ )+ .toEqual({ imgFound: true, caretPastImgEnd: true });});test('PLACEHOLDER-CLOSE-RETURNS-DOM-FOCUS: typing after Escape lands keystrokes in the editor', async ({@@ -448,19 +494,27 @@ test('PLACEHOLDER-CLOSE-RETURNS-DOM-FOCUS: typing after Escape lands keystrokesawait waitForSlashMenuFirstOption(page, 'image');await page.keyboard.press('Enter');- await expect(page.locator('[data-prop-panel]')).toBeVisible({ timeout: PROP_PANEL_TIMEOUT });+ await expect(page.locator('[data-prop-panel]')).toBeVisible();const srcInput = page.locator('[data-prop-panel] input#prop-src');await srcInput.fill('https://example.com/test.png');await page.keyboard.press('Escape');- await expect(page.locator('[data-prop-panel]')).toBeHidden({ timeout: PROP_PANEL_TIMEOUT });-- // Two rAFs settle the onCloseAutoFocus setTimeout(0) tick (editor.view.focus())- // + the handleOpenChange rAF (PM selection advance).- await page.evaluate(- () => new Promise<void>((r) => requestAnimationFrame(() => requestAnimationFrame(() => r()))),- );+ await expect(page.locator('[data-prop-panel]')).toBeHidden();++ // The sentinel can only land in the editor once DOM focus is back on the+ // contenteditable, which the onCloseAutoFocus setTimeout(0) tick restores.+ // Poll for that state instead of assuming it fits in a fixed frame budget —+ // typing early would send the keystrokes to document.body and lose them.+ await expect+ .poll(() =>+ page.evaluate(() => {+ const ed = (window as unknown as { __activeEditor?: { view: { dom: HTMLElement } } })+ .__activeEditor;+ return ed ? ed.view.dom.contains(document.activeElement) : false;+ }),+ )+ .toBe(true);// Sentinel chosen long enough that partial keystrokes are detectable, with// characters PM won't intercept as a shortcut.@@ -473,40 +527,40 @@ test('PLACEHOLDER-CLOSE-RETURNS-DOM-FOCUS: typing after Escape lands keystrokes// Asserting both pins the contract: typing is routed to the editor AND the// PM caret position is past the img so the text doesn't insert in the wrong// location.- const result = await page.evaluate((sentinel) => {- interface PmNode {- type: { name: string };- nodeSize: number;- attrs: { componentName?: string };- }- interface WindowEditor {- state: {- doc: PmNode & {- textContent: string;- descendants: (cb: (n: PmNode, p: number) => boolean | undefined) => void;+ await expect+ .poll(() =>+ page.evaluate((sentinel) => {+ interface PmNode {+ type: { name: string };+ nodeSize: number;+ attrs: { componentName?: string };+ }+ interface WindowEditor {+ state: {+ doc: PmNode & {+ textContent: string;+ descendants: (cb: (n: PmNode, p: number) => boolean | undefined) => void;+ };+ };+ view: { dom: HTMLElement };+ }+ const ed = (window as unknown as { __activeEditor?: WindowEditor }).__activeEditor;+ if (!ed) return null;+ const focusInEditor = ed.view.dom.contains(document.activeElement);+ const docText = ed.state.doc.textContent;+ let imgPos = -1;+ ed.state.doc.descendants((n, p) => {+ if (n.type.name === 'jsxComponent' && n.attrs.componentName === 'img' && imgPos === -1) {+ imgPos = p;+ }+ return true;+ });+ return {+ focusInEditor,+ sentinelInDoc: docText.includes(sentinel),+ imgFound: imgPos >= 0,};- };- view: { dom: HTMLElement };- }- const ed = (window as unknown as { __activeEditor?: WindowEditor }).__activeEditor;- if (!ed) return null;- const focusInEditor = ed.view.dom.contains(document.activeElement);- const docText = ed.state.doc.textContent;- let imgPos = -1;- ed.state.doc.descendants((n, p) => {- if (n.type.name === 'jsxComponent' && n.attrs.componentName === 'img' && imgPos === -1) {- imgPos = p;- }- });- return {- focusInEditor,- sentinelInDoc: docText.includes(sentinel),- imgFound: imgPos >= 0,- };- }, SENTINEL);-- expect(result).not.toBeNull();- expect(result?.imgFound).toBe(true);- expect(result?.focusInEditor).toBe(true);- expect(result?.sentinelInDoc).toBe(true);+ }, SENTINEL),+ )+ .toEqual({ focusInEditor: true, sentinelInDoc: true, imgFound: true });});