Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): reconcile Pattern-D pre-warm walk-to-mount gap (#1750)
Nick Gomeza353305a59e8
diff --git a/.changeset/pattern-d-walk-currency.md b/.changeset/pattern-d-walk-currency.mdnew file mode 100644index 000000000..cd4f790ff--- /dev/null+++ b/.changeset/pattern-d-walk-currency.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Fix silent loss of collaborative edits that land while a document editor is still opening. The editor's pre-warm mount path captures document state at construct time, and a remote or agent edit arriving in the brief window before the editor view binds was never reconciled — the editor showed stale content, and the first click or keystroke could republish that stale copy over the shared document, erasing the missed edit for every peer and on disk. A walk-currency check now rides every pre-warm mount: it watches the document fragment from construction, and if anything changed before the view bound, it invalidates the pre-warm and re-derives the editor content from current state. Quiet mounts keep the full pre-warm fast path.diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsxindex 71693267f..8a57ce4a6 100644--- a/packages/app/src/editor/TiptapEditor.tsx+++ b/packages/app/src/editor/TiptapEditor.tsx@@ -53,6 +53,7 @@ import {import { TableCellHandles } from './table-controls/TableCellHandles';import { attachTypingBurstDetector } from './typing-burst-detector';import { getEditorView } from './utils/get-editor-view';+import { walkCurrencyExtension } from './walk-currency-extension';function renderCursor(user: Record<string, string>): HTMLElement {const cursor = document.createElement('span');@@ -121,8 +122,35 @@ interface BuildEditorOptionsArgs {onWedged?: (detail: WedgeDetail) => void;}-function buildExtensionList(args: BuildEditorOptionsArgs): AnyExtension[] {+interface PrewarmBoundCollaboration {+ collaboration: AnyExtension;+ guard: AnyExtension[];+}++function buildPrewarmBoundCollaboration(+ provider: HocuspocusProvider,+ prebuiltMapping: ProsemirrorMapping | undefined,+): PrewarmBoundCollaboration {+ if (!prebuiltMapping) {+ return { collaboration: Collaboration.configure({ document: provider.document }), guard: [] };+ }+ return {+ collaboration: Collaboration.configure({+ document: provider.document,+ ySyncOptions: { mapping: prebuiltMapping },+ }),+ guard: [+ walkCurrencyExtension({+ fragment: provider.document.getXmlFragment('default'),+ docName: provider.configuration.name ?? '',+ }),+ ],+ };+}++export function buildExtensionList(args: BuildEditorOptionsArgs): AnyExtension[] {const { provider, placeholder, prebuiltMapping, onWedged } = args;+ const { collaboration, guard } = buildPrewarmBoundCollaboration(provider, prebuiltMapping);return [...sharedExtensions.map((ext) => {if (ext.name === 'link' || ext.name === 'wikiLink' || ext.name === 'jsxComponent') {@@ -134,10 +162,7 @@ function buildExtensionList(args: BuildEditorOptionsArgs): AnyExtension[] {placeholder: placeholder ?? "Type '/' for commands",showOnlyCurrent: true,}),- Collaboration.configure({- document: provider.document,- ...(prebuiltMapping ? { ySyncOptions: { mapping: prebuiltMapping } } : {}),- }),+ collaboration,Extension.create({name: 'imageUploadDecoration',addProseMirrorPlugins() {@@ -172,6 +197,7 @@ function buildExtensionList(args: BuildEditorOptionsArgs): AnyExtension[] {];},}),+ ...guard,];}diff --git a/packages/app/src/editor/pattern-d-walk-currency.test.ts b/packages/app/src/editor/pattern-d-walk-currency.test.tsnew file mode 100644index 000000000..831d105d4--- /dev/null+++ b/packages/app/src/editor/pattern-d-walk-currency.test.ts@@ -0,0 +1,186 @@+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { HocuspocusProvider } from '@hocuspocus/provider';+import { Editor } from '@tiptap/core';+import { TextSelection } from '@tiptap/pm/state';+import { Awareness } from 'y-protocols/awareness';+import * as Y from 'yjs';+import { __resetCacheForTests, evictTiptapEditor } from './editor-cache';+import { __resetMountPromiseCache, mountTiptapEditorPromise } from './mount-promise';+import { buildPatternDConstructorOptions } from './TiptapEditor';+import {+ appendToFirstParagraph,+ applyRemoteEdit,+ createGapOrderingRecorder,+ fakeClipboard,+ flushMicrotasksAndTimers,+ type GapOrderingRecorder,+ insertParagraphAt,+ installDomGlobals,+ seedFragmentParagraph,+ viewCreationSignalExtension,+} from './walk-currency-test-harness';++let restoreDomGlobals: (() => void) | null = null;++beforeAll(() => {+ restoreDomGlobals = installDomGlobals();+});++afterAll(() => {+ restoreDomGlobals?.();+ restoreDomGlobals = null;+});++function dispatchSelectionOnly(editor: Editor): void {+ const { state } = editor.view;+ editor.view.dispatch(state.tr.setSelection(TextSelection.create(state.doc, 1)));+}++interface GapMountHarness {+ docName: string;+ ydoc: Y.Doc;+ fragment: Y.XmlFragment;+ awareness: Awareness;+ provider: HocuspocusProvider;+ /** Resolves with the mounted editor; the gap edit lands in the+ * construct→mount window of this very mount cycle. */+ mountWithGapEdit: () => Promise<Editor>;+ /** Ordinals proving the gap edit landed BEFORE the EditorView was created+ * (i.e. truly inside the construct→mount gap, not post-mount). */+ ordering: GapOrderingRecorder;+ cleanup: () => void;+}++function createGapMountHarness(gapEdit: (fragment: Y.XmlFragment) => void): GapMountHarness {+ const docName = `walk-currency-${randomUUID()}`;+ const ydoc = new Y.Doc();+ seedFragmentParagraph(ydoc, 'hello world');+ const fragment = ydoc.getXmlFragment('default');+ const awareness = new Awareness(ydoc);+ const provider = {+ document: ydoc,+ configuration: { name: docName },+ awareness,+ } as unknown as HocuspocusProvider;++ const ordering = createGapOrderingRecorder();++ const construct = () => {+ const ctorStart = performance.now();+ const options = buildPatternDConstructorOptions({+ provider,+ clipboard: fakeClipboard,+ ctorStart,+ });+ options.extensions = [...(options.extensions ?? []), viewCreationSignalExtension(ordering)];+ const editor = new Editor(options);+ queueMicrotask(() => {+ applyRemoteEdit(ydoc, gapEdit);+ ordering.recordGapEdit();+ });+ return {+ editor,+ ydoc,+ ytext: ydoc.getText('source'),+ provider,+ };+ };++ const mountWithGapEdit = async (): Promise<Editor> => {+ const entry = await mountTiptapEditorPromise({+ docName,+ mountId: randomUUID(),+ construct,+ sizeStats: { viewCount: 0, bytes: ydoc.getText('source').length },+ });+ await flushMicrotasksAndTimers();+ return entry.editor;+ };++ const cleanup = () => {+ evictTiptapEditor(docName);+ awareness.destroy();+ ydoc.destroy();+ };++ return { docName, ydoc, fragment, awareness, provider, mountWithGapEdit, ordering, cleanup };+}++function expectGapEditLandedBeforeMount(ordering: GapOrderingRecorder): void {+ expect(ordering.gapEditOrdinal).not.toBeNull();+ expect(ordering.viewCreatedOrdinal).not.toBeNull();+ expect(ordering.gapEditOrdinal).toBeLessThan(ordering.viewCreatedOrdinal as number);+}++const appendGapEdit = (frag: Y.XmlFragment): void => appendToFirstParagraph(frag, ' GAPEDIT');++afterEach(() => {+ __resetMountPromiseCache();+ __resetCacheForTests();+});++describe('Pattern D walk currency (construct→mount gap)', () => {+ test('a remote update landing between construct and mount survives into the mounted PM doc', async () => {+ const harness = createGapMountHarness(appendGapEdit);+ try {+ const editor = await harness.mountWithGapEdit();++ expectGapEditLandedBeforeMount(harness.ordering);++ const yXml = harness.fragment.toString();+ const pmText = editor.state.doc.textContent;++ expect(pmText).toContain('GAPEDIT');+ expect(pmText).toContain('hello world');+ expect(yXml).toContain('GAPEDIT');+ expect(yXml).toContain('hello world');+ } finally {+ harness.cleanup();+ }+ });++ test('a post-mount selection-only transaction does not erase the gap update from the CRDT', async () => {+ const harness = createGapMountHarness(appendGapEdit);+ try {+ const editor = await harness.mountWithGapEdit();++ expectGapEditLandedBeforeMount(harness.ordering);++ dispatchSelectionOnly(editor);+ await flushMicrotasksAndTimers();++ const yXml = harness.fragment.toString();+ expect(yXml).toContain('GAPEDIT');+ expect(yXml).toContain('hello world');+ expect(editor.state.doc.textContent).toContain('GAPEDIT');+ expect(editor.state.doc.textContent).toContain('hello world');+ } finally {+ harness.cleanup();+ }+ });++ test('a remote paragraph inserted in the construct→mount gap survives mount and the first post-mount transaction', async () => {+ const harness = createGapMountHarness((frag) => insertParagraphAt(frag, 1, 'GAPPARAGRAPH'));+ try {+ const editor = await harness.mountWithGapEdit();++ expectGapEditLandedBeforeMount(harness.ordering);++ expect(editor.state.doc.textContent).toContain('GAPPARAGRAPH');+ expect(editor.state.doc.textContent).toContain('hello world');+ expect(harness.fragment.toString()).toContain('GAPPARAGRAPH');++ dispatchSelectionOnly(editor);+ await flushMicrotasksAndTimers();++ const yXml = harness.fragment.toString();+ expect(yXml).toContain('GAPPARAGRAPH');+ expect(yXml).toContain('hello world');+ expect(editor.state.doc.textContent).toContain('GAPPARAGRAPH');+ expect(editor.state.doc.textContent).toContain('hello world');+ } finally {+ harness.cleanup();+ }+ });+});diff --git a/packages/app/src/editor/walk-currency-extension.test.ts b/packages/app/src/editor/walk-currency-extension.test.tsnew file mode 100644index 000000000..79508198a--- /dev/null+++ b/packages/app/src/editor/walk-currency-extension.test.ts@@ -0,0 +1,319 @@+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { HocuspocusProvider } from '@hocuspocus/provider';+import { Editor, Extension, getSchema } from '@tiptap/core';+import { Plugin, type PluginKey } from '@tiptap/pm/state';+import { initProseMirrorDoc, ySyncPluginKey } from '@tiptap/y-tiptap';+import { Awareness } from 'y-protocols/awareness';+import * as Y from 'yjs';+import { __resetCacheForTests, evictTiptapEditor } from './editor-cache';+import { sharedExtensions } from './extensions/shared';+import {+ __resetMountPromiseCache,+ invalidateMountPromise,+ mountTiptapEditorPromise,+} from './mount-promise';+import { buildExtensionList, buildPatternDConstructorOptions } from './TiptapEditor';+import { walkCurrencyExtension } from './walk-currency-extension';+import {+ appendToFirstParagraph,+ fakeClipboard,+ flushMicrotasksAndTimers,+ installDomGlobals,+ seedFragmentParagraph,+} from './walk-currency-test-harness';++let restoreDomGlobals: (() => void) | null = null;++beforeAll(() => {+ restoreDomGlobals = installDomGlobals();+});++afterAll(() => {+ restoreDomGlobals?.();+ restoreDomGlobals = null;+});++afterEach(() => {+ __resetMountPromiseCache();+ __resetCacheForTests();+});++function makeProvider(docName: string): {+ ydoc: Y.Doc;+ fragment: Y.XmlFragment;+ awareness: Awareness;+ provider: HocuspocusProvider;+ cleanup: () => void;+} {+ const ydoc = new Y.Doc();+ seedFragmentParagraph(ydoc, 'hello world');+ const fragment = ydoc.getXmlFragment('default');+ const awareness = new Awareness(ydoc);+ const provider = {+ document: ydoc,+ configuration: { name: docName },+ awareness,+ } as unknown as HocuspocusProvider;+ return {+ ydoc,+ fragment,+ awareness,+ provider,+ cleanup: () => {+ awareness.destroy();+ ydoc.destroy();+ },+ };+}++/** yjs stores deep observers as a filterable handler list; its length is the+ * only observable signal that a never-mounted editor's observer was+ * unhooked (the dirty flag is closure-private and nothing consumes it after+ * destroy). Internal to yjs — re-verify on a yjs bump. */+function deepObserverCount(fragment: Y.XmlFragment): number {+ return (fragment as unknown as { _dEH: { l: unknown[] } })._dEH.l.length;+}++/** Mirrors the vendored ySyncPlugin's state contract enough for the disarm+ * arms: a plugin registered under the real `ySyncPluginKey` whose state+ * carries (or omits) a binding — the same surface the extension reads via+ * `ySyncPluginKey.getState(...)` in production. */+function createYSyncStandIn(binding?: Record<string, unknown>): Plugin {+ return new Plugin({+ key: ySyncPluginKey as unknown as PluginKey,+ state: {+ init: () => ({+ snapshot: null,+ prevSnapshot: null,+ isChangeOrigin: false,+ ...(binding ? { binding } : {}),+ }),+ apply: (_tr, pluginState) => pluginState,+ },+ });+}++function captureWarnings<T>(fn: () => T): { result: T; warnings: string[] } {+ const warnings: string[] = [];+ const originalWarn = console.warn;+ console.warn = (...args: unknown[]) => {+ warnings.push(String(args[0]));+ };+ try {+ return { result: fn(), warnings };+ } finally {+ console.warn = originalWarn;+ }+}++describe('disarm branch', () => {+ /** Build a stale editor whose ySync state is supplied by a stand-in (no+ * real Collaboration — its real binding would occupy the seam under+ * test), then mount it. */+ function mountStaleWithStandIn(docName: string, binding?: Record<string, unknown>): Editor {+ const ydoc = new Y.Doc();+ seedFragmentParagraph(ydoc, 'hello world');+ const fragment = ydoc.getXmlFragment('default');+ const editor = new Editor({+ element: null,+ extensions: [+ ...sharedExtensions,+ Extension.create({+ name: 'ySyncStandIn',+ addProseMirrorPlugins() {+ return [createYSyncStandIn(binding)];+ },+ }),+ walkCurrencyExtension({ fragment, docName }),+ ],+ });+ ydoc.transact(() => appendToFirstParagraph(fragment, ' GAPEDIT'));+ editor.mount(document.createElement('div'));+ return editor;+ }++ test('a missing ySync binding disarms loudly, not silently, and leaves the editor usable', () => {+ const docName = `disarm-no-binding-${randomUUID()}`;+ const { result: editor, warnings } = captureWarnings(() => mountStaleWithStandIn(docName));+ try {+ expect(+ warnings.some((w) => w.includes('no ySync binding') && w.includes('stale pre-warm')),+ ).toBe(true);+ const before = editor.state.doc.textContent;+ editor.view.dispatch(editor.state.tr.insertText('x', 1));+ expect(editor.state.doc.textContent).not.toBe(before);+ } finally {+ editor.destroy();+ }+ });++ test('a binding without _forceRerender disarms loudly, not silently, and leaves the editor usable', () => {+ const docName = `disarm-no-rerender-${randomUUID()}`;+ const { result: editor, warnings } = captureWarnings(() => mountStaleWithStandIn(docName, {}));+ try {+ expect(+ warnings.some((w) => w.includes('no _forceRerender') && w.includes('stale pre-warm')),+ ).toBe(true);+ const before = editor.state.doc.textContent;+ editor.view.dispatch(editor.state.tr.insertText('x', 1));+ expect(editor.state.doc.textContent).not.toBe(before);+ } finally {+ editor.destroy();+ }+ });+});++describe('never-mounted cleanup', () => {+ test('invalidating the mount during the yield window destroys the pre-mount editor and unhooks the observer', async () => {+ const docName = `never-mounted-${randomUUID()}`;+ const { fragment, provider, cleanup } = makeProvider(docName);+ try {+ const baseline = deepObserverCount(fragment);+ let constructedEditor: Editor | null = null;++ const construct = () => {+ const ctorStart = performance.now();+ const editor = new Editor(+ buildPatternDConstructorOptions({ provider, clipboard: fakeClipboard, ctorStart }),+ );+ constructedEditor = editor;+ queueMicrotask(() => {+ invalidateMountPromise(docName);+ });+ return {+ editor,+ ydoc: provider.document,+ ytext: provider.document.getText('source'),+ provider,+ };+ };++ void mountTiptapEditorPromise({+ docName,+ mountId: randomUUID(),+ construct,+ sizeStats: { viewCount: 0, bytes: provider.document.getText('source').length },+ });+ await flushMicrotasksAndTimers();++ const editor = constructedEditor as unknown as Editor | null;+ expect(editor).not.toBeNull();+ expect((editor as Editor).isDestroyed).toBe(true);+ expect(deepObserverCount(fragment)).toBe(baseline);++ provider.document.transact(() => appendToFirstParagraph(fragment, ' AFTER-DESTROY'));+ await flushMicrotasksAndTimers();+ expect(deepObserverCount(fragment)).toBe(baseline);+ } finally {+ cleanup();+ }+ });+});++describe('non-stale fast path', () => {+ test('a quiet construct→mount gap triggers no rerender and the prebuilt mapping survives into the binding', async () => {+ const docName = `quiet-gap-${randomUUID()}`;+ const { fragment, provider, cleanup } = makeProvider(docName);+ try {+ let prebuiltMapping: Map<unknown, unknown> | null = null;+ let prebuiltParagraphNode: unknown = null;+ const yParagraph = fragment.get(0);+ const rerenderTransactions: unknown[] = [];++ const construct = () => {+ const ctorStart = performance.now();+ const opts = buildPatternDConstructorOptions({+ provider,+ clipboard: fakeClipboard,+ ctorStart,+ });+ const collaboration = opts.extensions?.find((ext) => ext.name === 'collaboration') as+ | { options?: { ySyncOptions?: { mapping?: Map<unknown, unknown> } } }+ | undefined;+ prebuiltMapping = collaboration?.options?.ySyncOptions?.mapping ?? null;+ prebuiltParagraphNode = prebuiltMapping?.get(yParagraph) ?? null;+ const editor = new Editor(opts);+ editor.on('transaction', ({ transaction }) => {+ const meta = transaction.getMeta(ySyncPluginKey) as+ | { isChangeOrigin?: boolean }+ | undefined;+ if (meta?.isChangeOrigin === true) rerenderTransactions.push(meta);+ });+ return {+ editor,+ ydoc: provider.document,+ ytext: provider.document.getText('source'),+ provider,+ };+ };++ const entry = await mountTiptapEditorPromise({+ docName,+ mountId: randomUUID(),+ construct,+ sizeStats: { viewCount: 0, bytes: provider.document.getText('source').length },+ });+ await flushMicrotasksAndTimers();++ expect(rerenderTransactions).toHaveLength(0);+ const syncState = ySyncPluginKey.getState(entry.editor.state) as {+ binding?: { mapping?: Map<unknown, unknown> };+ };+ expect(prebuiltMapping).not.toBeNull();+ expect(prebuiltParagraphNode).not.toBeNull();+ expect(syncState.binding?.mapping).toBe(prebuiltMapping as unknown as Map<unknown, unknown>);+ expect((prebuiltMapping as unknown as Map<unknown, unknown>).get(yParagraph)).toBe(+ prebuiltParagraphNode,+ );+ expect(entry.editor.state.doc.textContent).toContain('hello world');+ } finally {+ evictTiptapEditor(docName);+ cleanup();+ }+ });+});++describe('wiring arms', () => {+ test('no prebuiltMapping → walk-currency extension absent from the extension list', () => {+ const { provider, cleanup } = makeProvider(`wiring-negative-${randomUUID()}`);+ try {+ const extensions = buildExtensionList({+ provider,+ clipboard: fakeClipboard,+ ctorStart: 0,+ });+ expect(extensions.some((ext) => ext.name === 'walkCurrency')).toBe(false);+ } finally {+ cleanup();+ }+ });++ test('prebuiltMapping supplied → walk-currency extension present (and in the Pattern D options)', () => {+ const { fragment, provider, cleanup } = makeProvider(`wiring-positive-${randomUUID()}`);+ try {+ const baseExtensions = buildExtensionList({+ provider,+ clipboard: fakeClipboard,+ ctorStart: 0,+ });+ const { mapping } = initProseMirrorDoc(fragment, getSchema(baseExtensions));+ const extensions = buildExtensionList({+ provider,+ clipboard: fakeClipboard,+ ctorStart: 0,+ prebuiltMapping: mapping,+ });+ expect(extensions.some((ext) => ext.name === 'walkCurrency')).toBe(true);++ const opts = buildPatternDConstructorOptions({+ provider,+ clipboard: fakeClipboard,+ ctorStart: 0,+ });+ expect(opts.extensions?.some((ext) => ext.name === 'walkCurrency')).toBe(true);+ } finally {+ cleanup();+ }+ });+});diff --git a/packages/app/src/editor/walk-currency-extension.ts b/packages/app/src/editor/walk-currency-extension.tsnew file mode 100644index 000000000..86940c479--- /dev/null+++ b/packages/app/src/editor/walk-currency-extension.ts@@ -0,0 +1,85 @@+import { Extension } from '@tiptap/core';+import { Plugin } from '@tiptap/pm/state';+import type { EditorView } from '@tiptap/pm/view';+import { ySyncPluginKey } from '@tiptap/y-tiptap';+import type * as Y from 'yjs';+import { mark } from '../lib/perf/mark';++export interface WalkCurrencyExtensionOptions {+ /** The fragment the pre-warm walk derived `content`/`mapping` from — the+ * same fragment Collaboration binds (`provider.document`, field 'default'). */+ fragment: Y.XmlFragment;+ docName: string;+}++export function walkCurrencyExtension(options: WalkCurrencyExtensionOptions): Extension {+ const { fragment, docName } = options;++ let stale = false;+ let observing = false;+ let enforced = false;++ const markStale = (): void => {+ stale = true;+ };++ const disarmWarn = (lead: string): void => {+ console.warn(+ `[walk-currency] ${lead} at view init — stale pre-warm cannot be invalidated: a remote edit that landed in the construct→mount gap will not render, and the first local transaction may silently erase it from the CRDT for every peer and disk (vendored y-tiptap contract change? re-verify y-tiptap.cjs:263-268)`,+ );+ };++ const unobserve = (): void => {+ if (!observing) return;+ observing = false;+ fragment.unobserveDeep(markStale);+ };++ const enforce = (view: EditorView): void => {+ const syncState = ySyncPluginKey.getState(view.state) as+ | { binding?: { _forceRerender?: () => void } | null }+ | null+ | undefined;+ const binding = syncState?.binding;+ if (!binding) {+ mark.count('ok/editor/walk-currency-disarmed', { docName, reason: 'no-binding' });+ disarmWarn(`no ySync binding on "${docName}"`);+ return;+ }+ if (typeof binding._forceRerender !== 'function') {+ mark.count('ok/editor/walk-currency-disarmed', { docName, reason: 'no-force-rerender' });+ disarmWarn(`ySync binding on "${docName}" exposes no _forceRerender`);+ return;+ }+ mark.count('ok/editor/pattern-d-stale-prewarm', { docName });+ binding._forceRerender();+ };++ return Extension.create({+ name: 'walkCurrency',++ onBeforeCreate() {+ fragment.observeDeep(markStale);+ observing = true;+ },++ onDestroy() {+ unobserve();+ },++ addProseMirrorPlugins() {+ return [+ new Plugin({+ view: (view) => {+ if (!enforced) {+ enforced = true;+ unobserve();+ if (stale) enforce(view);+ }+ return {};+ },+ }),+ ];+ },+ });+}diff --git a/packages/app/src/editor/walk-currency-test-harness.ts b/packages/app/src/editor/walk-currency-test-harness.tsnew file mode 100644index 000000000..938b79c1c--- /dev/null+++ b/packages/app/src/editor/walk-currency-test-harness.ts@@ -0,0 +1,155 @@+import { Extension } from '@tiptap/core';+import { Plugin } from '@tiptap/pm/state';+import { JSDOM } from 'jsdom';+import * as Y from 'yjs';+import type { buildPatternDConstructorOptions } from './TiptapEditor';++export function installDomGlobals(): () => void {+ const dom = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>', {+ url: 'http://localhost:5173',+ pretendToBeVisual: true,+ });+ const win = dom.window as unknown as Window & typeof globalThis;+ const installed: Record<string, unknown> = {+ window: win,+ document: win.document,+ HTMLElement: win.HTMLElement,+ Element: win.Element,+ Node: win.Node,+ Document: win.Document,+ DocumentFragment: win.DocumentFragment,+ Text: win.Text,+ Range: win.Range,+ DOMParser: win.DOMParser,+ MutationObserver: win.MutationObserver,+ Event: win.Event,+ CustomEvent: win.CustomEvent,+ KeyboardEvent: win.KeyboardEvent,+ MouseEvent: win.MouseEvent,+ InputEvent: win.InputEvent,+ CompositionEvent: win.CompositionEvent,+ FocusEvent: win.FocusEvent,+ getComputedStyle: win.getComputedStyle.bind(win),+ requestAnimationFrame: win.requestAnimationFrame.bind(win),+ cancelAnimationFrame: win.cancelAnimationFrame.bind(win),+ };+ const previousDescriptors = new Map<string, PropertyDescriptor | undefined>();+ const globalRecord = globalThis as unknown as Record<string, unknown>;+ for (const [key, value] of Object.entries(installed)) {+ previousDescriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));+ Object.defineProperty(globalThis, key, { value, configurable: true, writable: true });+ }+ return () => {+ for (const [key, descriptor] of previousDescriptors) {+ if (descriptor) {+ Object.defineProperty(globalThis, key, descriptor);+ } else {+ Reflect.deleteProperty(globalRecord, key);+ }+ }+ dom.window.close();+ };+}++type ClipboardArg = Parameters<typeof buildPatternDConstructorOptions>[0]['clipboard'];++export const fakeClipboard = {+ mdManager: {},+ text: () => '',+ html: { serializer: {}, setView: () => {} },+ paste: () => false,+ drop: () => false,+} as unknown as ClipboardArg;++export function seedFragmentParagraph(ydoc: Y.Doc, text: string): void {+ const fragment = ydoc.getXmlFragment('default');+ const paragraph = new Y.XmlElement('paragraph');+ paragraph.insert(0, [new Y.XmlText(text)]);+ fragment.insert(0, [paragraph]);+}++/** Any Y transaction origin other than the binding's own — in production the+ * origin is the HocuspocusProvider instance. */+const REMOTE_PROVIDER_ORIGIN = Object.freeze({ kind: 'remote-provider-stand-in' });++export function applyRemoteEdit(local: Y.Doc, mutate: (fragment: Y.XmlFragment) => void): void {+ const remote = new Y.Doc();+ Y.applyUpdate(remote, Y.encodeStateAsUpdate(local));+ remote.transact(() => {+ mutate(remote.getXmlFragment('default'));+ });+ const diff = Y.encodeStateAsUpdate(remote, Y.encodeStateVector(local));+ Y.applyUpdate(local, diff, REMOTE_PROVIDER_ORIGIN);+ remote.destroy();+}++export function appendToFirstParagraph(fragment: Y.XmlFragment, text: string): void {+ const paragraph = fragment.get(0) as Y.XmlElement;+ const xmlText = paragraph.get(0) as Y.XmlText;+ xmlText.insert(xmlText.length, text);+}++/** Insert a fresh paragraph node at `index` — the structural counterpart to+ * `appendToFirstParagraph` for gap edits that add nodes the pre-warm walk+ * never saw. */+export function insertParagraphAt(fragment: Y.XmlFragment, index: number, text: string): void {+ const paragraph = new Y.XmlElement('paragraph');+ paragraph.insert(0, [new Y.XmlText(text)]);+ fragment.insert(index, [paragraph]);+}++export async function flushMicrotasksAndTimers(): Promise<void> {+ for (let i = 0; i < 5; i += 1) {+ await Promise.resolve();+ }+ await new Promise((resolve) => setTimeout(resolve, 10));+}++export interface GapOrderingRecorder {+ recordGapEdit(): void;+ recordViewCreated(): void;+ readonly gapEditOrdinal: number | null;+ readonly viewCreatedOrdinal: number | null;+}++export function createGapOrderingRecorder(): GapOrderingRecorder {+ let counter = 0;+ let gapEditOrdinal: number | null = null;+ let viewCreatedOrdinal: number | null = null;+ return {+ recordGapEdit() {+ if (gapEditOrdinal === null) {+ counter += 1;+ gapEditOrdinal = counter;+ }+ },+ recordViewCreated() {+ if (viewCreatedOrdinal === null) {+ counter += 1;+ viewCreatedOrdinal = counter;+ }+ },+ get gapEditOrdinal() {+ return gapEditOrdinal;+ },+ get viewCreatedOrdinal() {+ return viewCreatedOrdinal;+ },+ };+}++export function viewCreationSignalExtension(record: GapOrderingRecorder): Extension {+ return Extension.create({+ name: 'viewCreationSignal',+ addProseMirrorPlugins() {+ return [+ new Plugin({+ view: () => {+ record.recordViewCreated();+ return {};+ },+ }),+ ];+ },+ });+}