Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): client binding staleness guard — stop wedged editors resurrecting stale state (PRD-6955b) (#1733)

Nick Gomez92aa19f4f7a1
diff --git a/.changeset/binding-staleness-guard.md b/.changeset/binding-staleness-guard.md
new file mode 100644
index 000000000..ab28593ab
--- /dev/null
+++ b/.changeset/binding-staleness-guard.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Fix stale-editor content resurrection (PRD-6955b). An editor whose Y→PM apply path had stopped (a "wedged" collaboration binding) could silently re-publish its frozen, minutes-old copy of a document wholesale over newer collaborative state on the next click or keystroke — erasing remote fixes. A new client-side binding staleness guard now detects the wedge the moment an external update goes unapplied, refuses to publish the stale replica (both the transaction channel and the binding's write-back seam are gated), and transparently recycles the editor so it remounts from current document state. Healthy editors are unaffected; recovery is rate-capped per document to prevent recycle loops under a persistent fault.
diff --git a/packages/app/package.json b/packages/app/package.json
index ac5565d4e..74d566ac5 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -25,7 +25,7 @@
"measure:fuzz": "bash scripts/measure-fuzz.sh",
"measure:stress": "bash scripts/measure-stress.sh",
"perf:compare": "bash scripts/perf-compare.sh",
- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/init-load-byte-stable.e2e.ts tests/stress/single-file-ephemeral.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts",
+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/init-load-byte-stable.e2e.ts tests/stress/single-file-ephemeral.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts",
"test:e2e:install-browsers": "playwright install chromium webkit firefox",
"test:visual": "playwright test --config playwright.visual.config.ts",
"test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",
diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsx
index 4cd719ed5..80896124c 100644
--- a/packages/app/src/components/EditorActivityPool.tsx
+++ b/packages/app/src/components/EditorActivityPool.tsx
@@ -681,7 +681,7 @@ function ActivityEntry({
{gate.renderVisual ? (
<div className={isSourceMode ? 'ok-mode-hidden h-full' : 'h-full'}>
<TiptapEditor
- key={`${entry.docName}-${String(isNewDoc)}`}
+ key={`${entry.docName}-${String(isNewDoc)}-${entry.poolEventId}`}
provider={entry.provider}
placeholder={editorPlaceholder}
isSourceMode={isSourceMode}
diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsx
index ae1904c84..71693267f 100644
--- a/packages/app/src/editor/TiptapEditor.tsx
+++ b/packages/app/src/editor/TiptapEditor.tsx
@@ -29,6 +29,7 @@ import { wrapExtensionsWithTiming } from '@/lib/perf/cold-mount-instrumentation'
import { useIdentity } from '../presence/identity';
import { registerEditor, unregisterEditor } from './active-editor';
import { buildAwarenessUser } from './awareness-user';
+import { bindingStalenessGuardPlugin, type WedgeDetail } from './binding-staleness-guard';
import { BubbleMenuBar } from './bubble-menu/BubbleMenuBar';
import {
createClipboardHtmlSerializer,
@@ -117,10 +118,11 @@ interface BuildEditorOptionsArgs {
clipboard: ClipboardState;
ctorStart: number;
prebuiltMapping?: ProsemirrorMapping;
+ onWedged?: (detail: WedgeDetail) => void;
}
function buildExtensionList(args: BuildEditorOptionsArgs): AnyExtension[] {
- const { provider, placeholder, prebuiltMapping } = args;
+ const { provider, placeholder, prebuiltMapping, onWedged } = args;
return [
...sharedExtensions.map((ext) => {
if (ext.name === 'link' || ext.name === 'wikiLink' || ext.name === 'jsxComponent') {
@@ -158,6 +160,18 @@ function buildExtensionList(args: BuildEditorOptionsArgs): AnyExtension[] {
];
},
}),
+ Extension.create({
+ name: 'bindingStalenessGuard',
+ addProseMirrorPlugins() {
+ return [
+ bindingStalenessGuardPlugin({
+ fragment: provider.document.getXmlFragment('default'),
+ docName: provider.configuration.name ?? '',
+ onWedged: onWedged ?? (() => {}),
+ }),
+ ];
+ },
+ }),
];
}
@@ -206,6 +220,7 @@ interface BuildPatternDConstructorOptionsArgs {
placeholder?: string;
clipboard: ClipboardState;
ctorStart: number;
+ onWedged?: (detail: WedgeDetail) => void;
}
type PatternDConstructorOptions = Partial<EditorOptions> & { element: null };
@@ -213,13 +228,20 @@ type PatternDConstructorOptions = Partial<EditorOptions> & { element: null };
export function buildPatternDConstructorOptions(
args: BuildPatternDConstructorOptionsArgs,
): PatternDConstructorOptions {
- const { provider, placeholder, clipboard, ctorStart } = args;
+ const { provider, placeholder, clipboard, ctorStart, onWedged } = args;
const baseExtensions = buildExtensionList({ provider, placeholder, clipboard, ctorStart });
const schema = getSchema(baseExtensions);
const fragment = provider.document.getXmlFragment('default');
const { doc: prebuiltDoc, mapping: prebuiltMapping } = initProseMirrorDoc(fragment, schema);
return {
- ...buildEditorOptions({ provider, placeholder, clipboard, ctorStart, prebuiltMapping }),
+ ...buildEditorOptions({
+ provider,
+ placeholder,
+ clipboard,
+ ctorStart,
+ prebuiltMapping,
+ onWedged,
+ }),
content: prebuiltDoc.toJSON(),
element: null,
};
@@ -234,7 +256,7 @@ export const TiptapEditor: FC<TiptapEditorProps> = ({
const wrapperRef = useRef<HTMLDivElement | null>(null);
const flashStateRef = useRef(INITIAL_FLASH_STATE);
const identity = useIdentity();
- const { principal, activeDocName } = useDocumentContext();
+ const { principal, activeDocName, recycleDocument } = useDocumentContext();
const docName = provider.configuration.name ?? '';
const [clipboard] = useState(buildClipboardState);
@@ -247,6 +269,10 @@ export const TiptapEditor: FC<TiptapEditorProps> = ({
placeholder,
clipboard,
ctorStart,
+ onWedged: ({ externalSeq, appliedSeq }) => {
+ mark('ok/editor/binding-wedge-recycle', { docName, externalSeq, appliedSeq });
+ recycleDocument(docName);
+ },
}),
);
return {
diff --git a/packages/app/src/editor/binding-staleness-guard.test.ts b/packages/app/src/editor/binding-staleness-guard.test.ts
new file mode 100644
index 000000000..f09cdf132
--- /dev/null
+++ b/packages/app/src/editor/binding-staleness-guard.test.ts
@@ -0,0 +1,559 @@
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { getSchema } from '@tiptap/core';
+import { EditorState, Plugin, type PluginKey, Selection } from '@tiptap/pm/state';
+import { EditorView } from '@tiptap/pm/view';
+import { ySyncPluginKey, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { JSDOM } from 'jsdom';
+import * as Y from 'yjs';
+import {
+ bindingStalenessGuardPlugin,
+ isCatchUpApply,
+ isDiverged,
+ rateCapAllows,
+} from './binding-staleness-guard';
+import { sharedExtensions } from './extensions/shared';
+
+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();
+ };
+}
+
+let restoreDomGlobals: (() => void) | null = null;
+
+beforeAll(() => {
+ restoreDomGlobals = installDomGlobals();
+});
+
+afterAll(() => {
+ restoreDomGlobals?.();
+ restoreDomGlobals = null;
+});
+
+const schema = getSchema(sharedExtensions);
+
+/** Stands in for a provider applying a remote peer's update (origin is the
+ * provider instance in production — anything other than `ySyncPluginKey`). */
+const REMOTE_PROVIDER_ORIGIN = Object.freeze({ kind: 'remote-provider-stand-in' });
+
+function setFragmentParagraph(fragment: Y.XmlFragment, text: string): void {
+ fragment.delete(0, fragment.length);
+ const paragraph = new Y.XmlElement('paragraph');
+ paragraph.insert(0, [new Y.XmlText(text)]);
+ fragment.insert(0, [paragraph]);
+}
+
+type YSyncStandInState = Record<string, unknown>;
+
+/** Mirrors the vendored ySyncPlugin's state contract (meta merged into plugin
+ * state; `isChangeOrigin` true only on the transaction that carries it) so
+ * the guard reads `snapshot`/`prevSnapshot` through the production surface
+ * (`ySyncPluginKey.getState(...)`). */
+function createYSyncStandIn(binding?: HarnessOptions['binding']): Plugin<YSyncStandInState> {
+ return new Plugin<YSyncStandInState>({
+ key: ySyncPluginKey as unknown as PluginKey<YSyncStandInState>,
+ state: {
+ init: () => ({
+ snapshot: null,
+ prevSnapshot: null,
+ isChangeOrigin: false,
+ ...(binding ? { binding } : {}),
+ }),
+ apply: (tr, pluginState) => {
+ const change = tr.getMeta(ySyncPluginKey) as YSyncStandInState | undefined;
+ const next: YSyncStandInState =
+ change === undefined ? { ...pluginState } : { ...pluginState, ...change };
+ next.isChangeOrigin = change !== undefined && !!change.isChangeOrigin;
+ return next;
+ },
+ },
+ });
+}
+
+/** Simulates the binding's `_typeChanged` apply: full re-render of the PM doc
+ * from the CURRENT fragment, tagged with the meta the vendored binding
+ * attaches. */
+function dispatchYSyncRerender(view: EditorView, fragment: Y.XmlFragment): void {
+ const next = yXmlFragmentToProseMirrorRootNode(fragment, view.state.schema);
+ const tr = view.state.tr.replaceWith(0, view.state.doc.content.size, next.content);
+ tr.setMeta(ySyncPluginKey, { isChangeOrigin: true, isUndoRedoOperation: false });
+ view.dispatch(tr);
+}
+
+/** Simulates the binding's `unrenderSnapshot` apply: full re-render from the
+ * current fragment, tagged `{ snapshot: null, prevSnapshot: null }` (note:
+ * NO `isChangeOrigin`). */
+function dispatchSnapshotExitRerender(view: EditorView, fragment: Y.XmlFragment): void {
+ const next = yXmlFragmentToProseMirrorRootNode(fragment, view.state.schema);
+ const tr = view.state.tr.replaceWith(0, view.state.doc.content.size, next.content);
+ tr.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null });
+ view.dispatch(tr);
+}
+
+/** Resolves strictly after all pending microtasks (a macrotask hop), so the
+ * guard's deferred wedge check has definitely run. */
+function flushDetection(): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+interface HarnessOptions {
+ docName?: string;
+ seedText?: string;
+ /** 'none' (default) = wedged: external Y transactions are never followed by
+ * a y-sync apply. The other two attach a healthy simulated binding that
+ * synchronously dispatches the re-render apply inside the same observer
+ * cascade — registered before or after the guard's own fragment observer
+ * (the guard must be order-independent). */
+ simulatedBinding?: 'none' | 'registered-before-guard' | 'registered-after-guard';
+ /** Forwarded to the guard's onWedged after the harness records the call —
+ * lets tests inject a throwing recovery path. */
+ onWedged?: (detail: { externalSeq: number; appliedSeq: number }) => void;
+ /** When set, the y-sync stand-in exposes this object as `binding` on its
+ * plugin state (mirroring the vendored plugin, whose init state carries
+ * the ProsemirrorBinding instance), so the guard wraps its
+ * `_prosemirrorChanged` at view init. */
+ binding?: { _prosemirrorChanged?: (doc: unknown) => void };
+}
+
+interface GuardHarness {
+ docName: string;
+ ydoc: Y.Doc;
+ fragment: Y.XmlFragment;
+ view: EditorView;
+ wedgedCalls: Array<{ externalSeq: number; appliedSeq: number }>;
+ /** Replace the fragment's content in a Y transaction with a non-binding
+ * origin (a remote-peer update arriving through the provider). */
+ remoteReplace(text: string): void;
+ /** Dispatch a local typing transaction (no y-sync meta); returns whether it
+ * landed (doc changed) or was filtered. */
+ localType(char?: string): boolean;
+ destroy(): void;
+}
+
+const activeHarnesses: GuardHarness[] = [];
+
+afterEach(() => {
+ for (const harness of activeHarnesses.splice(0)) {
+ harness.destroy();
+ }
+});
+
+function createHarness(options: HarnessOptions = {}): GuardHarness {
+ const docName = options.docName ?? `staleness-guard-${randomUUID()}`;
+ const simulatedBinding = options.simulatedBinding ?? 'none';
+ const ydoc = new Y.Doc();
+ const fragment = ydoc.getXmlFragment('default');
+ ydoc.transact(() => setFragmentParagraph(fragment, options.seedText ?? 'seed'));
+
+ let viewRef: EditorView | null = null;
+ const bindingHandler = (_events: unknown, transaction: Y.Transaction): void => {
+ if (transaction.origin === ySyncPluginKey) return;
+ if (viewRef) dispatchYSyncRerender(viewRef, fragment);
+ };
+ if (simulatedBinding === 'registered-before-guard') {
+ fragment.observeDeep(bindingHandler);
+ }
+
+ const wedgedCalls: Array<{ externalSeq: number; appliedSeq: number }> = [];
+ const state = EditorState.create({
+ schema,
+ doc: yXmlFragmentToProseMirrorRootNode(fragment, schema),
+ plugins: [
+ createYSyncStandIn(options.binding),
+ bindingStalenessGuardPlugin({
+ fragment,
+ docName,
+ onWedged: (detail: { externalSeq: number; appliedSeq: number }) => {
+ wedgedCalls.push(detail);
+ options.onWedged?.(detail);
+ },
+ }),
+ ],
+ });
+ const view = new EditorView(document.createElement('div'), { state });
+ viewRef = view;
+
+ if (simulatedBinding === 'registered-after-guard') {
+ fragment.observeDeep(bindingHandler);
+ }
+
+ const harness: GuardHarness = {
+ docName,
+ ydoc,
+ fragment,
+ view,
+ wedgedCalls,
+ remoteReplace(text: string): void {
+ ydoc.transact(() => setFragmentParagraph(fragment, text), REMOTE_PROVIDER_ORIGIN);
+ },
+ localType(char = 'x'): boolean {
+ const before = view.state.doc.textContent;
+ view.dispatch(view.state.tr.insertText(char));
+ return view.state.doc.textContent !== before;
+ },
+ destroy(): void {
+ if (simulatedBinding !== 'none') {
+ fragment.unobserveDeep(bindingHandler);
+ }
+ view.destroy();
+ ydoc.destroy();
+ },
+ };
+ activeHarnesses.push(harness);
+ return harness;
+}
+
+describe('pure helpers', () => {
+ test('isDiverged is true exactly when external is ahead of applied', () => {
+ expect(isDiverged(0, 0)).toBe(false);
+ expect(isDiverged(1, 0)).toBe(true);
+ expect(isDiverged(5, 5)).toBe(false);
+ expect(isDiverged(7, 3)).toBe(true);
+ });
+
+ test('isCatchUpApply recognizes the two full-re-render meta shapes and nothing else', () => {
+ expect(isCatchUpApply({ isChangeOrigin: true, isUndoRedoOperation: false })).toBe(true);
+ expect(isCatchUpApply({ isChangeOrigin: true })).toBe(true);
+ expect(isCatchUpApply({ snapshot: null, prevSnapshot: null })).toBe(true);
+ expect(isCatchUpApply({ snapshot: {}, prevSnapshot: {} })).toBe(false);
+ expect(isCatchUpApply(undefined)).toBe(false);
+ expect(isCatchUpApply({ isChangeOrigin: false })).toBe(false);
+ });
+
+ test('rateCapAllows permits at most 3 firings per rolling 60s window', () => {
+ const now = 1_000_000_000;
+ expect(rateCapAllows([], now)).toBe(true);
+ expect(rateCapAllows([now - 1_000, now - 2_000], now)).toBe(true);
+ expect(rateCapAllows([now - 1_000, now - 2_000, now - 3_000], now)).toBe(false);
+ expect(rateCapAllows([now - 61_000, now - 62_000, now - 63_000], now)).toBe(true);
+ expect(rateCapAllows([now - 61_000, now - 30_000, now - 20_000], now)).toBe(true);
+ expect(rateCapAllows([now - 61_000, now - 30_000, now - 20_000, now - 10_000], now)).toBe(
+ false,
+ );
+ });
+});
+
+describe('counter semantics', () => {
+ test('a wedged external burst is reported once, deferred, with the full backlog', async () => {
+ const harness = createHarness();
+ harness.remoteReplace('remote one');
+ harness.remoteReplace('remote two');
+ harness.remoteReplace('remote three');
+ expect(harness.wedgedCalls).toHaveLength(0);
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(1);
+ const detail = harness.wedgedCalls[0];
+ if (!detail) throw new Error('unreachable: length asserted above');
+ expect(detail.externalSeq - detail.appliedSeq).toBe(3);
+ expect(isDiverged(detail.externalSeq, detail.appliedSeq)).toBe(true);
+ });
+
+ test('ONE y-sync re-render apply heals a multi-update backlog (catch-up, not increment)', async () => {
+ const harness = createHarness();
+ harness.remoteReplace('remote one');
+ harness.remoteReplace('remote two');
+ harness.remoteReplace('remote three');
+ await flushDetection();
+ expect(harness.localType()).toBe(false);
+ dispatchYSyncRerender(harness.view, harness.fragment);
+ expect(harness.view.state.doc.textContent).toContain('remote three');
+ expect(harness.localType()).toBe(true);
+ });
+
+ test("the binding's own PM→Y write-back origin does not count as external", async () => {
+ const harness = createHarness();
+ harness.ydoc.transact(
+ () => setFragmentParagraph(harness.fragment, 'self write-back'),
+ ySyncPluginKey,
+ );
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(0);
+ expect(harness.localType()).toBe(true);
+ });
+
+ test('Y transactions that do not touch the fragment do not open a backlog', async () => {
+ const harness = createHarness();
+ const ytext = harness.ydoc.getText('source');
+ harness.ydoc.transact(() => {
+ ytext.insert(0, 'frontmatter edit\n');
+ }, REMOTE_PROVIDER_ORIGIN);
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(0);
+ expect(harness.localType()).toBe(true);
+ });
+});
+
+describe('publication gate', () => {
+ test('while diverged, every transaction without y-sync meta is blocked — including selection-only', async () => {
+ const harness = createHarness({ seedText: 'long enough to move a cursor' });
+ harness.remoteReplace('remote fix');
+ expect(harness.localType()).toBe(false);
+
+ const selectionBefore = harness.view.state.selection;
+ const target = Selection.atEnd(harness.view.state.doc);
+ expect(target.eq(selectionBefore)).toBe(false);
+ harness.view.dispatch(harness.view.state.tr.setSelection(target));
+ expect(harness.view.state.selection.eq(selectionBefore)).toBe(true);
+
+ await flushDetection();
+ expect(harness.localType()).toBe(false);
+ });
+
+ test('y-sync applies are admitted while diverged, and the gate reopens after catch-up', async () => {
+ const harness = createHarness();
+ harness.remoteReplace('remote fix');
+ await flushDetection();
+ expect(harness.localType()).toBe(false);
+
+ dispatchYSyncRerender(harness.view, harness.fragment);
+ expect(harness.view.state.doc.textContent).toContain('remote fix');
+
+ expect(harness.localType()).toBe(true);
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(1);
+ });
+
+ test('snapshot mode suppresses both the gate and the wedge trigger; the exit re-render realigns', async () => {
+ const harness = createHarness();
+ harness.view.dispatch(
+ harness.view.state.tr.setMeta(ySyncPluginKey, {
+ snapshot: Y.snapshot(harness.ydoc),
+ prevSnapshot: Y.snapshot(harness.ydoc),
+ }),
+ );
+
+ harness.remoteReplace('remote while snapshotted');
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(0);
+ expect(harness.localType()).toBe(true);
+
+ dispatchSnapshotExitRerender(harness.view, harness.fragment);
+ expect(harness.view.state.doc.textContent).toContain('remote while snapshotted');
+ expect(harness.localType()).toBe(true);
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(0);
+ });
+});
+
+describe('wedge trigger', () => {
+ test('fires once per divergence episode across repeated wedged bumps; the gate keeps blocking', async () => {
+ const harness = createHarness();
+ harness.remoteReplace('remote one');
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(1);
+
+ harness.remoteReplace('remote two');
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(1);
+ expect(harness.localType()).toBe(false);
+ });
+
+ test('destroying the view unregisters the fragment observer', async () => {
+ const harness = createHarness();
+ harness.view.destroy();
+ harness.ydoc.transact(
+ () => setFragmentParagraph(harness.fragment, 'after destroy'),
+ REMOTE_PROVIDER_ORIGIN,
+ );
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(0);
+ });
+
+ test('a throwing onWedged is contained and recovery re-attempts on the next external bump', async () => {
+ let shouldThrow = true;
+ const harness = createHarness({
+ onWedged: () => {
+ if (shouldThrow) {
+ shouldThrow = false;
+ throw new Error('simulated recycle failure');
+ }
+ },
+ });
+ harness.remoteReplace('remote one');
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(1);
+ expect(harness.localType()).toBe(false);
+ harness.remoteReplace('remote two');
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(2);
+ });
+
+ test('a healed divergence ends the episode: a later re-wedge reports again', async () => {
+ const harness = createHarness();
+ harness.remoteReplace('remote one');
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(1);
+
+ dispatchYSyncRerender(harness.view, harness.fragment);
+ expect(harness.localType()).toBe(true);
+
+ harness.remoteReplace('remote two');
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(2);
+ expect(harness.localType()).toBe(false);
+ });
+
+ test('rate-capped per docName: beyond 3 firings the gate still blocks but onWedged stays silent', async () => {
+ const docName = `rate-cap-${randomUUID()}`;
+ const fired: boolean[] = [];
+ for (let i = 0; i < 4; i++) {
+ const harness = createHarness({ docName });
+ harness.remoteReplace(`remote ${i}`);
+ await flushDetection();
+ fired.push(harness.wedgedCalls.length === 1);
+ expect(harness.localType()).toBe(false);
+ harness.destroy();
+ }
+ expect(fired).toEqual([true, true, true, false]);
+ });
+});
+
+describe('binding write-back seam', () => {
+ /** What the vendored ySyncPlugin's pluginView `update` callback does
+ * unconditionally on every view-state update (y-tiptap.cjs view section):
+ * publish the current PM doc through `binding._prosemirrorChanged`. */
+ function invokeWriteBack(harness: GuardHarness): void {
+ const syncState = ySyncPluginKey.getState(harness.view.state) as {
+ binding?: { _prosemirrorChanged?: (doc: unknown) => void };
+ };
+ syncState.binding?._prosemirrorChanged?.(harness.view.state.doc);
+ }
+
+ test('while diverged the seam refuses to publish; after catch-up it publishes again', async () => {
+ const published: unknown[] = [];
+ const harness = createHarness({
+ binding: {
+ _prosemirrorChanged: (doc: unknown) => {
+ published.push(doc);
+ },
+ },
+ });
+
+ invokeWriteBack(harness);
+ expect(published).toHaveLength(1);
+
+ harness.remoteReplace('remote fix');
+ invokeWriteBack(harness);
+ expect(published).toHaveLength(1);
+ await flushDetection();
+ invokeWriteBack(harness);
+ expect(published).toHaveLength(1);
+
+ dispatchYSyncRerender(harness.view, harness.fragment);
+ invokeWriteBack(harness);
+ expect(published).toHaveLength(2);
+ });
+
+ test('a binding without _prosemirrorChanged disarms the write-back gate loudly, not silently', () => {
+ const warnings: string[] = [];
+ const originalWarn = console.warn;
+ console.warn = (...args: unknown[]) => {
+ warnings.push(String(args[0]));
+ };
+ try {
+ createHarness({ binding: {} });
+ } finally {
+ console.warn = originalWarn;
+ }
+ expect(
+ warnings.some((w) => w.includes('no _prosemirrorChanged — write-back gate disarmed')),
+ ).toBe(true);
+ });
+
+ test('a fragment with no Y.Doc disarms the whole guard loudly and leaves the editor usable', () => {
+ const errors: string[] = [];
+ const originalError = console.error;
+ console.error = (...args: unknown[]) => {
+ errors.push(String(args[0]));
+ };
+ let view: EditorView | null = null;
+ try {
+ const orphanFragment = new Y.XmlFragment();
+ const state = EditorState.create({
+ schema,
+ plugins: [
+ createYSyncStandIn(),
+ bindingStalenessGuardPlugin({
+ fragment: orphanFragment,
+ docName: `orphan-${randomUUID()}`,
+ onWedged: () => {},
+ }),
+ ],
+ });
+ view = new EditorView(document.createElement('div'), { state });
+ const before = view.state.doc.textContent;
+ view.dispatch(view.state.tr.insertText('x'));
+ expect(view.state.doc.textContent).not.toBe(before);
+ } finally {
+ view?.destroy();
+ console.error = originalError;
+ }
+ expect(errors.some((e) => e.includes('staleness guard disarmed'))).toBe(true);
+ });
+});
+
+describe('no false positives on healthy bindings', () => {
+ for (const order of ['registered-before-guard', 'registered-after-guard'] as const) {
+ test(`rapid external stream interleaved with local typing stays open (binding ${order})`, async () => {
+ const harness = createHarness({ simulatedBinding: order });
+ for (let i = 0; i < 15; i++) {
+ harness.remoteReplace(`remote ${i}`);
+ expect(harness.localType()).toBe(true);
+ }
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(0);
+ expect(harness.view.state.doc.textContent).toContain('remote 14');
+ });
+ }
+
+ test('a single healthy remote update never reports a wedge', async () => {
+ const harness = createHarness({ simulatedBinding: 'registered-after-guard' });
+ harness.remoteReplace('remote healthy');
+ await flushDetection();
+ expect(harness.wedgedCalls).toHaveLength(0);
+ expect(harness.view.state.doc.textContent).toContain('remote healthy');
+ expect(harness.localType()).toBe(true);
+ });
+});
diff --git a/packages/app/src/editor/binding-staleness-guard.ts b/packages/app/src/editor/binding-staleness-guard.ts
new file mode 100644
index 000000000..758caca8e
--- /dev/null
+++ b/packages/app/src/editor/binding-staleness-guard.ts
@@ -0,0 +1,193 @@
+import type { EditorState } from '@tiptap/pm/state';
+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 WedgeDetail {
+ externalSeq: number;
+ appliedSeq: number;
+}
+
+export interface BindingStalenessGuardOptions {
+ fragment: Y.XmlFragment;
+ docName: string;
+ onWedged: (detail: WedgeDetail) => void;
+}
+
+export function isDiverged(externalSeq: number, appliedSeq: number): boolean {
+ return externalSeq > appliedSeq;
+}
+
+export function isCatchUpApply(meta: unknown): boolean {
+ if (typeof meta !== 'object' || meta === null) return false;
+ const change = meta as Record<string, unknown>;
+ if (change.isChangeOrigin === true) return true;
+ return (
+ 'snapshot' in change &&
+ 'prevSnapshot' in change &&
+ change.snapshot === null &&
+ change.prevSnapshot === null
+ );
+}
+
+const RATE_CAP_MAX_FIRINGS = 3;
+const RATE_CAP_WINDOW_MS = 60_000;
+
+export function rateCapAllows(priorFiringTimestampsMs: readonly number[], nowMs: number): boolean {
+ let inWindow = 0;
+ for (const ts of priorFiringTimestampsMs) {
+ if (nowMs - ts < RATE_CAP_WINDOW_MS) inWindow += 1;
+ }
+ return inWindow < RATE_CAP_MAX_FIRINGS;
+}
+
+const wedgeFiringsByDocName = new Map<string, number[]>();
+
+function transactionTouchesFragment(transaction: Y.Transaction, fragment: Y.XmlFragment): boolean {
+ for (const changedType of transaction.changed.keys()) {
+ let current: unknown = changedType;
+ while (current != null) {
+ if (current === fragment) return true;
+ const item = (current as { _item?: { parent: unknown } | null })._item;
+ current = item == null ? null : item.parent;
+ }
+ }
+ return false;
+}
+
+function isSnapshotActive(state: EditorState): boolean {
+ const syncState = ySyncPluginKey.getState(state) as
+ | { snapshot?: unknown; prevSnapshot?: unknown }
+ | null
+ | undefined;
+ return syncState?.snapshot != null || syncState?.prevSnapshot != null;
+}
+
+export function bindingStalenessGuardPlugin(options: BindingStalenessGuardOptions): Plugin {
+ const { fragment, docName, onWedged } = options;
+
+ let externalSeq = 0;
+ let appliedSeq = 0;
+ let reported = false;
+ let active = false;
+ let checkQueued = false;
+ let viewRef: EditorView | null = null;
+ const wrappedBindings = new WeakSet<object>();
+
+ const wrapBindingWriteBack = (state: EditorState): void => {
+ const syncState = ySyncPluginKey.getState(state) as
+ | { binding?: { _prosemirrorChanged?: (doc: unknown) => void } | null }
+ | null
+ | undefined;
+ const binding = syncState?.binding;
+ if (!binding) return;
+ if (typeof binding._prosemirrorChanged !== 'function') {
+ mark.count('ok/editor/binding-guard-disarmed', {
+ docName,
+ reason: 'no-prosemirror-changed',
+ });
+ console.warn(
+ `[binding-staleness-guard] ySync binding on "${docName}" exposes no _prosemirrorChanged — write-back gate disarmed (vendored y-tiptap contract change?)`,
+ );
+ return;
+ }
+ if (wrappedBindings.has(binding)) return;
+ wrappedBindings.add(binding);
+ const original = binding._prosemirrorChanged.bind(binding);
+ binding._prosemirrorChanged = (doc: unknown): void => {
+ if (isDiverged(externalSeq, appliedSeq)) return;
+ original(doc);
+ };
+ };
+
+ const runWedgeCheck = (): void => {
+ checkQueued = false;
+ if (!active || reported) return;
+ if (!isDiverged(externalSeq, appliedSeq)) return;
+ if (viewRef !== null && isSnapshotActive(viewRef.state)) return;
+ reported = true;
+ const now = Date.now();
+ for (const [name, timestamps] of wedgeFiringsByDocName) {
+ if (timestamps.every((ts) => now - ts >= RATE_CAP_WINDOW_MS)) {
+ wedgeFiringsByDocName.delete(name);
+ }
+ }
+ const prior = wedgeFiringsByDocName.get(docName) ?? [];
+ const recent = prior.filter((ts) => now - ts < RATE_CAP_WINDOW_MS);
+ if (!rateCapAllows(recent, now)) {
+ wedgeFiringsByDocName.set(docName, recent);
+ mark.count('ok/editor/binding-wedge-rate-capped', { docName });
+ console.warn(
+ `[binding-staleness-guard] wedge on "${docName}" rate-capped (externalSeq=${externalSeq}, appliedSeq=${appliedSeq}) — publication gate stays closed, no further recycle`,
+ );
+ return;
+ }
+ recent.push(now);
+ wedgeFiringsByDocName.set(docName, recent);
+ console.warn(
+ `[binding-staleness-guard] wedged binding on "${docName}" — Y→PM apply missing (externalSeq=${externalSeq}, appliedSeq=${appliedSeq})`,
+ );
+ try {
+ onWedged({ externalSeq, appliedSeq });
+ } catch (err) {
+ reported = false;
+ mark.count('ok/editor/binding-wedge-recovery-error', { docName });
+ console.error(`[binding-staleness-guard] wedge recovery threw for "${docName}":`, err);
+ }
+ };
+
+ const handleBeforeObserverCalls = (transaction: Y.Transaction): void => {
+ if (transaction.origin === ySyncPluginKey) return;
+ if (!transactionTouchesFragment(transaction, fragment)) return;
+ externalSeq += 1;
+ if (!checkQueued) {
+ checkQueued = true;
+ queueMicrotask(runWedgeCheck);
+ }
+ };
+
+ return new Plugin({
+ state: {
+ init: () => null,
+ apply: (tr) => {
+ if (isCatchUpApply(tr.getMeta(ySyncPluginKey))) {
+ appliedSeq = externalSeq;
+ if (reported) {
+ mark.count('ok/editor/binding-wedge-recovered', { docName });
+ }
+ reported = false;
+ }
+ return null;
+ },
+ },
+ filterTransaction: (tr, state) => {
+ if (!isDiverged(externalSeq, appliedSeq)) return true;
+ if (isSnapshotActive(state)) return true;
+ return tr.getMeta(ySyncPluginKey) !== undefined;
+ },
+ view: (editorView) => {
+ const doc = fragment.doc;
+ if (doc == null) {
+ mark.count('ok/editor/binding-guard-disarmed', { docName, reason: 'no-ydoc' });
+ console.error(
+ `[binding-staleness-guard] fragment has no Y.Doc for "${docName}" — staleness guard disarmed`,
+ );
+ return {};
+ }
+ active = true;
+ viewRef = editorView;
+ wrapBindingWriteBack(editorView.state);
+ doc.off('beforeObserverCalls', handleBeforeObserverCalls);
+ doc.on('beforeObserverCalls', handleBeforeObserverCalls);
+ return {
+ destroy: () => {
+ active = false;
+ viewRef = null;
+ doc.off('beforeObserverCalls', handleBeforeObserverCalls);
+ },
+ };
+ },
+ });
+}
diff --git a/packages/app/tests/stress/prd-6955-reassertion-repro.e2e.ts b/packages/app/tests/stress/prd-6955-reassertion-repro.e2e.ts
new file mode 100644
index 000000000..e10317db3
--- /dev/null
+++ b/packages/app/tests/stress/prd-6955-reassertion-repro.e2e.ts
@@ -0,0 +1,81 @@
+import { randomUUID } from 'node:crypto';
+import type { Page } from '@playwright/test';
+import { expect, test, waitForActiveProviderSynced as waitForProvider } from './_helpers';
+
+async function sourceFor(page: Page, docName: string): Promise<string> {
+ return page.evaluate((name) => {
+ const pool = (
+ window as unknown as {
+ __providerPool?: {
+ entries?: {
+ get?: (
+ n: string,
+ ) =>
+ | { provider?: { document?: { getText: (s: string) => { toString(): string } } } }
+ | undefined;
+ };
+ };
+ }
+ ).__providerPool;
+ const viaPool = pool?.entries?.get?.(name)?.provider?.document?.getText('source')?.toString();
+ if (viaPool) return viaPool;
+ const active = (
+ window as unknown as {
+ __activeProvider?: { document?: { getText: (s: string) => { toString(): string } } };
+ }
+ ).__activeProvider;
+ return active?.document?.getText('source')?.toString() ?? '';
+ }, docName);
+}
+
+test('PRD-6955(b): remote fix to a hidden-but-mounted doc survives reveal + local touch', async ({
+ page,
+ api,
+ baseURL,
+}) => {
+ const docA = `prd-6955b-a-${randomUUID().slice(0, 8)}`;
+ const docB = `prd-6955b-b-${randomUUID().slice(0, 8)}`;
+ const ORIG = '# Doc A\n\nstate one CORRUPT marker.\n\ntail para.\n';
+ await api.seedDocs([
+ { name: docA, markdown: ORIG },
+ { name: docB, markdown: '# Doc B\n\nparking doc.\n' },
+ ]);
+
+ await page.goto(`/#/${docA}`);
+ await waitForProvider(page);
+ await expect(page.locator('.ProseMirror').last()).toContainText('state one CORRUPT marker.');
+ await page.goto(`/#/${docB}`);
+ await waitForProvider(page);
+ await expect(page.locator('.ProseMirror').last()).toContainText('parking doc.');
+
+ const res = await fetch(`${baseURL}/api/agent-patch`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ docName: docA,
+ find: 'state one CORRUPT marker.',
+ replace: 'state two FIXED marker.',
+ }),
+ });
+ expect(res.ok).toBe(true);
+
+ await expect
+ .poll(() => sourceFor(page, docA), { timeout: 10_000 })
+ .toContain('state two FIXED marker.');
+
+ await page.goto(`/#/${docA}`);
+ await waitForProvider(page);
+ await expect(page.locator('.ProseMirror').last()).toContainText('state two FIXED marker.');
+ const editor = page.locator('.ProseMirror').last();
+ await editor.click();
+ await page.keyboard.press('End');
+ await page.keyboard.type(' touched', { delay: 15 });
+ await expect
+ .poll(() => sourceFor(page, docA), { timeout: 10_000 })
+ .toContain('tail para. touched');
+
+ const text = await sourceFor(page, docA);
+ console.log('[6955b] final head:', JSON.stringify(text.slice(0, 120)));
+ expect(text).toContain('state two FIXED marker.');
+ expect(text).not.toContain('state one CORRUPT marker.');
+});
diff --git a/packages/app/tests/stress/prd-6955-reassertion-wedge.e2e.ts b/packages/app/tests/stress/prd-6955-reassertion-wedge.e2e.ts
new file mode 100644
index 000000000..d6bf916bc
--- /dev/null
+++ b/packages/app/tests/stress/prd-6955-reassertion-wedge.e2e.ts
@@ -0,0 +1,99 @@
+import { randomUUID } from 'node:crypto';
+import type { Page } from '@playwright/test';
+import { expect, test, waitForActiveProviderSynced as waitForProvider } from './_helpers';
+
+async function sourceText(page: Page): Promise<string> {
+ return page.evaluate(() => {
+ const active = (
+ window as unknown as {
+ __activeProvider?: { document?: { getText: (s: string) => { toString(): string } } };
+ }
+ ).__activeProvider;
+ return active?.document?.getText('source')?.toString() ?? '';
+ });
+}
+
+test('PRD-6955(b) wedge: Y→PM apply dropped + local touch → does stale PM resurrect over the fix?', async ({
+ page,
+ api,
+ baseURL,
+}) => {
+ const docName = `prd-6955-wedge-${randomUUID().slice(0, 8)}`;
+ await api.seedDocs([
+ { name: docName, markdown: '# Wedge probe\n\nstate one STALE marker.\n\ntail para.\n' },
+ ]);
+ await page.goto(`/#/${docName}`);
+ await waitForProvider(page);
+ await expect(page.locator('.ProseMirror').last()).toContainText('state one STALE marker.');
+ await expect
+ .poll(
+ () =>
+ page.evaluate(() => !!(window as unknown as { __activeEditor?: unknown }).__activeEditor),
+ { timeout: 10_000 },
+ )
+ .toBe(true);
+
+ expect(await sourceText(page)).toContain('state one STALE marker.');
+
+ const patched = await page.evaluate(() => {
+ const active = (
+ window as unknown as { __activeEditor?: { view?: { dispatch: (tr: unknown) => void } } }
+ ).__activeEditor;
+ const view = active?.view;
+ if (!view) return 'no-active-editor';
+ const orig = view.dispatch.bind(view);
+ (view as { dispatch: (tr: unknown) => void }).dispatch = (tr: unknown) => {
+ const t = tr as { meta?: Record<string, unknown> };
+ const meta = (t as { meta?: Record<string, unknown> }).meta ?? {};
+ const keys = Object.keys(meta);
+ if (keys.some((k) => k.includes('y-sync'))) {
+ (window as unknown as { __droppedYSync: number }).__droppedYSync =
+ ((window as unknown as { __droppedYSync?: number }).__droppedYSync ?? 0) + 1;
+ return; // WEDGE: remote Y→PM application silently dropped
+ }
+ orig(tr as never);
+ };
+ return 'patched';
+ });
+ console.log('[wedge] dispatch patch:', patched);
+ expect(patched).toBe('patched');
+
+ const res = await fetch(`${baseURL}/api/agent-patch`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ docName,
+ find: 'state one STALE marker.',
+ replace: 'state two FIXED marker.',
+ }),
+ });
+ expect(res.ok).toBe(true);
+
+ await expect
+ .poll(() => sourceText(page), { timeout: 10_000 })
+ .toContain('state two FIXED marker.');
+
+ const dropped = await page.evaluate(
+ () => (window as unknown as { __droppedYSync?: number }).__droppedYSync ?? 0,
+ );
+ console.log('[wedge] after fix: Y.Text has FIXED | dropped y-sync trs:', dropped);
+ expect(dropped).toBeGreaterThan(0);
+
+ const editor = page.locator('.ProseMirror').last();
+ await editor.click();
+ await page.keyboard.press('End');
+ await page.keyboard.type(' X', { delay: 20 });
+ await expect.poll(() => sourceText(page), { timeout: 10_000 }).toContain('tail para. X');
+
+ const finalY = await sourceText(page);
+ console.log('[wedge] FINAL Y.Text head:', JSON.stringify(finalY.slice(0, 140)));
+ console.log(
+ '[wedge] resurrection?',
+ finalY.includes('state one STALE marker.'),
+ '| fix survived?',
+ finalY.includes('state two FIXED marker.'),
+ );
+
+ expect(finalY).toContain('state two FIXED marker.');
+ expect(finalY).not.toContain('state one STALE marker.');
+});