Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): prevent destructive source undo (PRD-8464) (#4071)

serafin-garcia280bc35b79cc
diff --git a/.changeset/source-undo-mode-flip.md b/.changeset/source-undo-mode-flip.md
new file mode 100644
index 000000000..bdafb92e6
--- /dev/null
+++ b/.changeset/source-undo-mode-flip.md
@@ -0,0 +1,17 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Leaving Markdown source and coming back no longer lets a single Cmd+Z (Ctrl+Z on Windows and Linux) delete text you did not just type.
+
+This covers the Markdown source pane only. The Visual editor keeps its own separate undo history, and this change does not touch it.
+
+Typing quickly merges into one undo entry, so two lines typed back to back are a single Cmd+Z. If you then switch to the Visual editor or to another document, and something rewrites part of that text while you are away (the Visual editor, an agent, a file changing on disk, another person), replaying that entry is no longer meaningful. It removes everything the burst inserted, including the line you never touched on this visit, and leaves the newer edits stranded around the hole.
+
+Leaving Markdown source now closes off the current undo entry, so a burst typed just before you leave can never merge with typing that happens after you return. Coming back clears the source undo history, but only when something wrote to the document while you were away. Switching over for a look and coming straight back leaves your undo history intact, and so does moving to another tab and back while nothing writes to the document. Undo history is per document and per session. Opening many other documents in the meantime, or reopening the app, still starts it fresh.
+
+Standalone Mermaid diagram-label history now belongs to the current document session rather than to the diagram pane, so stepping away to another document and coming back keeps it; previously it could be lost that way. Flipping between the rendered diagram and raw source also leaves it intact. Closing the file's last tab, closing the app, or opening enough other documents that the file drops out of your recently opened set are examples of events that start it fresh. A full replacement from disk also starts it fresh, so an older diagram edit cannot be replayed into the replacement.
+
+Nothing is removed from the document when the history is cleared. What you lose is the ability to step back through those edits, and redo goes with it, so Cmd+Shift+Z has nothing to replay either. One case is still not covered: if a rewrite lands while you are sitting in Markdown source, that earlier entry remains, so a single Cmd+Z can still take back more than you typed.
+
+Separately from undo, the Timeline panel keeps earlier versions of the whole document if you need to go further back. Each timeline entry is a snapshot of the whole document. Agent edits, human edits, and file-system changes are batched into an entry once activity settles. Upstream syncs get their own entry when the sync lands.
diff --git a/docs/content/features/assets-and-embeds.mdx b/docs/content/features/assets-and-embeds.mdx
index 28ecd9664..9b0146c58 100644
--- a/docs/content/features/assets-and-embeds.mdx
+++ b/docs/content/features/assets-and-embeds.mdx
@@ -32,7 +32,7 @@ Type `/embed` for starters: a blank **HTML** canvas plus **Chart**, **Stat cards
## Diagrams
-A ` ```mermaid ` fence renders as a diagram — flowchart, sequence, class, state, ER, gantt, or pie; the **Mermaid** entry in the `/` menu inserts one. Rendered diagrams carry buttons for zoom, pan, and reset; mouse-wheel zoom and drag panning are off, so a diagram holds still while you scroll the doc. Standalone Mermaid files (`.mmd`, `.mermaid`) open the same way — rendered as a diagram in their own pane, with a toggle to read or edit the raw source directly.
+A ` ```mermaid ` fence renders as a diagram — flowchart, sequence, class, state, ER, gantt, or pie; the **Mermaid** entry in the `/` menu inserts one. Rendered diagrams carry buttons for zoom, pan, and reset; mouse-wheel zoom and drag panning are off, so a diagram holds still while you scroll the doc. Standalone Mermaid files (`.mmd`, `.mermaid`) open the same way — rendered as a diagram in their own pane, with a toggle to read or edit the raw source directly. For a standalone Mermaid file, switching from the rendered diagram to raw source does not by itself discard diagram-label history. That history belongs to the current document session: closing the file's last tab, closing the app, or opening enough other documents that the file drops out of your recently opened set are examples of events that start it fresh. A full replacement from disk also starts it fresh, so an older diagram edit cannot be replayed into the replacement.
## Sharing across apps
diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdx
index 7f9e02fb9..c99b71b73 100644
--- a/docs/content/features/editor.mdx
+++ b/docs/content/features/editor.mdx
@@ -30,6 +30,16 @@ A doc written before this behavior may still carry a blank line at the end that
Markdown problems (hard tabs, heading increments, and the rest) are flagged inline as you write, with a **Problems** panel in the document panel for the whole doc or project. See [Content rules](/docs/advanced/content-rules/overview).
+### Undo in source mode
+
+This section is about the Markdown source pane only. The visual editor keeps its own undo history, and none of what follows changes it.
+
+Undo in source mode covers the editing you did there. Switching to the visual editor for a look and coming straight back leaves that history intact. But if you leave source mode, by switching to the visual editor or by moving to another tab, and anything writes to the document while you are away, source-mode undo and redo start fresh when you come back. Many things count as a write, not only the obvious ones: your own edits in the visual editor, an agent, a collaborator, a change on disk, a field you change in the **Properties** panel, a fix applied from the **Problems** panel or from the visual editor, or the tail of a large paste you started in source mode that was still landing as you flipped away. Restoring an earlier version from the [Timeline](./timeline-and-recovery.mdx) counts as a write too, so if you restore while you are out of source mode, undo there starts fresh when you come back. Source-mode undo history belongs to the current document session: navigating through enough other documents to evict it, or closing and reopening the app, starts it fresh even if no one rewrote the file.
+
+No text is removed when that happens. One case is still not covered. If a rewrite lands while you are sitting in Markdown source rather than away from it, the history is left as it is, so a single undo can still take back more than you expect.
+
+To go further back, the [Timeline](./timeline-and-recovery.mdx) keeps earlier versions of the whole document. Each entry is a snapshot of the whole document. Agent edits, human edits, and file-system changes are batched into an entry once activity settles. Upstream syncs get their own entry when the sync lands. Restoring an entry brings back that version's content. Restoring is append-only, so the edits you made since then stay on the timeline and you can restore back to them.
+
### Tables
Insert a table from the slash menu. The header row stays visible as you scroll down a long table, the first column stays pinned as you scroll sideways, and dragging a row or column handle reorders it. Cells are single-line in the stored markdown: pressing Enter inside a cell — or pasting a table whose cells hold lists or paragraphs — joins the lines with `<br />`, the GFM line-break idiom, so the table stays valid for everyone else opening the file. `<br>` tags in existing files render as real line breaks and round-trip byte-for-byte.
diff --git a/docs/content/features/timeline-and-recovery.mdx b/docs/content/features/timeline-and-recovery.mdx
index 52e4a65f7..08f4ab180 100644
--- a/docs/content/features/timeline-and-recovery.mdx
+++ b/docs/content/features/timeline-and-recovery.mdx
@@ -20,6 +20,8 @@ Timeline entries include:
Project-wide checkpoints saved by agents via the [`checkpoint` MCP tool](/docs/reference/mcp#tools) do not appear on the timeline; agents find and restore them with the `history` and `restore_version` tools.
+The timeline is not the editor's undo history. Each timeline entry is a snapshot of the whole document, while undo steps back through your own recent edits in the pane where you are working. Agent edits, human edits, and file-system changes are batched into an entry once activity settles. Upstream syncs get their own entry when the sync lands. For when source-mode undo starts fresh, see [Editor → Undo in source mode](/docs/features/editor#undo-in-source-mode).
+
The timeline is per branch: it shows the branch's own edits, plus history from before the branch diverged from `main`. History is stored in a shadow git repo inside your project, so entries and attribution survive app restarts and agent sessions — see [Attribution and collaboration](/docs/reference/core-concepts#attribution-and-collaboration).
## Review changes
diff --git a/packages/app/package.json b/packages/app/package.json
index d0beac932..6f9500cb7 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -29,7 +29,7 @@
"measure:stress": "bash scripts/measure-stress.sh",
"measure:sweep": "bash scripts/measure-sweep.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/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-fractional-zoom.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/frozen-table-headers.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/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.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/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.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 tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts",
+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-fractional-zoom.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/frozen-table-headers.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/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.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/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.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 tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.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/MermaidDocEditor.test.ts b/packages/app/src/components/MermaidDocEditor.test.ts
index 349aca87e..0ddaadda7 100644
--- a/packages/app/src/components/MermaidDocEditor.test.ts
+++ b/packages/app/src/components/MermaidDocEditor.test.ts
@@ -1,6 +1,11 @@
-import { describe, expect, test } from 'vitest';
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import { describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
-import { replaceYText } from './MermaidDocEditor.tsx';
+import {
+ acquireMermaidUndoManager,
+ MERMAID_DIAGRAM_EDIT_ORIGIN,
+ replaceYText,
+} from './MermaidDocEditor.tsx';
function makeYText(initial: string): { doc: Y.Doc; ytext: Y.Text; events: Y.YTextEvent[] } {
const doc = new Y.Doc();
@@ -96,3 +101,156 @@ describe('replaceYText', () => {
expect(ytext.toString()).toBe('prefix NEW suffix');
});
});
+
+describe('acquireMermaidUndoManager', () => {
+ test('tracks diagram edits but excludes origin-less seed and reconcile writes', () => {
+ const { doc, ytext } = makeYText('');
+ const provider = {
+ document: doc,
+ on() {},
+ off() {},
+ } as unknown as HocuspocusProvider;
+
+ const undoManager = acquireMermaidUndoManager(provider, ytext);
+
+ expect(undoManager.trackedOrigins.has(null)).toBe(false);
+ expect(undoManager.trackedOrigins.has(MERMAID_DIAGRAM_EDIT_ORIGIN)).toBe(true);
+
+ replaceYText(ytext, 'seed');
+ expect(undoManager.undoStack).toHaveLength(0);
+
+ replaceYText(ytext, 'diagram edit', MERMAID_DIAGRAM_EDIT_ORIGIN);
+ expect(undoManager.undoStack).toHaveLength(1);
+ });
+
+ test('an untracked full reconcile clears a stale diagram edit before undo can corrupt it', () => {
+ const before = 'graph LR\n Shopper --> Storefront\n';
+ const afterDiagramEdit = 'graph LR\n Buyer --> Storefront\n';
+ const afterReconcile = 'graph LR\n Buyer --> Warehouse\n';
+ const { doc, ytext } = makeYText(before);
+ const provider = {
+ document: doc,
+ on() {},
+ off() {},
+ } as unknown as HocuspocusProvider;
+ const undoManager = acquireMermaidUndoManager(provider, ytext);
+
+ replaceYText(ytext, afterDiagramEdit, MERMAID_DIAGRAM_EDIT_ORIGIN);
+ expect(undoManager.canUndo()).toBe(true);
+
+ doc.transact(() => {
+ ytext.delete(0, ytext.length);
+ ytext.insert(0, afterReconcile);
+ }, Symbol('mermaid-source-reconcile'));
+
+ expect(ytext.toString()).toBe(afterReconcile);
+ expect(undoManager.undoStack).toHaveLength(0);
+ undoManager.undo();
+ expect(ytext.toString()).toBe(afterReconcile);
+ });
+
+ test('a remote full reconcile clears history even though transport replaces the server origin', () => {
+ const before = 'graph LR\n Shopper --> Storefront\n';
+ const afterDiagramEdit = 'graph LR\n Buyer --> Storefront\n';
+ const afterReconcile = 'graph LR\n Buyer --> Warehouse\n';
+ const serverDoc = new Y.Doc();
+ const serverText = serverDoc.getText('source');
+ serverText.insert(0, before);
+ const clientDoc = new Y.Doc();
+ Y.applyUpdate(clientDoc, Y.encodeStateAsUpdate(serverDoc));
+ const clientText = clientDoc.getText('source');
+ const provider = {
+ document: clientDoc,
+ on() {},
+ off() {},
+ } as unknown as HocuspocusProvider;
+ const undoManager = acquireMermaidUndoManager(provider, clientText);
+
+ replaceYText(clientText, afterDiagramEdit, MERMAID_DIAGRAM_EDIT_ORIGIN);
+ Y.applyUpdate(serverDoc, Y.encodeStateAsUpdate(clientDoc));
+ let reconcileUpdate: Uint8Array | undefined;
+ serverDoc.on('update', (update, origin) => {
+ if (origin === 'server-reconcile') reconcileUpdate = update;
+ });
+ serverDoc.transact(() => {
+ serverText.delete(0, serverText.length);
+ serverText.insert(0, afterReconcile);
+ }, 'server-reconcile');
+ expect(reconcileUpdate).toBeDefined();
+ if (!reconcileUpdate) throw new Error('Expected the server reconcile update');
+ Y.applyUpdate(clientDoc, reconcileUpdate, provider);
+
+ expect(clientText.toString()).toBe(afterReconcile);
+ expect(undoManager.canUndo()).toBe(false);
+ undoManager.undo();
+ expect(clientText.toString()).toBe(afterReconcile);
+ });
+
+ test('an untracked partial peer edit preserves diagram undo history', () => {
+ const { doc, ytext } = makeYText('graph LR\n Shopper --> Storefront\n');
+ const provider = {
+ document: doc,
+ on() {},
+ off() {},
+ } as unknown as HocuspocusProvider;
+ const undoManager = acquireMermaidUndoManager(provider, ytext);
+ replaceYText(ytext, 'graph LR\n Buyer --> Storefront\n', MERMAID_DIAGRAM_EDIT_ORIGIN);
+
+ doc.transact(() => ytext.insert(ytext.length, ' Storefront --> Cart\n'), Symbol('peer'));
+
+ expect(undoManager.canUndo()).toBe(true);
+ });
+
+ test('repeated acquisition installs one full-reconcile observer', () => {
+ const listeners = new Set<() => void>();
+ const { doc, ytext } = makeYText('graph LR\n Shopper --> Storefront\n');
+ const provider = {
+ document: doc,
+ on(name: string, listener: () => void) {
+ if (name === 'destroy') listeners.add(listener);
+ },
+ off(name: string, listener: () => void) {
+ if (name === 'destroy') listeners.delete(listener);
+ },
+ } as unknown as HocuspocusProvider;
+ const observe = vi.spyOn(ytext, 'observe');
+
+ const first = acquireMermaidUndoManager(provider, ytext);
+ const destroyListenerCount = listeners.size;
+ expect(observe).toHaveBeenCalledTimes(1);
+
+ const second = acquireMermaidUndoManager(provider, ytext);
+
+ expect(second).toBe(first);
+ expect(observe).toHaveBeenCalledTimes(1);
+ expect(listeners.size).toBe(destroyListenerCount);
+
+ for (const listener of listeners) listener();
+ expect(listeners.size).toBe(0);
+ });
+
+ test('provider teardown detaches the full-reconcile observer', () => {
+ const listeners = new Set<() => void>();
+ const { doc, ytext } = makeYText('graph LR\n Shopper --> Storefront\n');
+ const provider = {
+ document: doc,
+ on(name: string, listener: () => void) {
+ if (name === 'destroy') listeners.add(listener);
+ },
+ off(name: string, listener: () => void) {
+ if (name === 'destroy') listeners.delete(listener);
+ },
+ } as unknown as HocuspocusProvider;
+ const undoManager = acquireMermaidUndoManager(provider, ytext);
+ const clear = vi.spyOn(undoManager, 'clear');
+
+ for (const listener of listeners) listener();
+ clear.mockClear();
+ doc.transact(() => {
+ ytext.delete(0, ytext.length);
+ ytext.insert(0, 'graph LR\n Buyer --> Warehouse\n');
+ }, Symbol('late-reconcile'));
+
+ expect(clear).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/components/MermaidDocEditor.tsx b/packages/app/src/components/MermaidDocEditor.tsx
index f98c24708..8781df7c9 100644
--- a/packages/app/src/components/MermaidDocEditor.tsx
+++ b/packages/app/src/components/MermaidDocEditor.tsx
@@ -30,11 +30,12 @@ import { mermaid } from 'codemirror-lang-mermaid';
import { useTheme } from 'next-themes';
import { useEffect, useRef, useState } from 'react';
import { yCollab } from 'y-codemirror.next';
-import * as Y from 'yjs';
+import type * as Y from 'yjs';
import { propEditorHighlight } from '@/editor/components/CodeMirrorPropInput';
import { type MermaidSourceBinding, MermaidView } from '@/editor/components/Mermaid';
import { okCmTheme } from '@/editor/extensions/cm-theme';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
+import { acquireDocUndoManager } from './doc-undo-manager';
const darkTheme = okCmTheme({
dark: true,
@@ -105,7 +106,80 @@ function MermaidSourcePane({
return <div ref={containerRef} className="h-full min-h-0 overflow-auto" />;
}
-const MERMAID_DIAGRAM_EDIT_ORIGIN = Symbol('mermaid-diagram-edit');
+export const MERMAID_DIAGRAM_EDIT_ORIGIN = Symbol('mermaid-diagram-edit');
+
+const mermaidUndoResetByManager = new WeakMap<Y.UndoManager, () => void>();
+
+function insertedDeltaLength(insert: unknown): number {
+ if (typeof insert === 'string' || Array.isArray(insert)) return insert.length;
+ return 1;
+}
+
+function isUntrackedFullTextReplacement(
+ event: Y.YTextEvent,
+ transaction: Y.Transaction,
+ undoManager: Y.UndoManager,
+): boolean {
+ const origin = transaction.origin;
+ if (
+ undoManager.trackedOrigins.has(origin) ||
+ (origin != null &&
+ undoManager.trackedOrigins.has((origin as { constructor?: unknown }).constructor))
+ ) {
+ return false;
+ }
+
+ let deleted = 0;
+ let inserted = 0;
+ let retained = 0;
+ for (const delta of event.delta) {
+ deleted += delta.delete ?? 0;
+ inserted += delta.insert === undefined ? 0 : insertedDeltaLength(delta.insert);
+ retained += delta.retain ?? 0;
+ }
+ const beforeLength = event.target.length + deleted - inserted;
+ return retained === 0 && deleted === beforeLength && deleted + inserted > 0;
+}
+
+function installMermaidUndoReset(
+ provider: HocuspocusProvider,
+ ytext: Y.Text,
+ undoManager: Y.UndoManager,
+): void {
+ if (mermaidUndoResetByManager.has(undoManager)) return;
+
+ const resetStaleHistory = (event: Y.YTextEvent, transaction: Y.Transaction): void => {
+ if (isUntrackedFullTextReplacement(event, transaction, undoManager)) undoManager.clear();
+ };
+ let released = false;
+ const doc = ytext.doc;
+ const release = (): void => {
+ if (released) return;
+ released = true;
+ ytext.unobserve(resetStaleHistory);
+ provider.off('destroy', release);
+ doc?.off('destroy', release);
+ if (mermaidUndoResetByManager.get(undoManager) === release) {
+ mermaidUndoResetByManager.delete(undoManager);
+ }
+ };
+
+ mermaidUndoResetByManager.set(undoManager, release);
+ ytext.observe(resetStaleHistory);
+ provider.on('destroy', release);
+ doc?.on('destroy', release);
+}
+
+export function acquireMermaidUndoManager(
+ provider: HocuspocusProvider,
+ ytext: Y.Text,
+): Y.UndoManager {
+ const undoManager = acquireDocUndoManager(provider, ytext);
+ undoManager.removeTrackedOrigin(null);
+ undoManager.addTrackedOrigin(MERMAID_DIAGRAM_EDIT_ORIGIN);
+ installMermaidUndoReset(provider, ytext, undoManager);
+ return undoManager;
+}
export function MermaidDocEditor({
provider,
@@ -126,9 +200,7 @@ export function MermaidDocEditor({
return () => ytext.unobserve(sync);
}, [ytext]);
- const [undoManager] = useState(
- () => new Y.UndoManager(ytext, { trackedOrigins: new Set([MERMAID_DIAGRAM_EDIT_ORIGIN]) }),
- );
+ const undoManager = acquireMermaidUndoManager(provider, ytext);
const editBinding: MermaidSourceBinding = {
canEdit: true,
diff --git a/packages/app/src/components/TextDocEditor.tsx b/packages/app/src/components/TextDocEditor.tsx
index 25de248fd..c67009bf6 100644
--- a/packages/app/src/components/TextDocEditor.tsx
+++ b/packages/app/src/components/TextDocEditor.tsx
@@ -33,11 +33,11 @@ import {
import { useLingui } from '@lingui/react/macro';
import { basicSetup } from 'codemirror';
import { useTheme } from 'next-themes';
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useRef } from 'react';
import { yCollab } from 'y-codemirror.next';
-import * as Y from 'yjs';
import { propEditorHighlight } from '@/editor/components/CodeMirrorPropInput';
import { okCmTheme } from '@/editor/extensions/cm-theme';
+import { acquireDocUndoManager } from './doc-undo-manager';
import { loadCodeMirrorLanguageForExtension } from './text-viewer-languages';
const darkTheme = okCmTheme({
@@ -63,7 +63,7 @@ export function TextDocEditor({
const containerRef = useRef<HTMLDivElement>(null);
const { resolvedTheme } = useTheme();
const ytext = provider.document.getText('source');
- const [undoManager] = useState(() => new Y.UndoManager(ytext));
+ const undoManager = acquireDocUndoManager(provider, ytext);
useEffect(() => {
const el = containerRef.current;
diff --git a/packages/app/src/components/doc-undo-manager.test.ts b/packages/app/src/components/doc-undo-manager.test.ts
new file mode 100644
index 000000000..db95ddcef
--- /dev/null
+++ b/packages/app/src/components/doc-undo-manager.test.ts
@@ -0,0 +1,150 @@
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import { describe, expect, test } from 'vitest';
+import * as Y from 'yjs';
+import { __peekDocUndoManager, acquireDocUndoManager } from './doc-undo-manager';
+
+function createStubProvider(): {
+ provider: HocuspocusProvider;
+ emitDestroy: () => void;
+ listenerCount: () => number;
+ destroyListener: () => (() => void) | undefined;
+} {
+ const listeners = new Set<() => void>();
+ const provider = {
+ on(name: string, f: () => void) {
+ if (name === 'destroy') listeners.add(f);
+ },
+ off(name: string, f: () => void) {
+ if (name === 'destroy') listeners.delete(f);
+ },
+ };
+ return {
+ provider: provider as unknown as HocuspocusProvider,
+ emitDestroy: () => {
+ const pending = [...listeners];
+ listeners.clear();
+ for (const f of pending) f();
+ },
+ listenerCount: () => listeners.size,
+ destroyListener: () => [...listeners][0],
+ };
+}
+
+function makeDoc(): { doc: Y.Doc; ytext: Y.Text } {
+ const doc = new Y.Doc();
+ return { doc, ytext: doc.getText('source') };
+}
+
+const EDIT_ORIGIN = Symbol('test-edit');
+
+function destroyListeners(doc: Y.Doc): Set<unknown> {
+ const observers = (doc as unknown as { _observers: Map<string, Set<unknown>> })._observers;
+ return observers.get('destroy') ?? new Set();
+}
+
+describe('acquireDocUndoManager', () => {
+ test('a second acquisition of the same Y.Text reuses the manager instead of orphaning one', () => {
+ const { provider } = createStubProvider();
+ const { ytext } = makeDoc();
+
+ const first = acquireDocUndoManager(provider, ytext);
+ const second = acquireDocUndoManager(provider, ytext);
+
+ expect(second).toBe(first);
+ });
+
+ test('callers can add their own tracked origin to the shared manager', () => {
+ const { provider } = createStubProvider();
+ const { doc, ytext } = makeDoc();
+ const undoManager = acquireDocUndoManager(provider, ytext);
+ undoManager.addTrackedOrigin(EDIT_ORIGIN);
+
+ doc.transact(() => ytext.insert(0, 'tracked'), EDIT_ORIGIN);
+ expect(undoManager.undoStack.length).toBe(1);
+
+ doc.transact(() => ytext.insert(0, 'untracked'), Symbol('other'));
+ expect(undoManager.undoStack.length).toBe(1);
+ });
+
+ test('provider destroy clears the stacks and stops tracking', () => {
+ const { provider, emitDestroy } = createStubProvider();
+ const { doc, ytext } = makeDoc();
+ const undoManager = acquireDocUndoManager(provider, ytext);
+ undoManager.addTrackedOrigin(EDIT_ORIGIN);
+
+ doc.transact(() => ytext.insert(0, 'tracked'), EDIT_ORIGIN);
+ expect(undoManager.canUndo()).toBe(true);
+
+ emitDestroy();
+
+ expect(undoManager.undoStack.length).toBe(0);
+ expect(undoManager.canUndo()).toBe(false);
+ expect(__peekDocUndoManager(ytext)).toBeUndefined();
+
+ doc.transact(() => ytext.insert(0, 'after'), EDIT_ORIGIN);
+ expect(undoManager.undoStack.length).toBe(0);
+ });
+
+ test('acquiring after a release builds a fresh manager for the same Y.Text', () => {
+ const { provider, emitDestroy } = createStubProvider();
+ const { ytext } = makeDoc();
+
+ const first = acquireDocUndoManager(provider, ytext);
+ emitDestroy();
+ const second = acquireDocUndoManager(provider, ytext);
+
+ expect(second).not.toBe(first);
+ expect(__peekDocUndoManager(ytext)).toBe(second);
+ });
+
+ test('a released manager does not evict the replacement when its doc is destroyed later', () => {
+ const { provider, emitDestroy } = createStubProvider();
+ const { doc, ytext } = makeDoc();
+
+ const first = acquireDocUndoManager(provider, ytext);
+ first.addTrackedOrigin(EDIT_ORIGIN);
+ emitDestroy();
+ const second = acquireDocUndoManager(provider, ytext);
+ second.addTrackedOrigin(EDIT_ORIGIN);
+ expect(__peekDocUndoManager(ytext)).toBe(second);
+
+ doc.transact(() => ytext.insert(0, 'tracked'), EDIT_ORIGIN);
+ expect(second.undoStack.length).toBe(1);
+
+ doc.destroy();
+
+ expect(first.undoStack.length).toBe(0);
+ expect(second.undoStack.length).toBe(0);
+ expect(__peekDocUndoManager(ytext)).toBeUndefined();
+ });
+
+ test('provider destroy detaches the paired document listener', () => {
+ const { provider, emitDestroy, destroyListener } = createStubProvider();
+ const { doc, ytext } = makeDoc();
+
+ acquireDocUndoManager(provider, ytext);
+ const release = destroyListener();
+ if (!release) throw new Error('Expected a provider destroy listener');
+ expect(destroyListeners(doc).has(release)).toBe(true);
+ emitDestroy();
+
+ expect(destroyListeners(doc).has(release)).toBe(false);
+ });
+
+ test('doc destroy releases a manager whose provider never emitted destroy', () => {
+ const { provider, listenerCount } = createStubProvider();
+ const { doc, ytext } = makeDoc();
+ const undoManager = acquireDocUndoManager(provider, ytext);
+ undoManager.addTrackedOrigin(EDIT_ORIGIN);
+
+ doc.transact(() => ytext.insert(0, 'tracked'), EDIT_ORIGIN);
+ expect(undoManager.canUndo()).toBe(true);
+ expect(listenerCount()).toBe(1);
+
+ doc.destroy();
+
+ expect(undoManager.canUndo()).toBe(false);
+ expect(__peekDocUndoManager(ytext)).toBeUndefined();
+ expect(listenerCount()).toBe(0);
+ });
+});
diff --git a/packages/app/src/components/doc-undo-manager.ts b/packages/app/src/components/doc-undo-manager.ts
new file mode 100644
index 000000000..e16bae3b2
--- /dev/null
+++ b/packages/app/src/components/doc-undo-manager.ts
@@ -0,0 +1,33 @@
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import * as Y from 'yjs';
+
+const undoManagersByText = new WeakMap<Y.Text, Y.UndoManager>();
+
+export function acquireDocUndoManager(provider: HocuspocusProvider, ytext: Y.Text): Y.UndoManager {
+ const existing = undoManagersByText.get(ytext);
+ if (existing) return existing;
+
+ const undoManager = new Y.UndoManager(ytext);
+ undoManagersByText.set(ytext, undoManager);
+ const doc = ytext.doc;
+
+ let released = false;
+ const release = (): void => {
+ if (released) return;
+ released = true;
+ provider.off('destroy', release);
+ doc?.off('destroy', release);
+ if (undoManagersByText.get(ytext) === undoManager) undoManagersByText.delete(ytext);
+ undoManager.clear();
+ undoManager.destroy();
+ };
+
+ provider.on('destroy', release);
+ doc?.on('destroy', release);
+
+ return undoManager;
+}
+
+export function __peekDocUndoManager(ytext: Y.Text): Y.UndoManager | undefined {
+ return undoManagersByText.get(ytext);
+}
diff --git a/packages/app/src/editor/SourceEditor.dom.test.tsx b/packages/app/src/editor/SourceEditor.dom.test.tsx
index 0361befee..264d51588 100644
--- a/packages/app/src/editor/SourceEditor.dom.test.tsx
+++ b/packages/app/src/editor/SourceEditor.dom.test.tsx
@@ -2,7 +2,8 @@ import { EditorSelection } from '@codemirror/state';
import { EditorView } from '@codemirror/view';
import type { HocuspocusProvider } from '@hocuspocus/provider';
import type { Config } from '@inkeep/open-knowledge-core';
-import { act, cleanup, render, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';
+import { Activity } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { Awareness } from 'y-protocols/awareness';
import * as Y from 'yjs';
@@ -123,6 +124,8 @@ async function findCmContent(container: HTMLElement): Promise<HTMLElement> {
return container.querySelector<HTMLElement>('.cm-content');
}
+const ORIGINAL_PLATFORM = globalThis.navigator.platform;
+
function setPlatform(platform: string): void {
Object.defineProperty(globalThis.navigator, 'platform', {
value: platform,
@@ -146,6 +149,7 @@ describe('SourceEditor word-wrap preference wiring', () => {
});
afterEach(() => {
+ setPlatform(ORIGINAL_PLATFORM);
unsubscribeComposer?.();
unsubscribeComposer = null;
cleanup();
@@ -586,3 +590,147 @@ describe('SourceEditor Problems-row navigation', () => {
expect(peekPendingSourceNavigation(docName)).toBeNull();
});
});
+
+const FLIP_UNTRACKED_ORIGIN = Object.freeze({ kind: 'source-editor-dom-untracked-rewrite' });
+const MOD_KEY: 'metaKey' | 'ctrlKey' = /Mac/.test(ORIGINAL_PLATFORM) ? 'metaKey' : 'ctrlKey';
+
+function ActivityHarness({
+ provider,
+ ytext,
+ visible,
+ sourceMode = true,
+}: {
+ provider: HocuspocusProvider;
+ ytext: Y.Text;
+ visible: boolean;
+ sourceMode?: boolean;
+}) {
+ return (
+ <ConfigContext value={makeConfigValue(true)}>
+ <Activity mode={visible ? 'visible' : 'hidden'}>
+ <SourceEditor
+ docName={provider.configuration.name ?? 'test-source'}
+ ytext={ytext}
+ provider={provider}
+ isSourceModeActive={visible && sourceMode}
+ />
+ </Activity>
+ </ConfigContext>
+ );
+}
+
+async function pressUndo(content: HTMLElement): Promise<void> {
+ await act(async () => {
+ fireEvent.keyDown(content, { key: 'z', code: 'KeyZ', keyCode: 90, [MOD_KEY]: true });
+ });
+}
+
+describe('SourceEditor undo after leaving and returning to source mode', () => {
+ beforeEach(() => {
+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url === '/api/pages') return Response.json({ pages: [] });
+ if (url === '/api/documents') return Response.json({ documents: [] });
+ if (url === '/api/tags') return Response.json({ tags: [] });
+ return Response.json({}, { status: 404 });
+ }) as unknown as typeof fetch;
+ });
+
+ afterEach(() => {
+ cleanup();
+ for (const docName of mountedDocNames) {
+ evictCmEditor(docName);
+ }
+ mountedDocNames.clear();
+ globalThis.fetch = originalFetch;
+ });
+
+ async function mountAndType(docName: string): Promise<{
+ ytext: Y.Text;
+ content: HTMLElement;
+ rerender: (state: { visible: boolean; sourceMode?: boolean }) => void;
+ }> {
+ const { provider, ytext } = makeProvider(docName, '');
+ const view = render(<ActivityHarness provider={provider} ytext={ytext} visible={true} />);
+ const content = await findCmContent(view.container);
+ const cm = EditorView.findFromDOM(content);
+ expect(cm).toBeTruthy();
+ if (!cm) throw new Error('no CodeMirror view');
+ await act(async () => {
+ cm.dispatch({
+ changes: { from: 0, insert: 'hello bug\n\n\nhello bug' },
+ userEvent: 'input.type',
+ });
+ });
+ expect(ytext.toString()).toBe('hello bug\n\n\nhello bug');
+ return {
+ ytext,
+ content,
+ rerender: ({ visible, sourceMode }: { visible: boolean; sourceMode?: boolean }) =>
+ view.rerender(
+ <ActivityHarness
+ provider={provider}
+ ytext={ytext}
+ visible={visible}
+ sourceMode={sourceMode}
+ />,
+ ),
+ };
+ }
+
+ test('Cmd+Z after returning to a tab rewritten while hidden leaves the document unchanged', async () => {
+ const { ytext, content, rerender } = await mountAndType('source-flip-activity-rewrite');
+
+ await act(async () => rerender({ visible: false }));
+ await act(async () => {
+ ytext.doc?.transact(() => ytext.insert(ytext.length, ' oops'), FLIP_UNTRACKED_ORIGIN);
+ });
+ await act(async () => rerender({ visible: true }));
+
+ const beforeUndo = ytext.toString();
+ expect(beforeUndo).toBe('hello bug\n\n\nhello bug oops');
+
+ await pressUndo(content);
+
+ expect(ytext.toString()).toBe(beforeUndo);
+ });
+
+ test('Cmd+Z still undoes the pre-hide burst when nothing wrote while the tab was hidden', async () => {
+ const { ytext, content, rerender } = await mountAndType('source-flip-activity-quiet');
+
+ await act(async () => rerender({ visible: false }));
+ await act(async () => rerender({ visible: true }));
+
+ await pressUndo(content);
+
+ expect(ytext.toString()).toBe('');
+ });
+
+ test('Cmd+Z after an in-pane flip to Visual and back over a rewrite leaves the document unchanged', async () => {
+ const { ytext, content, rerender } = await mountAndType('source-flip-inpane-rewrite');
+
+ await act(async () => rerender({ visible: true, sourceMode: false }));
+ await act(async () => {
+ ytext.doc?.transact(() => ytext.insert(ytext.length, ' oops'), FLIP_UNTRACKED_ORIGIN);
+ });
+ await act(async () => rerender({ visible: true, sourceMode: true }));
+
+ const beforeUndo = ytext.toString();
+ expect(beforeUndo).toBe('hello bug\n\n\nhello bug oops');
+
+ await pressUndo(content);
+
+ expect(ytext.toString()).toBe(beforeUndo);
+ });
+
+ test('Cmd+Z still undoes the pre-flip burst after an in-pane flip with no rewrite', async () => {
+ const { ytext, content, rerender } = await mountAndType('source-flip-inpane-quiet');
+
+ await act(async () => rerender({ visible: true, sourceMode: false }));
+ await act(async () => rerender({ visible: true, sourceMode: true }));
+
+ await pressUndo(content);
+
+ expect(ytext.toString()).toBe('');
+ });
+});
diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsx
index 0c2727d9a..4bd29fd2e 100644
--- a/packages/app/src/editor/SourceEditor.tsx
+++ b/packages/app/src/editor/SourceEditor.tsx
@@ -11,7 +11,7 @@ import {
import { useTheme } from 'next-themes';
import { useEffect, useRef, useState } from 'react';
import { yCollab, yUndoManagerKeymap } from 'y-codemirror.next';
-import type * as Y from 'yjs';
+import * as Y from 'yjs';
import {
OUTLINE_NAV_BREADCRUMB,
OUTLINE_NAV_EVENT,
@@ -56,6 +56,10 @@ import { createLocalTargetDiagnosticsExtension } from './source-lint/local-targe
import { createMarkdownLintExtension } from './source-lint/markdown-lint-source';
import { sourceModeSetup } from './source-mode-setup';
import { createSourcePolishExtension } from './source-polish';
+import {
+ createSourceUndoFlipExtension,
+ setSourceViewUndoFlipActive,
+} from './source-undo-mode-flip';
import { attachTypingBurstDetector } from './typing-burst-detector';
const noScrollEffect = StateEffect.define<null>();
@@ -68,6 +72,18 @@ interface SourceEditorProps {
isSourceModeActive: boolean;
}
+function cleanupSourceEditorEntry(docName: string, entry: CmCacheEntry): void {
+ try {
+ setSourceViewUndoFlipActive(entry.view, false);
+ } finally {
+ try {
+ parkCmEditor(entry);
+ } finally {
+ unregisterSourceView(docName, entry.view);
+ }
+ }
+}
+
function applyOutlineNavigation(view: EditorView, detail: OutlineNavDetail, docName: string): void {
const lines = sourceHeadingLines(view.state.doc);
const heading = lines[detail.index];
@@ -153,12 +169,8 @@ export function SourceEditor({
: DEFAULT_LINTER_CONFIG);
const linterConfigKey = JSON.stringify(linterConfig);
- useEffect(() => {
- sourceModeActiveRef.current = isSourceModeActive;
- }, [isSourceModeActive]);
-
const cmEntryRef = useRef<CmCacheEntry | null>(null);
- // biome-ignore lint/correctness/useExhaustiveDependencies: see comment above
+ // biome-ignore lint/correctness/useExhaustiveDependencies: ytext and provider are the remount keys; docName is fixed for the lifetime of a mounted SourceEditor, and theme, wrap, placeholder and lint config reconfigure the live view through compartments
useEffect(() => {
const container = containerRef.current;
if (!container) return;
@@ -177,99 +189,108 @@ export function SourceEditor({
sizeStats,
factory: (el) => {
let selectionStatsTimer: ReturnType<typeof setTimeout> | null = null;
- const sourceClipboard = createSourceClipboardExtension({
- ydoc: provider.document,
- ytext,
- docName: resolvedDocName,
- });
- const themeCompartment = new Compartment();
- const wordWrapCompartment = new Compartment();
- const placeholderCompartment = new Compartment();
- const lintCompartment = new Compartment();
- const state = EditorState.create({
- doc: ytext.toString(),
- extensions: [
- sourceModeSetup,
- sourceLineDirection,
- search({
- scrollToMatch: (range) =>
- claimScrollerForNavigation(resolvedDocName, 'find-match')
- ? EditorView.scrollIntoView(range, { y: 'start' })
- : noScrollEffect.of(null),
- }),
- keymap.of([indentWithTab]),
- yCollab(ytext, provider.awareness),
- keymap.of(yUndoManagerKeymap),
- ...createNestedCMExtensions({
- themeCompartment,
- resolvedTheme,
- ydoc: provider.document,
- wordWrapCompartment,
- wordWrap,
- currentDocName: resolvedDocName,
- }),
- createSourcePolishExtension(),
- createSkillPathLinksSourceExtension(resolvedDocName),
- landingFlashSource(),
- lintCompartment.of(createMarkdownLintExtension(linterConfig, docName)),
- createLocalTargetDiagnosticsExtension(docName),
- sourceClipboard,
- EditorView.updateListener.of((update) => {
- if (!isUserIntentCmUpdate(update)) return;
- requestPreviewTabPromotion(resolvedDocName);
- }),
- EditorView.updateListener.of((update) => {
- if (!update.selectionSet && !update.docChanged) return;
- if (selectionStatsTimer !== null) clearTimeout(selectionStatsTimer);
- selectionStatsTimer = setTimeout(() => {
- selectionStatsTimer = null;
- publishSelectionStats(
- resolvedDocName,
- 'source',
- selectionStatsFromSource(update.view),
- );
- publishSelectionContext(
- resolvedDocName,
- 'source',
- selectionSnapshotFromSource(update.view, resolvedDocName),
- );
- }, SELECTION_STATS_DEBOUNCE_MS);
- }),
- placeholderCompartment.of(cmPlaceholder(placeholder ?? '')),
- EditorView.theme({
- '&': {
- height: '100%',
- },
- }),
- EditorView.scrollMargins.of(() => ({ top: editorToolbarOverlapPx() })),
- ],
- });
- const view = new EditorView({ state, parent: el });
- publishSelectionStats(resolvedDocName, 'source', selectionStatsFromSource(view));
- publishSelectionContext(
- resolvedDocName,
- 'source',
- selectionSnapshotFromSource(view, resolvedDocName),
- );
- const dom = view.contentDOM;
- dom.addEventListener('keydown', mark);
- dom.addEventListener('paste', mark);
- dom.addEventListener('drop', mark);
- dom.addEventListener('cut', mark);
- return {
- view,
- ydoc: provider.document,
- ytext,
- provider,
- themeCompartment,
- wordWrapCompartment,
- placeholderCompartment,
- lintCompartment,
- };
+ const undoManager = new Y.UndoManager(ytext);
+ try {
+ const sourceClipboard = createSourceClipboardExtension({
+ ydoc: provider.document,
+ ytext,
+ docName: resolvedDocName,
+ });
+ const themeCompartment = new Compartment();
+ const wordWrapCompartment = new Compartment();
+ const placeholderCompartment = new Compartment();
+ const lintCompartment = new Compartment();
+ const state = EditorState.create({
+ doc: ytext.toString(),
+ extensions: [
+ sourceModeSetup,
+ sourceLineDirection,
+ search({
+ scrollToMatch: (range) =>
+ claimScrollerForNavigation(resolvedDocName, 'find-match')
+ ? EditorView.scrollIntoView(range, { y: 'start' })
+ : noScrollEffect.of(null),
+ }),
+ keymap.of([indentWithTab]),
+ yCollab(ytext, provider.awareness, { undoManager }),
+ keymap.of(yUndoManagerKeymap),
+ createSourceUndoFlipExtension({ docName: resolvedDocName, ytext, undoManager }),
+ ...createNestedCMExtensions({
+ themeCompartment,
+ resolvedTheme,
+ ydoc: provider.document,
+ wordWrapCompartment,
+ wordWrap,
+ currentDocName: resolvedDocName,
+ }),
+ createSourcePolishExtension(),
+ createSkillPathLinksSourceExtension(resolvedDocName),
+ landingFlashSource(),
+ lintCompartment.of(createMarkdownLintExtension(linterConfig, docName)),
+ createLocalTargetDiagnosticsExtension(docName),
+ sourceClipboard,
+ EditorView.updateListener.of((update) => {
+ if (!isUserIntentCmUpdate(update)) return;
+ requestPreviewTabPromotion(resolvedDocName);
+ }),
+ EditorView.updateListener.of((update) => {
+ if (!update.selectionSet && !update.docChanged) return;
+ if (selectionStatsTimer !== null) clearTimeout(selectionStatsTimer);
+ selectionStatsTimer = setTimeout(() => {
+ selectionStatsTimer = null;
+ publishSelectionStats(
+ resolvedDocName,
+ 'source',
+ selectionStatsFromSource(update.view),
+ );
+ publishSelectionContext(
+ resolvedDocName,
+ 'source',
+ selectionSnapshotFromSource(update.view, resolvedDocName),
+ );
+ }, SELECTION_STATS_DEBOUNCE_MS);
+ }),
+ placeholderCompartment.of(cmPlaceholder(placeholder ?? '')),
+ EditorView.theme({
+ '&': {
+ height: '100%',
+ },
+ }),
+ EditorView.scrollMargins.of(() => ({ top: editorToolbarOverlapPx() })),
+ ],
+ });
+ const view = new EditorView({ state, parent: el });
+ publishSelectionStats(resolvedDocName, 'source', selectionStatsFromSource(view));
+ publishSelectionContext(
+ resolvedDocName,
+ 'source',
+ selectionSnapshotFromSource(view, resolvedDocName),
+ );
+ const dom = view.contentDOM;
+ dom.addEventListener('keydown', mark);
+ dom.addEventListener('paste', mark);
+ dom.addEventListener('drop', mark);
+ dom.addEventListener('cut', mark);
+ return {
+ view,
+ ydoc: provider.document,
+ ytext,
+ provider,
+ undoManager,
+ themeCompartment,
+ wordWrapCompartment,
+ placeholderCompartment,
+ lintCompartment,
+ };
+ } catch (err) {
+ undoManager.destroy();
+ throw err;
+ }
},
});
cmEntryRef.current = entry;
viewRef.current = entry.view;
+ setSourceViewUndoFlipActive(entry.view, isSourceModeActive);
registerSourceView(docName, entry.view);
if (claimNoteWindowInitialFocus()) entry.view.focus();
} catch (err) {
@@ -281,15 +302,20 @@ export function SourceEditor({
return () => {
const cur = cmEntryRef.current;
- if (cur) {
- parkCmEditor(cur);
- unregisterSourceView(docName, cur.view);
- }
cmEntryRef.current = null;
viewRef.current = null;
+ if (!cur) return;
+ cleanupSourceEditorEntry(docName, cur);
};
}, [ytext, provider]);
+ useEffect(() => {
+ sourceModeActiveRef.current = isSourceModeActive;
+ const view = viewRef.current;
+ if (!view) return;
+ setSourceViewUndoFlipActive(view, isSourceModeActive);
+ }, [isSourceModeActive]);
+
useEffect(() => {
if (import.meta.env.PROD) return;
const view = viewRef.current;
diff --git a/packages/app/src/editor/editor-cache.test.ts b/packages/app/src/editor/editor-cache.test.ts
index 1cdbb9003..b089588a4 100644
--- a/packages/app/src/editor/editor-cache.test.ts
+++ b/packages/app/src/editor/editor-cache.test.ts
@@ -774,6 +774,7 @@ describe('TipTap cache — undoManager.restore cleanup on destroy', () => {
});
test('cleanup is resilient when editor.destroy() throws', () => {
+ performance.clearMeasures('ok/cache/park-destroy-failed');
const h = makeTiptapHarness('doc-a');
const undoManager = attachStubUndoManager(h.editor);
(h.editor as unknown as { destroy: () => void }).destroy = () => {
@@ -795,6 +796,17 @@ describe('TipTap cache — undoManager.restore cleanup on destroy', () => {
expect(() => parkTiptapEditor(entry)).not.toThrow();
expect(h.spies.destroyCalls).toBe(1);
expect(undoManager.restore).toBeUndefined();
+ const failure = performance.getEntriesByName('ok/cache/park-destroy-failed').at(-1) as
+ | (PerformanceMeasure & {
+ detail?: { devtools?: { properties?: Array<[string, string]> } };
+ })
+ | undefined;
+ expect(Object.fromEntries(failure?.detail?.devtools?.properties ?? [])).toMatchObject({
+ docName: h.docName,
+ kind: 'tiptap',
+ stage: 'editor',
+ message: 'throwing-proxy',
+ });
});
test('evictTiptapEditor capture-before-destroy ordering: state inaccessible AFTER destroy still clears restore', () => {
@@ -1207,6 +1219,133 @@ describe('CM6 cache — lifecycle', () => {
});
});
+describe('CM6 cache — undoManager teardown', () => {
+ beforeEach(() => {
+ __resetCacheForTests();
+ __resetScrollRestoreCoordination();
+ });
+ afterEach(() => {
+ __resetCacheForTests();
+ });
+
+ function makeFakeCmUndoManager(): { undoManager: Y.UndoManager; calls: string[] } {
+ const calls: string[] = [];
+ const undoManager = {
+ clear() {
+ calls.push('clear');
+ },
+ destroy() {
+ calls.push('destroy');
+ },
+ } as unknown as Y.UndoManager;
+ return { undoManager, calls };
+ }
+
+ function mountWithUndoManager(h: CmHarness, undoManager: Y.UndoManager): CmCacheEntry {
+ return mountCmEditor({
+ docName: h.docName,
+ container: h.container as unknown as HTMLElement,
+ factory: ((ctr: FakeNode) => ({
+ ...h.factory(ctr),
+ undoManager,
+ })) as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,
+ });
+ }
+
+ test('parkCmEditor on an __uncached entry clears then destroys the undoManager', () => {
+ const h = makeCmHarness('cm-undo-uncached');
+ const { undoManager, calls } = makeFakeCmUndoManager();
+ const entry: CmCacheEntry = {
+ view: h.view,
+ ydoc: h.ydoc,
+ ytext: h.ytext,
+ provider: h.provider,
+ themeCompartment: h.themeCompartment,
+ wordWrapCompartment: h.wordWrapCompartment,
+ placeholderCompartment: h.placeholderCompartment,
+ lintCompartment: new Compartment(),
+ undoManager,
+ scrollTop: 0,
+ hadFocus: false,
+ activeMountKey: h.docName,
+ parkingNode: null,
+ __uncached: true,
+ };
+
+ parkCmEditor(entry);
+
+ expect(h.spies.destroyCalls).toBe(1);
+ expect(calls).toEqual(['clear', 'destroy']);
+ expect(entry.undoManager).toBeUndefined();
+ });
+
+ test('uncached park continues through undo-manager cleanup and marks a view teardown failure', () => {
+ performance.clearMeasures('ok/cache/park-destroy-failed');
+ const h = makeCmHarness('cm-view-uncached-failure');
+ const { undoManager, calls } = makeFakeCmUndoManager();
+ const entry: CmCacheEntry = {
+ view: h.view,
+ ydoc: h.ydoc,
+ ytext: h.ytext,
+ provider: h.provider,
+ themeCompartment: h.themeCompartment,
+ wordWrapCompartment: h.wordWrapCompartment,
+ placeholderCompartment: h.placeholderCompartment,
+ lintCompartment: new Compartment(),
+ scrollTop: 0,
+ hadFocus: false,
+ activeMountKey: h.docName,
+ parkingNode: null,
+ undoManager,
+ __uncached: true,
+ };
+ h.view.destroy = () => {
+ throw new Error('view teardown failed');
+ };
+
+ parkCmEditor(entry);
+
+ expect(calls).toEqual(['clear', 'destroy']);
+ expect(entry.undoManager).toBeUndefined();
+ const failure = performance.getEntriesByName('ok/cache/park-destroy-failed').at(-1) as
+ | (PerformanceMeasure & {
+ detail?: { devtools?: { properties?: Array<[string, string]> } };
+ })
+ | undefined;
+ expect(Object.fromEntries(failure?.detail?.devtools?.properties ?? [])).toMatchObject({
+ docName: h.docName,
+ kind: 'cm',
+ stage: 'view',
+ message: 'view teardown failed',
+ });
+ });
+
+ test('evictCmEditor clears then destroys the undoManager', () => {
+ const h = makeCmHarness('cm-undo-evict');
+ const { undoManager, calls } = makeFakeCmUndoManager();
+ const entry = mountWithUndoManager(h, undoManager);
+ expect(entry.undoManager).toBe(undoManager);
+
+ expect(evictCmEditor(h.docName)).toBe(true);
+
+ expect(h.spies.destroyCalls).toBe(1);
+ expect(calls).toEqual(['clear', 'destroy']);
+ expect(entry.undoManager).toBeUndefined();
+ });
+
+ test('the ordinary cached park leaves the undoManager alive for the reparent', () => {
+ const h = makeCmHarness('cm-undo-cached-park');
+ const { undoManager, calls } = makeFakeCmUndoManager();
+ const entry = mountWithUndoManager(h, undoManager);
+
+ parkCmEditor(entry);
+
+ expect(h.spies.destroyCalls).toBe(0);
+ expect(calls).toEqual([]);
+ expect(entry.undoManager).toBe(undoManager);
+ });
+});
+
describe('STOP rule: editor-cache never calls editor.mount() / editor.unmount()', () => {
test('source contains no reference to editor.mount( or editor.unmount(', async () => {
const sourceText = await Bun.file(`${import.meta.dir}/editor-cache.ts`).text();
diff --git a/packages/app/src/editor/editor-cache.ts b/packages/app/src/editor/editor-cache.ts
index 59e5bc348..b522e81aa 100644
--- a/packages/app/src/editor/editor-cache.ts
+++ b/packages/app/src/editor/editor-cache.ts
@@ -126,6 +126,7 @@ export interface CmCacheEntry {
wordWrapCompartment: Compartment;
placeholderCompartment: Compartment;
lintCompartment: Compartment;
+ undoManager?: Y.UndoManager;
scrollTop: number;
hadFocus: boolean;
activeMountKey: string | null;
@@ -147,6 +148,7 @@ interface CmFactoryResult {
ydoc: Y.Doc;
ytext: Y.Text;
provider: HocuspocusProvider;
+ undoManager?: Y.UndoManager;
themeCompartment: Compartment;
wordWrapCompartment: Compartment;
placeholderCompartment: Compartment;
@@ -445,6 +447,7 @@ export function parkTiptapEditor(entry: TiptapCacheEntry): void {
mark('ok/cache/park-destroy-failed', {
docName: docName ?? '',
kind: 'tiptap',
+ stage: 'editor',
message: err instanceof Error ? err.message : String(err),
});
}
@@ -539,6 +542,7 @@ export function mountCmEditor(params: MountCmParams): CmCacheEntry {
ydoc: fresh.ydoc,
ytext: fresh.ytext,
provider: fresh.provider,
+ undoManager: fresh.undoManager,
themeCompartment: fresh.themeCompartment,
wordWrapCompartment: fresh.wordWrapCompartment,
placeholderCompartment: fresh.placeholderCompartment,
@@ -602,6 +606,7 @@ export function mountCmEditor(params: MountCmParams): CmCacheEntry {
ydoc: fresh.ydoc,
ytext: fresh.ytext,
provider: fresh.provider,
+ undoManager: fresh.undoManager,
themeCompartment: fresh.themeCompartment,
wordWrapCompartment: fresh.wordWrapCompartment,
placeholderCompartment: fresh.placeholderCompartment,
@@ -642,9 +647,11 @@ export function parkCmEditor(entry: CmCacheEntry): void {
mark('ok/cache/park-destroy-failed', {
docName: entry.activeMountKey ?? '',
kind: 'cm',
+ stage: 'view',
message: err instanceof Error ? err.message : String(err),
});
}
+ destroyCmUndoManager(entry, entry.activeMountKey ?? '', 'park-destroy-failed');
entry.activeMountKey = null;
return;
}
@@ -664,6 +671,27 @@ export function parkCmEditor(entry: CmCacheEntry): void {
entry.activeMountKey = null;
}
+function destroyCmUndoManager(
+ entry: CmCacheEntry,
+ docName: string,
+ event: 'park-destroy-failed' | 'evict-failed',
+): void {
+ const undoManager = entry.undoManager;
+ if (!undoManager) return;
+ entry.undoManager = undefined;
+ try {
+ undoManager.clear();
+ undoManager.destroy();
+ } catch (err) {
+ mark(`ok/cache/${event}`, {
+ docName,
+ kind: 'cm',
+ stage: 'undo-manager',
+ message: err instanceof Error ? err.message : String(err),
+ });
+ }
+}
+
export function evictCmEditor(docName: string): boolean {
const entry = cmCache.get(docName);
if (!entry) return false;
@@ -680,6 +708,7 @@ export function evictCmEditor(docName: string): boolean {
message: err instanceof Error ? err.message : String(err),
});
}
+ destroyCmUndoManager(entry, docName, 'evict-failed');
try {
entry.provider.destroy();
} catch (err) {
diff --git a/packages/app/src/editor/source-undo-mode-flip.dom.test.ts b/packages/app/src/editor/source-undo-mode-flip.dom.test.ts
new file mode 100644
index 000000000..c9ee8f2d5
--- /dev/null
+++ b/packages/app/src/editor/source-undo-mode-flip.dom.test.ts
@@ -0,0 +1,90 @@
+import { EditorState } from '@codemirror/state';
+import { EditorView } from '@codemirror/view';
+import { afterEach, describe, expect, test } from 'vitest';
+import * as Y from 'yjs';
+import {
+ createSourceUndoFlipExtension,
+ setSourceViewUndoFlipActive,
+} from './source-undo-mode-flip';
+
+Object.defineProperty(window.Range.prototype, 'getClientRects', {
+ configurable: true,
+ value: () => [],
+});
+Object.defineProperty(window.Range.prototype, 'getBoundingClientRect', {
+ configurable: true,
+ value: () => ({ bottom: 0, height: 0, left: 0, right: 0, top: 0, width: 0 }),
+});
+
+const UNTRACKED_ORIGIN = Object.freeze({ kind: 'source-undo-flip-dom-untracked' });
+
+interface Rig {
+ doc: Y.Doc;
+ ytext: Y.Text;
+ undoManager: Y.UndoManager;
+ view: EditorView;
+ parent: HTMLElement;
+}
+
+const rigs: Rig[] = [];
+
+function mountRig(): Rig {
+ const doc = new Y.Doc();
+ const ytext = doc.getText('source');
+ const undoManager = new Y.UndoManager(ytext);
+ const parent = document.createElement('div');
+ document.body.appendChild(parent);
+ const view = new EditorView({
+ state: EditorState.create({
+ extensions: [
+ createSourceUndoFlipExtension({ docName: 'source-undo-flip-dom', ytext, undoManager }),
+ ],
+ }),
+ parent,
+ });
+ const rig = { doc, ytext, undoManager, view, parent };
+ rigs.push(rig);
+ return rig;
+}
+
+afterEach(() => {
+ for (const rig of rigs.splice(0)) {
+ try {
+ rig.view.destroy();
+ } catch {}
+ rig.parent.remove();
+ rig.doc.destroy();
+ }
+});
+
+describe('createSourceUndoFlipExtension plugin lifecycle', () => {
+ test('the view plugin registers a tracker the accessor can reach', () => {
+ const { doc, ytext, undoManager, view } = mountRig();
+ setSourceViewUndoFlipActive(view, true);
+ doc.transact(() => ytext.insert(0, 'one'));
+ expect(undoManager.undoStack.length).toBe(1);
+
+ setSourceViewUndoFlipActive(view, false);
+ doc.transact(() => ytext.insert(ytext.length, ' rewritten'), UNTRACKED_ORIGIN);
+ setSourceViewUndoFlipActive(view, true);
+
+ expect(undoManager.undoStack.length).toBe(0);
+ });
+
+ test('a destroyed view stops arming, so a later reactivation keeps the stack', () => {
+ const { doc, ytext, undoManager, view } = mountRig();
+ setSourceViewUndoFlipActive(view, true);
+ doc.transact(() => ytext.insert(0, 'one'));
+ expect(undoManager.undoStack.length).toBe(1);
+
+ setSourceViewUndoFlipActive(view, false);
+ view.destroy();
+
+ doc.transact(() => ytext.insert(ytext.length, ' rewritten'), UNTRACKED_ORIGIN);
+ setSourceViewUndoFlipActive(view, true);
+
+ expect(undoManager.undoStack.length).toBe(1);
+ undoManager.undo();
+ expect(ytext.toString()).toBe(' rewritten');
+ });
+});
diff --git a/packages/app/src/editor/source-undo-mode-flip.test.ts b/packages/app/src/editor/source-undo-mode-flip.test.ts
new file mode 100644
index 000000000..217cf4a34
--- /dev/null
+++ b/packages/app/src/editor/source-undo-mode-flip.test.ts
@@ -0,0 +1,267 @@
+import type { EditorView } from '@codemirror/view';
+import { FORM_WRITE_ORIGIN } from '@inkeep/open-knowledge-core';
+import { beforeEach, describe, expect, test } from 'vitest';
+import * as Y from 'yjs';
+import { createSourceUndoFlipTracker, setSourceViewUndoFlipActive } from './source-undo-mode-flip';
+
+const UNTRACKED_ORIGIN = Object.freeze({ kind: 'source-undo-flip-untracked' });
+const FLIP_CLEAR_MARK = 'ok/source-undo/flip-clear';
+const RIG_DOC_NAME = 'source-undo-flip-unit';
+
+function makeRig() {
+ const doc = new Y.Doc();
+ const ytext = doc.getText('source');
+ const undoManager = new Y.UndoManager(ytext);
+ const tracker = createSourceUndoFlipTracker({ docName: RIG_DOC_NAME, ytext, undoManager });
+ const trackedEdit = (text: string) => doc.transact(() => ytext.insert(ytext.length, text));
+ const untrackedEdit = (text: string) =>
+ doc.transact(() => ytext.insert(ytext.length, text), UNTRACKED_ORIGIN);
+ return { doc, ytext, undoManager, tracker, trackedEdit, untrackedEdit };
+}
+
+describe('createSourceUndoFlipTracker', () => {
+ test('deactivating source mode seals the capture window', () => {
+ const { ytext, undoManager, tracker, trackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+
+ trackedEdit('one');
+ tracker.setSourceModeActive(false);
+ trackedEdit('two');
+
+ expect(undoManager.undoStack.length).toBe(2);
+ undoManager.undo();
+ expect(ytext.toString()).toBe('one');
+ });
+
+ test('an untracked rewrite while inactive clears the stack on reactivation', () => {
+ const { ytext, undoManager, tracker, trackedEdit, untrackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+ trackedEdit('one');
+ expect(undoManager.undoStack.length).toBe(1);
+
+ tracker.setSourceModeActive(false);
+ untrackedEdit(' rewritten');
+ tracker.setSourceModeActive(true);
+
+ expect(undoManager.undoStack.length).toBe(0);
+ expect(undoManager.redoStack.length).toBe(0);
+ expect(undoManager.undo()).toBe(null);
+ expect(ytext.toString()).toBe('one rewritten');
+ });
+
+ test('a tracked write while inactive does not arm the reset', () => {
+ const { ytext, undoManager, tracker, trackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+ trackedEdit('one');
+
+ tracker.setSourceModeActive(false);
+ trackedEdit(' two');
+ tracker.setSourceModeActive(true);
+
+ expect(undoManager.undoStack.length).toBe(2);
+ undoManager.undo();
+ expect(ytext.toString()).toBe('one');
+ });
+
+ test('a real non-editor write surface arms the reset the same way a synthetic origin does', () => {
+ const { doc, ytext, undoManager, tracker, trackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+ trackedEdit('one');
+
+ tracker.setSourceModeActive(false);
+ doc.transact(() => ytext.insert(ytext.length, ' from the property panel'), FORM_WRITE_ORIGIN);
+ tracker.setSourceModeActive(true);
+
+ expect(undoManager.undoStack.length).toBe(0);
+ expect(undoManager.undo()).toBe(null);
+ expect(ytext.toString()).toBe('one from the property panel');
+ });
+
+ test('clearing on return drops redo along with undo', () => {
+ const { ytext, undoManager, tracker, trackedEdit, untrackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+ trackedEdit('one');
+ undoManager.stopCapturing();
+ trackedEdit(' two');
+ undoManager.undo();
+ expect(ytext.toString()).toBe('one');
+ expect(undoManager.redoStack.length).toBe(1);
+
+ tracker.setSourceModeActive(false);
+ untrackedEdit(' rewritten');
+ tracker.setSourceModeActive(true);
+
+ expect(undoManager.redoStack.length).toBe(0);
+ expect(undoManager.redo()).toBe(null);
+ expect(ytext.toString()).toBe('one rewritten');
+ });
+
+ test('undo works again on text typed after a clear, and only that text', () => {
+ const { ytext, undoManager, tracker, trackedEdit, untrackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+ trackedEdit('one');
+ tracker.setSourceModeActive(false);
+ untrackedEdit(' rewritten');
+ tracker.setSourceModeActive(true);
+
+ trackedEdit(' two');
+ expect(undoManager.undoStack.length).toBe(1);
+ undoManager.undo();
+ expect(ytext.toString()).toBe('one rewritten');
+
+ trackedEdit(' three');
+ tracker.setSourceModeActive(false);
+ tracker.setSourceModeActive(true);
+ expect(undoManager.undoStack.length).toBe(1);
+ undoManager.undo();
+ expect(ytext.toString()).toBe('one rewritten');
+ });
+
+ test('a flip with no intervening rewrite preserves the stack', () => {
+ const { ytext, undoManager, tracker, trackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+ trackedEdit('one');
+
+ tracker.setSourceModeActive(false);
+ tracker.setSourceModeActive(true);
+
+ expect(undoManager.undoStack.length).toBe(1);
+ undoManager.undo();
+ expect(ytext.toString()).toBe('');
+ });
+
+ test('an untracked rewrite while active does not arm the reset', () => {
+ const { ytext, undoManager, tracker, trackedEdit, untrackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+ trackedEdit('one');
+ untrackedEdit(' rewritten');
+
+ tracker.setSourceModeActive(false);
+ tracker.setSourceModeActive(true);
+
+ expect(undoManager.undoStack.length).toBe(1);
+ undoManager.undo();
+ expect(ytext.toString()).toBe(' rewritten');
+ });
+
+ test('characterization: an untracked rewrite while active leaves both bursts in one undo frame', () => {
+ const { ytext, undoManager, tracker, trackedEdit, untrackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+
+ trackedEdit('one');
+ untrackedEdit(' rewritten');
+ trackedEdit(' two');
+
+ expect(undoManager.undoStack.length).toBe(1);
+ undoManager.undo();
+ expect(ytext.toString()).toBe(' rewritten');
+ });
+
+ test('a destroyed tracker stops clearing an already-armed reset', () => {
+ const { ytext, undoManager, tracker, trackedEdit, untrackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+ trackedEdit('one');
+
+ tracker.setSourceModeActive(false);
+ untrackedEdit(' rewritten');
+ tracker.destroy();
+ tracker.setSourceModeActive(true);
+
+ expect(undoManager.undoStack.length).toBe(1);
+ undoManager.undo();
+ expect(ytext.toString()).toBe(' rewritten');
+ });
+
+ test('a destroyed tracker stops arming the reset', () => {
+ const { ytext, undoManager, tracker, trackedEdit, untrackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+ trackedEdit('one');
+
+ tracker.setSourceModeActive(false);
+ tracker.destroy();
+ untrackedEdit(' rewritten');
+ tracker.setSourceModeActive(true);
+
+ expect(undoManager.undoStack.length).toBe(1);
+ undoManager.undo();
+ expect(ytext.toString()).toBe(' rewritten');
+ });
+});
+
+describe('setSourceViewUndoFlipActive', () => {
+ test('throws when the flip extension is not installed on the view', () => {
+ const view = {} as EditorView;
+ expect(() => setSourceViewUndoFlipActive(view, true)).toThrow(/not installed/);
+ });
+});
+
+class FakeSyncConfig {}
+
+function makeClassOriginRig() {
+ const doc = new Y.Doc();
+ const ytext = doc.getText('source');
+ const undoManager = new Y.UndoManager(ytext);
+ undoManager.addTrackedOrigin(FakeSyncConfig);
+ const tracker = createSourceUndoFlipTracker({ docName: RIG_DOC_NAME, ytext, undoManager });
+ tracker.setSourceModeActive(true);
+ doc.transact(() => ytext.insert(0, 'seed'));
+ return { doc, ytext, undoManager, tracker };
+}
+
+describe('constructor-fallback origin classification', () => {
+ test('an instance of a class-registered tracked origin does not arm the reset', () => {
+ const { doc, ytext, undoManager, tracker } = makeClassOriginRig();
+ expect(undoManager.undoStack.length).toBe(1);
+
+ tracker.setSourceModeActive(false);
+ doc.transact(() => ytext.insert(ytext.length, ' from ySync'), new FakeSyncConfig());
+ tracker.setSourceModeActive(true);
+
+ expect(undoManager.undoStack.length).toBeGreaterThan(0);
+ undoManager.undo();
+ expect(ytext.toString()).toBe('seed');
+ });
+
+ test('an instance of an unregistered class still arms the reset', () => {
+ const { doc, ytext, undoManager, tracker } = makeClassOriginRig();
+ expect(undoManager.undoStack.length).toBe(1);
+
+ tracker.setSourceModeActive(false);
+ doc.transact(() => ytext.insert(ytext.length, ' rewritten'), UNTRACKED_ORIGIN);
+ tracker.setSourceModeActive(true);
+
+ expect(undoManager.undoStack.length).toBe(0);
+ expect(undoManager.undo()).toBe(null);
+ expect(ytext.toString()).toBe('seed rewritten');
+ });
+});
+
+describe('flip-clear observability mark', () => {
+ beforeEach(() => {
+ performance.clearMeasures(FLIP_CLEAR_MARK);
+ });
+
+ test('an armed reactivation emits the mark with the doc name', () => {
+ const { ytext, tracker, trackedEdit, untrackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+ trackedEdit('one');
+
+ tracker.setSourceModeActive(false);
+ untrackedEdit(' rewritten');
+ tracker.setSourceModeActive(true);
+
+ expect(ytext.toString()).toBe('one rewritten');
+ expect(performance.getEntriesByName(FLIP_CLEAR_MARK)).toHaveLength(1);
+ });
+
+ test('an unarmed peek emits nothing', () => {
+ const { tracker, trackedEdit } = makeRig();
+ tracker.setSourceModeActive(true);
+ trackedEdit('one');
+
+ tracker.setSourceModeActive(false);
+ tracker.setSourceModeActive(true);
+
+ expect(performance.getEntriesByName(FLIP_CLEAR_MARK)).toHaveLength(0);
+ });
+});
diff --git a/packages/app/src/editor/source-undo-mode-flip.ts b/packages/app/src/editor/source-undo-mode-flip.ts
new file mode 100644
index 000000000..6447ea3d6
--- /dev/null
+++ b/packages/app/src/editor/source-undo-mode-flip.ts
@@ -0,0 +1,81 @@
+import type { Extension } from '@codemirror/state';
+import { type EditorView, ViewPlugin } from '@codemirror/view';
+import type * as Y from 'yjs';
+import { mark } from '@/lib/perf';
+
+export interface SourceUndoFlipDeps {
+ docName: string;
+ ytext: Y.Text;
+ undoManager: Y.UndoManager;
+}
+
+export interface SourceUndoFlipTracker {
+ setSourceModeActive(active: boolean): void;
+ destroy(): void;
+}
+
+function isTrackedOrigin(undoManager: Y.UndoManager, origin: unknown): boolean {
+ const tracked = undoManager.trackedOrigins as Set<unknown>;
+ if (tracked.has(origin)) return true;
+ if (!origin) return false;
+ return tracked.has(origin.constructor);
+}
+
+export function createSourceUndoFlipTracker(deps: SourceUndoFlipDeps): SourceUndoFlipTracker {
+ const { docName, ytext, undoManager } = deps;
+ let active = false;
+ let sawUntrackedRewrite = false;
+ let destroyed = false;
+
+ const handler = (_event: Y.YTextEvent, transaction: Y.Transaction) => {
+ if (active) return;
+ if (isTrackedOrigin(undoManager, transaction.origin)) return;
+ sawUntrackedRewrite = true;
+ };
+ ytext.observe(handler);
+
+ return {
+ setSourceModeActive(next: boolean) {
+ if (destroyed) return;
+ if (next === active) return;
+ if (!next) {
+ active = false;
+ undoManager.stopCapturing();
+ return;
+ }
+ if (sawUntrackedRewrite) {
+ undoManager.clear();
+ mark('ok/source-undo/flip-clear', { docName });
+ }
+ sawUntrackedRewrite = false;
+ active = true;
+ },
+ destroy() {
+ if (destroyed) return;
+ destroyed = true;
+ ytext.unobserve(handler);
+ },
+ };
+}
+
+const trackerByView = new WeakMap<EditorView, SourceUndoFlipTracker>();
+
+export function createSourceUndoFlipExtension(deps: SourceUndoFlipDeps): Extension {
+ return ViewPlugin.define((view) => {
+ const tracker = createSourceUndoFlipTracker(deps);
+ trackerByView.set(view, tracker);
+ return {
+ destroy() {
+ tracker.destroy();
+ },
+ };
+ });
+}
+
+export function setSourceViewUndoFlipActive(view: EditorView, active: boolean): void {
+ const tracker = trackerByView.get(view);
+ if (!tracker) {
+ throw new Error('createSourceUndoFlipExtension is not installed on this EditorView');
+ }
+ tracker.setSourceModeActive(active);
+}
diff --git a/packages/app/tests/integration/origin-undoability-sweep.test.ts b/packages/app/tests/integration/origin-undoability-sweep.test.ts
index 388b048d1..07450204f 100644
--- a/packages/app/tests/integration/origin-undoability-sweep.test.ts
+++ b/packages/app/tests/integration/origin-undoability-sweep.test.ts
@@ -1,5 +1,5 @@
-import { readdirSync, readFileSync, statSync } from 'node:fs';
-import { join } from 'node:path';
+import { globSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import { basename, join } from 'node:path';
import { describe, expect, test } from 'vitest';
type UndoClass =
@@ -14,76 +14,93 @@ interface UndoRow {
undo: UndoClass;
why: string;
contract: string;
+ clearsSourceUndoOnModeReturn?: true;
}
const ORIGIN_UNDO_CONTRACT: Record<string, UndoRow> = {
AGENT_WRITE_ORIGIN: {
undo: 'agent-session-um',
- why: 'Typed exemplar for the agent-write origin; real writes carry the per-session session.origin. Undoable only by the server per-session UndoManager, never by a human Cmd+Z.',
- contract: 'session-undo-manager.test.ts, agent-undo.test.ts',
+ clearsSourceUndoOnModeReturn: true,
+ why: 'Typed exemplar for the agent-write origin; real writes carry the per-session session.origin. Undoable only by the server per-session UndoManager, never by a human Cmd+Z. The paired write reaches Y.Text(source), so one landing while source mode is inactive clears the source undo history on return.',
+ contract:
+ 'session-undo-manager.test.ts, integration/agent-undo.test.ts, source-undo-mode-flip.test.ts',
},
FILE_WATCHER_ORIGIN: {
undo: 'system-not-undoable',
- why: 'Disk-to-CRDT intake (paired). A system origin tracked by no UndoManager.',
- contract: 'external-change disk intake (system origin)',
+ clearsSourceUndoOnModeReturn: true,
+ why: 'Disk-to-CRDT intake (paired). A system origin tracked by no UndoManager. The paired write reaches Y.Text(source), so one landing while source mode is inactive clears the source undo history on return.',
+ contract: 'external-change disk intake (system origin), source-undo-mode-flip.test.ts',
},
ROLLBACK_ORIGIN: {
undo: 'system-not-undoable',
- why: 'Timeline restore rewrites body + fragment as a paired write; deliberately not client-undoable, and it stales pre-rollback client undo items.',
- contract: 'undo-after-rollback.test.ts',
+ clearsSourceUndoOnModeReturn: true,
+ why: 'Timeline restore rewrites body + fragment as a paired write; deliberately not client-undoable, and it stales pre-rollback client undo items. The paired write reaches Y.Text(source), so one landing while source mode is inactive clears the source undo history on return.',
+ contract: 'undo-after-rollback.test.ts, source-undo-mode-flip.test.ts',
},
MANAGED_RENAME_ORIGIN: {
undo: 'system-not-undoable',
- why: 'Managed-rename spine (paired). System origin tracked by no UndoManager.',
- contract: 'attribution-sweep-coverage.test.ts (identity threading)',
+ clearsSourceUndoOnModeReturn: true,
+ why: 'Managed-rename spine (paired). System origin tracked by no UndoManager. The paired write reaches Y.Text(source), so one landing while source mode is inactive clears the source undo history on return.',
+ contract:
+ 'attribution-sweep-coverage.test.ts (identity threading), source-undo-mode-flip.test.ts',
},
GENERATED_ARTIFACT_ORIGIN: {
undo: 'system-not-undoable',
- why: 'Machine-maintained generated documents are reconciled through a paired system write and are tracked by no UndoManager.',
- contract: 'generated-artifact.test.ts, server-factory.test.ts (generated index wiring)',
+ clearsSourceUndoOnModeReturn: true,
+ why: 'Machine-maintained generated documents are reconciled through a paired system write and are tracked by no UndoManager. The paired write reaches Y.Text(source), so one landing while source mode is inactive clears the source undo history on return.',
+ contract:
+ 'generated-artifact.test.ts, server-factory.test.ts (generated index wiring), source-undo-mode-flip.test.ts',
},
MERMAID_SOURCE_ORIGIN: {
undo: 'system-not-undoable',
- why: 'Mermaid diagram seed/reconcile into Y.Text(source); system origin, markdown bridge gated off.',
- contract: 'mermaid-persistence (system origin)',
+ why: 'Full Y.Text(source) seed/reconcile for standalone Mermaid, Excalidraw, and editable-text documents; system origin, markdown bridge gated off. A full replacement clears the Mermaid diagram UndoManager so stale label edits cannot replay into it; the editable-text pane exposes view-local CodeMirror history and the Excalidraw canvas its own scene history, so neither is reached by that clear.',
+ contract: 'MermaidDocEditor.test.ts (system reconcile)',
},
MERMAID_DIAGRAM_EDIT_ORIGIN: {
undo: 'client-editor-um',
why: 'Diagram-label commits, tracked by the MermaidDocEditor own client Y.UndoManager so Cmd+Z reverts a label edit.',
- contract: 'MermaidDocEditor (own UndoManager)',
+ contract: 'MermaidDocEditor.test.ts (own UndoManager)',
},
FORM_WRITE_ORIGIN: {
undo: 'no-undo-manager',
- why: 'Frontmatter property-panel write to the YAML region of Y.Text; single-root, captured by no editor UndoManager.',
- contract: 'write-surface-undo-exclusion.test.ts',
+ clearsSourceUndoOnModeReturn: true,
+ why: 'Frontmatter property-panel write to the YAML region of Y.Text; single-root, captured by no editor UndoManager, and one landing while source mode is inactive clears the source undo history on return.',
+ contract: 'write-surface-undo-exclusion.test.ts, source-undo-mode-flip.test.ts',
},
LINT_FIX_ORIGIN: {
undo: 'no-undo-manager',
- why: 'Client markdownlint auto-fix writing Y.Text(source) directly; captured by no editor UndoManager.',
- contract: 'write-surface-undo-exclusion.test.ts',
+ clearsSourceUndoOnModeReturn: true,
+ why: 'Client markdownlint auto-fix writing Y.Text(source) directly; captured by no editor UndoManager. Driven from the Problems panel and the visual editor, so one can land while source mode is inactive and clear the source undo history on return.',
+ contract: 'write-surface-undo-exclusion.test.ts, source-undo-mode-flip.test.ts',
},
SOURCE_PASTE_ORIGIN: {
undo: 'no-undo-manager',
- why: 'Chunked large source-mode paste writing Y.Text(source) directly, bypassing CM6 dispatch; captured by no editor UndoManager.',
- contract: 'write-surface-undo-exclusion.test.ts',
+ clearsSourceUndoOnModeReturn: true,
+ why: 'Chunked large source-mode paste writing Y.Text(source) directly, bypassing CM6 dispatch; captured by no editor UndoManager. Issued only from the source view paste handler, but the chunked insert yields per animation frame, so a tail chunk can land after a mode flip and clear the source undo history on return.',
+ contract: 'write-surface-undo-exclusion.test.ts, source-undo-mode-flip.test.ts',
},
TAB_REPLAY_ORIGIN: {
undo: 'replay-not-undoable',
- why: 'Recovery replay of buffered updates onto a recycled provider. The replayed bytes are durable but not Cmd+Z-undoable — post-recycle, the last pre-hiccup edits are recovery machinery, not a fresh user action.',
- contract: 'undo-recycle-reset.test.ts',
+ clearsSourceUndoOnModeReturn: true,
+ why: 'Recovery replay of buffered updates onto a recycled provider. The replayed bytes are durable but not Cmd+Z-undoable — post-recycle, the last pre-hiccup edits are recovery machinery, not a fresh user action. The replay reaches Y.Text(source), so one landing while source mode is inactive clears the source undo history on return.',
+ contract: 'undo-recycle-reset.test.ts, source-undo-mode-flip.test.ts',
},
};
const FACTORY_ORIGIN_ROWS: Record<string, UndoRow> = {
createSessionOrigin: {
undo: 'agent-session-um',
- why: 'Mints the per-session frozen agent-write origin (session.origin); object-identity-unique, added to the session UndoManager trackedOrigins so only that session can undo its writes.',
- contract: 'session-undo-manager.test.ts, agent-undo.test.ts',
+ clearsSourceUndoOnModeReturn: true,
+ why: 'Mints the per-session frozen agent-write origin (session.origin); object-identity-unique, added to the session UndoManager trackedOrigins so only that session can undo its writes. Its paired writes reach Y.Text(source), so one landing while source mode is inactive clears the source undo history on return.',
+ contract:
+ 'session-undo-manager.test.ts, integration/agent-undo.test.ts, source-undo-mode-flip.test.ts',
},
createUndoOrigin: {
undo: 'agent-undo-system',
- why: 'Mints the per-session agent-undo origin (session.undoOrigin); filtered out of its own stack so undo-of-undo never stacks. Idle-LRU eviction destroys the session UndoManager, and a later undo gets the loud no-active-session refusal rather than a wrong-frame pop.',
- contract: 'agent-undo.test.ts, agent-sessions.eviction.test.ts',
+ clearsSourceUndoOnModeReturn: true,
+ why: 'Mints the per-session agent-undo origin (session.undoOrigin); filtered out of its own stack so undo-of-undo never stacks. Idle-LRU eviction destroys the session UndoManager, and a later undo gets the loud no-active-session refusal rather than a wrong-frame pop. Its undo writes reach Y.Text(source), so one landing while source mode is inactive clears the source undo history on return.',
+ contract:
+ 'integration/agent-undo.test.ts, agent-sessions.eviction.test.ts, source-undo-mode-flip.test.ts',
},
};
@@ -119,15 +136,23 @@ const NON_CONTENT_ORIGINS: Record<string, string> = {
};
const HERE = import.meta.dirname;
+
const SRC_ROOTS = [
join(HERE, '../../../server/src'),
join(HERE, '../../../core/src'),
join(HERE, '../../src'),
];
const AGENT_SESSIONS_PATH = join(HERE, '../../../server/src/agent-sessions.ts');
+const CONTRACT_SEARCH_ROOTS = [
+ ...SRC_ROOTS,
+ join(HERE, '..'),
+ join(HERE, '../../../cli/src'),
+ join(HERE, '../../../desktop/src'),
+];
const ORIGIN_SEGMENT = /(^|_)ORIGIN(_|$)/;
const CONST_DECL = /\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::[^=;\n]+)?=/g;
+const CONTRACT_TEST_FILE = /[\w./-]+\.test\.tsx?\b/g;
function isScannedSource(fileName: string): boolean {
if (!fileName.endsWith('.ts') && !fileName.endsWith('.tsx')) return false;
@@ -149,6 +174,33 @@ function walkTsFiles(dir: string, out: string[]): void {
}
}
+function enumerateContractTestFiles(): Array<{ owner: string; file: string }> {
+ const rows: Array<[string, UndoRow]> = [
+ ...Object.entries(ORIGIN_UNDO_CONTRACT),
+ ...Object.entries(FACTORY_ORIGIN_ROWS),
+ ...Object.entries(RESERVED_UNDO_ROWS),
+ ];
+ return rows.flatMap(([owner, row]) =>
+ (row.contract.match(CONTRACT_TEST_FILE) ?? []).map((file) => ({ owner, file })),
+ );
+}
+
+function rowsPromisingSourceUndoClear(): Array<[string, UndoRow]> {
+ return [
+ ...Object.entries(ORIGIN_UNDO_CONTRACT),
+ ...Object.entries(FACTORY_ORIGIN_ROWS),
+ ...Object.entries(RESERVED_UNDO_ROWS),
+ ].filter(([, row]) => row.clearsSourceUndoOnModeReturn);
+}
+
+function contractFileHits(file: string): string[] {
+ return CONTRACT_SEARCH_ROOTS.flatMap((root) =>
+ globSync(`**/${file}`, { cwd: root, exclude: ['node_modules/**'] }).map((hit) =>
+ join(root, hit),
+ ),
+ );
+}
+
function enumerateOriginConstants(): string[] {
const files: string[] = [];
for (const root of SRC_ROOTS) walkTsFiles(root, files);
@@ -204,6 +256,27 @@ describe('origin-undoability sweep', () => {
]);
});
+ test('every test file named in a contract ruling resolves to exactly one path', () => {
+ const unresolved = enumerateContractTestFiles()
+ .map(({ owner, file }) => ({ owner, file, hits: contractFileHits(file) }))
+ .filter(({ hits }) => hits.length !== 1);
+ expect(unresolved).toEqual([]);
+ });
+
+ test('every ruling that promises a source-undo clear cites the mode-flip contract', () => {
+ expect(rowsPromisingSourceUndoClear().length).toBeGreaterThanOrEqual(11);
+ const missing = rowsPromisingSourceUndoClear()
+ .filter(([, row]) => !row.contract.includes('source-undo-mode-flip.test.ts'))
+ .map(([owner]) => owner);
+
+ expect(missing).toEqual([]);
+ });
+
+ test('the contract resolver catches an invented file (planted positive)', () => {
+ expect(contractFileHits('__never_a_real__.test.ts')).toEqual([]);
+ expect(contractFileHits(basename(import.meta.filename))).toHaveLength(1);
+ });
+
test('the reserved machine-merge undo row is documented for the conflict-spec extension point', () => {
expect(RESERVED_UNDO_ROWS['machine-merge']?.undo).toBe('system-not-undoable');
});
diff --git a/packages/app/tests/integration/source-undo-after-mode-flip.test.ts b/packages/app/tests/integration/source-undo-after-mode-flip.test.ts
new file mode 100644
index 000000000..75b2068bb
--- /dev/null
+++ b/packages/app/tests/integration/source-undo-after-mode-flip.test.ts
@@ -0,0 +1,181 @@
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import * as Y from 'yjs';
+import { installDomGlobals } from '../../src/editor/walk-currency-test-harness';
+import {
+ installCmMeasurementStubs,
+ mountSourceUndoEditor,
+ runSourceUndo,
+ typeInSource,
+} from './source-undo-rig.test-helper';
+import {
+ awaitDocQuiescence,
+ createTestClient,
+ createTestServer,
+ type TestClient,
+ type TestServer,
+ wait,
+} from './test-harness';
+
+const WYSIWYG_LOCAL_ORIGIN = Object.freeze({ kind: 'source-undo-flip-wysiwyg-local-edit' });
+
+let restoreDom: (() => void) | null = null;
+let server: TestServer;
+
+beforeAll(async () => {
+ const nativeEvent = globalThis.Event;
+ restoreDom = installDomGlobals();
+ installCmMeasurementStubs();
+ globalThis.Event = nativeEvent;
+ server = await createTestServer();
+}, 60_000);
+
+afterAll(async () => {
+ await server?.cleanup();
+ restoreDom?.();
+});
+
+async function pollUntil(predicate: () => boolean, label: string, timeoutMs = 8000): Promise<void> {
+ const start = Date.now();
+ while (Date.now() - start < timeoutMs) {
+ if (predicate()) return;
+ await wait(25);
+ }
+ throw new Error(`pollUntil timed out: ${label}`);
+}
+
+function paragraphTexts(fragment: Y.XmlFragment): string[] {
+ return fragment
+ .toArray()
+ .filter((n): n is Y.XmlElement => n instanceof Y.XmlElement)
+ .map((el) => el.toString().replace(/<[^>]+>/g, ''));
+}
+
+interface Mounted {
+ client: TestClient;
+ parent: HTMLElement;
+ mounted: ReturnType<typeof mountSourceUndoEditor>;
+}
+
+async function mountProductionEditor(): Promise<Mounted> {
+ const client: TestClient = await createTestClient(server.port);
+ const parent = globalThis.document.createElement('div');
+ globalThis.document.body.appendChild(parent);
+ const mounted = mountSourceUndoEditor({
+ ytext: client.ytext,
+ awareness: client.provider.awareness ?? undefined,
+ wiring: 'production',
+ parent,
+ });
+ return { client, parent, mounted };
+}
+
+async function teardown({ client, parent, mounted }: Mounted): Promise<void> {
+ mounted.destroy();
+ parent.remove();
+ await client.cleanup();
+}
+
+describe('source undo after a mode flip (real server observers + real provider)', () => {
+ test('one source undo after an untracked WYSIWYG-derived rewrite must not destroy the pre-flip burst', {
+ timeout: 60_000,
+ }, async () => {
+ const rig = await mountProductionEditor();
+ const { client } = rig;
+ const { view, undoManager, setSourceModeActive } = rig.mounted;
+
+ try {
+ setSourceModeActive(true);
+ typeInSource(view, 'hello bug\n');
+ typeInSource(view, '\n');
+ typeInSource(view, '\n');
+ typeInSource(view, 'hello bug');
+ expect(client.ytext.toString()).toBe('hello bug\n\n\nhello bug');
+ expect(undoManager.undoStack.length).toBe(1);
+
+ await pollUntil(
+ () => paragraphTexts(client.fragment).filter((t) => t.includes('hello bug')).length >= 2,
+ 'Observer B derived the two paragraphs into the client fragment',
+ );
+ await awaitDocQuiescence(client.doc, { timeoutMs: 5000 });
+
+ setSourceModeActive(false);
+
+ client.doc.transact(() => {
+ const p = new Y.XmlElement('paragraph');
+ const t = new Y.XmlText();
+ t.insert(0, 'oops');
+ p.insert(0, [t]);
+ client.fragment.insert(1, [p]);
+ }, WYSIWYG_LOCAL_ORIGIN);
+ await pollUntil(
+ () => client.ytext.toString().includes('oops'),
+ 'Observer A wrote the inserted paragraph back into Y.Text',
+ );
+
+ client.doc.transact(() => {
+ const paras = client.fragment
+ .toArray()
+ .filter((n): n is Y.XmlElement => n instanceof Y.XmlElement);
+ const last = paras[paras.length - 1];
+ const textNode = last?.get(0);
+ if (!(textNode instanceof Y.XmlText)) throw new Error('expected XmlText in paragraph');
+ textNode.insert(textNode.length, ' oops');
+ }, WYSIWYG_LOCAL_ORIGIN);
+ await pollUntil(
+ () => client.ytext.toString().includes('hello bug oops'),
+ 'Observer A wrote the appended text back into Y.Text',
+ );
+ await awaitDocQuiescence(client.doc, { timeoutMs: 5000 });
+
+ setSourceModeActive(true);
+
+ const textBeforeUndo = client.ytext.toString();
+ expect(textBeforeUndo.match(/hello bug/g)?.length).toBe(2);
+ expect(textBeforeUndo).toContain('oops');
+
+ runSourceUndo(view, 'production');
+ await awaitDocQuiescence(client.doc, { timeoutMs: 5000 });
+
+ expect(client.ytext.toString()).toBe(textBeforeUndo);
+ } finally {
+ await teardown(rig);
+ }
+ });
+
+ test('a flip round trip with no rewrite seals the capture window and preserves history', {
+ timeout: 60_000,
+ }, async () => {
+ const rig = await mountProductionEditor();
+ const { client } = rig;
+ const { view, undoManager, setSourceModeActive } = rig.mounted;
+
+ try {
+ setSourceModeActive(true);
+ typeInSource(view, 'hello bug\n\n\nhello bug');
+ expect(undoManager.undoStack.length).toBe(1);
+
+ await pollUntil(
+ () => paragraphTexts(client.fragment).filter((t) => t.includes('hello bug')).length >= 2,
+ 'Observer B derived the two paragraphs into the client fragment',
+ );
+ await awaitDocQuiescence(client.doc, { timeoutMs: 5000 });
+
+ setSourceModeActive(false);
+
+ await wait(250);
+ await awaitDocQuiescence(client.doc, { timeoutMs: 5000 });
+ expect(client.ytext.toString()).toBe('hello bug\n\n\nhello bug');
+
+ setSourceModeActive(true);
+
+ typeInSource(view, ' tail');
+ expect(undoManager.undoStack.length).toBe(2);
+
+ runSourceUndo(view, 'production');
+ await awaitDocQuiescence(client.doc, { timeoutMs: 5000 });
+ expect(client.ytext.toString()).toBe('hello bug\n\n\nhello bug');
+ } finally {
+ await teardown(rig);
+ }
+ });
+});
diff --git a/packages/app/tests/integration/source-undo-rig.test-helper.ts b/packages/app/tests/integration/source-undo-rig.test-helper.ts
index 869acdf29..1dde5c083 100644
--- a/packages/app/tests/integration/source-undo-rig.test-helper.ts
+++ b/packages/app/tests/integration/source-undo-rig.test-helper.ts
@@ -6,6 +6,10 @@ import { yCollab, yUndoManagerKeymap } from 'y-codemirror.next';
import type { Awareness } from 'y-protocols/awareness';
import * as Y from 'yjs';
import { sourceModeSetup } from '../../src/editor/source-mode-setup';
+import {
+ createSourceUndoFlipExtension,
+ setSourceViewUndoFlipActive,
+} from '../../src/editor/source-undo-mode-flip';
export type SourceUndoWiring = 'production' | 'legacy';
@@ -37,15 +41,22 @@ export function installCmMeasurementStubs(): void {
export interface MountedSourceUndoEditor {
view: EditorView;
undoManager: Y.UndoManager;
+ setSourceModeActive: (active: boolean) => void;
destroy: () => void;
}
export function mountSourceUndoEditor(opts: {
+ docName?: string;
ytext: Y.Text;
- awareness: Awareness;
+ awareness?: Awareness;
wiring: SourceUndoWiring;
parent: HTMLElement;
}): MountedSourceUndoEditor {
+ if (opts.wiring === 'production' && !opts.awareness) {
+ throw new Error(
+ 'mountSourceUndoEditor({ wiring: "production" }) requires awareness: yCollab drops yRemoteSelections without it, so the mount would install a smaller extension set than SourceEditor.tsx',
+ );
+ }
const undoManager = new Y.UndoManager(opts.ytext);
const undoWiring =
opts.wiring === 'production'
@@ -53,13 +64,28 @@ export function mountSourceUndoEditor(opts: {
sourceModeSetup,
yCollab(opts.ytext, opts.awareness, { undoManager }),
keymap.of(yUndoManagerKeymap),
+ createSourceUndoFlipExtension({
+ docName: opts.docName ?? 'source-undo-rig',
+ ytext: opts.ytext,
+ undoManager,
+ }),
]
: [basicSetup, yCollab(opts.ytext, opts.awareness, { undoManager })];
const view = new EditorView({
state: EditorState.create({ doc: opts.ytext.toString(), extensions: undoWiring }),
parent: opts.parent,
});
- return { view, undoManager, destroy: () => view.destroy() };
+ const setSourceModeActive = (active: boolean) => {
+ if (opts.wiring !== 'production') return;
+ setSourceViewUndoFlipActive(view, active);
+ };
+ setSourceModeActive(true);
+ return {
+ view,
+ undoManager,
+ setSourceModeActive,
+ destroy: () => view.destroy(),
+ };
}
export function typeInSource(view: EditorView, text: string, at?: number): void {
@@ -83,7 +109,8 @@ export function applyRemoteSourceEdit(local: Y.Doc, mutate: (ytext: Y.Text) => v
export function runSourceUndo(view: EditorView, wiring: SourceUndoWiring): boolean {
if (wiring === 'production') {
const binding = yUndoManagerKeymap.find((b) => b.key === 'Mod-z');
- return binding?.run?.(view) ?? false;
+ if (!binding?.run) throw new Error('yUndoManagerKeymap no longer binds Mod-z');
+ return binding.run(view);
}
return cmNativeUndo(view);
}
diff --git a/packages/app/tests/stress/source-undo-mode-flip.e2e.ts b/packages/app/tests/stress/source-undo-mode-flip.e2e.ts
new file mode 100644
index 000000000..6681bbc1d
--- /dev/null
+++ b/packages/app/tests/stress/source-undo-mode-flip.e2e.ts
@@ -0,0 +1,137 @@
+import { randomUUID } from 'node:crypto';
+import type { Page } from '@playwright/test';
+import { expect, test, waitForActiveProviderSynced as waitForProvider } from './_helpers';
+
+const sourceToggle = (page: Page) => page.getByRole('radio', { name: 'Markdown source' });
+const visualToggle = (page: Page) => page.getByRole('radio', { name: 'Visual editor' });
+
+function readSource(page: Page): Promise<string> {
+ return page.evaluate(() => window.__activeProvider?.document.getText('source').toString() ?? '');
+}
+
+async function waitForSourceQuiescence(page: Page): Promise<void> {
+ let previous: string | null = null;
+ await expect
+ .poll(
+ async () => {
+ const current = await readSource(page);
+ const settled = current === previous;
+ previous = current;
+ return settled;
+ },
+ { timeout: 10_000, intervals: [250] },
+ )
+ .toBe(true);
+}
+
+async function caretAtEndOf(page: Page, locatorText: string): Promise<void> {
+ const paragraph = page
+ .locator('.ProseMirror:not(.composer-prosemirror) > p')
+ .filter({ hasText: locatorText })
+ .last();
+ await paragraph.evaluate((el) => {
+ el.closest<HTMLElement>('.ProseMirror')?.focus();
+ const selection = window.getSelection();
+ const range = document.createRange();
+ range.selectNodeContents(el);
+ range.collapse(false);
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ });
+}
+
+async function openDocInSourceMode(
+ page: Page,
+ api: { createPage: (name: string) => Promise<unknown> },
+) {
+ const docName = `test-source-undo-flip-${randomUUID().slice(0, 8)}`;
+ await api.createPage(`${docName}.md`);
+ await page.goto(`/#/${docName}`);
+ await waitForProvider(page);
+ await page.waitForSelector('.ProseMirror:not(.composer-prosemirror)');
+ await sourceToggle(page).click();
+ const cm = page.locator('.cm-content').first();
+ await expect(cm).toBeVisible({ timeout: 10_000 });
+ return cm;
+}
+
+test.describe('source undo after a mode flip (live app)', () => {
+ test('source-mode Cmd+Z after WYSIWYG edits must not destroy the untouched pre-flip line', async ({
+ page,
+ api,
+ }) => {
+ const cm = await openDocInSourceMode(page, api);
+ await cm.click();
+ await page.keyboard.insertText('hello bug\n\n\nhello bug');
+ await expect
+ .poll(() => readSource(page), { timeout: 10_000 })
+ .toContain('hello bug\n\n\nhello bug');
+
+ await visualToggle(page).click();
+ const pm = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await expect(pm).toBeVisible({ timeout: 10_000 });
+ await expect(pm).toContainText('hello bug');
+
+ await caretAtEndOf(page, 'hello bug');
+ await page.keyboard.insertText(' oops');
+ await expect.poll(() => readSource(page), { timeout: 10_000 }).toContain('hello bug oops');
+
+ await waitForSourceQuiescence(page);
+ const blankParagraph = page
+ .locator('.ProseMirror:not(.composer-prosemirror) > p')
+ .filter({ hasText: /^$/ })
+ .first();
+ await blankParagraph.click();
+ await page.keyboard.type('zoops', { delay: 40 });
+ await expect.poll(() => readSource(page), { timeout: 10_000 }).toContain('zoops');
+
+ await sourceToggle(page).click();
+ await expect(cm).toBeVisible({ timeout: 10_000 });
+ await waitForSourceQuiescence(page);
+
+ const beforeUndo = await readSource(page);
+ expect((beforeUndo.match(/hello bug/g) ?? []).length).toBe(2);
+ expect(beforeUndo).toContain('hello bug oops');
+ expect(beforeUndo).toContain('zoops');
+
+ await cm.click();
+ await page.keyboard.press('ControlOrMeta+z');
+ await waitForSourceQuiescence(page);
+
+ expect((await readSource(page)).split('\n')).toEqual(beforeUndo.split('\n'));
+
+ await cm.click();
+ await page.keyboard.insertText('Q');
+ await expect.poll(() => readSource(page), { timeout: 10_000 }).toContain('Q');
+ await waitForSourceQuiescence(page);
+
+ await page.keyboard.press('ControlOrMeta+z');
+ await expect.poll(() => readSource(page), { timeout: 10_000 }).toBe(beforeUndo);
+ });
+
+ test('guard: a casual peek at Visual editor with no edit preserves source undo history', async ({
+ page,
+ api,
+ }) => {
+ const cm = await openDocInSourceMode(page, api);
+ await cm.click();
+ await page.keyboard.insertText('hello bug\n\n\nhello bug');
+ await expect
+ .poll(() => readSource(page), { timeout: 10_000 })
+ .toContain('hello bug\n\n\nhello bug');
+
+ await visualToggle(page).click();
+ const pm = page.locator('.ProseMirror:not(.composer-prosemirror)').first();
+ await expect(pm).toBeVisible({ timeout: 10_000 });
+ await expect(pm).toContainText('hello bug');
+
+ await sourceToggle(page).click();
+ await expect(cm).toBeVisible({ timeout: 10_000 });
+ await waitForSourceQuiescence(page);
+
+ await cm.click();
+ await page.keyboard.press('ControlOrMeta+z');
+
+ await expect.poll(() => readSource(page), { timeout: 10_000 }).not.toContain('hello bug');
+ });
+});