Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): keep your place when switching editor modes (#3010)
Nick Gomezbb1575e9a3c1
diff --git a/.changeset/mode-switch-position-fidelity.md b/.changeset/mode-switch-position-fidelity.mdnew file mode 100644index 000000000..4a20e8478--- /dev/null+++ b/.changeset/mode-switch-position-fidelity.md@@ -0,0 +1,27 @@+---+"@inkeep/open-knowledge": minor+---++Keep your place when switching between the visual and Markdown editors. Toggling+modes now keeps the block you were looking at in view in both directions instead+of dropping you at an unrelated scroll position, and a plain toggle no longer+disturbs either editor's own selection.++Add a **View in source** action that jumps from the visual editor to the exact+Markdown behind what you're looking at — centered, briefly highlighted, with the+caret placed ready to edit. Reach it from the selection bubble menu, the desktop+editor right-click menu, or the keyboard: `⌥⌘M` toggles between visual and+source, and `⌥⌘E` opens the source for the block at the caret. The highlight+respects your reduced-motion setting.++Landing is honest about uncertainty rather than confidently wrong. If the+document changes underneath a pending jump, or a block cannot be matched exactly,+it settles on the nearest enclosing block and drops the highlight instead of+guessing. Long documents keep working: the landing waits for the incoming editor+to actually render, re-aims itself if content shifts while it settles, and gives+up cleanly rather than fighting the page.++Explicit navigation always wins over a mode switch that is still settling.+Clicking a Problems-panel row, an outline entry, or a find/replace match takes+you there even immediately after a flip, and the composer's scroll-to-bottom no+longer pulls you off a landing.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 950f62646..4e5c464c1 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -20,7 +20,7 @@ It opens in the desktop app when it's installed, and falls back to your browser## Document body-Open any doc from the sidebar. The body renders as WYSIWYG markdown with familiar conventions: bold / italic / headings / lists / tables / code fences / links / images. Toggle to source mode from the editor controls to edit the raw markdown directly; both views are bound to the same CRDT document, so they stay in sync across users and AI agents.+Open any doc from the sidebar. The body renders as WYSIWYG markdown with familiar conventions: bold / italic / headings / lists / tables / code fences / links / images. Toggle to source mode from the editor controls or with `Cmd+Option+M` to edit the raw markdown directly; both views are bound to the same CRDT document, so they stay in sync across users and AI agents. Switching modes keeps your place — the block you were looking at stays in view either way.A slash command (`/`) opens an insert menu for headings, lists, tables, code blocks, callouts, footnotes, inline math, and the other content shapes the editor supports.@@ -55,6 +55,8 @@ Links work the way they do in the editors you already know:In the desktop app, right-clicking editable text opens a native context menu. Any editable field gets **Cut / Copy / Paste / Select All**; when there's a selection or a flagged word under the cursor, **Look Up** (the macOS dictionary panel) and **Search with Google** join it.+Over the document body, the menu also carries **View in Source `</>`** — the desktop equivalent of `Cmd+Option+E`, opening the Markdown behind the block you right-clicked in the visual editor.+Spell checking uses the native macOS spellchecker (language follows your macOS settings), so misspelled words get the familiar red underline. Right-clicking a flagged word adds the spelling section:| Item | Behavior |@@ -213,6 +215,8 @@ Keyboard shortcuts (use `Ctrl` on Windows / Linux in place of `Cmd`, unless the| `Cmd+K` | Command palette — or, with text selected in the visual editor, add a link (cursor inside a link edits it). || `Cmd+Option+S` | Show / Hide the file sidebar (left). Matches Apple's standard sidebar accelerator. || `Cmd+Option+B` | Show / Hide the document panel (right). Matches VS Code's Secondary Side Bar accelerator. |+| `Cmd+Option+M` | Toggle between the visual and source editors, keeping your place. |+| `Cmd+Option+E` | **View in source** — jump from the visual editor to the Markdown for the block at the cursor, centered and highlighted (visual editor only). || `Cmd+J` | Show / Hide the docked terminal (desktop app). With text selected, stages the passage into the AI CLI's input instead — nothing runs until you press Enter. || `Cmd+Shift+J` | Open an additional terminal tab (desktop app). With text selected, stages the passage into the new tab's AI CLI input. || `Cmd+K` | Open the [command palette](#command-palette). |diff --git a/knip.config.ts b/knip.config.tsindex 563d574d8..64bfa20a9 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -122,7 +122,9 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: ['@types/shell-quote'],+ ignoreDependencies: [+ '@types/shell-quote',+ ],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],diff --git a/packages/app/package.json b/packages/app/package.jsonindex 51fa41412..88cd18a75 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -26,7 +26,7 @@"measure:fuzz": "bash scripts/measure-fuzz.sh","measure:stress": "bash scripts/measure-stress.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.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/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/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/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/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/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/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.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",+ "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/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/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/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/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/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/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/slash-command-auto-open.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.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","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",@@ -52,7 +52,7 @@{"name": "all JS chunks combined (gzipped)","path": "dist/assets/*.js",- "limit": "3.61 MB",+ "limit": "3.62 MB","gzip": true,"running": false},diff --git a/packages/app/src/components/BottomComposer.tsx b/packages/app/src/components/BottomComposer.tsxindex bd3424531..6a6ccac1e 100644--- a/packages/app/src/components/BottomComposer.tsx+++ b/packages/app/src/components/BottomComposer.tsx@@ -49,6 +49,7 @@ import {ComposerMentionInput,type ComposerMentionInputHandle,} from '@/editor/ComposerMentionInput';+import { isScrollRestoreSuppressed } from '@/editor/scroll-restore-coordination';import {lightRenderMarkdownPreview,type SelectionSnapshot,@@ -279,6 +280,14 @@ export function BottomComposer({// eases down so the last lines stay above the newly-grown composer instead of// being covered. Also clamps any scroller stranded past shrinking content.const followBottom = () => {+ // A mode-switch landing owns the scroller for its whole settle window, so+ // the pin must stand down for it exactly as it does for the user's own+ // wheel. Without this the pin wins: a deep mode flip momentarily clamps+ // the scroller to the bottom (the outgoing mode's scrollTop overshoots the+ // incoming mode's shorter content), which reads here as "bottom-anchored"+ // and re-pins the user to the end of the document every frame, stomping+ // the landing after it settled.+ if (isScrollRestoreSuppressed(docName)) return;const pinned = [...document.querySelectorAll<HTMLElement>('.editor-doc-scroll')].filter((el) => {const max = el.scrollHeight - el.clientHeight;@@ -296,6 +305,10 @@ export function BottomComposer({window.addEventListener('touchstart', cancel, { passive: true });const start = performance.now();const step = () => {+ // A landing that starts mid-window cancels the pin outright rather than+ // pausing it: resuming afterwards would yank the settled landing back to+ // the bottom, since `pinned` was captured before the landing moved it.+ if (isScrollRestoreSuppressed(docName)) cancelled = true;if (cancelled || performance.now() - start >= 300) {window.removeEventListener('wheel', cancel);window.removeEventListener('touchstart', cancel);@@ -312,6 +325,9 @@ export function BottomComposer({const revealCaret = () => {if (surface !== 'wysiwyg') return;requestAnimationFrame(() => {+ // Same standing-down rule as the bottom pin: never write scroll while a+ // landing owns the scroller.+ if (isScrollRestoreSuppressed(docName)) return;const editor = getEditorForDoc(docName);const box = cardRef.current;if (!editor || editor.isDestroyed || !box) return;diff --git a/packages/app/src/components/EditorActivityPool.mount-gate.dom.test.tsx b/packages/app/src/components/EditorActivityPool.mount-gate.dom.test.tsxnew file mode 100644index 000000000..59f796184--- /dev/null+++ b/packages/app/src/components/EditorActivityPool.mount-gate.dom.test.tsx@@ -0,0 +1,144 @@+// @vitest-environment jsdom+/**+ * Composition coverage for the defer-mount gate.+ *+ * `computeEffectiveSourceMode` and `computeEditorMountGate` are each unit-tested+ * on their own, but the defect they exist to fix only reappears in how+ * `ActivityEntry` wires them together: the gate must be fed the entry's+ * EFFECTIVE mode (frozen for a hidden entry) rather than the raw global mode,+ * or a global flip materialises the other mode's editor inside a hidden+ * `display:none` subtree. Feeding the raw mode back in keeps every pure-helper+ * test green, so this renders the real pool and reads the decision off the+ * `ok/activity/defer-mount` mark the entry emits.+ *+ * The heavy editor graph is stubbed the way the sibling `EditorArea.*` DOM+ * tests do it — everything except the gate itself is a marker, so the assertion+ * observes which editors the pool decided to render and nothing else.+ */++import { cleanup, render } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import * as Y from 'yjs';+import { getCollector } from '@/lib/perf/collector';++// Small enough that a one-line document counts as "large", so the gate takes+// its defer branch without building a half-megabyte Y.Text.+window.__okPerfOverrides = { LARGE_DOC_CHAR_THRESHOLD: 4 };++interface FakePoolEntry {+ docName: string;+ provider: { document: Y.Doc; configuration: { name: string } };+ poolEventId: string;+ lastAccessedAt: number;+}++const poolEntries: FakePoolEntry[] = [];++vi.doMock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({ poolEntries, serverRestartRecovery: { kind: 'idle' } }),+}));+vi.doMock('./PageListContext', () => ({+ usePageList: () => ({ pages: new Map(), loading: false }),+}));+vi.doMock('@/hooks/use-lifecycle-status', () => ({ useLifecycleStatus: () => 'ready' }));+vi.doMock('@/editor/TiptapEditor', () => ({+ TiptapEditor: () => <div data-testid="tiptap-editor" />,+}));+vi.doMock('@/editor/SourceEditor', () => ({+ SourceEditor: () => <div data-testid="source-editor" />,+}));+vi.doMock('./DocumentBoundary', () => ({+ DocumentBoundary: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}));+vi.doMock('./DocumentErrorBoundary', () => ({+ DocumentErrorBoundary: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}));+vi.doMock('./DiffViewBoundary', () => ({ DiffViewBoundary: () => <div /> }));+vi.doMock('./EditorSkeleton', () => ({ EditorSkeleton: () => <div data-testid="skeleton" /> }));+vi.doMock('./PageHeader', () => ({ PageHeader: () => <div /> }));+vi.doMock('./PropertyPanel', () => ({ PropertyPanel: () => <div /> }));++const { EditorActivityPool } = await import('./EditorActivityPool');++function makeEntry(docName: string, lastAccessedAt: number): FakePoolEntry {+ const document = new Y.Doc();+ document.getText('source').insert(0, 'a body long enough to pass the threshold');+ return {+ docName,+ provider: { document, configuration: { name: docName } },+ poolEventId: `pool-${docName}`,+ lastAccessedAt,+ };+}++/** The most recent defer-mount decision the pool recorded for `docName`. */+function deferMountMark(docName: string): Record<string, unknown> | undefined {+ const marks = getCollector()+ ?.marks.toArray()+ .filter((m) => m.name === 'ok/activity/defer-mount' && m.properties?.docName === docName);+ return marks?.[marks.length - 1]?.properties;+}++function Pool({ isSourceMode, activeDocName }: { isSourceMode: boolean; activeDocName: string }) {+ return (+ <EditorActivityPool+ activeDocName={activeDocName}+ isSourceMode={isSourceMode}+ onRecycle={() => {}}+ />+ );+}++describe('ActivityEntry — mount gate reads the effective mode', () => {+ beforeEach(() => {+ poolEntries.length = 0;+ poolEntries.push(makeEntry('doc-active', 2), makeEntry('doc-hidden', 1));+ getCollector()?.reset();+ });++ afterEach(() => {+ cleanup();+ for (const entry of poolEntries) entry.provider.document.destroy();+ poolEntries.length = 0;+ });++ test('a global flip to source does not mount the source editor in a hidden entry', () => {+ const { rerender } = render(<Pool isSourceMode={false} activeDocName="doc-active" />);+ // Both entries open in visual mode: the deferred source editor is unmounted+ // on each of them.+ expect(deferMountMark('doc-hidden')?.renderSource).toBe(false);++ rerender(<Pool isSourceMode activeDocName="doc-active" />);++ // The active entry follows the flip and materialises its source editor …+ expect(deferMountMark('doc-active')?.renderSource).toBe(true);+ // … while the hidden entry stays frozen at the mode it last displayed, so+ // no editor is mounted into its display:none subtree.+ expect(deferMountMark('doc-hidden')?.renderSource).toBe(false);+ expect(deferMountMark('doc-hidden')?.isSourceMode).toBe(false);+ });++ test('a global flip to visual does not mount the visual editor in a hidden source entry', () => {+ // Mirror direction: both entries open in source mode, then the active one+ // flips back to visual.+ const { rerender } = render(<Pool isSourceMode activeDocName="doc-active" />);+ expect(deferMountMark('doc-hidden')?.renderVisual).toBe(false);++ rerender(<Pool isSourceMode={false} activeDocName="doc-active" />);++ expect(deferMountMark('doc-active')?.renderVisual).toBe(true);+ expect(deferMountMark('doc-hidden')?.renderVisual).toBe(false);+ });++ test('re-activating the hidden entry adopts the current global mode', () => {+ const { rerender } = render(<Pool isSourceMode={false} activeDocName="doc-active" />);+ rerender(<Pool isSourceMode activeDocName="doc-active" />);+ expect(deferMountMark('doc-hidden')?.renderSource).toBe(false);++ // The freeze is not permanent: becoming active again picks up the global+ // mode and mounts that editor.+ rerender(<Pool isSourceMode activeDocName="doc-hidden" />);+ expect(deferMountMark('doc-hidden')?.renderSource).toBe(true);+ });+});diff --git a/packages/app/src/components/EditorActivityPool.scroll-suppression.dom.test.tsx b/packages/app/src/components/EditorActivityPool.scroll-suppression.dom.test.tsxnew file mode 100644index 000000000..af8625eab--- /dev/null+++ b/packages/app/src/components/EditorActivityPool.scroll-suppression.dom.test.tsx@@ -0,0 +1,193 @@+// @vitest-environment jsdom+/**+ * Wiring coverage for the real `ScrollPreservingContainer` restore paths:+ * - the scroll-restore suppression seam: it must consult the coordination+ * registry and stand down (write no scrollTop) while a landing holds a+ * suppression handle, so a landing can be the single scroll writer;+ * - the cross-mode re-activation floor: when the saved position was captured+ * in a different mode than the one being re-activated, the container must+ * land proportionally in a single write (not drive the other mode's offset)+ * and emit a diagnostic mark — including when the restore cannot be applied.+ *+ * jsdom computes no layout, so scroll geometry is stubbed on the prototype:+ * `scrollHeight`/`clientHeight` read from mutable stand-ins (so a test can make+ * the content non-overflowing) and `scrollTop` is a settable backing store (the+ * observable the restore writes). The restore's Stage-1 / cross-mode write runs+ * synchronously inside the layout effect, so the assertions read it immediately+ * after mount without awaiting the rAF poll.+ */++import { cleanup, render } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import {+ __resetScrollRestoreCoordination,+ acquireScrollRestoreSuppression,+ rememberDocScrollState,+} from '@/editor/scroll-restore-coordination';+import type { EditorModeValue } from '@/editor/use-editor-mode';+import { getCollector } from '@/lib/perf/collector';+import { ScrollPreservingContainer } from './EditorActivityPool';++const scrollTops = new WeakMap<HTMLElement, number>();+let stubScrollHeight = 5000;+let stubClientHeight = 0;+let origScrollTop: PropertyDescriptor | undefined;+let origScrollHeight: PropertyDescriptor | undefined;+let origClientHeight: PropertyDescriptor | undefined;++function restoreDescriptor(+ prop: 'scrollTop' | 'scrollHeight' | 'clientHeight',+ desc: PropertyDescriptor | undefined,+) {+ if (desc) Object.defineProperty(HTMLElement.prototype, prop, desc);+ else Reflect.deleteProperty(HTMLElement.prototype, prop);+}++beforeEach(() => {+ __resetScrollRestoreCoordination();+ getCollector()?.reset();+ stubScrollHeight = 5000;+ stubClientHeight = 0;+ origScrollTop = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollTop');+ origScrollHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollHeight');+ origClientHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientHeight');+ Object.defineProperty(HTMLElement.prototype, 'scrollTop', {+ configurable: true,+ get(this: HTMLElement) {+ return scrollTops.get(this) ?? 0;+ },+ set(this: HTMLElement, value: number) {+ scrollTops.set(this, value);+ },+ });+ Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {+ configurable: true,+ get() {+ return stubScrollHeight;+ },+ });+ Object.defineProperty(HTMLElement.prototype, 'clientHeight', {+ configurable: true,+ get() {+ return stubClientHeight;+ },+ });+});++afterEach(() => {+ cleanup();+ __resetScrollRestoreCoordination();+ restoreDescriptor('scrollTop', origScrollTop);+ restoreDescriptor('scrollHeight', origScrollHeight);+ restoreDescriptor('clientHeight', origClientHeight);+});++function scrollerOf(container: HTMLElement): HTMLDivElement {+ const el = container.querySelector<HTMLDivElement>('[data-testid="editor-scroll-container"]');+ if (!el) throw new Error('editor-scroll-container not rendered');+ return el;+}++function crossModeMark(): { properties?: Record<string, unknown> } | undefined {+ return getCollector()+ ?.marks.toArray()+ .find((m) => m.name === 'ok/scroll-restore/cross-mode');+}++function Harness({+ active,+ docName,+ mode = 'wysiwyg',+ initialScrollTop = 500,+}: {+ active: boolean;+ docName: string;+ mode?: EditorModeValue;+ initialScrollTop?: number;+}) {+ return (+ <ScrollPreservingContainer+ isActive={active}+ docName={docName}+ mode={mode}+ initialScrollTop={initialScrollTop}+ >+ <div>body content</div>+ </ScrollPreservingContainer>+ );+}++describe('ScrollPreservingContainer scroll-restore suppression', () => {+ test('restores scroll position when no landing is active', () => {+ const { container } = render(<Harness active docName="doc-a" />);+ expect(scrollerOf(container).scrollTop).toBe(500);+ });++ test('stands down and writes no scroll position while a landing holds suppression', () => {+ acquireScrollRestoreSuppression('doc-b');+ const { container } = render(<Harness active docName="doc-b" />);+ expect(scrollerOf(container).scrollTop).toBe(0);+ });++ test('resumes restoring on the next activation after the landing releases', () => {+ const handle = acquireScrollRestoreSuppression('doc-c');+ const { container, rerender } = render(<Harness active={false} docName="doc-c" />);+ // Activate while suppressed → the restore stands down.+ rerender(<Harness active docName="doc-c" />);+ expect(scrollerOf(container).scrollTop).toBe(0);+ // Release, then re-activate → a fresh restore drives the saved position.+ handle.release();+ rerender(<Harness active={false} docName="doc-c" />);+ rerender(<Harness active docName="doc-c" />);+ expect(scrollerOf(container).scrollTop).toBe(500);+ });+});++describe('ScrollPreservingContainer cross-mode re-activation floor', () => {+ test('lands proportionally instead of driving the other mode saved offset', () => {+ // Saved in source at 40% through the doc; re-activated in wysiwyg. The+ // precise offset would drive the wysiwyg scroller against source geometry;+ // the floor lands proportionally: 0.4 * (5000 - 0) = 2000.+ rememberDocScrollState('doc-x', { offset: 4321, mode: 'source', fraction: 0.4 });+ const { container } = render(+ <Harness active docName="doc-x" mode="wysiwyg" initialScrollTop={0} />,+ );+ expect(scrollerOf(container).scrollTop).toBe(2000);+ });++ test('emits a diagnostic mark carrying both modes and the applied result', () => {+ rememberDocScrollState('doc-x', { offset: 4321, mode: 'source', fraction: 0.4 });+ render(<Harness active docName="doc-x" mode="wysiwyg" initialScrollTop={0} />);+ const m = crossModeMark();+ expect(m?.properties?.savedMode).toBe('source');+ expect(m?.properties?.mode).toBe('wysiwyg');+ expect(m?.properties?.target).toBe(2000);+ expect(m?.properties?.applied).toBe(true);+ });++ test('a same-mode re-activation is unaffected — no floor, no cross-mode mark', () => {+ // Same mode → the cross-mode branch is skipped and the normal restore drives+ // the saved position (raw target 777, since this harness renders no body+ // anchor), never the 0.4 proportional floor, and no cross-mode mark fires.+ rememberDocScrollState('doc-y', { offset: 4321, mode: 'wysiwyg', fraction: 0.4 });+ const { container } = render(+ <Harness active docName="doc-y" mode="wysiwyg" initialScrollTop={777} />,+ );+ expect(scrollerOf(container).scrollTop).toBe(777);+ expect(crossModeMark()).toBeUndefined();+ });++ test('marks applied:false when the new mode content cannot be scrolled', () => {+ // The new mode has no scrollable range (content fits the viewport), so the+ // floor cannot apply — but it must still emit the mark instead of failing+ // silently, which the old height-gated abandoned mark did not.+ stubScrollHeight = 400;+ stubClientHeight = 800;+ rememberDocScrollState('doc-z', { offset: 4321, mode: 'source', fraction: 0.4 });+ const { container } = render(+ <Harness active docName="doc-z" mode="wysiwyg" initialScrollTop={0} />,+ );+ expect(scrollerOf(container).scrollTop).toBe(0);+ expect(crossModeMark()?.properties?.applied).toBe(false);+ });+});diff --git a/packages/app/src/components/EditorActivityPool.test.ts b/packages/app/src/components/EditorActivityPool.test.tsindex 7e7cb5db3..0442b8aa9 100644--- a/packages/app/src/components/EditorActivityPool.test.ts+++ b/packages/app/src/components/EditorActivityPool.test.ts@@ -21,6 +21,7 @@ import {ACTIVITY_MOUNT_LIMIT,computeActivityMountList,computeEditorMountGate,+ computeEffectiveSourceMode,EditorActivityPool,getServerRestartRecoveryView,LARGE_DOC_CHAR_THRESHOLD,@@ -418,9 +419,10 @@ describe('computeEditorMountGate — invariant: at least one editor rendered', (// ---------------------------------------------------------------------------describe('shouldEmitFirstToggle — first-toggle mark gate', () => {- test('large doc, both editors rendering, not yet emitted → emit', () => {+ test('active large doc, both editors rendering, not yet emitted → emit', () => {expect(shouldEmitFirstToggle({+ isActive: true,isLarge: true,renderSource: true,renderVisual: true,@@ -429,9 +431,26 @@ describe('shouldEmitFirstToggle — first-toggle mark gate', () => {).toBe(true);});+ test('hidden entry that materialises both editors on a global flip → do NOT emit', () => {+ // A hidden large entry whose deferred editor mounts (e.g. because a global+ // flip set the other visited flag) must not spend the one-shot: it never+ // paid a first-toggle cost, and consuming the mark here would suppress the+ // real one when the doc is actually re-activated.+ expect(+ shouldEmitFirstToggle({+ isActive: false,+ isLarge: true,+ renderSource: true,+ renderVisual: true,+ hasEmittedFirstToggle: false,+ }),+ ).toBe(false);+ });+test('large doc, both rendering, already emitted → do NOT emit (one-shot per Activity)', () => {expect(shouldEmitFirstToggle({+ isActive: true,isLarge: true,renderSource: true,renderVisual: true,@@ -443,6 +462,7 @@ describe('shouldEmitFirstToggle — first-toggle mark gate', () => {test('large doc, only source rendering (initial cold load in source mode) → do NOT emit', () => {expect(shouldEmitFirstToggle({+ isActive: true,isLarge: true,renderSource: true,renderVisual: false,@@ -454,6 +474,7 @@ describe('shouldEmitFirstToggle — first-toggle mark gate', () => {test('large doc, only visual rendering (initial cold load in visual mode) → do NOT emit', () => {expect(shouldEmitFirstToggle({+ isActive: true,isLarge: true,renderSource: false,renderVisual: true,@@ -462,13 +483,14 @@ describe('shouldEmitFirstToggle — first-toggle mark gate', () => {).toBe(false);});- test('small doc with both editors mounted (default pre-mount-both) → do NOT emit (AC 3)', () => {+ test('small doc with both editors mounted (default pre-mount-both) → do NOT emit', () => {// Critical invariant: small docs have BOTH editors pre-mounted from// the start (computeEditorMountGate returns isLarge:false). The first-// toggle mark must NEVER fire for small docs because there's no defer-// mount transition to measure.expect(shouldEmitFirstToggle({+ isActive: true,isLarge: false,renderSource: true,renderVisual: true,@@ -480,6 +502,7 @@ describe('shouldEmitFirstToggle — first-toggle mark gate', () => {test('small doc, both rendered, already emitted (impossible in production but safe) → do NOT emit', () => {expect(shouldEmitFirstToggle({+ isActive: true,isLarge: false,renderSource: true,renderVisual: true,@@ -489,6 +512,26 @@ describe('shouldEmitFirstToggle — first-toggle mark gate', () => {});});+describe('computeEffectiveSourceMode — hidden-entry mode freeze', () => {+ test('the active entry follows the current global mode', () => {+ // isActive true → global mode wins regardless of the frozen last-active mode.+ expect(computeEffectiveSourceMode(true, true, false)).toBe(true);+ expect(computeEffectiveSourceMode(true, false, true)).toBe(false);+ });++ test('a hidden entry stays frozen at its last-active mode, ignoring the global flip', () => {+ // isActive false → the frozen mode wins, so a global flip the hidden entry+ // never displays cannot change what it would mount.+ expect(computeEffectiveSourceMode(false, true, false)).toBe(false);+ expect(computeEffectiveSourceMode(false, false, true)).toBe(true);+ });++ test('a hidden entry whose frozen mode matches the global mode is unaffected', () => {+ expect(computeEffectiveSourceMode(false, true, true)).toBe(true);+ expect(computeEffectiveSourceMode(false, false, false)).toBe(false);+ });+});+describe('computeActivityMountList — system doc filtering (DX7 defense-in-depth)', () => {test('__system__ doc filtered out even if present in entries', () => {// ProviderPool.open already rejects system docs at admission, but the helperdiff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsxindex 33bc0eb86..45f97e87c 100644--- a/packages/app/src/components/EditorActivityPool.tsx+++ b/packages/app/src/components/EditorActivityPool.tsx@@ -53,7 +53,15 @@ import { peekRenameSnapshot, setActivityMountList } from '@/editor/editor-cache'import { isSystemDoc } from '@/editor/is-system-doc';import { clearMountId, getMountId, setMountId } from '@/editor/mount-id-registry';import type { ServerRestartRecoveryState } from '@/editor/provider-pool';+import {+ BODY_ANCHOR_ATTR,+ getDocScrollState,+ isScrollRestoreSuppressed,+ rememberDocScrollState,+ scrollFraction,+} from '@/editor/scroll-restore-coordination';import { TiptapEditor } from '@/editor/TiptapEditor';+import type { EditorModeValue } from '@/editor/use-editor-mode';import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';import { mark, ProfilerBoundary } from '@/lib/perf';@@ -164,13 +172,20 @@ export function computeEditorMountGate(args: EditorMountGateArgs): EditorMountGa/*** Pure gate for the `ok/cold/first-toggle` mark emission. The mark is the- * first-toggle latency anchor — fires EXACTLY ONCE per ActivityEntry, only- * when the defer-mount path was active (`isLarge`) and the deferred editor- * has now mounted (both `renderSource` and `renderVisual` are true). For- * small docs whose default is pre-mount-both, the mark must NEVER fire —- * there is no defer-mount transition to measure.+ * first-toggle latency anchor — fires EXACTLY ONCE per ActivityEntry, only for+ * the ACTIVE entry, only when the defer-mount path was active (`isLarge`) and+ * the deferred editor has now mounted (both `renderSource` and `renderVisual`+ * are true). For small docs whose default is pre-mount-both, the mark must+ * NEVER fire — there is no defer-mount transition to measure.+ *+ * The `isActive` conjunct is load-bearing: a hidden entry whose deferred editor+ * mounts (e.g. a global flip materialising the other mode's editor in its+ * display:none subtree) must not spend the one-shot, or it both records a+ * phantom cold-mount it never paid AND suppresses the real mark that fires when+ * the doc is actually re-activated and pays the cost.*/interface ShouldEmitFirstToggleArgs {+ isActive: boolean;isLarge: boolean;renderSource: boolean;renderVisual: boolean;@@ -179,10 +194,28 @@ interface ShouldEmitFirstToggleArgs {export function shouldEmitFirstToggle(args: ShouldEmitFirstToggleArgs): boolean {if (args.hasEmittedFirstToggle) return false;+ if (!args.isActive) return false;if (!args.isLarge) return false;return args.renderSource && args.renderVisual;}+/**+ * The mode an Activity entry actually displays. Only the ACTIVE entry follows a+ * global mode flip; a hidden entry stays in the mode it last displayed+ * (`lastActiveIsSourceMode`) until it becomes active again, at which point it+ * adopts the current global mode. Freezing the mode for hidden entries is what+ * stops a global flip from mounting an editor inside a hidden (display:none)+ * subtree — the visited-mode gate and the mount gate both key off this value,+ * so a flip a hidden entry never displays can no longer flip its render flags.+ */+export function computeEffectiveSourceMode(+ isActive: boolean,+ isSourceMode: boolean,+ lastActiveIsSourceMode: boolean,+): boolean {+ return isActive ? isSourceMode : lastActiveIsSourceMode;+}+/*** Maximum number of editors mounted concurrently inside `<Activity>` boundaries.* Decoupled from `MAX_POOL` (exported from `provider-pool.ts`, default 10) per@@ -502,50 +535,28 @@ interface ActivityEntryProps {* mounted-but-hidden anchor (a Suspense fallback window during a slow* reveal) yields NO target for that frame rather than a degenerate* viewport-origin measurement that self-amplifies per applied frame.- */--/**- * Per-document scroll position, stored as a BODY OFFSET (scrollTop minus the- * above-body anchor height) and keyed by `docName`. Two reasons it lives at- * module scope, not in a per-instance ref:- * 1. Survives the editor's REMOUNT on navigate-back — the fresh- * ScrollPreservingContainer instance re-reads the same value instead of- * losing it (the per-instance ref was the bug: a remount dropped it and- * then re-captured churn from the resize).- * 2. Body-relative — a Properties-panel height change (collapse/expand, even- * globally on another doc) never invalidates it, because the offset is- * measured from the top of the body, not the top of the scroller.- * Restore = currentAnchor + storedOffset, so it always lands on the same body- * content regardless of the panel's current height.*- * Entries are deliberately kept PAST Activity eviction (so revisiting a- * pooled-out doc still restores scroll), so there is no per-eviction cleanup —- * but to keep a very long session from growing the map without bound,- * `rememberDocScrollOffset` caps it at `MAX_TRACKED_DOC_SCROLL`, dropping the- * least-recently-written entry (re-insert-on-write makes the order LRU).+ * The saved position itself lives in scroll-restore-coordination, not in+ * this module, so a mode-switch landing reads and writes the same map+ * rather than racing a private one.*/-const MAX_TRACKED_DOC_SCROLL = 256;-const docScrollBodyOffset = new Map<string, number>();-function rememberDocScrollOffset(docName: string, offset: number): void {- docScrollBodyOffset.delete(docName); // re-insert last → LRU order for eviction- docScrollBodyOffset.set(docName, offset);- if (docScrollBodyOffset.size > MAX_TRACKED_DOC_SCROLL) {- const oldest = docScrollBodyOffset.keys().next().value;- if (oldest !== undefined) docScrollBodyOffset.delete(oldest);- }-}--function ScrollPreservingContainer({+export function ScrollPreservingContainer({isActive,docName,+ mode,initialScrollTop,bodyAnchorRef,children,}: {isActive: boolean;/** The document this scroller belongs to — the key under which its scroll- * body-offset persists across remounts (see `docScrollBodyOffset`). */+ * body-offset persists across remounts (see scroll-restore-coordination). */docName: string;+ /** The editor mode this scroller currently displays. Captured with each saved+ * scroll position and compared on re-activation: a saved position from a+ * different mode is floored (proportional) instead of driving this mode's+ * geometry against the other mode's offset. */+ mode: EditorModeValue;/*** Seed value for `savedScrollTop` at mount. Used by the warm-skeleton* rename-restore path: when the new ActivityEntry mounts post-rename@@ -591,6 +602,18 @@ function ScrollPreservingContainer({isActiveRef.current = isActive;}, [isActive]);+ // Mirror the current mode into a ref the restore effect reads on re-activation.+ // It is a LAYOUT effect declared before the restore effect on purpose: when an+ // Activity flips hidden->visible React re-runs both effects' setup, layout+ // effects before passive and in declaration order, so a passive mirror would+ // update only AFTER the restore had already read a mode frozen at the last+ // hide. The restore keys on `isActive` (not `mode`), so an in-place flip of the+ // active doc — owned by the landing controller — never runs it.+ const modeRef = useRef(mode);+ useLayoutEffect(() => {+ modeRef.current = mode;+ }, [mode]);+// Track scrollTop via a scroll listener so we always have the latest user// position — `display:none` zeros scrollTop before any layout effect could// read it, so we MUST capture via scroll events.@@ -610,9 +633,15 @@ function ScrollPreservingContainer({savedScrollTop.current = el.scrollTop;savedAnchorPos.current = anchor.kind === 'measured' ? anchor.contentPos : null;// Persist the body-relative offset per doc so it survives a remount and- // stays valid across Properties-panel height changes.+ // stays valid across Properties-panel height changes. The mode + fraction+ // ride along so a later re-activation in a different mode can floor+ // instead of driving this offset against the other mode's geometry.if (anchor.kind === 'measured') {- rememberDocScrollOffset(docName, el.scrollTop - anchor.contentPos);+ rememberDocScrollState(docName, {+ offset: el.scrollTop - anchor.contentPos,+ mode: modeRef.current,+ fraction: scrollFraction(el.scrollTop, el.scrollHeight, el.clientHeight),+ });}}};@@ -656,16 +685,47 @@ function ScrollPreservingContainer({if (!isActive) return;const el = ref.current;if (!el) return;+ // A mode-switch landing owns the scroll for this document during its settle+ // window; stand down so there is a single writer and the restore does not+ // overwrite the landing with the pre-landing position.+ if (isScrollRestoreSuppressed(docName)) return;++ const saved = getDocScrollState(docName);+ // Cross-mode re-activation floor. The saved offset was measured against the+ // OTHER mode's geometry, so the precise anchor-tracking restore below would+ // actively drive the scroller onto a wrong-geometry target. Instead land+ // once at the same fraction through the scrollable range and stand down — a+ // near-miss, never actively wrong. A cross-mode restore that cannot be+ // applied (the new mode's content does not overflow, so there is no range to+ // be a fraction of) still emits a diagnostic mark, so the failure is+ // observable rather than silent (the old height-gated `abandoned` mark was+ // suppressed in exactly this case).+ if (saved && saved.mode !== modeRef.current) {+ const maxScroll = Math.max(0, el.scrollHeight - el.clientHeight);+ const target = Math.round(saved.fraction * maxScroll);+ const applicable = maxScroll > 0;+ if (applicable) el.scrollTop = target;+ mark('ok/scroll-restore/cross-mode', {+ docName,+ savedMode: saved.mode,+ mode: modeRef.current,+ fraction: Number(saved.fraction.toFixed(4)),+ target,+ applied: applicable && el.scrollTop === target,+ });+ return;+ }+const rawTarget = savedScrollTop.current;// Restore keeps the BODY offset — how far into the document body we were// scrolled — constant, instead of a raw pixel scrollTop, and recomputes the// target from the CURRENT anchor on every apply so it tracks the Properties// panel settling to its post-toggle height. Prefer the per-doc offset- // (`docScrollBodyOffset`) so it survives the editor's remount on+ // (`getDocScrollState`) so it survives the editor's remount on// navigate-back; fall back to this instance's captured pair, then the raw// scroll (fresh mount / warm rename-restore) so existing behavior is intact.- const sharedOffset = docScrollBodyOffset.get(docName);+ const sharedOffset = saved?.offset;const instanceOffset =savedAnchorPos.current !== null ? rawTarget - savedAnchorPos.current : null;const bodyOffset: number | null = sharedOffset ?? instanceOffset;@@ -753,6 +813,22 @@ function ScrollPreservingContainer({el.addEventListener('keydown', yieldToUser);const tick = () => {if (done) return;+ // A landing acquired the scroll for this document mid-restore — stop+ // competing so the landing is the single writer. Probed BEFORE the+ // external-scroll check below: a landing's own writes would otherwise+ // read as a takeover of unknown origin, and the named reason is the more+ // precise signal for an exit we can attribute exactly.+ if (isScrollRestoreSuppressed(docName)) {+ if (!hasLandedOnce) {+ mark('ok/scroll-restore/yielded', {+ reason: 'landing',+ elapsedMs: performance.now() - startTs,+ finalScrollTop: el.scrollTop,+ });+ }+ finish();+ return;+ }// An UPWARD scrollTop move we didn't write = someone else owns the// scroll now (outline-click scrollIntoView, find-in-doc). Yield// immediately — enforcing a stale target over an intentional scroll is@@ -829,7 +905,7 @@ function ScrollPreservingContainer({<divref={ref}data-testid="editor-scroll-container"- // Toolbar exclusion zone = 3.5rem (EditorToolbar's rendered height). Four+ // Toolbar exclusion zone = 3.5rem (EditorToolbar's rendered height). Five// load-bearing constants must move together if the toolbar height changes:// - `pt-14` (here): initial-paint content reserve so doc content doesn't// start behind the absolute-positioned EditorToolbar overlay.@@ -847,6 +923,9 @@ function ScrollPreservingContainer({// and have no programmatic scroll-into-view call sites today; adding// a `scrollMargins` contribution in the shared factory would mis-align// nested CM scrolls if they ever become scrollable.+ // - TOOLBAR_OVERLAP_PX in editor/mode-switch-landing.ts: the mode-switch+ // capture probes step in from this inset, and the landing hands it to+ // the controller as the target's resting offset below the toolbar.// The toolbar itself: components/EditorToolbar.tsx.className="editor-doc-scroll subtle-scrollbar h-full overflow-y-auto pt-14 scroll-pt-14"style={{ overflowAnchor: 'auto' }}@@ -1024,33 +1103,51 @@ function ActivityEntry({// so its length reliably signals "this doc will be expensive to render".const ytextLength = entry.provider.document.getText('source').length;+ // The mode this entry actually displays. Only the active entry follows the+ // global flip; a hidden entry stays frozen at its last-active mode until it is+ // re-activated. Freezing is what keeps a global flip from mounting an editor+ // inside a hidden (display:none) subtree — every mode-derived decision below+ // (visited tracking, mount gate, class swaps) keys off `effectiveIsSourceMode`,+ // so a flip a hidden entry never displays cannot flip its render flags.+ const [lastActiveIsSourceMode, setLastActiveIsSourceMode] = useState(isSourceMode);+ useEffect(() => {+ if (isActive && lastActiveIsSourceMode !== isSourceMode) {+ setLastActiveIsSourceMode(isSourceMode);+ }+ }, [isActive, isSourceMode, lastActiveIsSourceMode]);+ const effectiveIsSourceMode = computeEffectiveSourceMode(+ isActive,+ isSourceMode,+ lastActiveIsSourceMode,+ );+// Track which modes have been visited. useState (not useRef) because React// Compiler's Babel plugin rejects render-phase ref mutation — even though the// mutation here is idempotent and safe, the compiler can't prove it. State// with a lazy initializer + a post-commit effect is the compiler-approved// shape.//- // Correctness note: on the render where `isSourceMode` first flips from- // `false → true`, we need the newly-visited SourceEditor to render in THAT- // render (not wait for an effect + rerender). `computeEditorMountGate`- // handles this by OR-ing with `isSourceMode` directly, so even when the+ // Correctness note: on the render where `effectiveIsSourceMode` first flips+ // from `false → true`, we need the newly-visited SourceEditor to render in+ // THAT render (not wait for an effect + rerender). `computeEditorMountGate`+ // handles this by OR-ing with the mode directly, so even when the// `visitedSource` state is still false at the flipped render, the gate// returns `renderSource=true`. The effect then flips state, and subsequent// renders stay consistent.//// Activity mode=hidden preserves state across visibility flips (just like// refs would), so alt-tab between docs doesn't reset the visit history.- const [visitedSource, setVisitedSource] = useState(isSourceMode);- const [visitedVisual, setVisitedVisual] = useState(!isSourceMode);+ const [visitedSource, setVisitedSource] = useState(effectiveIsSourceMode);+ const [visitedVisual, setVisitedVisual] = useState(!effectiveIsSourceMode);useEffect(() => {- if (isSourceMode && !visitedSource) setVisitedSource(true);- else if (!isSourceMode && !visitedVisual) setVisitedVisual(true);- }, [isSourceMode, visitedSource, visitedVisual]);+ if (effectiveIsSourceMode && !visitedSource) setVisitedSource(true);+ else if (!effectiveIsSourceMode && !visitedVisual) setVisitedVisual(true);+ }, [effectiveIsSourceMode, visitedSource, visitedVisual]);const gate = computeEditorMountGate({ytextLength,- isSourceMode,+ isSourceMode: effectiveIsSourceMode,visitedSource,visitedVisual,});@@ -1068,7 +1165,7 @@ function ActivityEntry({mark('ok/activity/defer-mount', {docName: entry.docName,ytextLength,- isSourceMode,+ isSourceMode: effectiveIsSourceMode,renderSource: gate.renderSource,renderVisual: gate.renderVisual,});@@ -1080,7 +1177,7 @@ function ActivityEntry({gate.renderVisual,entry.docName,ytextLength,- isSourceMode,+ effectiveIsSourceMode,]);// Rename-induced cold-mount carries forward the PRIOR editor's HTML + scrollTop@@ -1132,6 +1229,7 @@ function ActivityEntry({useEffect(() => {if (!shouldEmitFirstToggle({+ isActive,isLarge: gate.isLarge,renderSource: gate.renderSource,renderVisual: gate.renderVisual,@@ -1144,17 +1242,18 @@ function ActivityEntry({docName: entry.docName,mountId: getMountId(entry.docName),ytextLength,- modeEnteredFirst: isSourceMode ? 'source' : 'visual',+ modeEnteredFirst: effectiveIsSourceMode ? 'source' : 'visual',});setHasEmittedFirstToggle(true);}, [hasEmittedFirstToggle,+ isActive,gate.isLarge,gate.renderSource,gate.renderVisual,entry.docName,ytextLength,- isSourceMode,+ effectiveIsSourceMode,]);return (@@ -1167,6 +1266,7 @@ function ActivityEntry({<ScrollPreservingContainerisActive={isActive}docName={entry.docName}+ mode={effectiveIsSourceMode ? 'source' : 'wysiwyg'}initialScrollTop={warmSnapshot?.scrollTop}bodyAnchorRef={bodyAnchorRef}>@@ -1218,7 +1318,7 @@ function ActivityEntry({<MermaidDocEditordocName={entry.docName}provider={entry.provider}- isSourceMode={isSourceMode}+ isSourceMode={effectiveIsSourceMode}/>) : (/* Dual-editor mount with size-gated defer for large docs. Small@@ -1248,7 +1348,7 @@ function ActivityEntry({frontmatter, and they have no cover/icon. Regular docs getPageHeader (decorative cover+icon, null when unset) +PropertyPanel (frontmatter table, null when empty). */}- {!isSourceMode &&+ {!effectiveIsSourceMode &&(isManagedArtifactDocName(entry.docName) ||parseProjectSkillContentDocName(entry.docName) ? (<Suspense fallback={null}>@@ -1266,21 +1366,33 @@ function ActivityEntry({{/* Body-top anchor for scroll-restore compensation (seeScrollPreservingContainer.bodyAnchorRef). Zero height,non-interactive — everything above it (page header +- Properties) is the variable region it measures. */}- <div ref={bodyAnchorRef} aria-hidden className="h-0" />+ Properties) is the variable region it measures. The+ BODY_ANCHOR_ATTR marker lets a landing find this node+ from a bare container it did not mount (see+ scroll-restore-coordination.writeLandingResult). */}+ <div+ ref={bodyAnchorRef}+ aria-hidden+ className="h-0"+ {...{ [BODY_ANCHOR_ATTR]: '' }}+ /><div className="relative flex-1">{gate.renderSource ? (- <div className={isSourceMode ? 'h-full' : 'ok-mode-hidden h-full'}>+ <div+ className={effectiveIsSourceMode ? 'h-full' : 'ok-mode-hidden h-full'}+ ><SourceEditorSlotentry={entry}isActive={isActive}- isSourceMode={isSourceMode}+ isSourceMode={effectiveIsSourceMode}editorPlaceholder={editorPlaceholder}/></div>) : null}{gate.renderVisual ? (- <div className={isSourceMode ? 'ok-mode-hidden h-full' : 'h-full'}>+ <div+ className={effectiveIsSourceMode ? 'ok-mode-hidden h-full' : 'h-full'}+ ><TiptapEditor// The isNewDoc segment forces TipTap remount on the draft → saved// transition (the flip changes the page list's membership of this@@ -1295,7 +1407,7 @@ function ActivityEntry({key={`${entry.docName}-${String(isNewDoc)}-${entry.poolEventId}`}provider={entry.provider}placeholder={editorPlaceholder}- isSourceMode={isSourceMode}+ isSourceMode={effectiveIsSourceMode}// Per-Activity exclusive portal target — see the// `portalTarget` useState declaration for// the bleed-prevention rationale. The target'sdiff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsxindex 7bf9aa99c..3ab1c2d66 100644--- a/packages/app/src/components/EditorPane.dom.test.tsx+++ b/packages/app/src/components/EditorPane.dom.test.tsx@@ -1,10 +1,19 @@+import { MarkdownManager, sharedExtensions, stripFrontmatter } from '@inkeep/open-knowledge-core';import { act, cleanup, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { isMacOS } from '@tiptap/core';+import { type Editor, getSchema, isMacOS } from '@tiptap/core';+import type { Node as PmNode } from '@tiptap/pm/model';import type { ReactNode } from 'react';import { afterEach, describe, expect, test, vi } from 'vitest';+import * as Y from 'yjs';+import { registerEditor, unregisterEditor } from '@/editor/active-editor';import { publishSelectionContext } from '@/editor/selection-context';import type { EditorSurface } from '@/editor/selection-stats';+import {+ clearPendingSourceNavigationsForTest,+ peekPendingSourceNavigation,+} from '@/editor/source-editor-navigation';+import { VIEW_IN_SOURCE_EVENT, type ViewInSourceDetail } from '@/editor/view-in-source-event';import { subscribeToPreferredSessionRequests } from './handoff/preferred-session-events';import { subscribeToActiveTerminalInput } from './handoff/terminal-input-events';@@ -30,6 +39,27 @@ function clearSelection(): void {publishSelectionContext(TEST_DOC, 'source', null);}+// Substrate for the view-in-source seam test: a stand-in editor whose mounted PM+// view carries the caret + doc, so the real jump reads the block under the caret.+const jumpMd = new MarkdownManager({ extensions: sharedExtensions });+const jumpSchema = getSchema(sharedExtensions);++/** PM position just inside top-level block `index`. */+function pmPosOfBlock(doc: PmNode, index: number): number {+ let pos = 0;+ for (let i = 0; i < index; i++) pos += doc.child(i).nodeSize;+ return pos + 1;+}++function makeJumpEditor(markdown: string, caretBlock: number): Editor {+ const { body } = stripFrontmatter(markdown);+ const doc = jumpSchema.nodeFromJSON(jumpMd.parse(body));+ return {+ isDestroyed: false,+ editorView: { state: { doc, selection: { from: pmPosOfBlock(doc, caretBlock) } } },+ } as unknown as Editor;+}+// Collect the Ask-AI passages EditorPane dispatches to the sessions host (which// owns reuse-vs-launch and preferred-AI resolution; mocked here). `newTab` rides// along so ⌘J (reuse when sensible) stays distinguishable from ⇧⌘J (always fresh).@@ -106,8 +136,16 @@ vi.doMock('@/lib/use-workspace', () => ({useWorkspace: () => ({ contentDir: '/tmp/project', pathSeparator: '/' }),}));+// Mutable so the view-in-source test can supply a provider — its source Y.Text+// is what the jump reads. Default undefined keeps every other test unchanged+// (EditorPane's view-in-source path early-returns without a provider).+let activeProvider: { document: Y.Doc } | undefined;vi.doMock('@/editor/DocumentContext', () => ({- useDocumentContext: () => ({ activeDocName: 'docs/notes', collabUrl: 'ws://test' }),+ useDocumentContext: () => ({+ activeDocName: 'docs/notes',+ collabUrl: 'ws://test',+ activeProvider,+ }),}));vi.doMock('@/editor/use-editor-mode', () => ({@@ -374,7 +412,7 @@ function makeOkDesktopStub(getDockState: () => Promise<{ visible: boolean }> = async () => ({ visible: false }),) {const menuHandlers: Array<(action: string) => void> = [];- const viewMenuPushes: Array<{ terminalVisible?: boolean }> = [];+ const viewMenuPushes: Array<{ terminalVisible?: boolean; canViewInSource?: boolean }> = [];return {viewMenuPushes,dispatchMenuAction(action: string) {@@ -393,7 +431,10 @@ function makeOkDesktopStub(};},editor: {- notifyViewMenuStateChanged(state: { terminalVisible?: boolean }) {+ notifyViewMenuStateChanged(state: {+ terminalVisible?: boolean;+ canViewInSource?: boolean;+ }) {viewMenuPushes.push(state);},},@@ -416,6 +457,8 @@ describe('EditorPane terminal dock wiring', () => {delete (window as { okDesktop?: unknown }).okDesktop;terminalOpenedCalls.length = 0;clearSelection();+ activeProvider = undefined;+ clearPendingSourceNavigationsForTest();});test('web host mounts the sessions host (host-agnostic) with no desktop bridge', async () => {@@ -539,6 +582,66 @@ describe('EditorPane terminal dock wiring', () => {expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');});+ test('desktop: the toggle-source menu action runs the view-in-source jump', async () => {+ // The Desktop editor context menu dispatches `toggle-source` over the same+ // menu-action channel the terminal actions use. This exercises the real+ // renderer half of that seam end to end: bridge → menu-action bus →+ // EditorPane subscriber → the real view-in-source jump.+ const desk = makeOkDesktopStub();+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;++ // The jump reads the caret block off the registered editor and the source+ // bytes off the active provider's Y.Text.+ const markdown = '# Title\n\nfirst paragraph\n\ntarget paragraph';+ const ydoc = new Y.Doc();+ ydoc.getText('source').insert(0, markdown);+ activeProvider = { document: ydoc };+ const editor = makeJumpEditor(markdown, 3); // caret inside "target paragraph"+ registerEditor('docs/notes', editor);++ const flips: string[] = [];+ const onFlip = (e: Event) => flips.push((e as CustomEvent<ViewInSourceDetail>).detail.docName);+ window.addEventListener(VIEW_IN_SOURCE_EVENT, onFlip);++ await renderEditorPane();+ act(() => desk.dispatchMenuAction('toggle-source'));++ window.removeEventListener(VIEW_IN_SOURCE_EVENT, onFlip);+ unregisterEditor('docs/notes', editor);++ // It requested the flip for this doc and banked a jump navigation — the+ // Desktop menu action reached the jump, not just the mode flip.+ expect(flips).toEqual(['docs/notes']);+ const nav = peekPendingSourceNavigation('docs/notes');+ if (nav?.kind !== 'selection-offset') throw new Error('expected a selection-offset nav');+ expect(nav.intent).toBe('jump');+ });++ // Main attaches the native context menu to every editable field in the window+ // and cannot tell which surface fired it, so whether the "View in Source" row+ // is offered rides entirely on this push. If it stopped happening, the row+ // would silently vanish from the desktop editor instead of appearing where it+ // does not belong.+ test('desktop: pushes the view-in-source capability for the context-menu row', async () => {+ const desk = makeOkDesktopStub();+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;++ // No provider: nothing for the jump to read, so the row must stay out.+ await renderEditorPane();+ expect(desk.viewMenuPushes).toContainEqual({ canViewInSource: false });+ expect(desk.viewMenuPushes).not.toContainEqual({ canViewInSource: true });++ cleanup();+ const ydoc = new Y.Doc();+ ydoc.getText('source').insert(0, '# Title\n\nbody');+ activeProvider = { document: ydoc };+ const live = makeOkDesktopStub();+ (window as { okDesktop?: unknown }).okDesktop = live.stub;++ await renderEditorPane();+ expect(live.viewMenuPushes).toContainEqual({ canViewInSource: true });+ });+test('desktop: each open records terminal-opened; mount (hidden) and close do not', async () => {const desk = makeOkDesktopStub();(window as { okDesktop?: unknown }).okDesktop = desk.stub;diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsxindex 2b8f4b1a7..09399d6b6 100644--- a/packages/app/src/components/EditorPane.tsx+++ b/packages/app/src/components/EditorPane.tsx@@ -1,12 +1,15 @@import type { TerminalCli } from '@inkeep/open-knowledge-core';import { lazy, Suspense, useEffect, useEffectEvent, useRef, useState } from 'react';+import { getEditorForDoc } from '@/editor/active-editor';import { EmojiInsertPopover } from '@/editor/components/EmojiInsertPopover';import { TagDialog } from '@/editor/components/TagDialog';import { useDocumentContext } from '@/editor/DocumentContext';import { RAW_MDX_NAV_EVENT, type RawMdxNavDetail } from '@/editor/extensions/raw-mdx-nav-event';+import { captureModeSwitchAnchor, requestViewInSource } from '@/editor/mode-switch-landing';import { getSelectionContext } from '@/editor/selection-context';import { rememberPendingSourceNavigation } from '@/editor/source-editor-navigation';import { type EditorModeValue, useEditorMode } from '@/editor/use-editor-mode';+import { VIEW_IN_SOURCE_EVENT, type ViewInSourceDetail } from '@/editor/view-in-source-event';import { useGitSyncStatus } from '@/hooks/use-git-sync-status';import { useInstalledClis } from '@/hooks/use-installed-clis';import { useNoPushPermissionToast } from '@/hooks/use-no-push-permission-toast';@@ -210,7 +213,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {const { projectConfig, projectLocalConfig, projectLocalSynced, projectSynced } =useConfigContext();- const { activeDocName } = useDocumentContext();+ const { activeDocName, activeProvider } = useDocumentContext();// Onboarding modal: open once per machine per project when every gate// input aligns. Decision logic lives in `resolveAutoSyncOnboarding`, which@@ -473,6 +476,17 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {useWorktreeAutoSyncNotice();function handleModeChange(mode: EditorModeValue) {+ // Capture the viewport anchor while the outgoing editor is still laid out,+ // before the mode flip hides it, so the incoming view can land on the same+ // block. Read-only — it banks a pending navigation, it never edits the doc.+ if (activeDocName && activeProvider && editorMode !== mode) {+ captureModeSwitchAnchor({+ from: editorMode,+ to: mode,+ docName: activeDocName,+ ytext: activeProvider.document.getText('source'),+ });+ }setEditorMode(mode);// User-initiated change — persist globally. Tool-driven flips (e.g.// RAW_MDX_NAV_EVENT → source) are session-only and deliberately do NOT@@ -480,6 +494,86 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {setPersistedMode(mode);}+ // Effect Events so the once-bound keydown listener below reads the current+ // closures (mode, active doc/provider) without re-subscribing on every change.+ const toggleEditorModeEvent = useEffectEvent(() => {+ handleModeChange(editorMode === 'source' ? 'wysiwyg' : 'source');+ });+ // "View in source" reads the visual editor's caret for the active document, so+ // it means nothing in source mode or with nothing open. One predicate: the+ // Desktop context menu gates its row on the pushed value while the handler+ // re-checks locally, and a drift between them is a row that is offered and+ // then silently does nothing.+ const canViewInSource =+ editorMode === 'wysiwyg' && Boolean(activeDocName) && Boolean(activeProvider);++ const requestViewInSourceEvent = useEffectEvent(() => {+ // The two nullable reads are restated so TypeScript narrows them.+ if (!canViewInSource || !activeDocName || !activeProvider) return;+ const editor = getEditorForDoc(activeDocName);+ if (!editor) return;+ requestViewInSource({+ editor,+ docName: activeDocName,+ ytext: activeProvider.document.getText('source'),+ });+ });++ // Main attaches the native editor context menu to every editable field in the+ // window and sees an editable target, not which surface it belongs to — so+ // without this push the "View in Source" row would ride the composer, every+ // rename field and every dialog input. Desktop-only; it goes over the existing+ // view-menu-state channel rather than teaching main anything about the doc.+ useEffect(() => {+ window.okDesktop?.editor.notifyViewMenuStateChanged({ canViewInSource });+ }, [canViewInSource]);++ // Mode-toggle + view-in-source keyboard commands. Capture phase so a focused+ // editor can't swallow the chord first; both use CmdOrCtrl+Alt+<letter>, clear+ // of the editors' single-modifier bindings. Capture phase is also why the+ // overlay check is needed: the chord is intercepted before an open modal or+ // palette could handle it, so without standing down the editor behind the+ // overlay would flip mode while the user is working in the overlay.+ useEffect(() => {+ function handleKeyDown(event: KeyboardEvent) {+ if (matchesKeyboardShortcut(event, 'toggle-editor-mode')) {+ if (isOverlayLayerOpen()) return;+ event.preventDefault();+ toggleEditorModeEvent();+ return;+ }+ if (matchesKeyboardShortcut(event, 'view-source-at-cursor')) {+ if (isOverlayLayerOpen()) return;+ event.preventDefault();+ requestViewInSourceEvent();+ }+ }+ window.addEventListener('keydown', handleKeyDown, { capture: true });+ return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });+ }, []);++ // The Desktop editor context menu's "View in Source" routes back over the+ // menu-action bus (not a second bridge listener) and runs the same jump the+ // keyboard command does; the shared guard makes it inert outside WYSIWYG.+ useEffect(() => {+ return subscribeLocalMenuAction((action) => {+ if (action === 'toggle-source') requestViewInSourceEvent();+ });+ }, []);++ // A "view in source" jump (keyboard, bubble menu, or Desktop menu) banks its+ // landing target, then fires this to request the flip. Session-only — a+ // contextual peek at one doc's source, not a change to the global mode+ // preference, mirroring the raw-MDX flip above.+ useEffect(() => {+ function onViewInSource(e: Event) {+ const detail = (e as CustomEvent<ViewInSourceDetail>).detail;+ if (detail?.docName === activeDocName) setEditorMode('source');+ }+ window.addEventListener(VIEW_IN_SOURCE_EVENT, onViewInSource);+ return () => window.removeEventListener(VIEW_IN_SOURCE_EVENT, onViewInSource);+ }, [activeDocName]);+return (<>{/* Binds the agent-thread client's WS URL — mounted once so threads staydiff --git a/packages/app/src/components/hidden-activity-dom-retention.dom.test.tsx b/packages/app/src/components/hidden-activity-dom-retention.dom.test.tsxnew file mode 100644index 000000000..d85b11674--- /dev/null+++ b/packages/app/src/components/hidden-activity-dom-retention.dom.test.tsx@@ -0,0 +1,70 @@+// @vitest-environment jsdom+/**+ * Observes the React 19 `<Activity mode="hidden">` behavior the pool's scroll+ * bookkeeping and the subtree AGENTS.md WARN rule depend on: hiding a subtree+ * does NOT unmount its DOM — the same element survives the flip (state/refs kept)+ * while only its effects unmount. This is what makes more than one+ * editor-scroll-container coexist at once (hence the painted-container filter in+ * `visibleEditorScrollContainer`) and what lets a pooled doc's ref-stored scroll+ * position survive a mode flip. If a React upgrade ever made hidden Activity+ * unmount the DOM, the same-node assertion fails and the rule needs revisiting.+ */+import { cleanup, render } from '@testing-library/react';+import { Activity, useEffect } from 'react';+import { afterEach, describe, expect, test } from 'vitest';++function EffectProbe({ onMount, onUnmount }: { onMount: () => void; onUnmount: () => void }) {+ useEffect(() => {+ onMount();+ return onUnmount;+ }, [onMount, onUnmount]);+ return <div data-testid="activity-probe">probe</div>;+}++afterEach(cleanup);++describe('React <Activity mode="hidden"> retains DOM while unmounting effects', () => {+ test('flipping visible to hidden keeps the same DOM node and runs the effect cleanup', () => {+ let mounts = 0;+ let unmounts = 0;+ const onMount = () => {+ mounts += 1;+ };+ const onUnmount = () => {+ unmounts += 1;+ };++ const { container, rerender } = render(+ <Activity mode="visible">+ <EffectProbe onMount={onMount} onUnmount={onUnmount} />+ </Activity>,+ );+ const before = container.querySelector('[data-testid="activity-probe"]');+ expect(before).not.toBeNull();+ expect(mounts).toBe(1);+ expect(unmounts).toBe(0);++ rerender(+ <Activity mode="hidden">+ <EffectProbe onMount={onMount} onUnmount={onUnmount} />+ </Activity>,+ );++ const after = container.querySelector('[data-testid="activity-probe"]');+ // The DOM is not unmounted: the exact same node survives the flip to hidden.+ expect(after).toBe(before);+ // ...but its effects do unmount — the cleanup ran once, with no re-mount.+ expect(unmounts).toBe(1);+ expect(mounts).toBe(1);++ rerender(+ <Activity mode="visible">+ <EffectProbe onMount={onMount} onUnmount={onUnmount} />+ </Activity>,+ );+ // Revealing re-mounts the effects on the still-present node (state preserved).+ expect(container.querySelector('[data-testid="activity-probe"]')).toBe(before);+ expect(mounts).toBe(2);+ expect(unmounts).toBe(1);+ });+});diff --git a/packages/app/src/editor/SourceEditor.dom.test.tsx b/packages/app/src/editor/SourceEditor.dom.test.tsxindex a6c87e9dd..f0c743b6a 100644--- a/packages/app/src/editor/SourceEditor.dom.test.tsx+++ b/packages/app/src/editor/SourceEditor.dom.test.tsx@@ -10,7 +10,38 @@ import { subscribeToOpenAskAiComposer } from '@/components/ask-ai-composer-eventimport { OUTLINE_NAV_EVENT, type OutlineNavDetail } from '@/components/OutlinePanel';import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';import { evictCmEditor } from './editor-cache';-import { SourceEditor } from './SourceEditor';+import type { LandingHandle } from './landing-controller';+import { applyRawMdxNavigation, SourceEditor } from './SourceEditor';+import {+ __resetScrollRestoreCoordination,+ registerLandingScrollOwner,+} from './scroll-restore-coordination';+import {+ clearPendingSourceNavigationsForTest,+ peekPendingSourceNavigation,+ rememberPendingSourceNavigation,+ type SelectionOffsetNavigation,+} from './source-editor-navigation';++/**+ * Override slot for the cross-mode landing start. Whether a landing starts is+ * the branch the replay effect's consume decision turns on, and neither answer+ * is reachable in jsdom (a landing needs a mounted WYSIWYG doc and a scroller+ * with real client rects). Unset by default, so every other test in this file+ * runs the real implementation.+ */+const landingOverride = vi.hoisted(() => ({+ start: null as (() => LandingHandle | null) | null,+}));++vi.mock('./mode-switch-landing', async (importOriginal) => {+ const actual = await importOriginal<typeof import('./mode-switch-landing')>();+ return {+ ...actual,+ startSourceLanding: (params: Parameters<typeof actual.startSourceLanding>[0]) =>+ landingOverride.start ? landingOverride.start() : actual.startSourceLanding(params),+ };+});const originalFetch = globalThis.fetch;(globalThis as { Window?: typeof window.Window }).Window = window.Window;@@ -346,3 +377,131 @@ describe('SourceEditor outline navigation', () => {expect(view.state.selection.main.head).toBe(headingLine.from);});});++describe('SourceEditor raw-MDX replay mode re-check', () => {+ interface FakeCmView {+ state: { doc: { length: number } };+ dispatch: (spec: unknown) => void;+ focus: () => void;+ dispatched: unknown[];+ }++ function fakeCmView(docLength = 100): FakeCmView {+ const dispatched: unknown[] = [];+ return {+ state: { doc: { length: docLength } },+ dispatch: (spec) => {+ dispatched.push(spec);+ },+ focus: () => {},+ dispatched,+ };+ }++ const nextFrame = () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => resolve());+ });++ const NAV_DOC = 'raw-mdx-doc';++ beforeEach(() => {+ __resetScrollRestoreCoordination();+ });++ afterEach(() => {+ __resetScrollRestoreCoordination();+ });++ test('does not dispatch when the editor left source mode before the frame ran', async () => {+ const view = fakeCmView();+ applyRawMdxNavigation(view as unknown as EditorView, { offset: 42 }, () => false, NAV_DOC);+ await nextFrame();+ expect(view.dispatched).toHaveLength(0);+ });++ test('dispatches the navigation when still in source mode', async () => {+ const view = fakeCmView();+ applyRawMdxNavigation(view as unknown as EditorView, { offset: 42 }, () => true, NAV_DOC);+ await nextFrame();+ expect(view.dispatched).toHaveLength(1);+ });++ test('supersedes a position-preserving landing still holding the scroller', async () => {+ const supersede = vi.fn();+ registerLandingScrollOwner(NAV_DOC, { yieldsToNavigation: true, supersede });+ const view = fakeCmView();++ applyRawMdxNavigation(view as unknown as EditorView, { offset: 42 }, () => true, NAV_DOC);+ await nextFrame();++ expect(supersede).toHaveBeenCalledTimes(1);+ expect(view.dispatched).toHaveLength(1);+ });++ test('stands down while a landing that is itself a navigation owns the scroller', async () => {+ registerLandingScrollOwner(NAV_DOC, { yieldsToNavigation: false, supersede: vi.fn() });+ const view = fakeCmView();++ applyRawMdxNavigation(view as unknown as EditorView, { offset: 42 }, () => true, NAV_DOC);+ await nextFrame();++ expect(view.dispatched).toHaveLength(0);+ });+});++/**+ * The queued cross-mode jump is consume-once, so consuming it before knowing a+ * landing actually started throws it away: `startSourceLanding` declines when+ * the WYSIWYG doc it grades against was never mounted (the deferred-mount path+ * a large document takes), and the user's jump target would be gone even though+ * the entry's TTL still allows a later replay.+ */+describe('SourceEditor cross-mode landing replay', () => {+ const NAVIGATION: SelectionOffsetNavigation = {+ kind: 'selection-offset',+ intent: 'jump',+ anchor: { blockIndex: 0, kind: 'heading', content: 'heading' },+ };++ beforeEach(() => {+ clearPendingSourceNavigationsForTest();+ globalThis.fetch = vi.fn(async () => Response.json({})) as unknown as typeof fetch;+ });++ afterEach(() => {+ landingOverride.start = null;+ clearPendingSourceNavigationsForTest();+ cleanup();+ for (const docName of mountedDocNames) evictCmEditor(docName);+ mountedDocNames.clear();+ globalThis.fetch = originalFetch;+ });++ /** Mount source mode over a banked jump and let the deferred replay run. */+ async function mountWithQueuedJump(docName: string): Promise<void> {+ const { provider, ytext } = makeProvider(docName);+ rememberPendingSourceNavigation(docName, NAVIGATION);+ const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);+ await findCmContent(container);+ // The replay is deferred to a microtask so a StrictMode mount/unmount cycle+ // finishes first; flush it before reading the store.+ await act(async () => {});+ }++ test('keeps the jump banked when no landing could start', async () => {+ landingOverride.start = () => null;++ await mountWithQueuedJump('source-landing-declined');++ expect(peekPendingSourceNavigation('source-landing-declined')).toEqual(NAVIGATION);+ });++ test('consumes the jump once a landing owns it', async () => {+ landingOverride.start = () => ({ cancel: () => {} });++ await mountWithQueuedJump('source-landing-started');++ expect(peekPendingSourceNavigation('source-landing-started')).toBeNull();+ });+});diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsxindex fe583f85a..66bf65686 100644--- a/packages/app/src/editor/SourceEditor.tsx+++ b/packages/app/src/editor/SourceEditor.tsx@@ -1,6 +1,6 @@import { indentWithTab } from '@codemirror/commands';import { search } from '@codemirror/search';-import { Compartment, EditorSelection, EditorState } from '@codemirror/state';+import { Compartment, EditorSelection, EditorState, StateEffect } from '@codemirror/state';import { placeholder as cmPlaceholder, EditorView, keymap } from '@codemirror/view';import type { HocuspocusProvider } from '@hocuspocus/provider';import {@@ -25,11 +25,15 @@ import {import type { RawMdxNavDetail } from '@/editor/extensions/raw-mdx-nav-event';import { useConfigContext } from '@/lib/config-provider';import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';+import { registerSourceView, unregisterSourceView } from './active-source-view';import { createSourceClipboardExtension } from './clipboard/index.ts';import { type CmCacheEntry, mountCmEditor, parkCmEditor } from './editor-cache';import { useDocLintConfig } from './lint-config-client';+import { startSourceLanding } from './mode-switch-landing';import { getMountId } from './mount-id-registry';import { markUserTyping } from './observers';+import { landingFlashSource } from './plugins/landing-flash-source';+import { claimScrollerForNavigation, runScrollNavigation } from './scroll-restore-coordination';import { publishSelectionContext, selectionSnapshotFromSource } from './selection-context';import {publishSelectionStats,@@ -39,6 +43,7 @@ import {import {clearPendingSourceNavigation,consumePendingSourceNavigation,+ peekPendingSourceNavigation,} from './source-editor-navigation';import { createMarkdownLintExtension } from './source-lint/markdown-lint-source';import { sourceModeSetup } from './source-mode-setup';@@ -56,6 +61,11 @@ import { attachTypingBurstDetector } from './typing-burst-detector';// components/EditorToolbar.tsx.const TOOLBAR_OVERLAP_PX = 56;+// CodeMirror's search config asks for a scroll EFFECT rather than performing+// the scroll, so standing a match-scroll down means handing back an effect no+// extension reads.+const noScrollEffect = StateEffect.define<null>();+interface SourceEditorProps {docName: string;ytext: Y.Text;@@ -64,7 +74,7 @@ interface SourceEditorProps {isSourceModeActive: boolean;}-function applyOutlineNavigation(view: EditorView, detail: OutlineNavDetail): void {+function applyOutlineNavigation(view: EditorView, detail: OutlineNavDetail, docName: string): void {const doc = view.state.doc;let startLine = 1;// FM fence recognition must agree with the server's extractHeadings (core@@ -89,11 +99,13 @@ function applyOutlineNavigation(view: EditorView, detail: OutlineNavDetail): voiif (isInCodeFence(line.text)) continue;if (/^#{1,6}\s/.test(line.text)) {if (seen === detail.index) {- view.dispatch({- selection: EditorSelection.cursor(line.from),- effects: EditorView.scrollIntoView(line.from, { y: 'start' }),+ runScrollNavigation(docName, () => {+ view.dispatch({+ selection: EditorSelection.cursor(line.from),+ effects: EditorView.scrollIntoView(line.from, { y: 'start' }),+ });+ view.focus();});- view.focus();return;}seen++;@@ -101,39 +113,52 @@ function applyOutlineNavigation(view: EditorView, detail: OutlineNavDetail): voi}}-function applyRawMdxNavigation(view: EditorView, detail: RawMdxNavDetail): void {+export function applyRawMdxNavigation(+ view: EditorView,+ detail: RawMdxNavDetail,+ stillInSourceMode: () => boolean,+ docName: string,+): void {requestAnimationFrame(() => {+ // The dispatch is deferred a frame, so the user may flip back to WYSIWYG+ // between scheduling and running. Applying then would move the caret and+ // scroll a now-hidden editor; re-read the live mode and bail if it changed.+ if (!stillInSourceMode()) return;const doc = view.state.doc;// Clamp offset to doc length (offset may exceed doc length if content// differs between Y.Text and originalSpan).const pos = Math.min(detail.offset, doc.length);- view.dispatch({- selection: EditorSelection.cursor(pos),- effects: EditorView.scrollIntoView(pos, { y: 'center' }),+ runScrollNavigation(docName, () => {+ view.dispatch({+ selection: EditorSelection.cursor(pos),+ effects: EditorView.scrollIntoView(pos, { y: 'center' }),+ });+ view.focus();});- view.focus();});}/** Jump to a lint diagnostic's 1-based line/column. Lines/columns are clamped —* the doc may shift between the click and this dispatch. */-function applyLintNavigation(view: EditorView, detail: LintNavDetail): void {+function applyLintNavigation(view: EditorView, detail: LintNavDetail, docName: string): void {const doc = view.state.doc;const lineNumber = Math.min(Math.max(detail.line, 1), doc.lines);const line = doc.line(lineNumber);const pos = Math.min(line.from + Math.max(0, detail.column - 1), line.to);- view.dispatch({- selection: EditorSelection.cursor(pos),- // `y: 'start'` (not 'center'/'nearest'): in full-page source mode the editor- // renders at content height with no internal scrollport, so CM measures the- // target as already visible against its own scrollDOM and 'center'/'nearest'- // never scroll the real ancestor (ScrollPreservingContainer) — the jump- // silently no-ops whenever the doc overflows the viewport. Top-edge alignment- // propagates to the ancestor and honors `scrollMargins`, matching the search- // scrollToMatch + outline-nav fix above.- effects: EditorView.scrollIntoView(pos, { y: 'start' }),+ runScrollNavigation(docName, () => {+ view.dispatch({+ selection: EditorSelection.cursor(pos),+ // `y: 'start'` (not 'center'/'nearest'): in full-page source mode the editor+ // renders at content height with no internal scrollport, so CM measures the+ // target as already visible against its own scrollDOM and 'center'/'nearest'+ // never scroll the real ancestor (ScrollPreservingContainer) — the jump+ // silently no-ops whenever the doc overflows the viewport. Top-edge alignment+ // propagates to the ancestor and honors `scrollMargins`, matching the search+ // scrollToMatch + outline-nav fix above.+ effects: EditorView.scrollIntoView(pos, { y: 'start' }),+ });+ view.focus();});- view.focus();}export function SourceEditor({@@ -266,8 +291,16 @@ export function SourceEditor({// found offscreen match lands just under the toolbar instead of staying// out of view. Drives every search entry point (Enter, Cmd+G, F3,// next/prev) since they all route through `config.scrollToMatch`.+ //+ // A match is an explicit navigation, so it claims the scroller from+ // an in-flight mode-switch landing first — without that, a search+ // run inside a landing's settle window scrolls and is reset to the+ // landing's own target milliseconds later.search({- scrollToMatch: (range) => EditorView.scrollIntoView(range, { y: 'start' }),+ scrollToMatch: (range) =>+ claimScrollerForNavigation(resolvedDocName)+ ? EditorView.scrollIntoView(range, { y: 'start' })+ : noScrollEffect.of(null),}),// Tab inserts indentation instead of escaping focus. CM6's default is// to let Tab move focus (WCAG "no keyboard trap") — for a code-style@@ -293,6 +326,8 @@ export function SourceEditor({currentDocName: resolvedDocName,}),createSourcePolishExtension(),+ // Transient highlight for a mode-switch jump that lands in source.+ landingFlashSource(),lintCompartment.of(createMarkdownLintExtension(linterConfig, docName)),sourceClipboard,EditorView.updateListener.of((update) => {@@ -364,6 +399,9 @@ export function SourceEditor({});cmEntryRef.current = entry;viewRef.current = entry.view;+ // Publish the live view so a source-to-WYSIWYG flip can read its viewport+ // synchronously at flip time, before this editor is hidden.+ registerSourceView(docName, entry.view);} catch (err) {// Surface mount failures through DocumentErrorBoundary.console.error('[SourceEditor] mountCmEditor failed', err);@@ -376,6 +414,7 @@ export function SourceEditor({const cur = cmEntryRef.current;if (cur) {parkCmEditor(cur);+ unregisterSourceView(docName, cur.view);}// Listener cleanup is implicit when evictCmEditor calls view.destroy().// We do NOT remove listeners here because the view is still alive in@@ -496,7 +535,7 @@ export function SourceEditor({if (!detail || detail.mode !== 'source' || !isSourceModeActive) return;const view = viewRef.current;if (!view) return;- applyOutlineNavigation(view, detail);+ applyOutlineNavigation(view, detail, docName);clearPendingSourceNavigation(docName);}window.addEventListener(OUTLINE_NAV_EVENT, onNav);@@ -510,7 +549,7 @@ export function SourceEditor({if (!detail || !isSourceModeActive) return;const view = viewRef.current;if (!view) return;- applyLintNavigation(view, detail);+ applyLintNavigation(view, detail, docName);clearPendingSourceNavigation(docName);}window.addEventListener(LINT_NAV_EVENT, onLintNav);@@ -525,21 +564,62 @@ export function SourceEditor({const view = viewRef.current;if (!view) return;- const pendingNavigation = consumePendingSourceNavigation(docName);+ const pendingNavigation = peekPendingSourceNavigation(docName);if (!pendingNavigation) return;- if (pendingNavigation.kind === 'outline') {- applyOutlineNavigation(view, pendingNavigation.detail);- return;- }-- if (pendingNavigation.kind === 'lint') {- applyLintNavigation(view, pendingNavigation.detail);+ // The one-shot navs apply synchronously and consume their entry; re-running+ // this effect (a StrictMode mount is invoked twice) simply finds nothing left.+ if (pendingNavigation.kind !== 'selection-offset') {+ consumePendingSourceNavigation(docName);+ if (pendingNavigation.kind === 'outline') {+ applyOutlineNavigation(view, pendingNavigation.detail, docName);+ } else if (pendingNavigation.kind === 'lint') {+ applyLintNavigation(view, pendingNavigation.detail, docName);+ } else if (pendingNavigation.kind === 'raw-mdx') {+ applyRawMdxNavigation(+ view,+ pendingNavigation.detail,+ () => sourceModeActiveRef.current,+ docName,+ );+ }return;}- applyRawMdxNavigation(view, pendingNavigation.detail);- }, [docName, isSourceModeActive]);+ // The cross-mode landing runs through the settle contract instead of a+ // one-shot scroll, so it hands back a handle the cleanup cancels if the mode+ // flips away (or the doc changes) before it settles. Because that cleanup+ // cancels — and a cancelled landing is discarded without settling — starting+ // it synchronously here loses the whole landing to the immediate+ // mount→cleanup→remount a StrictMode mount performs. Deferring the consume+ // and start to a microtask lets that synchronous cycle finish first; only the+ // surviving closure's callback runs, so the landing starts once and settles.+ let cancelled = false;+ let landing: ReturnType<typeof startSourceLanding> = null;+ queueMicrotask(() => {+ if (cancelled) return;+ const navigation = peekPendingSourceNavigation(docName);+ if (navigation?.kind !== 'selection-offset') return;+ landing = startSourceLanding({+ view,+ docName,+ navigation,+ ydoc: provider.document,+ transition: { from: 'wysiwyg', to: 'source' },+ });+ // Consume only once a landing actually started. `startSourceLanding`+ // declines when the WYSIWYG doc it grades against is not mounted (a large+ // document that deferred it), and consuming first would drop the user's+ // jump target for good — leaving it banked lets a later entry replay it+ // inside its TTL. A landing that did start owns the entry from here: its+ // own cancel path discards it.+ if (landing) consumePendingSourceNavigation(docName);+ });+ return () => {+ cancelled = true;+ landing?.cancel('mode-flip');+ };+ }, [docName, isSourceModeActive, provider]);return <div ref={containerRef} className="source-editor h-full pb-3" />;}diff --git a/packages/app/src/editor/TiptapEditor.hash-ladder.dom.test.tsx b/packages/app/src/editor/TiptapEditor.hash-ladder.dom.test.tsxnew file mode 100644index 000000000..8b5fb5c0f--- /dev/null+++ b/packages/app/src/editor/TiptapEditor.hash-ladder.dom.test.tsx@@ -0,0 +1,196 @@+// @vitest-environment jsdom+/**+ * Deep-link hash-ladder mode gate.+ *+ * The WYSIWYG editor stays mounted while source mode is active (the flip is a+ * CSS swap, not an unmount), so the anchor-scroll ladder — which retries on a+ * timer and re-runs on every editor transaction — has to stand down in source+ * mode or it drives a hidden view. This renders the real component and observes+ * the ladder's only user-visible act: `scrollIntoView` on the anchor element.+ *+ * The editor construction path (V2 cache + mount promise) is replaced by a real+ * TipTap editor built here, so the component's own effects run unchanged+ * against a genuine ProseMirror view; the surrounding chrome is stubbed to+ * markers.+ */++import type { HocuspocusProvider } from '@hocuspocus/provider';+import { act, cleanup, render } from '@testing-library/react';+import { Editor } from '@tiptap/core';+import { Suspense } from 'react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { Awareness } from 'y-protocols/awareness';+import * as Y from 'yjs';+import { sharedExtensions } from './extensions/shared';++const DOC_NAME = 'hash-ladder-doc';++let editorEntry: {+ editor: Editor;+ ydoc: Y.Doc;+ ytext: Y.Text;+ provider: HocuspocusProvider;+} | null = null;++vi.doMock('./DocumentContext', () => ({+ useDocumentContext: () => ({+ principal: null,+ activeDocName: DOC_NAME,+ recycleDocument: () => {},+ openTarget: () => {},+ }),+}));+vi.doMock('../presence/identity', () => ({+ useIdentity: () => ({ name: 'Tester', color: '#336699' }),+}));+vi.doMock('./mount-promise', () => ({+ mountTiptapEditorPromise: () => Promise.resolve(editorEntry),+}));+vi.doMock('./editor-cache', () => ({+ parkTiptapEditor: () => {},+ peekRenameSnapshot: () => null,+ clearRenameSnapshot: () => {},+}));+vi.doMock('./bubble-menu/BubbleMenuBar', () => ({ BubbleMenuBar: () => <div /> }));+vi.doMock('./table-controls/TableCellHandles', () => ({ TableCellHandles: () => <div /> }));+vi.doMock('@/components/editor/SelectionAnnouncer', () => ({+ SelectionAnnouncer: () => <div />,+}));+vi.doMock('./interaction-layer', () => ({ InteractionLayerView: () => <div /> }));+vi.doMock('@tiptap/react', () => ({ EditorContent: () => <div data-testid="editor-content" /> }));++const { TiptapEditor } = await import('./TiptapEditor');++// jsdom ships no `CSS` object; the ladder escapes the anchor before querying+// for it. Backfilling the one method used keeps the production path intact.+if (typeof globalThis.CSS === 'undefined') {+ Object.defineProperty(globalThis, 'CSS', {+ value: { escape: (value: string) => value.replace(/[^\w-]/g, (c) => `\\${c}`) },+ configurable: true,+ });+}++function makeProvider(ydoc: Y.Doc): HocuspocusProvider {+ return {+ document: ydoc,+ awareness: new Awareness(ydoc),+ configuration: { name: DOC_NAME },+ on: () => {},+ off: () => {},+ } as unknown as HocuspocusProvider;+}++describe('TiptapEditor deep-link hash ladder', () => {+ let host: HTMLElement;+ let portalTarget: HTMLElement;+ let scrollIntoView: ReturnType<typeof vi.fn>;+ let originalScrollIntoView: PropertyDescriptor | undefined;++ beforeEach(() => {+ host = document.createElement('div');+ document.body.appendChild(host);+ portalTarget = document.createElement('div');+ document.body.appendChild(portalTarget);++ const ydoc = new Y.Doc();+ const ytext = ydoc.getText('source');+ ytext.insert(0, '# Target Heading\n\nbody');+ const editor = new Editor({+ element: host,+ extensions: sharedExtensions,+ content: {+ type: 'doc',+ content: [+ {+ type: 'heading',+ attrs: { level: 1 },+ content: [{ type: 'text', text: 'Target Heading' }],+ },+ { type: 'paragraph', content: [{ type: 'text', text: 'body' }] },+ ],+ },+ });+ editorEntry = { editor, ydoc, ytext, provider: makeProvider(ydoc) };++ // jsdom implements neither scroll nor layout; the ladder's only observable+ // act is this call on the resolved anchor element.+ scrollIntoView = vi.fn();+ originalScrollIntoView = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ 'scrollIntoView',+ );+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {+ value: scrollIntoView,+ configurable: true,+ writable: true,+ });+ window.location.hash = `#/${DOC_NAME}#target-heading`;+ });++ afterEach(() => {+ cleanup();+ editorEntry?.editor.destroy();+ editorEntry = null;+ host.remove();+ portalTarget.remove();+ if (originalScrollIntoView) {+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', originalScrollIntoView);+ } else {+ Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView');+ }+ window.location.hash = '';+ });++ function tree(isSourceMode: boolean) {+ const entry = editorEntry;+ if (!entry) throw new Error('editor entry not prepared');+ return (+ <Suspense fallback={null}>+ <TiptapEditor+ provider={entry.provider}+ isSourceMode={isSourceMode}+ portalTarget={portalTarget}+ />+ </Suspense>+ );+ }++ async function renderEditor(+ isSourceMode: boolean,+ ): Promise<ReturnType<typeof render> | undefined> {+ let result: ReturnType<typeof render> | undefined;+ // The editor arrives through a suspended promise, so the commit that runs+ // the effects happens after it resolves — inside this awaited act scope.+ await act(async () => {+ result = render(tree(isSourceMode));+ });+ return result;+ }++ test('anchor id is present so the ladder has a target to find', () => {+ expect(editorEntry?.editor.view.dom.querySelector('#target-heading')).not.toBeNull();+ });++ test('scrolls the hash anchor into view in visual mode', async () => {+ await renderEditor(false);+ expect(scrollIntoView).toHaveBeenCalled();+ });++ test('does not run the ladder while source mode is active', async () => {+ await renderEditor(true);+ expect(scrollIntoView).not.toHaveBeenCalled();+ });++ test('picks the hash up on the flip back out of source mode', async () => {+ // The editor is never unmounted by a flip, so the deep link that arrived+ // while it was hidden has to land when it becomes visible again.+ const result = await renderEditor(true);+ expect(scrollIntoView).not.toHaveBeenCalled();++ await act(async () => {+ result?.rerender(tree(false));+ });++ expect(scrollIntoView).toHaveBeenCalled();+ });+});diff --git a/packages/app/src/editor/TiptapEditor.replay-create-retry.dom.test.tsx b/packages/app/src/editor/TiptapEditor.replay-create-retry.dom.test.tsxnew file mode 100644index 000000000..53d83def8--- /dev/null+++ b/packages/app/src/editor/TiptapEditor.replay-create-retry.dom.test.tsx@@ -0,0 +1,163 @@+// @vitest-environment jsdom+/**+ * Source-to-WYSIWYG landing replay: pre-mount create retry.+ *+ * The replay effect fires when the WYSIWYG editor becomes the active surface,+ * but its ProseMirror view can still be mid-creation at that moment — a large+ * doc's deferred mount, or an Activity hidden->visible recycle. TipTap's+ * `'create'` mutates the editor in place without changing the effect's deps, so+ * an effect that merely bails when the view is absent never re-runs and silently+ * drops the queued landing. This renders the real component with the view held+ * absent, then fires `'create'`, and observes the effect's only decision point:+ * whether the queued navigation is consumed (a landing started) at all.+ *+ * `getEditorView` is the thin adapter over TipTap's throwing view proxy; stubbing+ * it models the pre-mount window the real adapter reports as `undefined`, rather+ * than mocking the effect under test.+ */++import type { HocuspocusProvider } from '@hocuspocus/provider';+import { act, cleanup, render } from '@testing-library/react';+import { Editor } from '@tiptap/core';+import { Suspense } from 'react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { Awareness } from 'y-protocols/awareness';+import * as Y from 'yjs';+import { sharedExtensions } from './extensions/shared';+import {+ clearPendingWysiwygNavigationsForTest,+ peekPendingWysiwygNavigation,+ rememberPendingWysiwygNavigation,+} from './source-editor-navigation';++const DOC_NAME = 'replay-create-retry-doc';++let editorEntry: {+ editor: Editor;+ ydoc: Y.Doc;+ ytext: Y.Text;+ provider: HocuspocusProvider;+} | null = null;++// Controls whether the stubbed `getEditorView` reports the view yet, modeling+// the deferred-mount window. Flipped true just before `'create'` fires.+let viewReady = false;++vi.doMock('./DocumentContext', () => ({+ useDocumentContext: () => ({+ principal: null,+ activeDocName: DOC_NAME,+ recycleDocument: () => {},+ openTarget: () => {},+ }),+}));+vi.doMock('../presence/identity', () => ({+ useIdentity: () => ({ name: 'Tester', color: '#336699' }),+}));+vi.doMock('./mount-promise', () => ({+ mountTiptapEditorPromise: () => Promise.resolve(editorEntry),+}));+vi.doMock('./editor-cache', () => ({+ parkTiptapEditor: () => {},+ peekRenameSnapshot: () => null,+ clearRenameSnapshot: () => {},+ visibleEditorScrollContainer: () => null,+}));+vi.doMock('./bubble-menu/BubbleMenuBar', () => ({ BubbleMenuBar: () => <div /> }));+vi.doMock('./table-controls/TableCellHandles', () => ({ TableCellHandles: () => <div /> }));+vi.doMock('@/components/editor/SelectionAnnouncer', () => ({+ SelectionAnnouncer: () => <div />,+}));+vi.doMock('./interaction-layer', () => ({ InteractionLayerView: () => <div /> }));+vi.doMock('@tiptap/react', () => ({ EditorContent: () => <div data-testid="editor-content" /> }));+vi.doMock('./utils/get-editor-view', () => ({+ getEditorView: (editor: Editor) =>+ viewReady ? (editor as unknown as { editorView?: unknown }).editorView : undefined,+}));++const { TiptapEditor } = await import('./TiptapEditor');++function makeProvider(ydoc: Y.Doc): HocuspocusProvider {+ return {+ document: ydoc,+ awareness: new Awareness(ydoc),+ configuration: { name: DOC_NAME },+ on: () => {},+ off: () => {},+ } as unknown as HocuspocusProvider;+}++describe('TiptapEditor source-to-WYSIWYG replay create retry', () => {+ let host: HTMLElement;+ let portalTarget: HTMLElement;++ beforeEach(() => {+ clearPendingWysiwygNavigationsForTest();+ viewReady = false;+ host = document.createElement('div');+ document.body.appendChild(host);+ portalTarget = document.createElement('div');+ document.body.appendChild(portalTarget);++ const ydoc = new Y.Doc();+ const ytext = ydoc.getText('source');+ ytext.insert(0, '# Title\n\nbody');+ const editor = new Editor({+ element: host,+ extensions: sharedExtensions,+ content: {+ type: 'doc',+ content: [+ { type: 'heading', attrs: { level: 1 }, content: [{ type: 'text', text: 'Title' }] },+ { type: 'paragraph', content: [{ type: 'text', text: 'body' }] },+ ],+ },+ });+ editorEntry = { editor, ydoc, ytext, provider: makeProvider(ydoc) };+ });++ afterEach(() => {+ cleanup();+ editorEntry?.editor.destroy();+ editorEntry = null;+ clearPendingWysiwygNavigationsForTest();+ host.remove();+ portalTarget.remove();+ });++ async function renderVisual(): Promise<void> {+ await act(async () => {+ render(+ <Suspense fallback={null}>+ <TiptapEditor+ provider={editorEntry?.provider as HocuspocusProvider}+ isSourceMode={false}+ portalTarget={portalTarget}+ />+ </Suspense>,+ );+ });+ }++ test('consumes a queued landing only once the view finishes mounting', async () => {+ rememberPendingWysiwygNavigation(DOC_NAME, {+ kind: 'selection-offset',+ anchor: { blockIndex: 1, kind: 'paragraph', content: 'body' },+ });++ // The active surface mounts with its view still deferred: the effect must not+ // drop the queued landing here.+ await renderVisual();+ expect(peekPendingWysiwygNavigation(DOC_NAME)).not.toBeNull();++ // The view finishes creating. `'create'` does not change the effect's deps,+ // so only a create-listening effect picks the landing back up.+ await act(async () => {+ viewReady = true;+ editorEntry?.editor.emit('create', { editor: editorEntry.editor });+ await Promise.resolve();+ });++ expect(peekPendingWysiwygNavigation(DOC_NAME)).toBeNull();+ });+});diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsxindex 72c3aa63a..0cbe6e486 100644--- a/packages/app/src/editor/TiptapEditor.tsx+++ b/packages/app/src/editor/TiptapEditor.tsx@@ -56,6 +56,8 @@ import { FrozenTableHeaders } from './extensions/frozen-table-headers.ts';import { MarkdownLintDecorations } from './extensions/markdown-lint-decorations.ts';import { sharedExtensions } from './extensions/shared.ts';import { uploadDecorationPlugin } from './image-upload/index.ts';+import type { LandingHandle } from './landing-controller';+import { startWysiwygLanding } from './mode-switch-landing';import { getMountId } from './mount-id-registry';import { mountTiptapEditorPromise } from './mount-promise';import { markUserTyping } from './observers';@@ -67,6 +69,7 @@ import {computeChangedRange,createAgentInsertFlashPlugin,} from './plugins/agent-insert-flash';+import { isScrollRestoreSuppressed, runScrollNavigation } from './scroll-restore-coordination';import { publishSelectionContext, selectionSnapshotFromWysiwyg } from './selection-context';import {publishSelectionStats,@@ -74,6 +77,10 @@ import {selectionStatsFromWysiwyg,} from './selection-stats';import { createSidebarAwareHandleDrop, openSidebarDropPayload } from './sidebar-drop';+import {+ consumePendingWysiwygNavigation,+ peekPendingWysiwygNavigation,+} from './source-editor-navigation';import { TableCellHandles } from './table-controls/TableCellHandles';import { attachTypingBurstDetector } from './typing-burst-detector';import { getEditorView } from './utils/get-editor-view';@@ -851,6 +858,56 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({return () => unregisterEditor(docName, editor);}, [editor, provider]);+ // Replays a queued source-to-WYSIWYG landing once this editor is the active,+ // visible surface for its doc — the WYSIWYG twin of SourceEditor's source-side+ // replay. The cross-mode landing runs through the settle contract rather than a+ // one-shot scroll, so it hands back a handle the cleanup cancels if the mode+ // flips away before it settles. Deferring the consume + start to a microtask+ // lets StrictMode's synchronous mount->cleanup->remount finish first, so only+ // the surviving closure starts the landing and it settles once.+ useEffect(() => {+ if (isSourceMode) return;+ const docName = provider.configuration.name;+ if (!docName) return;+ if (!peekPendingWysiwygNavigation(docName)) return;++ let cancelled = false;+ let landing: LandingHandle | null = null;+ const begin = (): void => {+ // Deferring the consume + start to a microtask lets StrictMode's+ // synchronous mount->cleanup->remount finish first, so only the surviving+ // closure starts the landing and it settles once.+ queueMicrotask(() => {+ if (cancelled) return;+ const navigation = consumePendingWysiwygNavigation(docName);+ if (navigation?.kind !== 'selection-offset') return;+ landing = startWysiwygLanding({+ editor,+ docName,+ navigation,+ ydoc: provider.document,+ transition: { from: 'source', to: 'wysiwyg' },+ });+ });+ };+ // The view can still be mid-creation when this passive effect runs — a large+ // doc's deferred mount, or an Activity hidden->visible recycle. `'create'`+ // mutates the editor in place without changing this effect's deps, so bailing+ // here would strand the queued landing until some unrelated re-render; defer+ // to the editor's `'create'` instead, matching this file's other view-guarded+ // effects.+ if (getEditorView(editor)) {+ begin();+ } else {+ editor.on('create', begin);+ }+ return () => {+ cancelled = true;+ editor.off('create', begin);+ landing?.cancel('mode-flip');+ };+ }, [editor, provider, isSourceMode]);+// Publish selection-scoped stats so the footer can scope its counts to the// current selection. Debounced because selection events fire rapidly during// drag-select; cleared to null on unmount so a closed tab leaves no entry.@@ -1276,6 +1333,10 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({const scrollToChange = (): void => {const sv = liveView();if (sv == null || sv.hasFocus() || document.visibilityState !== 'visible') return;+ // Following an agent's write is not the user navigating, so it defers to+ // a mode-switch landing rather than pre-empting one; the later follow-up+ // attempts run once the landing has settled and released.+ if (isScrollRestoreSuppressed(docName)) return;try {const docSize = sv.state.doc.content.size;const pos = Math.max(0, Math.min(Math.floor((from + to) / 2), docSize - 1));@@ -1367,6 +1428,13 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({// the case where the user clicks a deep-link to a doc already in the// pool — provider doesn't change, but the hash anchor does).useEffect(() => {+ // This editor stays mounted while source mode is active (the flip is a CSS+ // swap, not an unmount), so without this gate the ladder's retry timers and+ // transaction-driven re-scroll would keep driving a hidden WYSIWYG view. Skip+ // the work entirely in source mode; the effect re-runs on the flip back and+ // reads the current hash then, so a deep link that arrived while hidden still+ // lands when the editor becomes visible.+ if (isSourceMode) return;let attempts = 0;let timeoutId: number | undefined;let pendingAnchor: string | null = null;@@ -1397,8 +1465,12 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({function scrollAnchorIntoView(anchor: string): boolean {const el = findAnchorTarget(anchor);if (!el) return false;- el.scrollIntoView({ behavior: 'smooth', block: 'start' });- return true;+ // A deep link is an explicit navigation and supersedes a position-+ // preserving landing. Reporting a stand-down as "not scrolled" feeds the+ // retry ladder below, which re-tries once the other navigation released.+ return runScrollNavigation(docName, () => {+ el.scrollIntoView({ behavior: 'smooth', block: 'start' });+ });}// Cold deep links can hit while Activity/ProseMirror layout is still@@ -1490,7 +1562,7 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({editor.off('transaction', retryPendingOrSchedule);window.removeEventListener('hashchange', scheduleScrollFromHash);};- }, [provider, editor, docName, activeDocName]);+ }, [provider, editor, docName, activeDocName, isSourceMode]);// Outline panel click → scroll the Nth heading in the WYSIWYG DOM into view.// Using index (not slug) keeps this robust to duplicate heading texts without@@ -1506,11 +1578,14 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({if (!realView) return;const headings = realView.dom.querySelectorAll<HTMLElement>('h1, h2, h3, h4, h5, h6');const target = headings[detail.index];- if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });+ if (!target) return;+ runScrollNavigation(docName, () => {+ target.scrollIntoView({ behavior: 'smooth', block: 'start' });+ });}window.addEventListener(OUTLINE_NAV_EVENT, onNav);return () => window.removeEventListener(OUTLINE_NAV_EVENT, onNav);- }, [editor]);+ }, [editor, docName]);// Publish (or clear) this tab's awareness for the doc this editor binds to.//diff --git a/packages/app/src/editor/active-source-view.ts b/packages/app/src/editor/active-source-view.tsnew file mode 100644index 000000000..e8e5be013--- /dev/null+++ b/packages/app/src/editor/active-source-view.ts@@ -0,0 +1,32 @@+/**+ * Module-level registry mapping docName → the doc's live CodeMirror source view.+ *+ * The mode-toggle chokepoint captures the outgoing editor's viewport at flip+ * time, before React hides it. For a source-to-WYSIWYG flip the outgoing editor+ * is CodeMirror, whose view SourceEditor holds in a component-local ref — so it+ * publishes the live view here for that synchronous, one-shot capture to read.+ * The TipTap twin of this registry is `active-editor.ts`.+ *+ * Registration is last-writer-wins per docName; unregister matches on the view+ * ref so a StrictMode double-invoke (register-A, register-B, cleanup-A) does not+ * leave the map empty. No subscriber channel — unlike the TipTap registry no+ * reactive UI reads this, only the capture path.+ */++import type { EditorView } from '@codemirror/view';++const sourceViews = new Map<string, EditorView>();++export function registerSourceView(docName: string, view: EditorView): void {+ sourceViews.set(docName, view);+}++export function unregisterSourceView(docName: string, view: EditorView): void {+ if (sourceViews.get(docName) === view) {+ sourceViews.delete(docName);+ }+}++export function getSourceViewForDoc(docName: string): EditorView | null {+ return sourceViews.get(docName) ?? null;+}diff --git a/packages/app/src/editor/block-spans.ts b/packages/app/src/editor/block-spans.tsnew file mode 100644index 000000000..8c706dc92--- /dev/null+++ b/packages/app/src/editor/block-spans.ts@@ -0,0 +1,247 @@+/**+ * Top-level block-ordinal coordinate substrate shared by the WYSIWYG lint+ * decorations and cross-mode position mapping.+ *+ * Both surfaces need the same primitive: the alignment between the body's mdast+ * top-level blocks and the PM doc's top-level nodes. The bridge invariant makes+ * them 1:1 (Y.Text is truth; the fragment derives via parse), so a block's+ * ordinal is a representation-independent handle — provided the count-equality+ * tripwire (`comparableChildCount`) holds. This module is intentionally+ * dependency-light (no React, no floating-ui) so the resolver can build on it+ * without dragging in a decoration plugin's module graph.+ */++import { type MarkdownManager, stripFrontmatter } from '@inkeep/open-knowledge-core';+import type { Node as PmNode } from '@tiptap/pm/model';++/** 1-based inclusive line spans of top-level body blocks, in full-source coordinates. */+export interface SourceBlockSpans {+ spans: { start: number; end: number }[];+ /** Lines the frontmatter region occupies at the top of the source (0 when none). */+ fmLineCount: number;+}++/** A top-level source block enriched with the fields the position resolver grades on. */+export interface SourceBlock {+ /** 1-based inclusive line span in full-source coordinates. */+ start: number;+ end: number;+ /** Canonical block kind, normalized across the mdast and PM vocabularies. */+ kind: string;+ /** Plain text content (markdown syntax stripped), for content-equality checks. */+ text: string;+}++/**+ * Normalize a mdast or ProseMirror node-type name to a shared block-kind+ * vocabulary so a block captured in one representation can be type-matched+ * against the other. mdast and PM disagree on several names for the same+ * construct (`list` vs `bulletList`/`orderedList`, `code` vs `codeBlock`,+ * `thematicBreak` vs `horizontalRule`); unknown names pass through unchanged so+ * an exact name match still counts.+ */+export function canonicalBlockKind(typeName: string): string {+ switch (typeName) {+ case 'bulletList':+ case 'orderedList':+ case 'taskList':+ case 'list':+ return 'list';+ case 'codeBlock':+ case 'code':+ return 'code';+ case 'horizontalRule':+ case 'thematicBreak':+ return 'thematicBreak';+ case 'jsxComponent':+ case 'mdxJsxFlowElement':+ case 'mdxJsxTextElement':+ return 'jsx';+ case 'htmlBlock':+ case 'html':+ return 'html';+ default:+ return typeName;+ }+}++/**+ * Concatenate the visible text of an mdast node (its descendant literal values),+ * the mdast counterpart of ProseMirror's `node.textContent`. Kept structural+ * (walks `value`/`children` without an mdast type import) so this leaf module+ * stays free of the `mdast` dependency.+ */+function mdastText(node: unknown): string {+ if (typeof node !== 'object' || node === null) return '';+ if ('value' in node && typeof node.value === 'string') return node.value;+ if ('children' in node && Array.isArray(node.children)) {+ return node.children.map(mdastText).join('');+ }+ return '';+}++/**+ * Top-level body blocks for a full `Y.Text('source')` snapshot. The body region+ * (after the FM fence) is parsed to mdast; line spans are shifted back into+ * full-source coordinates so full-source line numbers index into them directly.+ * The single positioned parse the resolver relies on.+ */+export function computeSourceBlocks(+ source: string,+ md: MarkdownManager,+): { blocks: SourceBlock[]; fmLineCount: number } {+ const { frontmatter, body } = stripFrontmatter(source);+ const fmLineCount = frontmatter === '' ? 0 : frontmatter.split('\n').length - 1;+ // The editor view, not the CommonMark one: a preserved blank line is a+ // paragraph in the PM doc, and this array is index-aligned with those+ // children. Losing the alignment silently disables every decoration and+ // strands the count tripwire.+ //+ // `parseToEditorMdast` throws on structurally invalid MDX (an unclosed or mismatched+ // JSX tag) — a routine transient state while editing raw source. Every consumer+ // (the lint decorations and the mode-switch resolver) already treats an empty+ // block list as "no anchor", so degrading to no blocks reproduces the+ // pre-feature no-op flip. A synchronous throw would be worse than a lost anchor:+ // the toggle captures the source block before the mode flips, so it would abort+ // the flip and strand the user in the mode they were leaving.+ try {+ const blocks = md.parseToEditorMdast(body).children.map((child) => ({+ start: (child.position?.start.line ?? Number.POSITIVE_INFINITY) + fmLineCount,+ end: (child.position?.end.line ?? Number.NEGATIVE_INFINITY) + fmLineCount,+ kind: canonicalBlockKind(child.type),+ text: mdastText(child),+ }));+ return { blocks, fmLineCount };+ } catch {+ // Leave a breadcrumb: the no-blocks degradation is indistinguishable from a+ // genuinely empty body downstream, and a systematic parse regression on+ // valid markdown would silently send every mode switch to the top of the+ // document with nothing to find. Raw `performance.mark` rather than the+ // `mark()` helper keeps this leaf free of the perf module's graph; the name+ // follows the same ok/<subsystem>/<event> convention.+ performance.mark('ok/block-spans/parse-failed');+ return { blocks: [], fmLineCount };+ }+}++/**+ * Line spans for a full `Y.Text('source')` snapshot — the projection of+ * `computeSourceBlocks` that lint diagnostics (which carry full-source lines —+ * markdownlint skips the FM region itself) index into directly.+ */+export function computeSourceBlockSpans(source: string, md: MarkdownManager): SourceBlockSpans {+ const { blocks, fmLineCount } = computeSourceBlocks(source, md);+ return { spans: blocks.map((b) => ({ start: b.start, end: b.end })), fmLineCount };+}++/**+ * Map a 1-based full-source line to a top-level block index. Lines inside a+ * block map to it; between-block lines (blank-line runs — where rules like+ * MD012 report) anchor to the NEXT block; lines past the last block anchor to+ * the last one. Null only when there are no blocks at all.+ *+ * Spans are ascending and non-overlapping (mdast top-level positions), so a+ * binary search for the first span whose end is at or after the line yields+ * both the containing case and the gap-anchors-to-next case in one probe: that+ * span contains the line when its start is also below it, and is the next block+ * otherwise. A line past every span's end falls through to the last block.+ */+export function blockIndexForLine(spans: SourceBlockSpans['spans'], line: number): number | null {+ if (spans.length === 0) return null;+ let lo = 0;+ let hi = spans.length - 1;+ let candidate = spans.length - 1;+ while (lo <= hi) {+ const mid = (lo + hi) >> 1;+ const span = spans[mid];+ if (span !== undefined && span.end >= line) {+ candidate = mid;+ hi = mid - 1;+ } else {+ lo = mid + 1;+ }+ }+ return candidate;+}++/**+ * Top-level child count comparable against body block spans. A doc whose last+ * block isn't a paragraph renders with a trailing empty paragraph (the+ * type-here affordance below a final heading/list) that has NO source+ * counterpart — parse of the source never yields an empty paragraph. Without+ * this allowance the span↔doc count comparison fails PERMANENTLY on+ * heading-final docs, silently disabling decorations and navigation.+ */+export function comparableChildCount(doc: PmNode): number {+ const last = doc.childCount > 0 ? doc.child(doc.childCount - 1) : null;+ const trailingEmptyParagraph =+ last !== null && last.type.name === 'paragraph' && last.content.size === 0;+ return trailingEmptyParagraph ? doc.childCount - 1 : doc.childCount;+}++/**+ * ProseMirror positions spanning top-level blocks `[fromBlock, toBlock)`: from+ * the boundary before the first block through the boundary after the last. Block+ * indices address PM top-level nodes directly (y-prosemirror mirrors the+ * XmlFragment's children onto the PM doc). Both ends are clamped to the document+ * size; null when the range is empty or falls entirely outside the document. The+ * PM-position sibling of the line-and-offset helpers below.+ */+export function blockRangeToPositions(+ doc: PmNode,+ fromBlock: number,+ toBlock: number,+): { from: number; to: number } | null {+ const childCount = doc.childCount;+ const first = Math.max(0, Math.min(fromBlock, childCount));+ const last = Math.max(first, Math.min(toBlock, childCount));+ if (last <= first) return null;+ let pos = 0;+ for (let i = 0; i < first; i++) pos += doc.child(i).nodeSize;+ const from = pos;+ for (let i = first; i < last; i++) pos += doc.child(i).nodeSize;+ const to = pos;+ const size = doc.content.size;+ const clampedFrom = Math.max(0, Math.min(from, size));+ const clampedTo = Math.max(clampedFrom, Math.min(to, size));+ if (clampedTo <= clampedFrom) return null;+ return { from: clampedFrom, to: clampedTo };+}++/**+ * Char offset where each 1-based line begins. `offsets[i]` is the start of line+ * `i + 1`; index 0 is always 0. Used to convert the line-based block spans into+ * the full `Y.Text` char offsets that cross the resolver's boundary.+ */+export function lineStartOffsets(source: string): number[] {+ const offsets = [0];+ for (let i = 0; i < source.length; i++) {+ if (source[i] === '\n') offsets.push(i + 1);+ }+ return offsets;+}++/** Full-source char offset of the start of a 1-based line, clamped to the source. */+export function lineToOffset(offsets: number[], line: number, sourceLength: number): number {+ if (line <= 1) return 0;+ if (line - 1 >= offsets.length) return sourceLength;+ return offsets[line - 1] ?? sourceLength;+}++/** 1-based line containing a full-source char offset. */+export function offsetToLine(offsets: number[], offset: number): number {+ // offsets is ascending; find the last line start <= offset.+ let lo = 0;+ let hi = offsets.length - 1;+ let line = 1;+ while (lo <= hi) {+ const mid = (lo + hi) >> 1;+ if ((offsets[mid] ?? 0) <= offset) {+ line = mid + 1;+ lo = mid + 1;+ } else {+ hi = mid - 1;+ }+ }+ return line;+}diff --git a/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsx b/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsxindex 39345ccd7..ef831977d 100644--- a/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsx+++ b/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsx@@ -14,6 +14,7 @@ import { FootnoteBubbleButton } from './FootnoteBubbleButton';import { ImageAlignButtons, isImageNodeSelected } from './ImageAlignButtons';import { InlineFormatButtons } from './InlineFormatButtons';import { LinkEditPopover } from './LinkEditPopover';+import { ViewInSourceBubbleButton } from './ViewInSourceBubbleButton';export function BubbleMenuBar({editor,@@ -136,6 +137,7 @@ export function BubbleMenuBar({shortcutEnabled={shortcutEnabled}/><FootnoteBubbleButton key={`${tooltipKey}-footnote`} editor={editor} />+ <ViewInSourceBubbleButton key={`${tooltipKey}-view-source`} editor={editor} /><EditWithAiBubbleButtonkey={`${tooltipKey}-edit-ai`}editor={editor}diff --git a/packages/app/src/editor/bubble-menu/ViewInSourceBubbleButton.dom.test.tsx b/packages/app/src/editor/bubble-menu/ViewInSourceBubbleButton.dom.test.tsxnew file mode 100644index 000000000..27f074b19--- /dev/null+++ b/packages/app/src/editor/bubble-menu/ViewInSourceBubbleButton.dom.test.tsx@@ -0,0 +1,168 @@+/**+ * RTL behavior tests for `ViewInSourceBubbleButton` — the WYSIWYG bubble-menu+ * "View in source" entry.+ *+ * These exercise the real `requestViewInSource` wiring end to end: the button+ * reads the doc name and Y.Doc off the editor, derives the source `Y.Text`, and+ * drives the jump. The observable effects are the real ones — the flip event+ * that `EditorPane` subscribes to, and the jump navigation banked in the shared+ * pending-navigation store — so nothing internal is mocked.+ *+ * The keyboard cases are the point of the story: the icon-only siblings in this+ * bar act on `mousedown` only and so never fire from the keyboard. This entry+ * puts its action on `onClick`, which a focused button raises from Enter and+ * Space alike, and leaves `mousedown` to only hold the selection paint.+ *+ * Invocation: `pnpm run test:dom` from `packages/app/`.+ */++import { MarkdownManager, sharedExtensions, stripFrontmatter } from '@inkeep/open-knowledge-core';+import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { type Editor, getSchema } from '@tiptap/core';+import type { Node as PmNode } from '@tiptap/pm/model';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import * as Y from 'yjs';+import { TooltipProvider } from '@/components/ui/tooltip';+import { setEditorDocName } from '../extensions/doc-context.ts';+import {+ clearPendingSourceNavigationsForTest,+ peekPendingSourceNavigation,+} from '../source-editor-navigation.ts';+import { VIEW_IN_SOURCE_EVENT, type ViewInSourceDetail } from '../view-in-source-event.ts';+import { ViewInSourceBubbleButton } from './ViewInSourceBubbleButton.tsx';++const md = new MarkdownManager({ extensions: sharedExtensions });+const schema = getSchema(sharedExtensions);++const DOC = '# Title\n\nfirst\n\ntarget paragraph';++/** PM position just inside top-level block `index`. */+function pmPosOfBlock(doc: PmNode, index: number): number {+ let pos = 0;+ for (let i = 0; i < index; i++) pos += doc.child(i).nodeSize;+ return pos + 1;+}++/**+ * A stand-in TipTap editor complete enough for the real jump: a ProseMirror+ * view carrying the caret + doc (`getEditorView`), a Collaboration extension+ * whose document is the seeded Y.Doc (`getYDoc`), and a registered doc name+ * (`getEditorDocName`). Pass `docName: null` to leave it unregistered. `caretBlock`+ * places the caret inside that top-level block, so the jump targets it.+ */+function makeEditor(+ markdown: string,+ caretBlock: number,+ docName: string | null = 'doc-view',+): { editor: Editor; ydoc: Y.Doc } {+ const { body } = stripFrontmatter(markdown);+ const doc = schema.nodeFromJSON(md.parse(body));+ const ydoc = new Y.Doc();+ ydoc.getText('source').insert(0, markdown);+ const editor = {+ isDestroyed: false,+ editorView: { state: { doc, selection: { from: pmPosOfBlock(doc, caretBlock) } } },+ extensionManager: { extensions: [{ name: 'collaboration', options: { document: ydoc } }] },+ } as unknown as Editor;+ setEditorDocName(editor, docName);+ return { editor, ydoc };+}++function renderButton(editor: Editor) {+ return render(+ <TooltipProvider>+ <ViewInSourceBubbleButton editor={editor} />+ </TooltipProvider>,+ );+}++let flipped: string[] = [];+let unsubscribe: (() => void) | null = null;++beforeEach(() => {+ clearPendingSourceNavigationsForTest();+ flipped = [];+ const onFlip = (e: Event) => {+ flipped.push((e as CustomEvent<ViewInSourceDetail>).detail.docName);+ };+ window.addEventListener(VIEW_IN_SOURCE_EVENT, onFlip);+ unsubscribe = () => window.removeEventListener(VIEW_IN_SOURCE_EVENT, onFlip);+});++afterEach(() => {+ unsubscribe?.();+ unsubscribe = null;+ cleanup();+});++describe('ViewInSourceBubbleButton', () => {+ test('renders a labelled, native-button entry', () => {+ const { editor } = makeEditor(DOC, 2);+ renderButton(editor);++ const button = screen.getByTestId('view-in-source-bubble-button');+ expect(button.tagName).toBe('BUTTON');+ expect(button.getAttribute('aria-label')).toBe('View in source markdown');+ });++ test('clicking jumps to the selection block and asks the pane to flip', async () => {+ const user = userEvent.setup();+ const { editor } = makeEditor(DOC, 2);+ renderButton(editor);++ await user.click(screen.getByTestId('view-in-source-bubble-button'));++ expect(flipped).toEqual(['doc-view']);+ const nav = peekPendingSourceNavigation('doc-view');+ if (nav?.kind !== 'selection-offset') throw new Error('expected a selection-offset nav');+ expect(nav.intent).toBe('jump');+ expect(nav.anchor.blockIndex).toBe(2);+ });++ test('activates from a keyboard Enter press', async () => {+ const user = userEvent.setup();+ const { editor } = makeEditor(DOC, 2);+ renderButton(editor);++ screen.getByTestId('view-in-source-bubble-button').focus();+ await user.keyboard('{Enter}');++ expect(flipped).toEqual(['doc-view']);+ expect(peekPendingSourceNavigation('doc-view')?.kind).toBe('selection-offset');+ });++ test('activates from a keyboard Space press', async () => {+ const user = userEvent.setup();+ const { editor } = makeEditor(DOC, 2);+ renderButton(editor);++ screen.getByTestId('view-in-source-bubble-button').focus();+ await user.keyboard('[Space]');++ expect(flipped).toEqual(['doc-view']);+ expect(peekPendingSourceNavigation('doc-view')?.kind).toBe('selection-offset');+ });++ test('the action is not bound to mousedown alone, so it never fires from mousedown', () => {+ const { editor } = makeEditor(DOC, 2);+ renderButton(editor);++ // A bare mousedown (no click, no keyboard) must not act — that is exactly the+ // mouse-down-only shape the icon siblings use, which the keyboard cannot reach.+ fireEvent.mouseDown(screen.getByTestId('view-in-source-bubble-button'));++ expect(flipped).toEqual([]);+ expect(peekPendingSourceNavigation('doc-view')).toBeNull();+ });++ test('no-ops when the editor has no registered doc name', async () => {+ const user = userEvent.setup();+ const { editor } = makeEditor(DOC, 2, null);+ renderButton(editor);++ await user.click(screen.getByTestId('view-in-source-bubble-button'));++ expect(flipped).toEqual([]);+ });+});diff --git a/packages/app/src/editor/bubble-menu/ViewInSourceBubbleButton.tsx b/packages/app/src/editor/bubble-menu/ViewInSourceBubbleButton.tsxnew file mode 100644index 000000000..f5302de58--- /dev/null+++ b/packages/app/src/editor/bubble-menu/ViewInSourceBubbleButton.tsx@@ -0,0 +1,68 @@+/**+ * "View in source" entry for the WYSIWYG bubble menu — jumps from the current+ * selection to its markdown source. Activating it flips the editor to source+ * mode and lands the selected block's source range centered and flashed, caret+ * at its start, so a user reading a passage can inspect or fix its markdown+ * without re-scrolling.+ *+ * The jump targets the selection's block: `requestViewInSource` reads the+ * selection start, which is where the bubble bar is anchored anyway.+ *+ * Unlike the icon-only siblings in this bar, this entry is keyboard-operable.+ * The action lives on `onClick`, which a focused button fires from both a mouse+ * click and a keyboard Enter/Space press; `onMouseDown` only suppresses the+ * focus shift so the selection stays painted through the flip, matching the bar+ * convention without moving the action off the keyboard-reachable path.+ */++import { useLingui } from '@lingui/react/macro';+import type { Editor } from '@tiptap/react';+import type { ReactNode } from 'react';+import { Markdown } from '@/components/icons/markdown';+import { Button } from '@/components/ui/button';+import { Kbd } from '@/components/ui/kbd';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';+import { getEditorDocName } from '../extensions/doc-context';+import { requestViewInSource } from '../mode-switch-landing';+import { getYDoc } from '../utils/get-ydoc';++export function ViewInSourceBubbleButton({ editor }: { editor: Editor }): ReactNode {+ const { t } = useLingui();++ const jump = (): void => {+ const docName = getEditorDocName(editor);+ const ydoc = getYDoc(editor);+ // Read the doc identity at activation time, not render time: the pooled+ // editor can be torn down between the bubble rendering and the click. With+ // no registered doc name or Y.Doc there is nothing to navigate into, so the+ // entry no-ops rather than dispatching a flip that would land nowhere.+ if (docName === null || !ydoc) return;+ requestViewInSource({ editor, docName, ytext: ydoc.getText('source') });+ };++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ data-testid="view-in-source-bubble-button"+ className="text-accent-foreground/80"+ aria-label={t`View in source markdown`}+ onMouseDown={(e) => e.preventDefault()}+ onClick={jump}+ >+ <Markdown className="size-3.5" aria-hidden="true" />+ </Button>+ </TooltipTrigger>+ <TooltipContent side="bottom" sideOffset={8}>+ <span>{t`View in source markdown`}</span>+ <Kbd aria-label={formatShortcutLabel('view-source-at-cursor')}>+ {formatShortcut('view-source-at-cursor')}+ </Kbd>+ </TooltipContent>+ </Tooltip>+ );+}diff --git a/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.ts b/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.tsindex a33d53d6c..57f931ca4 100644--- a/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.ts+++ b/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.ts@@ -1,11 +1,12 @@/*** Per-descriptor static palette for the live-DOM clipboard walker.*- * Used only when `view.nodeDOM(pos)` returns `null` — the slice originates- * inside an `<Activity mode="hidden">` subtree whose live DOM was unmounted.- * The walker's primary path captures whatever React rendered + whatever CSS- * resolved; this fallback emits a hand-built palette for each canonical /- * compat descriptor so the Activity-hidden case isn't silently empty.+ * Used only when `view.nodeDOM(pos)` returns `null` — nothing is rendered for+ * the slice's position. Hiding an `<Activity>` subtree does not produce that:+ * React keeps its DOM at `display:none`. The walker's primary path captures+ * whatever React rendered + whatever CSS resolved; this fallback emits a+ * hand-built palette for each canonical / compat descriptor so a slice with no+ * live DOM isn't silently empty.** Output shape per descriptor mirrors what the React render produces (post* walker filter), so cross-app destinations see the same shape regardless ofdiff --git a/packages/app/src/editor/clipboard/clipboard-walker.ts b/packages/app/src/editor/clipboard/clipboard-walker.tsindex 0c9ab1649..f419a20e1 100644--- a/packages/app/src/editor/clipboard/clipboard-walker.ts+++ b/packages/app/src/editor/clipboard/clipboard-walker.ts@@ -15,9 +15,10 @@* state (Tabs / Carousel / Canvas) opt in to a `descriptor.toClipboardHast`* override.*- * Activity-hidden edge: `view.nodeDOM(pos)` returns null when the slice is in- * an `<Activity mode="hidden">` subtree whose DOM was unmounted. The walker- * delegates to the per-descriptor static palette in+ * No-live-DOM edge: `view.nodeDOM(pos)` returns null when nothing is rendered+ * for the slice's position. Hiding an `<Activity>` subtree is not that case —+ * React keeps its DOM at `display:none` — so the null is unexpected and logged.+ * The walker then delegates to the per-descriptor static palette in* `clipboard-walker-fallback-palette.ts`.** Opt-out: a descriptor can mark a subtree with `data-clipboard-omit="true"`diff --git a/packages/app/src/editor/editor-cache-visible-scroll-container.test.ts b/packages/app/src/editor/editor-cache-visible-scroll-container.test.tsnew file mode 100644index 000000000..f6cc3454a--- /dev/null+++ b/packages/app/src/editor/editor-cache-visible-scroll-container.test.ts@@ -0,0 +1,45 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, test } from 'vitest';+import { visibleEditorScrollContainer } from './editor-cache.ts';++/**+ * jsdom has no layout engine, so `getClientRects()` is empty for every element.+ * Stub it to model the real browser signal the helper relies on: a painted+ * element has layout boxes, a `display:none` (hidden `<Activity>`) element has+ * none. This stubs the missing platform capability, not the module under test.+ */+function addScrollContainer(painted: boolean, scrollTop: number): HTMLDivElement {+ const el = document.createElement('div');+ el.setAttribute('data-testid', 'editor-scroll-container');+ el.scrollTop = scrollTop;+ el.getClientRects = () =>+ (painted ? [{ width: 800, height: 600 } as DOMRect] : []) as unknown as DOMRectList;+ document.body.append(el);+ return el;+}++afterEach(() => {+ document.body.innerHTML = '';+});++describe('visibleEditorScrollContainer', () => {+ test('picks the painted container even when a hidden pooled one precedes it in DOM order', () => {+ // A hidden pooled entry's container survives in the DOM and sorts first; a+ // plain first-match query would return it and read its stale scrollTop.+ addScrollContainer(false, 111);+ const active = addScrollContainer(true, 222);+ expect(visibleEditorScrollContainer()).toBe(active);+ expect(visibleEditorScrollContainer()?.scrollTop).toBe(222);+ });++ test('returns null when no container is painted', () => {+ addScrollContainer(false, 1);+ addScrollContainer(false, 2);+ expect(visibleEditorScrollContainer()).toBeNull();+ });++ test('returns the sole container when nothing is pooled', () => {+ const only = addScrollContainer(true, 42);+ expect(visibleEditorScrollContainer()).toBe(only);+ });+});diff --git a/packages/app/src/editor/editor-cache.test.ts b/packages/app/src/editor/editor-cache.test.tsindex b6ea4518d..9ff2a32db 100644--- a/packages/app/src/editor/editor-cache.test.ts+++ b/packages/app/src/editor/editor-cache.test.ts@@ -64,6 +64,10 @@ import {__resetMountPromiseCache,mountTiptapEditorPromise,} from './mount-promise';+import {+ __resetScrollRestoreCoordination,+ acquireScrollRestoreSuppression,+} from './scroll-restore-coordination';// ---------------------------------------------------------------------------// Minimal HTMLElement fake — satisfies the subset the cache uses.@@ -339,9 +343,11 @@ describe('MAX_CACHE constant', () => {describe('TipTap cache — lifecycle', () => {beforeEach(() => {__resetCacheForTests();+ __resetScrollRestoreCoordination();});afterEach(() => {__resetCacheForTests();+ __resetScrollRestoreCoordination();});test('mount: cache-miss calls factory and stores entry', () => {@@ -410,6 +416,41 @@ describe('TipTap cache — lifecycle', () => {expect(newContainer.scrollTop).toBe(1234);});+ test('mount: cache-hit stands down on scroll restore while a landing holds the scroller', () => {+ // A warm mount and a mode-switch landing fire at the same moment; the+ // landing is the single scroll writer for its window, so the parked+ // position must not be written over it.+ const h = makeTiptapHarness('doc-a');+ const entry = mountTiptapEditor({+ docName: h.docName,+ container: h.container as unknown as HTMLElement,+ factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,+ });+ h.editorDom.scrollTop = 1234;+ parkTiptapEditor(entry);++ const suppression = acquireScrollRestoreSuppression(h.docName);+ const suppressed = makeNode();+ mountTiptapEditor({+ docName: h.docName,+ container: suppressed as unknown as HTMLElement,+ factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,+ });+ expect(suppressed.scrollTop).toBe(0);++ // Suppression is per-document and lifts on release: the next warm mount+ // restores again.+ parkTiptapEditor(entry);+ suppression.release();+ const released = makeNode();+ mountTiptapEditor({+ docName: h.docName,+ container: released as unknown as HTMLElement,+ factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,+ });+ expect(released.scrollTop).toBe(1234);+ });+test('mount: cache-hit restores focus ONLY when editor owned focus at park time', () => {const h = makeTiptapHarness('doc-a');const entry = mountTiptapEditor({@@ -1010,8 +1051,14 @@ describe('TipTap cache — undoManager.restore cleanup on destroy', () => {// ---------------------------------------------------------------------------describe('CM6 cache — lifecycle', () => {- beforeEach(() => __resetCacheForTests());- afterEach(() => __resetCacheForTests());+ beforeEach(() => {+ __resetCacheForTests();+ __resetScrollRestoreCoordination();+ });+ afterEach(() => {+ __resetCacheForTests();+ __resetScrollRestoreCoordination();+ });test('mount: cache-miss calls factory and stores entry', () => {const h = makeCmHarness('cm-doc-a');@@ -1156,6 +1203,39 @@ describe('CM6 cache — lifecycle', () => {expect(h.spies.focusCalls).toBeGreaterThan(before2);});+ test('mount after park: stands down on scroll restore while a landing holds the scroller', () => {+ // Source-mode twin of the TipTap case: a source landing owns the scroller+ // for its settle window, so the warm mount must not write the parked+ // position over it.+ const h = makeCmHarness('cm-doc-a');+ const entry = mountCmEditor({+ docName: h.docName,+ container: h.container as unknown as HTMLElement,+ factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,+ });+ h.viewDom.scrollTop = 42;+ parkCmEditor(entry);++ const suppression = acquireScrollRestoreSuppression(h.docName);+ const suppressed = makeNode();+ mountCmEditor({+ docName: h.docName,+ container: suppressed as unknown as HTMLElement,+ factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,+ });+ expect(suppressed.scrollTop).toBe(0);++ parkCmEditor(entry);+ suppression.release();+ const released = makeNode();+ mountCmEditor({+ docName: h.docName,+ container: released as unknown as HTMLElement,+ factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,+ });+ expect(released.scrollTop).toBe(42);+ });+test('evict: destroys view + provider + ydoc', () => {const h = makeCmHarness('cm-doc-a');mountCmEditor({diff --git a/packages/app/src/editor/editor-cache.ts b/packages/app/src/editor/editor-cache.tsindex 80b41203e..16083cb54 100644--- a/packages/app/src/editor/editor-cache.ts+++ b/packages/app/src/editor/editor-cache.ts@@ -65,6 +65,7 @@ import { getMountId } from './mount-id-registry';// module — keep it that way to preserve coordinated lifecycle between this// V2 cache and the mount-promise cache.import { invalidateMountPromise } from './mount-promise';+import { isScrollRestoreSuppressed } from './scroll-restore-coordination';/*** Read the per-editor Yjs UndoManager so the caller can null its `restore`@@ -437,17 +438,31 @@ export function __resetRenameSnapshotStore(): void {}/**- * Best-effort live scrollTop read from the active editor scroll container.- * The active doc's `ScrollPreservingContainer` pins `data-testid="editor-scroll-container"`- * on its outer scrollable div (`EditorActivityPool.tsx`). Only the active doc's- * container is rendered at any time (hidden Activity entries don't paint DOM per- * React 19.2), so the query is unambiguous.+ * The painted editor scroll container, or null. Each pooled doc's+ * `ScrollPreservingContainer` pins `data-testid="editor-scroll-container"` on its+ * outer scrollable div (`EditorActivityPool.tsx`). A hidden `<Activity>` entry+ * keeps that div in the DOM (display:none, not unmounted), so more than one can be+ * present at once and a plain `querySelector` may return a backgrounded doc's.+ * Only the active doc's container is painted, so filtering by layout boxes+ * (`getClientRects`) selects it and never reads a stale scrollTop off a hidden one.+ */+export function visibleEditorScrollContainer(): HTMLDivElement | null {+ if (typeof document === 'undefined') return null;+ const containers = document.querySelectorAll<HTMLDivElement>(+ '[data-testid="editor-scroll-container"]',+ );+ for (const el of containers) {+ if (el.getClientRects().length > 0) return el;+ }+ return null;+}++/**+ * Best-effort live scrollTop read from the painted editor scroll container.*/function readActiveScrollTop(): number {try {- if (typeof document === 'undefined') return 0;- const el = document.querySelector<HTMLDivElement>('[data-testid="editor-scroll-container"]');- return el?.scrollTop ?? 0;+ return visibleEditorScrollContainer()?.scrollTop ?? 0;} catch (err) {// The fallback 0 is indistinguishable from a legitimate "scroll at top";// without this mark, a querySelector failure would silently produce a@@ -657,8 +672,11 @@ export function mountTiptapEditor(params: MountTiptapParams): TiptapCacheEntry {reuse.activeMountKey = docName;touchLru(tiptapLru, docName);// Restore scroll AFTER DOM is re-attached (scrollTop on detached nodes- // is a no-op in real browsers).- container.scrollTop = reuse.scrollTop;+ // is a no-op in real browsers). Stand down when a mode-switch landing owns+ // the scroller for this doc — this warm-mount restore fires at the same+ // moment as a landing and would otherwise overwrite it with the parked+ // position.+ if (!isScrollRestoreSuppressed(docName)) container.scrollTop = reuse.scrollTop;// Focus restore is gated on "had focus at park time". Blindly calling// .focus() on every mount hijacks focus from keyboard users// Tab-navigating through the sidebar and from deep-link cold loads@@ -977,7 +995,9 @@ export function mountCmEditor(params: MountCmParams): CmCacheEntry {reparentCmDom(reuse, container);reuse.activeMountKey = docName;touchLru(cmLru, docName);- container.scrollTop = reuse.scrollTop;+ // Stand down when a mode-switch landing owns the scroller for this doc, so+ // the warm-mount restore cannot overwrite the landing with the parked scroll.+ if (!isScrollRestoreSuppressed(docName)) container.scrollTop = reuse.scrollTop;if (reuse.hadFocus) {try {reuse.view.focus();diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.test.tsindex 0ece09a69..64f27c8b5 100644--- a/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts@@ -1,9 +1,14 @@+// @vitest-environment jsdom/*** Unit tests for the WYSIWYG lint→block mapping. `mapDiagnosticsToBlocks`* groups source-line diagnostics by the top-level mdast block they fall in,* which is what the plugin then maps onto top-level PM nodes (1:1 by the* bridge invariant — the fragment derives from parse of the same Y.Text* source the diagnostics were linted against).+ *+ * The Problems-row navigation is covered against a real mounted editor at the+ * bottom of this file, so jsdom is on for the whole file; the pure mapping+ * tests are unaffected by it.*/import {@@ -11,12 +16,15 @@ import {type LintDiagnostic,MarkdownManager,} from '@inkeep/open-knowledge-core';-import { describe, expect, test } from 'vitest';+import { Editor } from '@tiptap/core';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { LINT_NAV_EVENT, type LintNavDetail } from '@/components/ProblemsPanel';+import { blockIndexForLine, computeSourceBlockSpans } from '../block-spans.ts';import {- blockIndexForLine,- computeSourceBlockSpans,- mapDiagnosticsToBlocks,-} from './markdown-lint-decorations.ts';+ __resetScrollRestoreCoordination,+ registerLandingScrollOwner,+} from '../scroll-restore-coordination.ts';+import { MarkdownLintDecorations, mapDiagnosticsToBlocks } from './markdown-lint-decorations.ts';const md = new MarkdownManager({ extensions: coreExtensions });@@ -205,7 +213,138 @@ describe('blockIndexForLine', () => {expect(blockIndexForLine(spans, 12)).toBe(2);});+ test('line on a span boundary → that block', () => {+ expect(blockIndexForLine(spans, 3)).toBe(1);+ expect(blockIndexForLine(spans, 6)).toBe(1);+ expect(blockIndexForLine(spans, 8)).toBe(2);+ });++ test('line before the first block → the first block', () => {+ const offset = [+ { start: 3, end: 4 },+ { start: 7, end: 8 },+ ];+ expect(blockIndexForLine(offset, 1)).toBe(0);+ expect(blockIndexForLine(offset, 5)).toBe(1);+ });+test('no spans → null', () => {expect(blockIndexForLine([], 1)).toBeNull();});});++describe('Problems-row navigation — scroll suppression', () => {+ const DOC = 'lint-nav-doc';+ // 1: # Heading / 2: blank / 3: First paragraph. / 4: blank / 5: Second paragraph.+ const BODY = '# Heading\n\nFirst paragraph.\n\nSecond paragraph.\n';+ let editor: Editor | null = null;+ let host: HTMLElement | null = null;+ let scrollIntoView: ReturnType<typeof vi.fn>;+ let originalScrollIntoView: PropertyDescriptor | undefined;+ let originalFetch: typeof globalThis.fetch;++ /**+ * Mount the extension on a real editor. jsdom implements neither of the two+ * DOM surfaces this path turns on, so both are installed here: `offsetParent`+ * is the plugin's "am I the visible editor" gate, and `scrollIntoView` is the+ * observable the suppression guard controls.+ */+ function mountEditor(): Editor {+ host = document.createElement('div');+ document.body.appendChild(host);+ const mounted = new Editor({+ element: host,+ extensions: [+ ...coreExtensions,+ MarkdownLintDecorations.configure({ docName: DOC, getSource: () => BODY }),+ ],+ content: md.parse(BODY),+ });+ Object.defineProperty(mounted.view.dom, 'offsetParent', { value: host, configurable: true });+ return mounted;+ }++ function clickProblemsRow(line: number): void {+ const detail: LintNavDetail = { line, column: 1 };+ window.dispatchEvent(new CustomEvent<LintNavDetail>(LINT_NAV_EVENT, { detail }));+ }++ beforeEach(() => {+ __resetScrollRestoreCoordination();+ originalFetch = globalThis.fetch;+ globalThis.fetch = vi.fn(async () =>+ Response.json({ effective: {} }),+ ) as unknown as typeof fetch;+ scrollIntoView = vi.fn();+ originalScrollIntoView = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ 'scrollIntoView',+ );+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {+ value: scrollIntoView,+ configurable: true,+ writable: true,+ });+ editor = mountEditor();+ });++ afterEach(() => {+ editor?.destroy();+ editor = null;+ host?.remove();+ host = null;+ if (originalScrollIntoView) {+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', originalScrollIntoView);+ } else {+ Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView');+ }+ globalThis.fetch = originalFetch;+ __resetScrollRestoreCoordination();+ });++ test('scrolls the diagnostic block into view and places the caret in it', () => {+ clickProblemsRow(3); // "First paragraph." — the second top-level block++ expect(scrollIntoView).toHaveBeenCalledTimes(1);+ const { $from } = editor?.state.selection ?? {};+ expect($from?.parent.textContent).toBe('First paragraph.');+ });++ test('supersedes a position-preserving landing rather than standing down under it', () => {+ // The row the user clicked outranks the position a mode-switch toggle was+ // preserving. Standing the scroll down while still moving the caret would+ // leave them looking at a viewport that never went anywhere.+ const supersede = vi.fn();+ registerLandingScrollOwner(DOC, { yieldsToNavigation: true, supersede });++ clickProblemsRow(3);++ expect(supersede).toHaveBeenCalledTimes(1);+ expect(scrollIntoView).toHaveBeenCalledTimes(1);+ const { $from } = editor?.state.selection ?? {};+ expect($from?.parent.textContent).toBe('First paragraph.');+ });++ test('stands down whole while a landing that is itself a navigation owns the scroller', () => {+ registerLandingScrollOwner(DOC, { yieldsToNavigation: false, supersede: vi.fn() });+ const before = editor?.state.selection.$from.parent.textContent;++ clickProblemsRow(3);++ // Caret and scroll move together or not at all — a half-applied navigation+ // is the failure mode, not the fallback.+ expect(scrollIntoView).not.toHaveBeenCalled();+ expect(editor?.state.selection.$from.parent.textContent).toBe(before);+ });++ test('a landing on another document does not gate this one', () => {+ registerLandingScrollOwner('some-other-doc', {+ yieldsToNavigation: false,+ supersede: vi.fn(),+ });++ clickProblemsRow(3);++ expect(scrollIntoView).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.tsindex 8df2dff93..7a68d9f2f 100644--- a/packages/app/src/editor/extensions/markdown-lint-decorations.ts+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.ts@@ -34,7 +34,6 @@ import {type LintTextEdit,lintDocument,MarkdownManager,- stripFrontmatter,} from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';import { Extension } from '@tiptap/core';@@ -49,7 +48,9 @@ import {peekPendingSourceNavigation,} from '@/editor/source-editor-navigation';import { cn } from '@/lib/utils';+import { blockIndexForLine, comparableChildCount, computeSourceBlockSpans } from '../block-spans';import { fetchEffectiveLintConfig, subscribeToLintConfigChanged } from '../lint-config-client';+import { runScrollNavigation } from '../scroll-restore-coordination';const markdownLintDecorationKey = new PluginKey<DecorationSet>('markdownLintDecorations');@@ -62,46 +63,6 @@ const OK_LINT_BLOCK_ATOM_CLASS = 'ok-lint-block-atom';const RECOMPUTE_DEBOUNCE_MS = 400;-/** 1-based inclusive line spans of top-level body blocks, in full-source coordinates. */-export interface SourceBlockSpans {- spans: { start: number; end: number }[];- /** Lines the frontmatter region occupies at the top of the source (0 when none). */- fmLineCount: number;-}--/**- * Top-level block line spans for a full `Y.Text('source')` snapshot. The body- * region (after the FM fence) is parsed to mdast; spans are shifted back into- * full-source coordinates so lint diagnostics (which carry full-source lines —- * markdownlint skips the FM region itself) index into them directly.- */-export function computeSourceBlockSpans(source: string, md: MarkdownManager): SourceBlockSpans {- const { frontmatter, body } = stripFrontmatter(source);- const fmLineCount = frontmatter === '' ? 0 : frontmatter.split('\n').length - 1;- // The editor view, not the CommonMark one: a preserved blank line is a- // paragraph in the PM doc, and this array is index-aligned with those- // children. Losing the alignment silently disables every decoration.- const spans = md.parseToEditorMdast(body).children.map((child) => ({- start: (child.position?.start.line ?? Number.POSITIVE_INFINITY) + fmLineCount,- end: (child.position?.end.line ?? Number.NEGATIVE_INFINITY) + fmLineCount,- }));- return { spans, fmLineCount };-}--/**- * Map a 1-based full-source line to a top-level block index. Lines inside a- * block map to it; between-block lines (blank-line runs — where rules like- * MD012 report) anchor to the NEXT block; lines past the last block anchor to- * the last one. Null only when there are no blocks at all.- */-export function blockIndexForLine(spans: SourceBlockSpans['spans'], line: number): number | null {- const containing = spans.findIndex((s) => line >= s.start && line <= s.end);- if (containing >= 0) return containing;- const following = spans.findIndex((s) => s.start > line);- if (following >= 0) return following;- return spans.length > 0 ? spans.length - 1 : null;-}-/*** Group diagnostics by the index of the top-level block they fall in.* `source` is the full document text (frontmatter included); diagnostics in@@ -129,21 +90,6 @@ export function mapDiagnosticsToBlocks(return byBlock;}-/**- * Top-level child count comparable against body block spans. A doc whose last- * block isn't a paragraph renders with a trailing empty paragraph (the- * type-here affordance below a final heading/list) that has NO source- * counterpart — parse of the source never yields an empty paragraph. Without- * this allowance the span↔doc count comparison fails PERMANENTLY on- * heading-final docs, silently disabling decorations and navigation.- */-function comparableChildCount(doc: PmNode): number {- const last = doc.childCount > 0 ? doc.child(doc.childCount - 1) : null;- const trailingEmptyParagraph =- last !== null && last.type.name === 'paragraph' && last.content.size === 0;- return trailingEmptyParagraph ? doc.childCount - 1 : doc.childCount;-}-/** DOM attribute that carries a block's diagnostic lines for the hover tooltip. */const LINT_TOOLTIP_ATTR = 'data-ok-lint';/** Marks a decorated block whose diagnostics carry auto-fixable edits. */@@ -586,17 +532,24 @@ export const MarkdownLintDecorations = Extension.create<MarkdownLintDecorationsOif (i === index) blockOffset = offset;});if (blockOffset < 0) return false;- view.dispatch(- view.state.tr.setSelection(- TextSelection.near(view.state.doc.resolve(blockOffset + 1)),- ),- );- view.focus();- const blockDom = view.nodeDOM(blockOffset);- if (blockDom instanceof HTMLElement) {- blockDom.scrollIntoView({ behavior: 'smooth', block: 'start' });- }- return true;+ // Caret and viewport move together or not at all. A position-+ // preserving mode-switch landing is superseded here — the row the+ // user clicked outranks the position they were keeping — while a+ // landing that is itself an explicit navigation keeps the scroller+ // and this click stands down whole, leaving the banked source-mode+ // intent alive for the caller to replay.+ return runScrollNavigation(docName, () => {+ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.near(view.state.doc.resolve(blockOffset + 1)),+ ),+ );+ view.focus();+ const blockDom = view.nodeDOM(blockOffset);+ if (blockDom instanceof HTMLElement) {+ blockDom.scrollIntoView({ behavior: 'smooth', block: 'start' });+ }+ });}// Live Problems-row click for the OPEN doc. The cross-doc projectdiff --git a/packages/app/src/editor/extensions/shared.ts b/packages/app/src/editor/extensions/shared.tsindex f2e6334fd..c28dd4fed 100644--- a/packages/app/src/editor/extensions/shared.ts+++ b/packages/app/src/editor/extensions/shared.ts@@ -12,6 +12,7 @@ import { GfmAutolink } from '../gfm-autolink-plugin';import { uploadAndInsert } from '../image-upload/index.ts';import { InlineLinkInputRule } from '../inline-link-input-rule';import { MathInputRule } from '../math-input-rule';+import { LandingFlash } from '../plugins/landing-flash-wysiwyg';import { getComponentItems, getInlineComponentItems } from '../slash-command/component-items';import { getEmbedStarterItems } from '../slash-command/embed-starter-items';import { getSlashCommandItems } from '../slash-command/items';@@ -182,6 +183,13 @@ export const sharedExtensions = [// so it can be configured per-editor-instance with context-aware text.BridgeIdPlugin,SelectionStatePlugin,+ // LandingFlash — transient inline highlight on the range a mode-switch jump+ // lands on, the WYSIWYG counterpart of the source landing flash. Decoration-+ // only, no documentName keying, no write path. Registered on every WYSIWYG+ // editor for symmetry but dormant today: the in-scope jump lands in source and+ // the plain toggle is scroll-only, so nothing dispatches it until a "view in+ // WYSIWYG" jump exists to drive it.+ LandingFlash,// Block-chunked content-visibility:auto. Applies the// `ok-chunk-wrapper` class to every top-level direct child of the doc// via PM Decoration.node. Off-viewport blocks skip layout/paint per thediff --git a/packages/app/src/editor/landing-controller.test.ts b/packages/app/src/editor/landing-controller.test.tsnew file mode 100644index 000000000..7fba7d31c--- /dev/null+++ b/packages/app/src/editor/landing-controller.test.ts@@ -0,0 +1,569 @@+// @vitest-environment jsdom+/**+ * Coverage for the landing controller: the centered-scroll math and the settle+ * contract (immediate dispatch, event-driven re-dispatch on drift, user-scroll+ * cancel, mode-flip cancel with queue discard, the bounded abandon, and the+ * precedence between a landing and an explicit navigation arriving mid-settle).+ * The controller drives real DOM (scroll writes, event listeners, ResizeObserver)+ * so this file opts into jsdom via the docblock above; it is not a React mount+ * test, so it stays `.test.ts`.+ *+ * Real geometry (`getBoundingClientRect`, layout, `content-visibility`) does not+ * exist in jsdom, so `clientHeight`/`scrollHeight`/`scrollTop` are defined on the+ * container as plain properties and the target geometry is injected through+ * `measureTarget` — the same seam production callers use. `requestAnimationFrame`+ * is stubbed to a no-op so the settle is driven deterministically by the injected+ * signals and the fake timers, never by a real frame callback.+ */++import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { getCollector } from '../lib/perf/collector';+import {+ centeredScrollTop,+ type LandingCancelReason,+ type LandingHandle,+ type LandingOutcome,+ type LandingPlacement,+ type StartLandingParams,+ startLanding,+ type TargetMetrics,+} from './landing-controller';+import {+ __resetScrollRestoreCoordination,+ getDocScrollState,+ isScrollRestoreSuppressed,+ runScrollNavigation,+} from './scroll-restore-coordination';++const TOOLBAR = 56;+const VIEWPORT = 800;++function buildScroller(scrollHeight = 6000): { container: HTMLElement; content: HTMLElement } {+ const container = document.createElement('div');+ const content = document.createElement('div');+ container.appendChild(content);+ Object.defineProperty(container, 'clientHeight', { value: VIEWPORT, configurable: true });+ Object.defineProperty(container, 'scrollHeight', { value: scrollHeight, configurable: true });+ Object.defineProperty(container, 'scrollTop', { value: 0, writable: true, configurable: true });+ container.style.overflowAnchor = 'auto';+ document.body.appendChild(container);+ return { container, content };+}++// jsdom's CSS engine may not persist `overflow-anchor`; only assert its value+// where the environment actually round-trips the property.+const OVERFLOW_ANCHOR_SUPPORTED = (() => {+ const probe = document.createElement('div');+ probe.style.overflowAnchor = 'none';+ return probe.style.overflowAnchor === 'none';+})();++type StartOverrides = Partial<StartLandingParams> &+ Pick<StartLandingParams, 'container' | 'measureTarget'>;++function startLandingWith(overrides: StartOverrides): LandingHandle {+ const placement: LandingPlacement = overrides.placement ?? 'center';+ const params: StartLandingParams = {+ docName: 'doc',+ grade: 'exact',+ placement,+ intent: 'toggle',+ landedMode: 'source',+ toolbarOffset: TOOLBAR,+ ...overrides,+ };+ return startLanding(params);+}++function markNamed(name: string): { properties?: Record<string, unknown> } | undefined {+ return getCollector()+ ?.marks.toArray()+ .find((m) => m.name === name);+}++beforeEach(() => {+ vi.useFakeTimers();+ // The frame callback is an accelerator, not a terminal signal; removing it+ // makes the settle deterministic under fake timers + injected events.+ vi.stubGlobal('requestAnimationFrame', () => 0);+ vi.stubGlobal('cancelAnimationFrame', () => {});+ getCollector()?.reset();+ __resetScrollRestoreCoordination();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ document.body.replaceChildren();+});++describe('centeredScrollTop', () => {+ test('lands the target center at the center of the region below the toolbar', () => {+ const m: TargetMetrics = { top: 1000, height: 100 };+ const scrollTop = centeredScrollTop(m, VIEWPORT, TOOLBAR);+ expect(scrollTop).toBe(622); // 1000 + 50 - (56 + 800) / 2++ const targetCenterOnScreen = m.top + m.height / 2 - scrollTop;+ expect(targetCenterOnScreen).toBe((TOOLBAR + VIEWPORT) / 2); // 428, center of [56, 800]+ });++ test('the toolbar offset biases the landing down by half the toolbar height', () => {+ const m: TargetMetrics = { top: 1000, height: 100 };+ expect(centeredScrollTop(m, VIEWPORT, TOOLBAR)).toBe(+ centeredScrollTop(m, VIEWPORT, 0) - TOOLBAR / 2,+ );+ });+});++describe('startLanding — dispatch and settle', () => {+ test('dispatches the centered target immediately, then lands and releases its holds', () => {+ const { container } = buildScroller();+ const outcomes: LandingOutcome[] = [];+ startLandingWith({+ container,+ measureTarget: () => ({ top: 2000, height: 60 }),+ onOutcome: (o) => outcomes.push(o),+ });++ const expected = centeredScrollTop({ top: 2000, height: 60 }, VIEWPORT, TOOLBAR);+ expect(container.scrollTop).toBe(expected); // synchronous dispatch+ expect(isScrollRestoreSuppressed('doc')).toBe(true); // held for the window+ if (OVERFLOW_ANCHOR_SUPPORTED) expect(container.style.overflowAnchor).toBe('none');++ vi.advanceTimersByTime(150); // trailing quiet elapses → land++ expect(outcomes).toEqual([{ status: 'landed', delta: 0 }]);+ const landMark = markNamed('ok/landing/land');+ expect(landMark?.properties?.grade).toBe('exact');+ expect(landMark?.properties?.delta).toBe(0);+ expect(isScrollRestoreSuppressed('doc')).toBe(false); // released on land+ if (OVERFLOW_ANCHOR_SUPPORTED) expect(container.style.overflowAnchor).toBe('auto');+ });++ test('persists the landing so a later scroll restore reproduces it', () => {+ const { container } = buildScroller();+ expect(getDocScrollState('doc')).toBeUndefined(); // nothing persisted yet+ startLandingWith({+ container,+ measureTarget: () => ({ top: 2000, height: 60 }),+ landedMode: 'wysiwyg',+ });+ const expected = centeredScrollTop({ top: 2000, height: 60 }, VIEWPORT, TOOLBAR);+ vi.advanceTimersByTime(150); // land++ // The landing is persisted body-relative; with no above-body anchor in this+ // container the stored offset is the raw target, so a later restore lands+ // back on it instead of the pre-landing position. The landed mode is stamped+ // so a later re-activation in the other mode floors instead of driving it.+ expect(getDocScrollState('doc')?.offset).toBe(expected);+ expect(getDocScrollState('doc')?.mode).toBe('wysiwyg');+ });++ test('holds the queued target while the editor is still mounting, then lands it', () => {+ const { container } = buildScroller();+ let metrics: TargetMetrics | null = null; // not yet measurable+ startLandingWith({ container, measureTarget: () => metrics });++ expect(container.scrollTop).toBe(0); // nothing to dispatch yet+ expect(isScrollRestoreSuppressed('doc')).toBe(true); // window open, target retained++ metrics = { top: 3000, height: 50 }; // editor laid out+ container.dispatchEvent(new Event('contentvisibilityautostatechange'));++ expect(container.scrollTop).toBe(centeredScrollTop(metrics, VIEWPORT, TOOLBAR));+ });++ test('re-dispatches when the target drifts beyond the threshold', () => {+ const { container } = buildScroller();+ let top = 1000;+ startLandingWith({ container, measureTarget: () => ({ top, height: 40 }), grade: 'ordinal' });++ const first = centeredScrollTop({ top: 1000, height: 40 }, VIEWPORT, TOOLBAR);+ expect(container.scrollTop).toBe(first);++ top = 500; // blocks above materialize; the target moves up+ container.dispatchEvent(new Event('contentvisibilityautostatechange'));++ const second = centeredScrollTop({ top: 500, height: 40 }, VIEWPORT, TOOLBAR);+ expect(second).not.toBe(first); // the target genuinely moved+ expect(container.scrollTop).toBe(second); // and the view followed it+ });++ test('re-dispatches on a content-column resize', () => {+ let fire: (() => void) | undefined;+ class FakeResizeObserver {+ constructor(cb: () => void) {+ fire = cb;+ }+ observe(): void {}+ disconnect(): void {}+ }+ vi.stubGlobal('ResizeObserver', FakeResizeObserver);++ const { container, content } = buildScroller();+ let top = 1000;+ const handle = startLandingWith({+ container,+ contentColumn: content,+ measureTarget: () => ({ top, height: 40 }),+ });+ const first = container.scrollTop;++ top = 1400;+ fire?.(); // the content column grew++ const second = centeredScrollTop({ top: 1400, height: 40 }, VIEWPORT, TOOLBAR);+ expect(second).not.toBe(first);+ expect(container.scrollTop).toBe(second);+ handle.cancel('mode-flip');+ });++ test("'top' placement pins the block top just below the toolbar", () => {+ const { container } = buildScroller();+ startLandingWith({+ container,+ measureTarget: () => ({ top: 1000, height: 40 }),+ placement: 'top',+ });+ expect(container.scrollTop).toBe(1000 - TOOLBAR);+ });++ test('emits a mode-switch transition mark when a transition is provided', () => {+ const { container } = buildScroller();+ startLandingWith({+ container,+ measureTarget: () => ({ top: 1000, height: 40 }),+ placement: 'top',+ transition: { from: 'wysiwyg', to: 'source' },+ });+ const transitionMark = markNamed('ok/mode-switch/transition');+ expect(transitionMark?.properties?.from).toBe('wysiwyg');+ expect(transitionMark?.properties?.to).toBe('source');+ });+});++describe('startLanding — cancel and abandon', () => {+ test('cancels on the user wheel and does not re-dispatch afterward', () => {+ const { container } = buildScroller();+ let top = 1000;+ const outcomes: LandingOutcome[] = [];+ const discard = vi.fn();+ startLandingWith({+ container,+ measureTarget: () => ({ top, height: 40 }),+ onOutcome: (o) => outcomes.push(o),+ onDiscardQueuedTarget: discard,+ });+ const afterDispatch = container.scrollTop;++ container.dispatchEvent(new Event('wheel'));++ expect(outcomes).toEqual([{ status: 'cancelled', reason: 'user-scroll' }]);+ expect(isScrollRestoreSuppressed('doc')).toBe(false); // released+ expect(discard).not.toHaveBeenCalled(); // user-scroll keeps the queue (already consumed)++ // A late layout signal must not drag the view back onto the target.+ top = 200;+ container.dispatchEvent(new Event('contentvisibilityautostatechange'));+ expect(container.scrollTop).toBe(afterDispatch);+ });++ test('cancels on a touch gesture', () => {+ const { container } = buildScroller();+ const outcomes: LandingOutcome[] = [];+ startLandingWith({+ container,+ measureTarget: () => ({ top: 1000, height: 40 }),+ onOutcome: (o) => outcomes.push(o),+ });+ container.dispatchEvent(new Event('touchstart'));+ expect(outcomes).toEqual([{ status: 'cancelled', reason: 'user-scroll' }]);+ });++ test('cancels on a mode flip and discards the queued target', () => {+ const { container } = buildScroller();+ const outcomes: LandingOutcome[] = [];+ const discard = vi.fn();+ const handle = startLandingWith({+ container,+ measureTarget: () => ({ top: 1000, height: 40 }),+ onOutcome: (o) => outcomes.push(o),+ onDiscardQueuedTarget: discard,+ });++ const reason: LandingCancelReason = 'mode-flip';+ handle.cancel(reason);++ expect(outcomes).toEqual([{ status: 'cancelled', reason: 'mode-flip' }]);+ expect(discard).toHaveBeenCalledTimes(1);+ expect(isScrollRestoreSuppressed('doc')).toBe(false);+ });++ test('abandons after the window when the target never settles, marking target and delta', () => {+ const { container } = buildScroller();+ let top = 1000;+ const outcomes: LandingOutcome[] = [];+ startLandingWith({+ container,+ measureTarget: () => ({ top, height: 40 }),+ onOutcome: (o) => outcomes.push(o),+ });++ // Perpetual layout churn: every 100ms the target oscillates between two+ // in-range positions and a signal fires, so each step drifts past the+ // threshold, the settle countdown is always reset, and it never elapses+ // before the 2s cap. Oscillating (not growing) keeps both targets off the+ // clamp ceiling, where a pinned target would stop drifting and settle.+ for (let elapsed = 0; elapsed < 2000; elapsed += 100) {+ top = top === 1000 ? 2500 : 1000;+ container.dispatchEvent(new Event('contentvisibilityautostatechange'));+ vi.advanceTimersByTime(100);+ }++ expect(outcomes.some((o) => o.status === 'abandoned')).toBe(true);+ expect(outcomes.some((o) => o.status === 'landed')).toBe(false);+ const abandonMark = markNamed('ok/landing/abandoned');+ expect(typeof abandonMark?.properties?.target).toBe('number');+ expect(typeof abandonMark?.properties?.delta).toBe('number');+ expect(isScrollRestoreSuppressed('doc')).toBe(false); // released on abandon+ });++ test('terminates exactly once — a cancel after landing is a no-op', () => {+ const { container } = buildScroller();+ const outcomes: LandingOutcome[] = [];+ const handle = startLandingWith({+ container,+ measureTarget: () => ({ top: 1000, height: 40 }),+ onOutcome: (o) => outcomes.push(o),+ });+ vi.advanceTimersByTime(150); // land+ handle.cancel('mode-flip'); // must not add a second outcome or re-discard++ expect(outcomes).toEqual([{ status: 'landed', delta: 0 }]);+ });++ test('abandons (not lands) when the target is never measurable', () => {+ const { container } = buildScroller();+ const outcomes: LandingOutcome[] = [];+ startLandingWith({+ container,+ measureTarget: () => null, // editor never lays out+ onOutcome: (o) => outcomes.push(o),+ });+ expect(container.scrollTop).toBe(0);+ vi.advanceTimersByTime(2000);+ expect(outcomes).toEqual([{ status: 'abandoned', delta: 0 }]);+ });+});++/**+ * An explicit navigation — a Problems-panel or outline row, a find/replace+ * match, a deep link — landing inside an open settle window. The scroll below+ * stands in for whichever applier ran it; what is under test is who owns the+ * scroller afterward.+ */+describe('startLanding — explicit navigation pre-emption', () => {+ const NAV_SCROLL_TOP = 1189;++ test('supersedes a toggle landing, and the navigation keeps the scroller', () => {+ const { container } = buildScroller();+ const outcomes: LandingOutcome[] = [];+ const discard = vi.fn();+ let top = 2000;+ startLandingWith({+ container,+ measureTarget: () => ({ top, height: 60 }),+ placement: 'top',+ intent: 'toggle',+ onOutcome: (o) => outcomes.push(o),+ onDiscardQueuedTarget: discard,+ });+ expect(container.scrollTop).toBe(2000 - TOOLBAR);++ const ran = runScrollNavigation('doc', () => {+ container.scrollTop = NAV_SCROLL_TOP;+ });++ expect(ran).toBe(true);+ expect(container.scrollTop).toBe(NAV_SCROLL_TOP);+ expect(outcomes).toEqual([{ status: 'cancelled', reason: 'superseded' }]);+ expect(isScrollRestoreSuppressed('doc')).toBe(false); // released before the scroll+ // The queued intent was already consumed to start this landing, so there is+ // nothing stale left to replay — same as a user-scroll cancel.+ expect(discard).not.toHaveBeenCalled();++ // The settle loop is closed: neither a late layout signal nor the elapsed+ // quiet window may pull the view back onto the landing's target.+ top = 400;+ container.dispatchEvent(new Event('contentvisibilityautostatechange'));+ vi.advanceTimersByTime(2000);+ expect(container.scrollTop).toBe(NAV_SCROLL_TOP);+ expect(outcomes).toHaveLength(1);+ });++ test('does not persist the position it would have erased', () => {+ const { container } = buildScroller();+ startLandingWith({+ container,+ measureTarget: () => ({ top: 2000, height: 60 }),+ placement: 'top',+ intent: 'toggle',+ });++ runScrollNavigation('doc', () => {+ container.scrollTop = NAV_SCROLL_TOP;+ });+ vi.advanceTimersByTime(2000);++ // Landing on a superseded target would write it into the doc scroll state+ // and reproduce the erasure on every later restore. A superseded landing+ // never lands, so it records nothing; the navigation's own position is+ // captured by the container's scroll listener instead.+ expect(getDocScrollState('doc')).toBeUndefined();+ });++ test('a jump landing keeps the scroller and the navigation stands down', () => {+ const { container } = buildScroller();+ const outcomes: LandingOutcome[] = [];+ const scroll = vi.fn();+ startLandingWith({+ container,+ measureTarget: () => ({ top: 2000, height: 60 }),+ placement: 'center',+ intent: 'jump',+ onOutcome: (o) => outcomes.push(o),+ });+ const landingTarget = container.scrollTop;++ const ran = runScrollNavigation('doc', scroll);++ // A jump has already placed the caret, so pre-empting it would split caret+ // from viewport — the failure this contract exists to prevent.+ expect(ran).toBe(false);+ expect(scroll).not.toHaveBeenCalled();+ expect(container.scrollTop).toBe(landingTarget);+ expect(outcomes).toEqual([]); // still open++ vi.advanceTimersByTime(150);+ expect(outcomes).toEqual([{ status: 'landed', delta: 0 }]);+ });++ test('a navigation on another document leaves the landing alone', () => {+ const { container } = buildScroller();+ const outcomes: LandingOutcome[] = [];+ startLandingWith({+ container,+ measureTarget: () => ({ top: 2000, height: 60 }),+ placement: 'top',+ intent: 'toggle',+ onOutcome: (o) => outcomes.push(o),+ });++ expect(runScrollNavigation('some-other-doc', () => {})).toBe(true);++ expect(outcomes).toEqual([]);+ vi.advanceTimersByTime(150);+ expect(outcomes).toEqual([{ status: 'landed', delta: 0 }]);+ });++ test('a landing that already terminated no longer holds the scroller', () => {+ const { container } = buildScroller();+ startLandingWith({+ container,+ measureTarget: () => ({ top: 2000, height: 60 }),+ placement: 'center',+ intent: 'jump',+ });+ vi.advanceTimersByTime(150); // land++ const scroll = vi.fn();+ expect(runScrollNavigation('doc', scroll)).toBe(true);+ expect(scroll).toHaveBeenCalledTimes(1);+ });+});++/**+ * `measureTarget` is injected, and the production measurers read a live editor+ * view — which can be torn down mid-settle, and then throws rather than+ * answering. Neither hold the controller takes decays on its own: a stranded+ * suppression disables scroll restore for the document for the rest of the+ * session, and a stranded `jump` owner (which does not yield) makes every later+ * outline click, Problems row, find match and deep link for it silently no-op.+ * So every exit — including the throwing ones, and including a start that never+ * returns a handle to cancel — has to release both. A `jump` landing is used+ * throughout: it is the shape whose leak `runScrollNavigation` can observe.+ */+describe('startLanding — a throwing measurer releases every hold', () => {+ const BOOM = 'view destroyed mid-settle';++ /** Both holds are gone and an explicit navigation can take the scroller. */+ function expectHoldsReleased(): void {+ expect(isScrollRestoreSuppressed('doc')).toBe(false);+ const scroll = vi.fn();+ expect(runScrollNavigation('doc', scroll)).toBe(true);+ expect(scroll).toHaveBeenCalledTimes(1);+ }++ test('when the first dispatch throws, before any handle is returned', () => {+ const { container } = buildScroller();++ expect(() =>+ startLandingWith({+ container,+ measureTarget: () => {+ throw new Error(BOOM);+ },+ placement: 'center',+ intent: 'jump',+ }),+ ).toThrow(BOOM);++ expectHoldsReleased();+ });++ test('when the measurer starts throwing before the settle lands', () => {+ const { container } = buildScroller();+ const outcomes: LandingOutcome[] = [];+ let throwing = false;+ startLandingWith({+ container,+ measureTarget: (): TargetMetrics | null => {+ if (throwing) throw new Error(BOOM);+ return { top: 2000, height: 60 };+ },+ placement: 'center',+ intent: 'jump',+ onOutcome: (o) => outcomes.push(o),+ });++ throwing = true; // the view goes away while the quiet window is running+ expect(() => vi.advanceTimersByTime(150)).toThrow(BOOM);++ expectHoldsReleased();+ expect(outcomes).toEqual([]); // a throw is not reported as a landing+ });++ test('when the measurer throws at the abandon deadline', () => {+ const { container } = buildScroller();+ const outcomes: LandingOutcome[] = [];+ let throwing = false;+ startLandingWith({+ container,+ // Never measurable, so nothing arms the quiet timer and the abandon+ // deadline is the terminal path this lands on.+ measureTarget: (): TargetMetrics | null => {+ if (throwing) throw new Error(BOOM);+ return null;+ },+ placement: 'center',+ intent: 'jump',+ onOutcome: (o) => outcomes.push(o),+ });++ throwing = true;+ expect(() => vi.advanceTimersByTime(2000)).toThrow(BOOM);++ expectHoldsReleased();+ expect(outcomes).toEqual([]);+ });+});diff --git a/packages/app/src/editor/landing-controller.ts b/packages/app/src/editor/landing-controller.tsnew file mode 100644index 000000000..055b2ba0d--- /dev/null+++ b/packages/app/src/editor/landing-controller.ts@@ -0,0 +1,345 @@+/**+ * The landing controller: the single scroll writer during a mode-switch landing.+ *+ * A landing dispatched into a freshly-flipped editor cannot land in one write.+ * The incoming editor's content has no layout at dispatch time (the outgoing+ * mode was `content-visibility: hidden` and out of flow), so a scrollTop written+ * before layout runs clamps against a stale `scrollHeight`; and as virtualized+ * blocks above the target materialize, the target's real position keeps moving.+ * This controller owns the settle contract that resolves that: dispatch+ * immediately, verify on layout signals, re-dispatch on drift, and terminate in+ * exactly one of four ways — land, cancel on the user's own scroll intent,+ * cancel because an explicit navigation superseded it, or abandon after a+ * bounded window with a diagnostic mark.+ *+ * It is the single writer for its window: it holds the scroll-restore+ * suppression handle (so `ScrollPreservingContainer` and the other gated writers+ * stand down) and turns off the browser's own scroll anchoring, releasing both+ * on every terminal path. Being the single writer is a claim it has to be able+ * to LOSE, though — a user who clicks a Problems row mid-settle is not drift —+ * so it also registers as the document's landing scroll owner, and a+ * position-preserving toggle is superseded there by any explicit navigation.+ * Geometry is injected via `measureTarget`, so the controller is+ * representation-agnostic — a WYSIWYG caller measures with `coordsAtPos`, a+ * source caller through CodeMirror, and this file never touches either editor's+ * internals.+ */++import { mark } from '@/lib/perf';+import type { ResolveConfidence } from './mode-switch-position-resolver';+import {+ acquireScrollRestoreSuppression,+ registerLandingScrollOwner,+ writeLandingResult,+} from './scroll-restore-coordination';+import type { EditorModeValue } from './use-editor-mode';++/**+ * Content-space geometry of the landing target: the distance of its top from the+ * top of the scroll content, and its rendered height. Both are re-read on every+ * verification pass so a landing re-centers as blocks above it materialize.+ */+export interface TargetMetrics {+ top: number;+ height: number;+}++/**+ * Where the target sits in the readable area. `center` puts its geometric center+ * at the center of the region below the toolbar (an explicit jump); `top` pins+ * its top just below the toolbar (a plain toggle preserving the topmost block).+ */+export type LandingPlacement = 'center' | 'top';++/**+ * What the landing is FOR, which decides whether it can be pre-empted. A+ * `toggle` preserves the position the user already had, so any explicit+ * navigation outranks it; a `jump` is itself an explicit navigation and holds+ * the scroller until it terminates on its own.+ */+type LandingIntent = 'toggle' | 'jump';++/**+ * Why an in-flight landing stopped short of settling. Every reason has a+ * producer: the controller raises `user-scroll` itself, the callers' effect+ * cleanup raises `mode-flip` — which is also how a document navigation arrives,+ * since the same effect is keyed on the document — and an explicit navigation+ * taking the scroller through `runScrollNavigation` raises `superseded`.+ */+export type LandingCancelReason = 'user-scroll' | 'mode-flip' | 'superseded';++/** How a landing terminated — every landing produces exactly one of these. */+export type LandingOutcome =+ | { status: 'landed'; delta: number }+ | { status: 'cancelled'; reason: LandingCancelReason }+ | { status: 'abandoned'; delta: number };++export interface StartLandingParams {+ docName: string;+ /** The shared per-document scroller (the one true scrollport in both modes). */+ container: HTMLElement;+ /**+ * The element whose resize signals a content-layout shift. The scroller itself+ * is sized by its parent and does not resize when `scrollHeight` grows inside+ * it, so the observer must watch the growing content column, not the scroller.+ * Defaults to the scroller's first element child.+ */+ contentColumn?: HTMLElement | null;+ /**+ * Current content-space geometry of the target, or null while the incoming+ * editor is still mounting and the target is not yet measurable.+ */+ measureTarget: () => TargetMetrics | null;+ placement: LandingPlacement;+ /**+ * Stated by every caller rather than derived from `placement`: placement is+ * geometry, and a precedence rule keyed on geometry breaks silently the first+ * time a jump wants a top-aligned landing.+ */+ intent: LandingIntent;+ grade: ResolveConfidence;+ /** The mode this landing lands in — stamped on the persisted result so a+ * later re-activation in a different mode floors instead of driving it. */+ landedMode: EditorModeValue;+ /** When the landing accompanies a mode flip, emits the transition mark. */+ transition?: { from: EditorModeValue; to: EditorModeValue };+ /** Height of the fixed toolbar overlay occluding the top of the scroller. */+ toolbarOffset?: number;+ /** Re-dispatch when the current scroll drifts beyond this from the target. */+ driftThresholdPx?: number;+ /** Settle once no further correction happens for this long (trailing edge). */+ quietMs?: number;+ /** Give up this long after dispatch if the target never settles. */+ abandonAfterMs?: number;+ onOutcome?: (outcome: LandingOutcome) => void;+ /**+ * Discard the durable pending-navigation entry when the landing is cancelled+ * by the caller's effect cleanup (`mode-flip` — a mode flip or a document+ * navigation), so a stale target cannot replay on a later entry. Not invoked+ * on a user-scroll or superseded cancel: the queued intent was already+ * consumed to start this landing, and the user simply took over.+ */+ onDiscardQueuedTarget?: () => void;+}++export interface LandingHandle {+ cancel(reason: LandingCancelReason): void;+}++// Mirrors SourceEditor's TOOLBAR_OVERLAP_PX; real callers pass that constant, so+// this default only covers a caller that omits it. Numeric tuning knobs below+// are intentionally overridable and read out through the ok/landing/* marks.+const DEFAULT_TOOLBAR_OFFSET_PX = 56;+const DEFAULT_DRIFT_THRESHOLD_PX = 2;+const DEFAULT_SETTLE_QUIET_MS = 150;+const DEFAULT_ABANDON_MS = 2000;++/**+ * Scroll offset that centers `metrics` in the readable region below the toolbar.+ * The readable region spans `[toolbarOffset, viewportHeight]`, so its center is+ * `(toolbarOffset + viewportHeight) / 2`; placing the target's center there gives+ * this offset. The half-toolbar bias is the definition of centered here, not a+ * tolerance — a landing is centered when it lands exactly on this value.+ */+export function centeredScrollTop(+ metrics: TargetMetrics,+ viewportHeight: number,+ toolbarOffset: number,+): number {+ return metrics.top + metrics.height / 2 - (toolbarOffset + viewportHeight) / 2;+}++function clampScroll(value: number, container: HTMLElement): number {+ const max = Math.max(0, container.scrollHeight - container.clientHeight);+ return Math.max(0, Math.min(value, max));+}++export function startLanding(params: StartLandingParams): LandingHandle {+ const {+ docName,+ container,+ measureTarget,+ placement,+ intent,+ grade,+ landedMode,+ transition,+ onOutcome,+ onDiscardQueuedTarget,+ toolbarOffset = DEFAULT_TOOLBAR_OFFSET_PX,+ driftThresholdPx = DEFAULT_DRIFT_THRESHOLD_PX,+ quietMs = DEFAULT_SETTLE_QUIET_MS,+ abandonAfterMs = DEFAULT_ABANDON_MS,+ } = params;+ const contentColumn = params.contentColumn ?? container.firstElementChild;++ const suppression = acquireScrollRestoreSuppression(docName);+ const scrollOwner = registerLandingScrollOwner(docName, {+ yieldsToNavigation: intent === 'toggle',+ supersede: () => cancel('superseded'),+ });+ // Scroll anchoring would re-adjust scrollTop as blocks above the target grow,+ // fighting the settle write for write; hold it off for the whole window.+ const priorOverflowAnchor = container.style.overflowAnchor;+ container.style.overflowAnchor = 'none';++ if (transition) {+ mark('ok/mode-switch/transition', { from: transition.from, to: transition.to, grade });+ }++ let closed = false;+ let lastTarget: number | null = null;+ let quietTimer: ReturnType<typeof setTimeout> | undefined;+ let abandonTimer: ReturnType<typeof setTimeout> | undefined;+ let raf = 0;+ let resizeObserver: ResizeObserver | undefined;++ const currentTarget = (): number | null => {+ const m = measureTarget();+ if (m === null) return null;+ const raw =+ placement === 'center'+ ? centeredScrollTop(m, container.clientHeight, toolbarOffset)+ : m.top - toolbarOffset;+ return clampScroll(raw, container);+ };++ // Apply the target when it is measurable and has drifted past the threshold.+ // Reports whether a target was measurable at all, and whether it moved.+ const dispatch = (): { measurable: boolean; moved: boolean } => {+ const target = currentTarget();+ if (target === null) return { measurable: false, moved: false };+ lastTarget = target;+ const moved = Math.abs(container.scrollTop - target) > driftThresholdPx;+ if (moved) container.scrollTop = target;+ return { measurable: true, moved };+ };++ const finalDelta = (): number =>+ container.scrollTop - (currentTarget() ?? lastTarget ?? container.scrollTop);++ const teardown = (): void => {+ if (quietTimer) clearTimeout(quietTimer);+ if (abandonTimer) clearTimeout(abandonTimer);+ if (raf) cancelAnimationFrame(raf);+ resizeObserver?.disconnect();+ container.removeEventListener('wheel', onUserInterrupt);+ container.removeEventListener('touchstart', onUserInterrupt);+ container.removeEventListener('contentvisibilityautostatechange', onSignal, true);+ container.style.overflowAnchor = priorOverflowAnchor;+ suppression.release();+ // Released before the superseding navigation's scroll runs, so it writes+ // into a scroller this landing has fully let go of.+ scrollOwner.release();+ };++ // Both terminal paths below measure before they release, and `measureTarget` is+ // injected: a throw out of it (a view destroyed mid-settle) would otherwise+ // strand the suppression handle, the owner registration and the saved+ // `overflowAnchor` for the rest of the session, since nothing else releases+ // them and neither map decays. The `finally` makes the release unconditional+ // while keeping the happy-path order (release, then report); the throw+ // propagates from there, so the failure stays visible rather than swallowed.+ const land = (): void => {+ if (closed) return;+ closed = true;+ let delta: number;+ try {+ dispatch(); // final snap to the settled geometry before recording the result+ delta = finalDelta();+ // Persist so the container's remount-survival restore reproduces the landing+ // rather than the pre-landing position.+ if (lastTarget !== null) {+ writeLandingResult({+ docName,+ container,+ targetScrollTop: container.scrollTop,+ mode: landedMode,+ });+ }+ } finally {+ teardown();+ }+ mark('ok/landing/land', { grade, delta });+ onOutcome?.({ status: 'landed', delta });+ };++ const abandon = (): void => {+ if (closed) return;+ closed = true;+ const target = lastTarget ?? container.scrollTop;+ let delta: number;+ try {+ delta = finalDelta();+ } finally {+ teardown();+ }+ mark('ok/landing/abandoned', { grade, target, delta });+ onOutcome?.({ status: 'abandoned', delta });+ };++ const cancel = (reason: LandingCancelReason): void => {+ if (closed) return;+ closed = true;+ teardown();+ if (reason === 'mode-flip') onDiscardQueuedTarget?.();+ onOutcome?.({ status: 'cancelled', reason });+ };++ const armQuiet = (): void => {+ if (quietTimer) clearTimeout(quietTimer);+ quietTimer = setTimeout(land, quietMs);+ };++ function onUserInterrupt(): void {+ cancel('user-scroll');+ }++ function onSignal(): void {+ if (closed) return;+ const { measurable, moved } = dispatch();+ if (!measurable) return;+ // Restart the settle countdown only when we actually corrected: a signal that+ // finds us already in place lets the countdown run down to a land, while a+ // correction means layout is still moving and we wait for it to quiesce.+ if (moved || quietTimer === undefined) armQuiet();+ }++ // The holds are already acquired, and a throw before the handle is returned+ // leaves no one able to cancel — so the start is transactional: undo the+ // acquisition, then rethrow. The first `dispatch()` is the exposure (it is the+ // first call into the injected measurer), but the whole setup is covered so a+ // half-armed landing cannot keep them either.+ try {+ // Stage 1 — immediate synchronous dispatch. Even when the target is not yet+ // measurable, verification stays armed and the retained target survives until+ // a layout signal makes it measurable or the abandon window closes.+ if (dispatch().measurable) armQuiet();++ // Verification is event-driven. The content-visibility state change fires as+ // blocks engage/disengage on the target path, but never for JSX-component or+ // code-block targets (they opt out of content-visibility), so it is an+ // accelerator, not the gate; the content-column ResizeObserver and the trailing+ // quiet timer are the always-available terminal signals. Capture phase catches+ // the event on any descendant block.+ container.addEventListener('contentvisibilityautostatechange', onSignal, true);+ container.addEventListener('wheel', onUserInterrupt, { passive: true });+ container.addEventListener('touchstart', onUserInterrupt, { passive: true });+ if (typeof ResizeObserver !== 'undefined' && contentColumn) {+ resizeObserver = new ResizeObserver(onSignal);+ resizeObserver.observe(contentColumn);+ }+ // One post-first-frame retry covers a target that becomes measurable only after+ // the first layout yet fires no resize or content-visibility event (a small,+ // already-laid-out doc landing on a content-visibility-exempt block).+ raf = requestAnimationFrame(onSignal);++ abandonTimer = setTimeout(abandon, abandonAfterMs);+ } catch (err) {+ closed = true; // a listener that did get registered must not re-enter+ teardown();+ throw err;+ }++ return { cancel };+}diff --git a/packages/app/src/editor/mode-switch-landing.test.ts b/packages/app/src/editor/mode-switch-landing.test.tsnew file mode 100644index 000000000..287b615f6--- /dev/null+++ b/packages/app/src/editor/mode-switch-landing.test.ts@@ -0,0 +1,918 @@+// @vitest-environment jsdom+import { EditorState as CmEditorState, type TransactionSpec } from '@codemirror/state';+import type { EditorView as CodeMirrorView, DecorationSet } from '@codemirror/view';+import { MarkdownManager, sharedExtensions, stripFrontmatter } from '@inkeep/open-knowledge-core';+import { type Editor, getSchema } from '@tiptap/core';+import type { Node as PmNode } from '@tiptap/pm/model';+import { EditorState as PmEditorState } from '@tiptap/pm/state';+import type { EditorView as ProseMirrorView } from '@tiptap/pm/view';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import * as Y from 'yjs';+import { getCollector } from '../lib/perf/collector.ts';+import { registerEditor, unregisterEditor } from './active-editor.ts';+import { registerSourceView, unregisterSourceView } from './active-source-view.ts';+import {+ buildSourceLandingNav,+ buildWysiwygLandingNav,+ captureModeSwitchAnchor,+ requestViewInSource,+ resolveSourceLandingTarget,+ resolveWysiwygLandingTarget,+ sourceTargetMetrics,+ startSourceLanding,+ startWysiwygLanding,+ wysiwygTargetMetrics,+} from './mode-switch-landing.ts';+import { type BlockAnchor, createApproxResolver } from './mode-switch-position-resolver.ts';+import { blockRangeToPositions } from './plugins/agent-insert-flash.ts';+import { FLASH_DURATION_MS } from './plugins/flash-shared.ts';+import { landingFlashField } from './plugins/landing-flash-source.ts';+import { createLandingFlashPlugin, landingFlashKey } from './plugins/landing-flash-wysiwyg.ts';+import { __resetScrollRestoreCoordination } from './scroll-restore-coordination.ts';+import {+ clearPendingSourceNavigationsForTest,+ clearPendingWysiwygNavigationsForTest,+ peekPendingSourceNavigation,+ peekPendingWysiwygNavigation,+ rememberPendingSourceNavigation,+ resolveNavigationPin,+ type SelectionOffsetNavigation,+} from './source-editor-navigation.ts';+import { VIEW_IN_SOURCE_EVENT, type ViewInSourceDetail } from './view-in-source-event.ts';++const md = new MarkdownManager({ extensions: sharedExtensions });+const schema = getSchema(sharedExtensions);+const resolver = createApproxResolver(md);++function present<T>(value: T | null | undefined): T {+ if (value == null) throw new Error('expected a value, got null/undefined');+ return value;+}++/** A shared document snapshot: a PM doc from the body and a Y.Text holding the full source. */+function setup(markdown: string): { doc: PmNode; ydoc: Y.Doc; ytext: Y.Text; source: string } {+ const { body } = stripFrontmatter(markdown);+ const doc = schema.nodeFromJSON(md.parse(body));+ const ydoc = new Y.Doc();+ const ytext = ydoc.getText('source');+ ytext.insert(0, markdown);+ return { doc, ydoc, ytext, source: markdown };+}++/** PM position just inside top-level block `index`. */+function pmPosOfBlock(doc: PmNode, index: number): number {+ let pos = 0;+ for (let i = 0; i < index; i++) pos += doc.child(i).nodeSize;+ return pos + 1;+}++/** PM position at the start (before) top-level block `index`. */+function pmBlockStart(doc: PmNode, index: number): number {+ return present(blockRangeToPositions(doc, index, index + 1)).from;+}++function docFrom(source: string): PmNode {+ return schema.nodeFromJSON(md.parse(stripFrontmatter(source).body));+}++describe('buildSourceLandingNav', () => {+ test('captures the block under the position with a pin over its source range', () => {+ const { doc, ydoc, ytext, source } = setup('# Title\n\nfirst\n\n## Second\n\ntarget para');+ const nav = present(buildSourceLandingNav(doc, pmPosOfBlock(doc, 3), ytext, resolver));+ expect(nav.kind).toBe('selection-offset');+ expect(nav.anchor).toMatchObject({ blockIndex: 3, content: 'target para' });+ // The pin resolves to the captured block's start offset in the source.+ expect(resolveNavigationPin(present(nav.pin), ydoc)).toBe(source.indexOf('target para'));+ });++ test('omits the pin when the body has no top-level block to pin', () => {+ const { doc, ytext } = setup('');+ const nav = buildSourceLandingNav(doc, 0, ytext, resolver);+ // An empty body has no source block, so any captured anchor rides ordinal-only.+ expect(nav?.pin).toBeUndefined();+ });+});++describe('resolveSourceLandingTarget', () => {+ test('resolves the anchor ordinal to the matching source block with no pin', () => {+ const { doc, ydoc, source } = setup('# A\n\nfirst\n\ntarget');+ const anchor = present(resolver.captureFromSource(source, source.indexOf('target')));+ const nav: SelectionOffsetNavigation = { kind: 'selection-offset', anchor };+ const resolved = present(+ resolveSourceLandingTarget(nav, { source, pmDoc: doc, ydoc, resolver }),+ );+ expect(resolved.blockStart).toBe(source.indexOf('target'));+ });++ test('a surviving pin tracks a block a remote insert moved, beating the stale ordinal', () => {+ const { doc, ydoc, ytext, source } = setup('# A\n\nfirst para\n\ntarget para');+ const nav = present(buildSourceLandingNav(doc, pmPosOfBlock(doc, 2), ytext, resolver));++ // A remote peer inserts a whole new block above the target: the target's+ // ordinal (2) now points at 'first para', but the pin followed the content.+ ydoc.transact(() => ytext.insert(source.indexOf('first para'), 'inserted para\n\n'));+ const moved = ytext.toString();++ const resolved = present(+ resolveSourceLandingTarget(nav, { source: moved, pmDoc: docFrom(moved), ydoc, resolver }),+ );+ expect(resolved.blockStart).toBe(moved.indexOf('target para'));+ });++ test('a deleted pin degrades to a clamped landing rather than a stale offset', () => {+ const { doc, ydoc, ytext, source } = setup('# A\n\nfirst para\n\ntarget para');+ const nav = present(buildSourceLandingNav(doc, pmPosOfBlock(doc, 2), ytext, resolver));++ const start = source.indexOf('target para');+ ydoc.transact(() => ytext.delete(start, ytext.length - start));+ const shrunk = ytext.toString();++ const resolved = present(+ resolveSourceLandingTarget(nav, { source: shrunk, pmDoc: docFrom(shrunk), ydoc, resolver }),+ );+ expect(resolved.confidence).toBe('clamped');+ });++ test('returns null when the body has no blocks to land on', () => {+ const { doc, ydoc } = setup('');+ const anchor: BlockAnchor = { blockIndex: 0, kind: 'paragraph', content: '' };+ const nav: SelectionOffsetNavigation = { kind: 'selection-offset', anchor };+ expect(resolveSourceLandingTarget(nav, { source: '', pmDoc: doc, ydoc, resolver })).toBeNull();+ });+});++describe('buildWysiwygLandingNav', () => {+ test('captures the source block under the offset with a pin over its source range', () => {+ const { doc, ydoc, ytext, source } = setup('# Title\n\nfirst\n\n## Second\n\ntarget para');+ const off = source.indexOf('target para');+ const nav = present(buildWysiwygLandingNav(source, off, ytext, resolver, doc));+ expect(nav.kind).toBe('selection-offset');+ expect(nav.anchor).toMatchObject({ blockIndex: 3, content: 'target para' });+ expect(resolveNavigationPin(present(nav.pin), ydoc)).toBe(off);+ });++ test('omits the pin when no WYSIWYG doc is available to derive the source range', () => {+ const { ytext, source } = setup('# Title\n\ntarget');+ const nav = present(+ buildWysiwygLandingNav(source, source.indexOf('target'), ytext, resolver, undefined),+ );+ expect(nav.pin).toBeUndefined();+ expect(nav.anchor.blockIndex).toBe(1);+ });++ test('an offset inside the frontmatter region maps to the first body block', () => {+ const { doc, ytext, source } = setup('---\ntitle: hi\n---\n\n# Heading\n\nbody');+ const nav = present(+ buildWysiwygLandingNav(source, source.indexOf('title'), ytext, resolver, doc),+ );+ expect(nav.anchor.blockIndex).toBe(0);+ });++ test('returns null for an empty body with no block to capture', () => {+ const { ytext } = setup('');+ expect(buildWysiwygLandingNav('', 0, ytext, resolver, undefined)).toBeNull();+ });+});++describe('resolveWysiwygLandingTarget', () => {+ test('resolves the anchor ordinal to the matching WYSIWYG block with no pin', () => {+ const { doc, ydoc, source } = setup('# A\n\nfirst\n\ntarget');+ const anchor = present(resolver.captureFromSource(source, source.indexOf('target')));+ const nav: SelectionOffsetNavigation = { kind: 'selection-offset', anchor };+ const resolved = present(+ resolveWysiwygLandingTarget(nav, { source, pmDoc: doc, ydoc, resolver }),+ );+ expect(resolved.blockStart).toBe(pmBlockStart(doc, 2));+ });++ test('a surviving pin tracks a block a remote insert moved, beating the stale ordinal', () => {+ const { doc, ydoc, ytext, source } = setup('# A\n\nfirst para\n\ntarget para');+ const nav = present(+ buildWysiwygLandingNav(source, source.indexOf('target para'), ytext, resolver, doc),+ );++ // A remote peer inserts a whole new block above the target: its ordinal (2)+ // now points at 'first para', but the pin followed the content to block 3.+ ydoc.transact(() => ytext.insert(source.indexOf('first para'), 'inserted para\n\n'));+ const moved = ytext.toString();+ const movedDoc = docFrom(moved);++ const resolved = present(+ resolveWysiwygLandingTarget(nav, { source: moved, pmDoc: movedDoc, ydoc, resolver }),+ );+ expect(resolved.blockStart).toBe(pmBlockStart(movedDoc, 3));+ });++ test('a deleted pin degrades to a clamped landing rather than a stale ordinal', () => {+ const { doc, ydoc, ytext, source } = setup('# A\n\nfirst para\n\ntarget para');+ const nav = present(+ buildWysiwygLandingNav(source, source.indexOf('target para'), ytext, resolver, doc),+ );++ const start = source.indexOf('target para');+ ydoc.transact(() => ytext.delete(start, ytext.length - start));+ const shrunk = ytext.toString();++ const resolved = present(+ resolveWysiwygLandingTarget(nav, { source: shrunk, pmDoc: docFrom(shrunk), ydoc, resolver }),+ );+ expect(resolved.confidence).toBe('clamped');+ });++ test('returns null when the doc has no block to land on', () => {+ const { doc, ydoc } = setup('');+ const anchor: BlockAnchor = { blockIndex: 0, kind: 'paragraph', content: '' };+ const nav: SelectionOffsetNavigation = { kind: 'selection-offset', anchor };+ expect(resolveWysiwygLandingTarget(nav, { source: '', pmDoc: doc, ydoc, resolver })).toBeNull();+ });+});++describe('sourceTargetMetrics', () => {+ test('uses the measured rect from coordsAtPos when the target line is rendered', () => {+ const view = {+ state: { doc: { length: 1000 } },+ coordsAtPos: () => ({ top: 66, bottom: 86, left: 0, right: 0 }),+ // Must be ignored while the measured rect is available.+ documentTop: 999,+ lineBlockAt: () => ({ top: 999, height: 999 }),+ } as unknown as CodeMirrorView;+ const container = {+ getBoundingClientRect: () => ({ top: 10 }) as DOMRect,+ scrollTop: 100,+ } as unknown as HTMLElement;++ // content-space top = coords.top(66) - containerTop(10) + scrollTop(100) = 156.+ expect(sourceTargetMetrics(view, container, 300)).toEqual({ top: 156, height: 20 });+ });++ test('falls back to the height-map estimate only while the line is off-viewport', () => {+ const view = {+ state: { doc: { length: 1000 } },+ coordsAtPos: () => null, // not rendered yet+ documentTop: 20,+ lineBlockAt: (pos: number) => ({ top: pos, height: 40 }),+ } as unknown as CodeMirrorView;+ const container = {+ getBoundingClientRect: () => ({ top: 10 }) as DOMRect,+ scrollTop: 100,+ } as unknown as HTMLElement;++ // cmDocTop = documentTop(20) - containerTop(10) + scrollTop(100) = 110; + block.top(300).+ expect(sourceTargetMetrics(view, container, 300)).toEqual({ top: 410, height: 40 });+ });++ test('clamps an out-of-range offset to the document length before measuring', () => {+ let measuredAt = -1;+ const view = {+ state: { doc: { length: 500 } },+ coordsAtPos: (pos: number) => {+ measuredAt = pos;+ return null;+ },+ documentTop: 0,+ lineBlockAt: (pos: number) => ({ top: pos, height: 10 }),+ } as unknown as CodeMirrorView;+ const container = {+ getBoundingClientRect: () => ({ top: 0 }) as DOMRect,+ scrollTop: 0,+ } as unknown as HTMLElement;++ // 9999 is past the doc end, so both the measurement and the estimate use 500.+ expect(sourceTargetMetrics(view, container, 9999)?.top).toBe(500);+ expect(measuredAt).toBe(500);+ });++ test('degrades to null when a torn-down view throws instead of measuring', () => {+ // CodeMirror drops its document view on destroy, so the geometry accessors+ // throw rather than returning null. A landing outlives a frame, so its+ // measurer can be called after that — and the throw must not reach the+ // controller, whose holds do not decay.+ const view = {+ state: { doc: { length: 1000 } },+ coordsAtPos: () => {+ throw new TypeError('reading null docView');+ },+ documentTop: 0,+ lineBlockAt: () => {+ throw new TypeError('reading null docView');+ },+ } as unknown as CodeMirrorView;+ const container = {+ getBoundingClientRect: () => ({ top: 0 }) as DOMRect,+ scrollTop: 0,+ } as unknown as HTMLElement;++ expect(sourceTargetMetrics(view, container, 300)).toBeNull();+ });++ test('falls back to the height map when only the measured rect throws', () => {+ const view = {+ state: { doc: { length: 1000 } },+ coordsAtPos: () => {+ throw new RangeError('position out of range');+ },+ documentTop: 0,+ lineBlockAt: (pos: number) => ({ top: pos, height: 40 }),+ } as unknown as CodeMirrorView;+ const container = {+ getBoundingClientRect: () => ({ top: 0 }) as DOMRect,+ scrollTop: 0,+ } as unknown as HTMLElement;++ expect(sourceTargetMetrics(view, container, 300)).toEqual({ top: 300, height: 40 });+ });+});++describe('wysiwygTargetMetrics', () => {+ test('measures the block element rect in the scroller coordinate space', () => {+ const el = document.createElement('div');+ el.getBoundingClientRect = () => ({ top: 66, bottom: 92, height: 26 }) as DOMRect;+ const view = {+ state: { doc: { content: { size: 1000 } } },+ nodeDOM: () => el,+ domAtPos: () => ({ node: el, offset: 0 }),+ } as unknown as ProseMirrorView;+ const container = {+ getBoundingClientRect: () => ({ top: 10 }) as DOMRect,+ scrollTop: 100,+ } as unknown as HTMLElement;++ // content-space top = rect.top(66) - containerTop(10) + scrollTop(100) = 156.+ expect(wysiwygTargetMetrics(view, container, 300)).toEqual({ top: 156, height: 26 });+ });++ test('returns null when the position resolves to no element', () => {+ const view = {+ state: { doc: { content: { size: 500 } } },+ nodeDOM: () => null,+ domAtPos: () => ({ node: { parentElement: null } as unknown as Node, offset: 0 }),+ } as unknown as ProseMirrorView;+ const container = {+ getBoundingClientRect: () => ({ top: 0 }) as DOMRect,+ scrollTop: 0,+ } as unknown as HTMLElement;+ expect(wysiwygTargetMetrics(view, container, 9999)).toBeNull();+ });++ test('returns null for a destroyed view without touching its DOM accessors', () => {+ let touched = false;+ const view = {+ isDestroyed: true,+ state: { doc: { content: { size: 500 } } },+ nodeDOM: () => {+ touched = true;+ return null;+ },+ domAtPos: () => {+ touched = true;+ return { node: document.createElement('div'), offset: 0 };+ },+ } as unknown as ProseMirrorView;+ const container = {+ getBoundingClientRect: () => ({ top: 0 }) as DOMRect,+ scrollTop: 0,+ } as unknown as HTMLElement;++ expect(wysiwygTargetMetrics(view, container, 300)).toBeNull();+ expect(touched).toBe(false);+ });++ test('degrades to null when a recycled view throws out of its DOM accessors', () => {+ const view = {+ state: { doc: { content: { size: 500 } } },+ nodeDOM: () => {+ throw new Error('view recycled');+ },+ domAtPos: () => {+ throw new Error('view recycled');+ },+ } as unknown as ProseMirrorView;+ const container = {+ getBoundingClientRect: () => ({ top: 0 }) as DOMRect,+ scrollTop: 0,+ } as unknown as HTMLElement;++ expect(wysiwygTargetMetrics(view, container, 300)).toBeNull();+ });+});++describe('captureModeSwitchAnchor', () => {+ beforeEach(() => {+ clearPendingSourceNavigationsForTest();+ clearPendingWysiwygNavigationsForTest();+ });++ test('does not overwrite a tool-driven raw-MDX target already queued for source', () => {+ const { ytext } = setup('# A\n\nbody');+ rememberPendingSourceNavigation('doc-raw', { kind: 'raw-mdx', detail: { offset: 5 } });+ captureModeSwitchAnchor({ from: 'wysiwyg', to: 'source', docName: 'doc-raw', ytext });+ expect(peekPendingSourceNavigation('doc-raw')?.kind).toBe('raw-mdx');+ });++ test('queues nothing when no WYSIWYG editor is registered for the doc', () => {+ const { ytext } = setup('# A\n\nbody');+ captureModeSwitchAnchor({ from: 'wysiwyg', to: 'source', docName: 'doc-none', ytext });+ expect(peekPendingSourceNavigation('doc-none')).toBeNull();+ });++ test('queues nothing for source-to-WYSIWYG when no source view is registered', () => {+ const { ytext } = setup('# A\n\nbody');+ captureModeSwitchAnchor({ from: 'source', to: 'wysiwyg', docName: 'doc-rev', ytext });+ expect(peekPendingWysiwygNavigation('doc-rev')).toBeNull();+ });++ test('queues a WYSIWYG landing for source-to-WYSIWYG from the registered source view', () => {+ const { ytext, source } = setup('# A\n\nfirst\n\ntarget para');+ const container = document.createElement('div');+ container.setAttribute('data-testid', 'editor-scroll-container');+ container.getBoundingClientRect = () =>+ ({ top: 0, left: 0, width: 100, height: 400 }) as DOMRect;+ container.getClientRects = () =>+ [{ width: 100, height: 400 } as DOMRect] as unknown as DOMRectList;+ document.body.appendChild(container);+ const view = { posAtCoords: () => source.indexOf('target para') } as unknown as CodeMirrorView;+ registerSourceView('doc-fwd', view);+ try {+ captureModeSwitchAnchor({ from: 'source', to: 'wysiwyg', docName: 'doc-fwd', ytext });+ const nav = peekPendingWysiwygNavigation('doc-fwd');+ expect(nav?.kind).toBe('selection-offset');+ expect(nav?.anchor.content).toBe('target para');+ // The reverse direction leaves the source-destined store untouched.+ expect(peekPendingSourceNavigation('doc-fwd')).toBeNull();+ } finally {+ unregisterSourceView('doc-fwd', view);+ container.remove();+ }+ });+});++describe('buildSourceLandingNav intent', () => {+ test('a jump refines the anchor to the caret offset and marks the nav a jump', () => {+ const { doc, ytext } = setup('# Title\n\nfirst\n\ntarget paragraph');+ // Three characters into the target block.+ const nav = present(+ buildSourceLandingNav(doc, pmPosOfBlock(doc, 2) + 3, ytext, resolver, 'jump'),+ );+ expect(nav.intent).toBe('jump');+ expect(nav.anchor).toMatchObject({ blockIndex: 2, selectionInBlock: 3 });+ });++ test('a toggle stays scroll-only: no inline refinement, intent toggle', () => {+ const { doc, ytext } = setup('# Title\n\nfirst\n\ntarget paragraph');+ const nav = present(buildSourceLandingNav(doc, pmPosOfBlock(doc, 2) + 3, ytext, resolver));+ expect(nav.intent).toBe('toggle');+ expect(nav.anchor.selectionInBlock).toBeUndefined();+ });+});++describe('requestViewInSource', () => {+ beforeEach(() => {+ clearPendingSourceNavigationsForTest();+ });++ /** A stand-in editor whose ProseMirror view carries the caret and doc. */+ function fakeWysiwygEditor(doc: PmNode, caret: number): Editor {+ const view = { state: { doc, selection: { from: caret } } } as unknown as ProseMirrorView;+ return { editorView: view } as unknown as Editor;+ }++ test('banks a jump landing for the caret block and asks the pane to flip', () => {+ const { doc, ytext } = setup('# Title\n\nfirst\n\ntarget paragraph');+ const editor = fakeWysiwygEditor(doc, pmPosOfBlock(doc, 2) + 3);++ let flipped: string | null = null;+ const onFlip = (e: Event) => {+ flipped = (e as CustomEvent<ViewInSourceDetail>).detail.docName;+ };+ window.addEventListener(VIEW_IN_SOURCE_EVENT, onFlip);+ try {+ requestViewInSource({ editor, docName: 'doc-jump', ytext });+ } finally {+ window.removeEventListener(VIEW_IN_SOURCE_EVENT, onFlip);+ }++ const nav = peekPendingSourceNavigation('doc-jump');+ if (nav?.kind !== 'selection-offset') throw new Error('expected a selection-offset nav');+ expect(nav.intent).toBe('jump');+ expect(nav.anchor).toMatchObject({ blockIndex: 2, selectionInBlock: 3 });+ expect(flipped).toBe('doc-jump');+ });++ test('flips to source even for an empty-body doc', () => {+ // A ProseMirror doc always carries at least the default empty paragraph, so+ // the jump still banks a (block 0) target — the point of this case is that+ // the switch fires regardless, so the user always reaches source mode.+ const { doc, ytext } = setup('');+ const editor = fakeWysiwygEditor(doc, 0);++ let flipped = false;+ const onFlip = () => {+ flipped = true;+ };+ window.addEventListener(VIEW_IN_SOURCE_EVENT, onFlip);+ try {+ requestViewInSource({ editor, docName: 'doc-empty', ytext });+ } finally {+ window.removeEventListener(VIEW_IN_SOURCE_EVENT, onFlip);+ }++ expect(flipped).toBe(true);+ expect(peekPendingSourceNavigation('doc-empty')?.kind).toBe('selection-offset');+ });+});++// ---------------------------------------------------------------------------+// Landing dispatch. Both entry points are driven end to end against real editor+// state — a CodeMirror state carrying the landing-flash field, a ProseMirror+// state carrying the landing-flash plugin — so the flash is observed as a+// decoration the production path actually produced, not as a mocked call.+// ---------------------------------------------------------------------------++/** Trailing quiet window the landing controller settles on. */+const SETTLE_QUIET_MS = 150;+/** Bounded window after which a landing that never settles abandons. */+const ABANDON_WINDOW_MS = 2000;+const TOOLBAR_OVERLAP_PX = 56;+const VIEWPORT_HEIGHT = 800;+const SCROLL_HEIGHT = 6000;++function buildScrollContainer(): HTMLElement {+ const container = document.createElement('div');+ container.setAttribute('data-testid', 'editor-scroll-container');+ Object.defineProperty(container, 'clientHeight', {+ value: VIEWPORT_HEIGHT,+ configurable: true,+ });+ Object.defineProperty(container, 'scrollHeight', { value: SCROLL_HEIGHT, configurable: true });+ Object.defineProperty(container, 'scrollTop', { value: 0, writable: true, configurable: true });+ container.getBoundingClientRect = () =>+ ({ top: 0, bottom: VIEWPORT_HEIGHT, left: 0, width: 600 }) as DOMRect;+ // jsdom paints nothing, so model the browser signal the visible-container+ // lookup relies on: a laid-out container reports client rects, a hidden+ // (display:none) one reports none.+ container.getClientRects = () =>+ [{ width: 600, height: VIEWPORT_HEIGHT } as DOMRect] as unknown as DOMRectList;+ document.body.appendChild(container);+ return container;+}++interface DrivenSourceView {+ view: CodeMirrorView;+ state: () => CmEditorState;+ /** Move the target's content-space position, as a relayout above it would. */+ setContentTop: (top: number) => void;+}++/**+ * A CodeMirror view surface backed by a real EditorState carrying the landing+ * flash field, so every dispatch the landing makes (scroll prime, caret+ * placement, flash) runs the production reducers. jsdom lays nothing out, so+ * geometry is modelled the way a real editor reports it: `coordsAtPos` returns+ * a viewport-relative rect that moves as the scroller is written, which keeps+ * the derived content-space position fixed across the settle.+ */+function drivenSourceView(+ markdown: string,+ container: HTMLElement,+ contentTop = 2000,+): DrivenSourceView {+ let state = CmEditorState.create({ doc: markdown, extensions: [landingFlashField] });+ let top = contentTop;+ const view = {+ get state() {+ return state;+ },+ dispatch(spec: TransactionSpec) {+ state = state.update(spec).state;+ },+ // Non-null coords are what release the landing's bounded wait for the+ // primed scroll to render the target line.+ coordsAtPos: () => ({ top: top - container.scrollTop, bottom: top - container.scrollTop + 20 }),+ lineBlockAt: () => ({ top, height: 20 }),+ documentTop: 0,+ contentDOM: document.createElement('div'),+ focus: () => {},+ };+ return {+ view: view as unknown as CodeMirrorView,+ state: () => state,+ setContentTop: (next: number) => {+ top = next;+ },+ };+}++interface DrivenWysiwygView {+ editor: Editor;+ state: () => PmEditorState;+}++/**+ * A ProseMirror view surface backed by a real EditorState carrying the landing+ * flash plugin, so a flash dispatched on this side would be observable. The+ * block element's rect moves with the scroller for the same reason the source+ * view's coords do.+ */+function drivenWysiwygView(+ doc: PmNode,+ container: HTMLElement,+ contentTop = 2000,+): DrivenWysiwygView {+ let state = PmEditorState.create({ doc, plugins: [createLandingFlashPlugin()] });+ const el = document.createElement('div');+ el.getBoundingClientRect = () =>+ ({ top: contentTop - container.scrollTop, height: 40 }) as DOMRect;+ const view = {+ get state() {+ return state;+ },+ dispatch(tr: ReturnType<PmEditorState['tr']['setMeta']>) {+ state = state.apply(tr);+ },+ dom: document.createElement('div'),+ nodeDOM: () => el,+ domAtPos: () => ({ node: el, offset: 0 }),+ };+ return {+ editor: { editorView: view } as unknown as Editor,+ state: () => state,+ };+}++/** Register a stand-in WYSIWYG editor so the source landing can grade against its doc. */+function registerWysiwygDoc(docName: string, doc: PmNode): Editor {+ const editor = { editorView: { state: { doc } } } as unknown as Editor;+ registerEditor(docName, editor);+ return editor;+}++function cmFlashRanges(set: DecorationSet): Array<{ from: number; to: number }> {+ const out: Array<{ from: number; to: number }> = [];+ const cursor = set.iter();+ while (cursor.value) {+ out.push({ from: cursor.from, to: cursor.to });+ cursor.next();+ }+ return out;+}++function markNamed(name: string): { properties?: Record<string, unknown> } | undefined {+ return getCollector()+ ?.marks.toArray()+ .find((m) => m.name === name);+}++describe('startSourceLanding', () => {+ const DOC = 'landing-source-doc';+ let container: HTMLElement;+ let registered: Editor | null = null;++ beforeEach(() => {+ vi.useFakeTimers();+ // The frame callback is an accelerator, not a terminal signal; stubbing it+ // out makes the settle driven only by the injected signals + fake timers.+ vi.stubGlobal('requestAnimationFrame', () => 0);+ vi.stubGlobal('cancelAnimationFrame', () => {});+ getCollector()?.reset();+ __resetScrollRestoreCoordination();+ clearPendingSourceNavigationsForTest();+ container = buildScrollContainer();+ });++ afterEach(() => {+ if (registered) unregisterEditor(DOC, registered);+ registered = null;+ vi.useRealTimers();+ vi.unstubAllGlobals();+ container.remove();+ });++ /** Seed a jump navigation for the last block of `markdown` and mount its doc. */+ function jumpToLastBlock(markdown: string): {+ nav: SelectionOffsetNavigation;+ ydoc: Y.Doc;+ lastBlockStart: number;+ } {+ const { doc, ydoc, ytext } = setup(markdown);+ registered = registerWysiwygDoc(DOC, doc);+ const lastIndex = doc.childCount - 1;+ const nav = present(+ buildSourceLandingNav(doc, pmPosOfBlock(doc, lastIndex), ytext, resolver, 'jump'),+ );+ return { nav, ydoc, lastBlockStart: markdown.lastIndexOf('\n\n') + 2 };+ }++ test('a landed jump flashes the resolved block range and places the caret in it', () => {+ const md = '# Title\n\nfirst para\n\ntarget para';+ const { nav, ydoc, lastBlockStart } = jumpToLastBlock(md);+ const source = drivenSourceView(md, container);++ startSourceLanding({ view: source.view, docName: DOC, navigation: nav, ydoc });++ // The flash waits for the controller's terminal signal, so nothing is+ // painted while the settle window is still open.+ expect(cmFlashRanges(source.state().field(landingFlashField))).toEqual([]);++ vi.advanceTimersByTime(SETTLE_QUIET_MS);++ expect(cmFlashRanges(source.state().field(landingFlashField))).toEqual([+ { from: lastBlockStart, to: md.length },+ ]);+ // The jump also places the caret inside the landed block.+ expect(source.state().selection.main.head).toBeGreaterThanOrEqual(lastBlockStart);+ });++ test('the flash clock starts when the landing lands, not when it was dispatched', () => {+ const md = '# Title\n\nfirst para\n\ntarget para';+ const { nav, ydoc } = jumpToLastBlock(md);+ const source = drivenSourceView(md, container);++ startSourceLanding({ view: source.view, docName: DOC, navigation: nav, ydoc });+ vi.advanceTimersByTime(SETTLE_QUIET_MS);+ expect(source.state().field(landingFlashField).size).toBe(1);++ // Total elapsed is now past FLASH_DURATION_MS measured from dispatch, so a+ // clock started at dispatch would already have cleared this.+ vi.advanceTimersByTime(FLASH_DURATION_MS - 1);+ expect(source.state().field(landingFlashField).size).toBe(1);++ vi.advanceTimersByTime(1);+ expect(source.state().field(landingFlashField).size).toBe(0);+ });++ test('a plain toggle lands without flashing and without touching the selection', () => {+ const md = '# Title\n\nfirst para\n\ntarget para';+ const { doc, ydoc, ytext } = setup(md);+ registered = registerWysiwygDoc(DOC, doc);+ const nav = present(buildSourceLandingNav(doc, pmPosOfBlock(doc, 2), ytext, resolver));+ const source = drivenSourceView(md, container);++ startSourceLanding({ view: source.view, docName: DOC, navigation: nav, ydoc });+ vi.advanceTimersByTime(SETTLE_QUIET_MS);++ // The toggle landed (top placement pins the block below the toolbar) …+ expect(container.scrollTop).toBe(2000 - TOOLBAR_OVERLAP_PX);+ // … but it is scroll-only: no flash, no caret write.+ expect(source.state().field(landingFlashField).size).toBe(0);+ expect(source.state().selection.main.head).toBe(0);+ });++ test('a jump cancelled before it settles never flashes', () => {+ const md = '# Title\n\nfirst para\n\ntarget para';+ const { nav, ydoc } = jumpToLastBlock(md);+ const source = drivenSourceView(md, container);++ const handle = startSourceLanding({+ view: source.view,+ docName: DOC,+ navigation: nav,+ ydoc,+ });+ handle?.cancel('mode-flip');++ // Asserted at the cancel itself, not only after the flash duration: a flash+ // painted on the cancel would expire on its own and read as clean later.+ expect(source.state().field(landingFlashField).size).toBe(0);+ vi.advanceTimersByTime(SETTLE_QUIET_MS + FLASH_DURATION_MS);+ expect(source.state().field(landingFlashField).size).toBe(0);+ });++ test('a jump that abandons never flashes', () => {+ const md = '# Title\n\nfirst para\n\ntarget para';+ const { nav, ydoc } = jumpToLastBlock(md);+ const source = drivenSourceView(md, container);++ startSourceLanding({ view: source.view, docName: DOC, navigation: nav, ydoc });++ // Perpetual layout churn: the target oscillates between two in-range+ // positions and a signal fires each step, so the settle countdown never+ // elapses before the abandon cap.+ for (let elapsed = 0; elapsed < ABANDON_WINDOW_MS; elapsed += 100) {+ source.setContentTop(elapsed % 200 === 0 ? 4000 : 2000);+ container.dispatchEvent(new Event('contentvisibilityautostatechange'));+ vi.advanceTimersByTime(100);+ }++ expect(markNamed('ok/landing/abandoned')).toBeDefined();+ expect(markNamed('ok/landing/land')).toBeUndefined();+ expect(source.state().field(landingFlashField).size).toBe(0);+ });++ test('a jump graded clamped lands but suppresses the flash', () => {+ const md = '# Title\n\nfirst para\n\ntarget para';+ const { doc, ydoc, ytext } = setup(md);+ const nav = present(buildSourceLandingNav(doc, pmPosOfBlock(doc, 2), ytext, resolver, 'jump'));++ // Delete the pinned block so the resolve degrades to a clamped landing.+ const start = md.indexOf('target para');+ ydoc.transact(() => ytext.delete(start, ytext.length - start));+ const shrunk = ytext.toString();+ registered = registerWysiwygDoc(DOC, docFrom(shrunk));+ const source = drivenSourceView(shrunk, container);++ startSourceLanding({ view: source.view, docName: DOC, navigation: nav, ydoc });+ vi.advanceTimersByTime(SETTLE_QUIET_MS);++ // It still lands — only the highlight, which would assert a precision the+ // landing does not have, is withheld.+ expect(container.scrollTop).toBeGreaterThan(0);+ expect(source.state().field(landingFlashField).size).toBe(0);+ });++ test('does nothing when no WYSIWYG doc is mounted to grade against', () => {+ const md = '# Title\n\ntarget para';+ const { doc, ydoc, ytext } = setup(md);+ const nav = present(buildSourceLandingNav(doc, pmPosOfBlock(doc, 1), ytext, resolver, 'jump'));+ const source = drivenSourceView(md, container);++ // No editor registered for this docName — the count tripwire has nothing to+ // grade against, so the landing degrades to the pre-feature no-op.+ expect(+ startSourceLanding({ view: source.view, docName: DOC, navigation: nav, ydoc }),+ ).toBeNull();+ vi.advanceTimersByTime(SETTLE_QUIET_MS);+ expect(container.scrollTop).toBe(0);+ expect(source.state().field(landingFlashField).size).toBe(0);+ });+});++describe('startWysiwygLanding', () => {+ const DOC = 'landing-wysiwyg-doc';+ let container: HTMLElement;++ beforeEach(() => {+ vi.useFakeTimers();+ vi.stubGlobal('requestAnimationFrame', () => 0);+ vi.stubGlobal('cancelAnimationFrame', () => {});+ getCollector()?.reset();+ __resetScrollRestoreCoordination();+ clearPendingWysiwygNavigationsForTest();+ container = buildScrollContainer();+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ container.remove();+ });++ test('lands the block below the toolbar and paints no flash', () => {+ const md = '# Title\n\nfirst para\n\ntarget para';+ const { doc, ydoc, ytext, source } = setup(md);+ const nav = present(+ buildWysiwygLandingNav(source, source.indexOf('target para'), ytext, resolver, doc),+ );+ const wysiwyg = drivenWysiwygView(doc, container);+ const selectionBefore = wysiwyg.state().selection;++ startWysiwygLanding({ editor: wysiwyg.editor, docName: DOC, navigation: nav, ydoc });+ vi.advanceTimersByTime(SETTLE_QUIET_MS);++ expect(container.scrollTop).toBe(2000 - TOOLBAR_OVERLAP_PX);+ // Scroll-only: the WYSIWYG side of a toggle never flashes or moves the caret.+ expect(landingFlashKey.getState(wysiwyg.state())?.find() ?? []).toHaveLength(0);+ expect(wysiwyg.state().selection.eq(selectionBefore)).toBe(true);+ });++ test('does nothing when the editor view is not mounted', () => {+ const md = '# Title\n\ntarget para';+ const { doc, ydoc, ytext, source } = setup(md);+ const nav = present(+ buildWysiwygLandingNav(source, source.indexOf('target para'), ytext, resolver, doc),+ );+ const editor = {} as unknown as Editor; // pre-mount: `editorView` is undefined++ expect(startWysiwygLanding({ editor, docName: DOC, navigation: nav, ydoc })).toBeNull();+ expect(container.scrollTop).toBe(0);+ });++ test('drives the visible container, not a hidden pooled one first in DOM order', () => {+ // A backgrounded pooled doc keeps its scroll container in the DOM (a hidden+ // <Activity> is display:none, not unmounted) and can precede the active one+ // in DOM order. A first-match lookup would measure and scroll that hidden+ // container, silently no-op-ing the landing in the multi-doc workflow.+ const hidden = document.createElement('div');+ hidden.setAttribute('data-testid', 'editor-scroll-container');+ Object.defineProperty(hidden, 'clientHeight', { value: VIEWPORT_HEIGHT, configurable: true });+ Object.defineProperty(hidden, 'scrollHeight', { value: SCROLL_HEIGHT, configurable: true });+ Object.defineProperty(hidden, 'scrollTop', { value: 0, writable: true, configurable: true });+ hidden.getBoundingClientRect = () =>+ ({ top: 0, bottom: VIEWPORT_HEIGHT, left: 0, width: 600 }) as DOMRect;+ hidden.getClientRects = () => [] as unknown as DOMRectList; // display:none → no boxes+ document.body.insertBefore(hidden, container); // hidden sorts first++ const md = '# Title\n\nfirst para\n\ntarget para';+ const { doc, ydoc, ytext, source } = setup(md);+ const nav = present(+ buildWysiwygLandingNav(source, source.indexOf('target para'), ytext, resolver, doc),+ );+ const wysiwyg = drivenWysiwygView(doc, container);++ startWysiwygLanding({ editor: wysiwyg.editor, docName: DOC, navigation: nav, ydoc });+ vi.advanceTimersByTime(SETTLE_QUIET_MS);++ expect(container.scrollTop).toBe(2000 - TOOLBAR_OVERLAP_PX);+ expect(hidden.scrollTop).toBe(0);+ hidden.remove();+ });+});diff --git a/packages/app/src/editor/mode-switch-landing.ts b/packages/app/src/editor/mode-switch-landing.tsnew file mode 100644index 000000000..20b3a8329--- /dev/null+++ b/packages/app/src/editor/mode-switch-landing.ts@@ -0,0 +1,547 @@+/**+ * Wires the mode-switch position resolver, the pending-navigation stores, and+ * the landing controller into an actual "flip mode, then keep my place" toggle.+ *+ * Two halves that meet through the pending-navigation store:+ *+ * - CAPTURE runs at flip time, while the outgoing editor is still laid out.+ * It reads the topmost visible block, turns it into a resolver anchor plus a+ * relative-position pin over the corresponding source range, and banks that+ * as a pending navigation for the incoming view to replay.+ * - DISPATCH runs when the incoming view is mounted and active. It resolves+ * the anchor against the live document, reconciles it with the pin (so a+ * remote edit in the capture-to-dispatch window moves the target with the+ * content), and hands a measured target to the landing controller.+ *+ * Everything cross-representation goes through `ModeSwitchPositionResolver`, so+ * no coordinate logic lives here beyond turning a CodeMirror offset into the+ * scroll-content geometry the controller measures against. Navigation is+ * read-only: nothing here mutates a Y.Text, a fragment, or a selection.+ */++import { EditorSelection } from '@codemirror/state';+import { EditorView } from '@codemirror/view';+import type { Editor } from '@tiptap/core';+import type { Node as PmNode } from '@tiptap/pm/model';+import type { EditorView as ProseMirrorView } from '@tiptap/pm/view';+import type * as Y from 'yjs';+import { getEditorForDoc } from './active-editor';+import { getSourceViewForDoc } from './active-source-view';+import { visibleEditorScrollContainer } from './editor-cache';+import { type LandingHandle, startLanding, type TargetMetrics } from './landing-controller';+import {+ createApproxResolver,+ type ModeSwitchPositionResolver,+ type ResolvedPosition,+} from './mode-switch-position-resolver';+import { flashSourceLanding } from './plugins/landing-flash-source';+import { registerLandingScrollOwner } from './scroll-restore-coordination';+import {+ clearPendingSourceNavigation,+ clearPendingWysiwygNavigation,+ createNavigationPin,+ peekPendingSourceNavigation,+ rememberPendingSourceNavigation,+ rememberPendingWysiwygNavigation,+ resolveNavigationPin,+ type SelectionOffsetNavigation,+} from './source-editor-navigation';+import type { EditorModeValue } from './use-editor-mode';+import { getEditorView } from './utils/get-editor-view';+import { getSharedMarkdownManager } from './utils/md-singleton';+import { VIEW_IN_SOURCE_EVENT, type ViewInSourceDetail } from './view-in-source-event';++// Toolbar exclusion zone in px (= EditorToolbar's rendered 3.5rem height). The+// toolbar overlays the top of the shared scroller, so both the capture probe+// (below the toolbar) and the landing offset (target sits just under it) start+// here. Restated rather than shared to keep this leaf free of a React-component+// import cycle; keep in sync with TOOLBAR_OVERLAP_PX in SourceEditor.tsx and the+// scroll-pt-14 in components/EditorActivityPool.tsx.+const TOOLBAR_OVERLAP_PX = 56;++let sharedResolver: ModeSwitchPositionResolver | null = null;+function getSharedResolver(): ModeSwitchPositionResolver {+ sharedResolver ??= createApproxResolver(getSharedMarkdownManager());+ return sharedResolver;+}++/**+ * Build the source-destined pending navigation for a WYSIWYG-to-source flip: the+ * block anchor under `pos` plus a pin over its source range so a queued landing+ * tracks remote edits. Null when there is no anchor to capture (empty doc), which+ * reproduces the pre-feature no-op flip. The pin is omitted when the block has no+ * source counterpart (a body with no top-level blocks); the ordinal still lands.+ *+ * A `jump` intent additionally refines the anchor to the caret's inline offset,+ * so an `exact` landing can place the caret inside the block rather than only at+ * its start; a `toggle` captures the block alone and stays scroll-only.+ */+export function buildSourceLandingNav(+ doc: PmNode,+ pos: number,+ ytext: Y.Text,+ resolver: ModeSwitchPositionResolver,+ intent: 'toggle' | 'jump' = 'toggle',+): SelectionOffsetNavigation | null {+ const anchor = resolver.captureFromWysiwyg(doc, pos, { refine: intent === 'jump' });+ if (!anchor) return null;+ const resolved = resolver.resolveInSource(anchor, { source: ytext.toString(), doc });+ const pin = resolved+ ? createNavigationPin(ytext, resolved.blockStart, resolved.blockEnd)+ : undefined;+ return { kind: 'selection-offset', intent, anchor, pin };+}++/**+ * Bank an explicit "view in source" jump for the WYSIWYG caret and ask the pane+ * to flip to source. The landing target is stored before the flip so the+ * incoming source view replays it; the flip itself is left to `EditorPane` via+ * the window event, which owns the mode state — the same split the raw-MDX+ * navigation uses. The switch fires even for an empty document (no block to+ * bank) so the user always reaches source mode.+ *+ * The caret is the only input: every entry point (bubble button, keyboard+ * command, desktop context menu) acts on the selection the user already has.+ * The desktop menu therefore lands on the block under the pointer only because+ * Chromium moves the caret when you right-click editable text — nothing here+ * records the pointer, and a caller that needs a pointer-anchored jump has to+ * carry the coordinates through rather than assume this reads them.+ */+export function requestViewInSource(params: {+ editor: Editor;+ docName: string;+ ytext: Y.Text;+}): void {+ const { editor, docName, ytext } = params;+ const view = getEditorView(editor);+ if (!view) return;+ const pos = view.state.selection.from;+ const nav = buildSourceLandingNav(view.state.doc, pos, ytext, getSharedResolver(), 'jump');+ if (nav) rememberPendingSourceNavigation(docName, nav);+ window.dispatchEvent(+ new CustomEvent<ViewInSourceDetail>(VIEW_IN_SOURCE_EVENT, { detail: { docName } }),+ );+}++/**+ * Build the WYSIWYG-destined pending navigation for a source-to-WYSIWYG flip: the+ * block anchor for `fullOffset` (the topmost visible source line's char offset)+ * plus a pin over that block's source range so a queued landing tracks remote+ * edits. Both directions pin the source range because `Y.Text('source')` is the+ * document's truth. Null when there is no anchor to capture (empty body), which+ * reproduces the pre-feature no-op flip. The pin is omitted when the WYSIWYG doc+ * is not mounted to derive the source range against (a large doc that deferred+ * it); the ordinal still lands.+ */+export function buildWysiwygLandingNav(+ source: string,+ fullOffset: number,+ ytext: Y.Text,+ resolver: ModeSwitchPositionResolver,+ pmDoc: PmNode | undefined,+): SelectionOffsetNavigation | null {+ const anchor = resolver.captureFromSource(source, fullOffset);+ if (!anchor) return null;+ const sourceRange = pmDoc ? resolver.resolveInSource(anchor, { source, doc: pmDoc }) : null;+ const pin = sourceRange+ ? createNavigationPin(ytext, sourceRange.blockStart, sourceRange.blockEnd)+ : undefined;+ return { kind: 'selection-offset', anchor, pin };+}++/**+ * Resolve a queued WYSIWYG landing against the live document. Mirrors the+ * source-side resolve: a surviving pin re-anchors on its live source offset so a+ * remotely-moved block is followed; a pin that can no longer resolve degrades to+ * a clamped block-start; a pinless navigation rides the ordinal. The returned+ * positions are ProseMirror positions. Null when the doc has no block to land on.+ */+export function resolveWysiwygLandingTarget(+ navigation: SelectionOffsetNavigation,+ ctx: { source: string; pmDoc: PmNode; ydoc: Y.Doc; resolver: ModeSwitchPositionResolver },+): ResolvedPosition | null {+ const { source, pmDoc, ydoc, resolver } = ctx;+ if (navigation.pin) {+ const live = resolveNavigationPin(navigation.pin, ydoc);+ if (live === null) {+ const resolved = resolver.resolveInWysiwyg(navigation.anchor, { source, doc: pmDoc });+ return resolved ? { ...resolved, point: resolved.blockStart, confidence: 'clamped' } : null;+ }+ const liveAnchor = resolver.captureFromSource(source, live);+ if (liveAnchor) return resolver.resolveInWysiwyg(liveAnchor, { source, doc: pmDoc });+ }+ return resolver.resolveInWysiwyg(navigation.anchor, { source, doc: pmDoc });+}++/**+ * Resolve a queued source landing against the live document. The pin is+ * authoritative when it survives: re-anchoring on its live offset follows a+ * block that remote edits moved during the capture-to-dispatch window. A pin+ * that can no longer resolve means the captured block was deleted, so the+ * landing degrades to a clamped block-start rather than trusting an ordinal that+ * now points at unrelated content. Null when the body has no blocks to land on.+ */+export function resolveSourceLandingTarget(+ navigation: SelectionOffsetNavigation,+ ctx: { source: string; pmDoc: PmNode; ydoc: Y.Doc; resolver: ModeSwitchPositionResolver },+): ResolvedPosition | null {+ const { source, pmDoc, ydoc, resolver } = ctx;+ if (navigation.pin) {+ const live = resolveNavigationPin(navigation.pin, ydoc);+ if (live === null) {+ const resolved = resolver.resolveInSource(navigation.anchor, { source, doc: pmDoc });+ return resolved ? { ...resolved, point: resolved.blockStart, confidence: 'clamped' } : null;+ }+ const liveAnchor = resolver.captureFromSource(source, live);+ if (liveAnchor) return resolver.resolveInSource(liveAnchor, { source, doc: pmDoc });+ }+ return resolver.resolveInSource(navigation.anchor, { source, doc: pmDoc });+}++/**+ * Measured coordinates of a CodeMirror offset, or null when the view cannot+ * answer. A landing outlives a single frame, so its measurer can be called after+ * the view it closed over was torn down or recycled — CodeMirror drops its+ * document view on destroy and then throws out of the geometry accessors rather+ * than returning null (it exposes no public destroyed predicate to pre-check).+ * A landing has to degrade to "not measurable yet" there, never propagate a+ * throw into the controller's terminal paths, where it would strand their holds.+ */+function safeCoordsAtPos(view: EditorView, pos: number): ReturnType<EditorView['coordsAtPos']> {+ try {+ return view.coordsAtPos(pos);+ } catch {+ return null;+ }+}++/**+ * Scroll-content geometry of a CodeMirror offset, in the shared scroller's+ * coordinate space. `coordsAtPos` returns the target line's measured rect once it+ * is rendered, which is authoritative; the settle loop converges on it. The+ * height map (`lineBlockAt`) estimates off-viewport lines from a gap average, and+ * those estimates never refine for lines above a downward scroll, so trusting it+ * lands on the estimate and stays there — it is used only as a bootstrap to move+ * the scroller near the target, which renders it so the measured branch takes+ * over. Null when the view is gone (see `safeCoordsAtPos`).+ */+export function sourceTargetMetrics(+ view: EditorView,+ container: HTMLElement,+ offset: number,+): TargetMetrics | null {+ const clamped = Math.max(0, Math.min(offset, view.state.doc.length));+ const containerTop = container.getBoundingClientRect().top;+ const coords = safeCoordsAtPos(view, clamped);+ if (coords) {+ return {+ top: coords.top - containerTop + container.scrollTop,+ height: coords.bottom - coords.top,+ };+ }+ // Same teardown exposure as `safeCoordsAtPos`: the height map is gone with the+ // document view, so a torn-down view throws here too.+ try {+ const block = view.lineBlockAt(clamped);+ const cmDocTop = view.documentTop - containerTop + container.scrollTop;+ return { top: cmDocTop + block.top, height: block.height };+ } catch {+ return null;+ }+}++/**+ * The top-level block element containing a ProseMirror position, or null — which+ * includes the case where the view was destroyed or the position no longer+ * resolves against it, since both throw out of the DOM accessors.+ */+function blockElementForPos(view: ProseMirrorView, pos: number): HTMLElement | null {+ if (view.isDestroyed) return null;+ try {+ const node = view.nodeDOM(pos);+ if (node instanceof HTMLElement) return node;+ const { node: domNode } = view.domAtPos(pos);+ if (domNode instanceof HTMLElement) return domNode;+ return domNode.parentElement;+ } catch {+ return null;+ }+}++/**+ * Scroll-content geometry of a ProseMirror position, in the shared scroller's+ * coordinate space. The top-level block element carries the content-visibility+ * box, so its `getBoundingClientRect` is laid out from the intrinsic-size+ * estimate even while the block's contents are render-skipped — the settle loop+ * re-measures as blocks above it materialize and the estimate refines, so no+ * virtualization-aware prime is needed (unlike the source path, where an+ * off-viewport line has no DOM at all). Null when the position resolves to no+ * element, e.g. while the incoming editor is still mounting.+ */+export function wysiwygTargetMetrics(+ view: ProseMirrorView,+ container: HTMLElement,+ pmPos: number,+): TargetMetrics | null {+ if (view.isDestroyed) return null;+ const clamped = Math.max(0, Math.min(pmPos, view.state.doc.content.size));+ const el = blockElementForPos(view, clamped);+ if (!el) return null;+ const rect = el.getBoundingClientRect();+ const containerTop = container.getBoundingClientRect().top;+ return { top: rect.top - containerTop + container.scrollTop, height: rect.height };+}++function findScrollContainer(): HTMLElement | null {+ if (typeof document === 'undefined') return null;+ // A backgrounded pooled doc keeps its scroll container in the DOM (a hidden+ // <Activity> is display:none, not unmounted), so a plain first-match query can+ // return a container the user cannot see. The visible-container helper filters+ // by client rects so a landing always measures and scrolls the active one.+ return visibleEditorScrollContainer();+}++/**+ * PM position of the topmost visible content, probed just under the toolbar and+ * stepped down a little to clear the margin between blocks. Null when no probe+ * lands on content (e.g. the scroller sits below all content), so the caller+ * leaves the flip a no-op.+ */+function topmostVisiblePos(view: ProseMirrorView, container: HTMLElement): number | null {+ const rect = container.getBoundingClientRect();+ const x = rect.left + rect.width / 2;+ for (const dy of [TOOLBAR_OVERLAP_PX + 1, TOOLBAR_OVERLAP_PX + 12, TOOLBAR_OVERLAP_PX + 40]) {+ const found = view.posAtCoords({ left: x, top: rect.top + dy });+ if (found) return found.pos;+ }+ return null;+}++/**+ * Full `Y.Text` offset of the topmost visible source line, probed just under the+ * toolbar and stepped down to clear the inter-line margin. Null when no probe+ * lands on a line (the scroller sits below all content), so the caller leaves+ * the flip a no-op.+ */+function topmostVisibleSourceOffset(view: EditorView, container: HTMLElement): number | null {+ const rect = container.getBoundingClientRect();+ const x = rect.left + rect.width / 2;+ for (const dy of [TOOLBAR_OVERLAP_PX + 1, TOOLBAR_OVERLAP_PX + 12, TOOLBAR_OVERLAP_PX + 40]) {+ const pos = view.posAtCoords({ x, y: rect.top + dy });+ if (pos !== null) return pos;+ }+ return null;+}++/**+ * Capture the viewport anchor for a mode flip and bank it for the incoming view.+ * Runs synchronously at flip time, before the outgoing editor is hidden, so the+ * geometry it reads is the one the user is looking at. A tool-driven flip that+ * already queued its own target (a raw-MDX jump) is left untouched — the toggle+ * yields rather than overwriting it.+ */+export function captureModeSwitchAnchor(params: {+ from: EditorModeValue;+ to: EditorModeValue;+ docName: string;+ ytext: Y.Text;+}): void {+ const { from, to, docName, ytext } = params;+ if (from === 'wysiwyg' && to === 'source') captureWysiwygToSource(docName, ytext);+ else if (from === 'source' && to === 'wysiwyg') captureSourceToWysiwyg(docName, ytext);+}++function captureWysiwygToSource(docName: string, ytext: Y.Text): void {+ const existing = peekPendingSourceNavigation(docName);+ if (existing && existing.kind !== 'selection-offset') return;+ const editor = getEditorForDoc(docName);+ if (!editor) return;+ const view = getEditorView(editor);+ if (!view) return;+ const container = findScrollContainer();+ if (!container) return;+ const pos = topmostVisiblePos(view, container);+ if (pos === null) return;+ const nav = buildSourceLandingNav(view.state.doc, pos, ytext, getSharedResolver());+ if (nav) rememberPendingSourceNavigation(docName, nav);+}++function captureSourceToWysiwyg(docName: string, ytext: Y.Text): void {+ const view = getSourceViewForDoc(docName);+ if (!view) return;+ const container = findScrollContainer();+ if (!container) return;+ const offset = topmostVisibleSourceOffset(view, container);+ if (offset === null) return;+ // The WYSIWYG doc — mounted CSS-hidden underneath source mode — supplies the+ // source range for the pin. Absent for a large doc that deferred it; the+ // ordinal then lands pinless.+ const wysiwygEditor = getEditorForDoc(docName);+ const pmDoc = wysiwygEditor ? getEditorView(wysiwygEditor)?.state.doc : undefined;+ const nav = buildWysiwygLandingNav(ytext.toString(), offset, ytext, getSharedResolver(), pmDoc);+ if (nav) rememberPendingWysiwygNavigation(docName, nav);+}++/**+ * Start the source-side landing for a replayed selection-offset navigation. The+ * WYSIWYG doc supplies the count tripwire the resolver grades on; when it is not+ * mounted (a large doc that deferred it) the landing degrades to today's no-op+ * rather than grading blind.+ *+ * A `toggle` intent preserves the topmost block at the toolbar edge and never+ * touches the selection. A `jump` intent centers the block, places the caret at+ * its resolved point (refined inline only at `exact`), and flashes the block once+ * it lands on screen — the explicit "view in source" behavior. Returns the+ * controller handle so the caller can cancel it if the mode flips away before it+ * settles, or null when there is nothing to land on.+ */+export function startSourceLanding(params: {+ view: EditorView;+ docName: string;+ navigation: SelectionOffsetNavigation;+ ydoc: Y.Doc;+ transition?: { from: EditorModeValue; to: EditorModeValue };+}): LandingHandle | null {+ const { view, docName, navigation, ydoc, transition } = params;+ const wysiwygEditor = getEditorForDoc(docName);+ const pmDoc = wysiwygEditor ? getEditorView(wysiwygEditor)?.state.doc : undefined;+ if (!pmDoc) return null;+ const resolved = resolveSourceLandingTarget(navigation, {+ source: view.state.doc.toString(),+ pmDoc,+ ydoc,+ resolver: getSharedResolver(),+ });+ if (!resolved) return null;+ const container = findScrollContainer();+ if (!container) return null;+ const target = resolved;+ const isJump = navigation.intent === 'jump';+ // A jump lands (and places the caret) at the resolved point; a toggle preserves+ // the block from its start.+ const landingOffset = isJump ? target.point : target.blockStart;+ // Prime CodeMirror's own virtualization-aware scroll so the target line renders+ // and its measured rect drives the settle. The prime is scroll-only; a jump's+ // caret and focus come after the line renders, below. `y: 'start'` is the only+ // alignment that propagates to the ancestor scrollport in full-page source mode.+ view.dispatch({ effects: EditorView.scrollIntoView(landingOffset, { y: 'start' }) });++ // The prime applies on CodeMirror's next measure, so the target line is not+ // rendered yet this frame and `coordsAtPos` returns null. Starting the settle+ // now would make its first measure fall back to the over-tall off-viewport+ // estimate and overshoot, and the source path has no content-resize or+ // content-visibility signal to correct it afterward. Wait (bounded) for the+ // primed scroll to render the line so the settle's first measure is the real+ // rect. The returned handle cancels the deferred start if the mode flips away+ // before it begins.+ let cancelled = false;+ let handle: LandingHandle | null = null;+ // The render-wait belongs to the landing's ownership window too. Without a+ // registration covering it, an explicit navigation arriving in these frames+ // would scroll, see no owner to pre-empt, and then be overwritten by the+ // controller a frame later — the same erasure, just earlier.+ const pendingOwner = registerLandingScrollOwner(docName, {+ yieldsToNavigation: !isJump,+ supersede: () => {+ cancelled = true;+ pendingOwner.release();+ },+ });+ const MAX_RENDER_FRAMES = 8;+ const beginWhenRendered = (attempt: number): void => {+ if (cancelled) return;+ if (safeCoordsAtPos(view, landingOffset) === null && attempt < MAX_RENDER_FRAMES) {+ requestAnimationFrame(() => beginWhenRendered(attempt + 1));+ return;+ }+ try {+ if (isJump) {+ // Place the caret at the landed point so the user can edit immediately.+ // Selection-only (no `scrollIntoView`): the controller owns scroll for the+ // whole settle window, so this cannot fight it. This is the one selection+ // write the feature makes — exclusive to the explicit jump.+ view.dispatch({ selection: EditorSelection.cursor(landingOffset) });+ view.focus();+ }+ } finally {+ pendingOwner.release(); // the controller registers its own for the settle+ }+ handle = startLanding({+ docName,+ container,+ contentColumn: view.contentDOM,+ measureTarget: () => sourceTargetMetrics(view, container, landingOffset),+ placement: isJump ? 'center' : 'top',+ intent: isJump ? 'jump' : 'toggle',+ grade: target.confidence,+ landedMode: 'source',+ transition,+ toolbarOffset: TOOLBAR_OVERLAP_PX,+ onOutcome: isJump+ ? (outcome) => {+ // Flash the whole block once it is genuinely on screen (the controller+ // landed it), so the highlight's 2s clock measures visible time. A+ // clamped grade self-suppresses inside `flashSourceLanding`.+ if (outcome.status === 'landed') {+ flashSourceLanding(view, target.blockStart, target.blockEnd, target.confidence);+ }+ }+ : undefined,+ onDiscardQueuedTarget: () => clearPendingSourceNavigation(docName),+ });+ };+ beginWhenRendered(0);+ return {+ cancel: (reason) => {+ cancelled = true;+ pendingOwner.release();+ handle?.cancel(reason);+ },+ };+}++/**+ * Start the WYSIWYG-side landing for a replayed selection-offset navigation. The+ * target block element carries a laid-out content-visibility box even while+ * off-viewport, so its geometry is measurable immediately and the settle loop+ * converges as the estimate refines — no virtualization-aware prime and no+ * render-wait are needed (the source path needs both because an off-viewport CM+ * line has no DOM). Scroll-only: no selection, focus, or flash change, so the+ * plain toggle stays non-interfering. Returns the controller handle so the+ * caller can cancel it if the mode flips away before it settles, or null when+ * the editor is unmounted or there is nothing to land on.+ */+export function startWysiwygLanding(params: {+ editor: Editor;+ docName: string;+ navigation: SelectionOffsetNavigation;+ ydoc: Y.Doc;+ transition?: { from: EditorModeValue; to: EditorModeValue };+}): LandingHandle | null {+ const { editor, docName, navigation, ydoc, transition } = params;+ const view = getEditorView(editor);+ if (!view) return null;+ const resolved = resolveWysiwygLandingTarget(navigation, {+ source: ydoc.getText('source').toString(),+ pmDoc: view.state.doc,+ ydoc,+ resolver: getSharedResolver(),+ });+ if (!resolved) return null;+ const container = findScrollContainer();+ if (!container) return null;+ const target = resolved;+ return startLanding({+ docName,+ container,+ contentColumn: view.dom,+ measureTarget: () => wysiwygTargetMetrics(view, container, target.point),+ placement: 'top',+ intent: 'toggle',+ grade: target.confidence,+ landedMode: 'wysiwyg',+ transition,+ toolbarOffset: TOOLBAR_OVERLAP_PX,+ onDiscardQueuedTarget: () => clearPendingWysiwygNavigation(docName),+ });+}diff --git a/packages/app/src/editor/mode-switch-position-resolver.test.ts b/packages/app/src/editor/mode-switch-position-resolver.test.tsnew file mode 100644index 000000000..ad9cffadb--- /dev/null+++ b/packages/app/src/editor/mode-switch-position-resolver.test.ts@@ -0,0 +1,432 @@+import { MarkdownManager, sharedExtensions, stripFrontmatter } from '@inkeep/open-knowledge-core';+import { getSchema } from '@tiptap/core';+import type { Node as PmNode } from '@tiptap/pm/model';+import { commonmark } from 'commonmark.json';+import * as fc from 'fast-check';+import { describe, expect, test, vi } from 'vitest';+import { comparableChildCount, computeSourceBlocks } from './block-spans.ts';+import {+ type BlockAnchor,+ type CaptureOptions,+ CONFIDENCE_ORDER,+ createApproxResolver,+ type DocSnapshot,+ type ResolvedPosition,+} from './mode-switch-position-resolver.ts';+import { blockRangeToPositions } from './plugins/agent-insert-flash.ts';++const md = new MarkdownManager({ extensions: sharedExtensions });+const schema = getSchema(sharedExtensions);+const resolver = createApproxResolver(md);++/** Narrow a nullable resolver result before using it, without a `!` assertion. */+function present<T>(value: T | null | undefined): T {+ if (value == null) throw new Error('expected a value, got null/undefined');+ return value;+}++/**+ * A both-representations snapshot for a markdown string. The PM doc is built+ * from the frontmatter-stripped body (frontmatter lives in Y.Text, never the PM+ * doc), while `source` stays the full string so full-Y.Text offsets are tested.+ */+function snap(markdown: string): DocSnapshot {+ const { body } = stripFrontmatter(markdown);+ const doc = schema.nodeFromJSON(md.parse(body));+ return { source: markdown, doc };+}++/** PM position just inside top-level block `index`. */+function pmPosOfBlock(doc: PmNode, index: number): number {+ let pos = 0;+ for (let i = 0; i < index; i++) pos += doc.child(i).nodeSize;+ return pos + 1;+}++describe('invalid-MDX resilience', () => {+ // The single positioned parse (`parseToEditorMdast`) throws on structurally invalid+ // MDX — an unclosed or mismatched JSX tag, a common transient state while+ // editing raw source. The plain toggle captures the source anchor+ // synchronously as the mode flips, so a throw here would abort the flip and+ // strand the user in the mode they were leaving. `computeSourceBlocks` is the+ // shared parse chokepoint every consumer routes through, so it must degrade to+ // no-blocks (reproducing the pre-feature no-anchor flip) rather than throw.+ const invalid = 'Intro paragraph.\n\n<Foo>hi</Bar>\n\nMismatched JSX tag above.';++ test('computeSourceBlocks returns no blocks instead of throwing', () => {+ expect(() => computeSourceBlocks(invalid, md)).not.toThrow();+ expect(computeSourceBlocks(invalid, md).blocks).toHaveLength(0);+ });++ test('the degradation leaves a mark, so a parse regression is not silent', () => {+ // No-blocks is indistinguishable from an empty body downstream, and every+ // mode switch would quietly land at the top of the document. The mark is the+ // only thing separating "invalid MDX mid-edit" from a broken parser.+ const marks = vi.spyOn(performance, 'mark').mockImplementation(() => ({}) as PerformanceMark);+ try {+ computeSourceBlocks(invalid, md);+ expect(marks).toHaveBeenCalledWith('ok/block-spans/parse-failed');++ marks.mockClear();+ computeSourceBlocks('# valid\n\nbody', md);+ expect(marks).not.toHaveBeenCalled();+ } finally {+ marks.mockRestore();+ }+ });++ test('captureFromSource degrades to null (no anchor) on invalid MDX', () => {+ expect(() => resolver.captureFromSource(invalid, 0)).not.toThrow();+ expect(resolver.captureFromSource(invalid, 0)).toBeNull();+ });++ test('resolveInSource and resolveInWysiwyg do not throw on invalid source', () => {+ const anchor: BlockAnchor = { blockIndex: 0, kind: 'paragraph', content: 'Intro paragraph.' };+ const { doc } = snap('Intro paragraph.\n\nSecond.');+ expect(() => resolver.resolveInSource(anchor, { source: invalid, doc })).not.toThrow();+ expect(() => resolver.resolveInWysiwyg(anchor, { source: invalid, doc })).not.toThrow();+ });+});++describe('BlockAnchor capture', () => {+ test('captures block index, kind, and content from WYSIWYG', () => {+ const { doc } = snap('# Title\n\nA paragraph.');+ const anchor = resolver.captureFromWysiwyg(doc, pmPosOfBlock(doc, 1));+ expect(anchor).toMatchObject({ blockIndex: 1, kind: 'paragraph', content: 'A paragraph.' });+ });++ test('captures block index, kind, and content from source', () => {+ const source = '# Title\n\nA paragraph.';+ const anchor = resolver.captureFromSource(source, source.indexOf('paragraph'));+ expect(anchor).toMatchObject({ blockIndex: 1, kind: 'paragraph', content: 'A paragraph.' });+ });++ test('normalizes a bullet list to the shared list kind across representations', () => {+ const source = '- one\n- two';+ const { doc } = snap(source);+ const wanchor = resolver.captureFromWysiwyg(doc, pmPosOfBlock(doc, 0));+ const sanchor = resolver.captureFromSource(source, 0);+ expect(wanchor?.kind).toBe('list');+ expect(sanchor?.kind).toBe('list');+ });+});++describe('confidence grades', () => {+ test('grades run exact to clamped, most to least precise', () => {+ expect(CONFIDENCE_ORDER).toEqual(['exact', 'same-type-ordinal', 'ordinal', 'clamped']);+ });++ test('an in-range aligned anchor whose content matches resolves exact', () => {+ const source = '# A\n\nbody\n\n## B';+ const { doc } = snap(source);+ const anchor = present(resolver.captureFromSource(source, source.indexOf('body')));+ expect(resolver.resolveInSource(anchor, { source, doc })?.confidence).toBe('exact');+ });++ test('same ordinal, same kind, different content resolves same-type-ordinal', () => {+ const source = '# A\n\nthe source paragraph';+ const { doc } = snap(source);+ const anchor: BlockAnchor = {+ blockIndex: 1,+ kind: 'paragraph',+ content: 'a different paragraph',+ };+ expect(resolver.resolveInSource(anchor, { source, doc })?.confidence).toBe('same-type-ordinal');+ });++ test('same ordinal, different kind resolves ordinal', () => {+ const source = '# A\n\nparagraph';+ const { doc } = snap(source);+ // Content differs (so not exact) and kind differs (heading vs list).+ const anchor: BlockAnchor = { blockIndex: 0, kind: 'list', content: 'a stale list item' };+ expect(resolver.resolveInSource(anchor, { source, doc })?.confidence).toBe('ordinal');+ });++ test('an out-of-range ordinal clamps to the nearest block', () => {+ const source = '# A\n\nonly two blocks';+ const { doc } = snap(source);+ const anchor: BlockAnchor = { blockIndex: 9, kind: 'paragraph', content: 'gone' };+ const resolved = present(resolver.resolveInSource(anchor, { source, doc }));+ expect(resolved.confidence).toBe('clamped');+ // Clamped lands on the last block, never off the end of the document.+ expect(resolved.blockStart).toBeLessThanOrEqual(source.length);+ expect(resolved.blockStart).toBe(source.indexOf('only two blocks'));+ });+});++describe('count tripwire', () => {+ test('a ProseMirror/mdast block-count mismatch degrades the grade and never reports exact', () => {+ // Source has three paragraphs; the PM doc is built from a two-paragraph+ // version, so the top-level counts disagree.+ const source = 'para zero\n\npara one\n\npara two';+ const { doc } = snap('para zero\n\npara one');+ const anchor = present(resolver.captureFromSource(source, source.indexOf('para one')));+ // The anchor content matches the source block at that ordinal, yet the+ // mismatch caps the grade below exact.+ expect(anchor.content).toBe('para one');+ expect(resolver.resolveInSource(anchor, { source, doc })?.confidence).toBe('ordinal');+ });++ test('the tripwire reads the comparable ProseMirror child count, not a children.length', () => {+ // A heading-final doc renders with a trailing empty "type here" paragraph+ // that has no source counterpart: mdast sees N blocks, the live PM doc N+1.+ const source = '# A\n\nbody\n\n## Tail';+ const baseJson = md.parse('# A\n\nbody\n\n## Tail') as { type: string; content: unknown[] };+ const affordanceDoc = schema.nodeFromJSON({+ ...baseJson,+ content: [...baseJson.content, { type: 'paragraph' }],+ });+ const mdastCount = computeSourceBlocks(source, md).blocks.length;++ // The comparable count subtracts the affordance paragraph and aligns with+ // mdast; the raw child count is one higher and would report a false mismatch.+ expect(comparableChildCount(affordanceDoc)).toBe(mdastCount);+ expect(affordanceDoc.childCount).toBe(mdastCount + 1);+ // A resolver that read the raw `children.length` (as if the PM node were an+ // mdast root) counts the affordance paragraph too, so it would mis-compare+ // against mdast's count on every heading-final doc.+ expect(affordanceDoc.children.length).toBe(mdastCount + 1);++ // With the comparable count the landing is trusted (exact); the raw count+ // would have degraded it.+ const anchor = present(+ resolver.captureFromWysiwyg(affordanceDoc, pmPosOfBlock(affordanceDoc, 0)),+ );+ expect(resolver.resolveInSource(anchor, { source, doc: affordanceDoc })?.confidence).toBe(+ 'exact',+ );+ expect(affordanceDoc.childCount === mdastCount).toBe(false);+ });+});++describe('content-equality gating', () => {+ test('a content match refines the landing inline at exact confidence', () => {+ const source = '# A\n\nthe target paragraph';+ const { doc } = snap(source);+ const jumpOpts: CaptureOptions = { refine: true };+ const anchor = present(resolver.captureFromSource(source, source.indexOf('target'), jumpOpts));+ const resolved: ResolvedPosition = present(resolver.resolveInSource(anchor, { source, doc }));+ expect(resolved.confidence).toBe('exact');+ // The refined point sits past the block start (at the captured selection).+ expect(resolved.point).toBeGreaterThan(resolved.blockStart);+ expect(resolved.point).toBe(source.indexOf('target'));+ });++ test('a content mismatch lands at block start rather than an inline position', () => {+ const source = '# A\n\nthe source paragraph';+ const { doc } = snap(source);+ const anchor: BlockAnchor = {+ blockIndex: 1,+ kind: 'paragraph',+ content: 'a stale captured paragraph',+ selectionInBlock: 8,+ };+ const resolved = present(resolver.resolveInSource(anchor, { source, doc }));+ expect(resolved.confidence).not.toBe('exact');+ expect(resolved.point).toBe(resolved.blockStart);+ });+});++describe('offset normalization', () => {+ test('source offsets crossing the boundary include the frontmatter region', () => {+ const source = '---\ntitle: Doc\n---\n\n# Heading\n\nBody paragraph\n';+ const { doc } = snap(source);+ const anchor = present(resolver.captureFromSource(source, source.indexOf('Body paragraph')));+ const resolved = present(resolver.resolveInSource(anchor, { source, doc }));+ // The landed offset is a full-source offset, past the frontmatter fence.+ expect(resolved.blockStart).toBe(source.indexOf('Body paragraph'));+ expect(resolved.blockStart).toBeGreaterThan(source.indexOf('---'));+ });++ test('an offset inside the frontmatter maps to the top of the body', () => {+ const source = '---\ntitle: Doc\n---\n\n# Heading\n\nBody\n';+ const anchor = resolver.captureFromSource(source, source.indexOf('title'));+ expect(anchor?.blockIndex).toBe(0);+ });++ test('a WYSIWYG landing returns ProseMirror positions', () => {+ const source = '# Heading\n\nBody paragraph';+ const { doc } = snap(source);+ const anchor = present(resolver.captureFromSource(source, source.indexOf('Body')));+ const resolved = present(resolver.resolveInWysiwyg(anchor, { source, doc }));+ const expected = present(blockRangeToPositions(doc, 1, 2));+ expect(resolved.blockStart).toBe(expected.from);+ });+});++describe('no-anchor and purity', () => {+ test('capturing from an empty source yields no anchor', () => {+ expect(resolver.captureFromSource('', 0)).toBeNull();+ });++ test('resolving into a body-empty document yields no anchor', () => {+ const { doc } = snap('');+ const anchor: BlockAnchor = { blockIndex: 0, kind: 'paragraph', content: 'x' };+ expect(resolver.resolveInWysiwyg(anchor, { source: '', doc })).toBeNull();+ });++ test('resolving does not mutate the document snapshot', () => {+ const source = '# A\n\nbody';+ const { doc } = snap(source);+ const before = { count: doc.childCount, text: doc.textContent, size: doc.content.size };+ const anchor = present(resolver.captureFromWysiwyg(doc, pmPosOfBlock(doc, 1)));+ resolver.resolveInSource(anchor, { source, doc });+ resolver.resolveInWysiwyg(anchor, { source, doc });+ expect({ count: doc.childCount, text: doc.textContent, size: doc.content.size }).toEqual(+ before,+ );+ });+});++describe('per-source parse reuse', () => {+ /**+ * A resolver over a `MarkdownManager` that counts the positioned parses. The+ * count is the cost being pinned: one mode switch drives three of the four+ * methods over the same source inside one synchronous frame, and a parse per+ * call puts three or four full mdast builds on the main thread before the+ * landing's first dispatch.+ */+ function countingResolver() {+ let parses = 0;+ const counting = Object.create(md) as MarkdownManager;+ counting.parseToEditorMdast = (input: string) => {+ parses += 1;+ return md.parseToEditorMdast(input);+ };+ return { resolver: createApproxResolver(counting), parses: () => parses };+ }++ test('one mode switch over one source parses it once', () => {+ const source = '# A\n\nfirst\n\n## B\n\nsecond';+ const { doc } = snap(source);+ const counted = countingResolver();++ // The source-to-WYSIWYG shape: capture the topmost block, derive its source+ // range for the pin, re-anchor off the pin, then resolve into the PM doc.+ const anchor = present(counted.resolver.captureFromSource(source, 0));+ counted.resolver.resolveInSource(anchor, { source, doc });+ const reAnchored = present(counted.resolver.captureFromSource(source, 0));+ counted.resolver.resolveInWysiwyg(reAnchored, { source, doc });++ expect(counted.parses()).toBe(1);+ });++ test('a changed source is re-parsed, never served from the previous one', () => {+ const before = '# A\n\nfirst';+ const after = '# A\n\nfirst\n\n## B\n\nsecond';+ const counted = countingResolver();++ counted.resolver.captureFromSource(before, 0);+ expect(counted.parses()).toBe(1);++ // The last block of the edited source only exists in the new parse, so a+ // stale entry could not answer this.+ const anchor = present(counted.resolver.captureFromSource(after, after.indexOf('second')));+ expect(anchor.content).toBe('second');+ expect(counted.parses()).toBe(2);++ // Reverting the source is an ordinary key change, not a cache hit.+ counted.resolver.captureFromSource(before, 0);+ expect(counted.parses()).toBe(3);+ });+});++describe('cross-mode consistency', () => {+ const docs = [+ '# A\n\nfirst\n\n## B\n\nsecond',+ '- one\n- two\n\nafter list',+ 'intro\n\n```js\ncode()\n```\n\noutro',+ ];++ test.each(docs)('every block round-trips WYSIWYG to source and back (%#)', (source) => {+ const { doc } = snap(source);+ const blockCount = computeSourceBlocks(source, md).blocks.length;+ for (let b = 0; b < blockCount; b++) {+ const fromWysiwyg = present(resolver.captureFromWysiwyg(doc, pmPosOfBlock(doc, b)));+ const inSource = present(resolver.resolveInSource(fromWysiwyg, { source, doc }));+ expect(inSource.confidence).toBe('exact');+ // Re-capturing at the landed source offset yields the same ordinal.+ expect(resolver.captureFromSource(source, inSource.blockStart)?.blockIndex).toBe(b);++ const fromSource = present(resolver.captureFromSource(source, inSource.blockStart));+ const inWysiwyg = present(resolver.resolveInWysiwyg(fromSource, { source, doc }));+ expect(inWysiwyg.confidence).toBe('exact');+ expect(resolver.captureFromWysiwyg(doc, inWysiwyg.point + 1)?.blockIndex).toBe(b);+ }+ });+});++function alignedCorpus(): string[] {+ const examples: string[] = [];+ for (const ex of commonmark) {+ try {+ const { blocks } = computeSourceBlocks(ex.markdown, md);+ if (blocks.length === 0) continue;+ if (comparableChildCount(snap(ex.markdown).doc) === blocks.length) examples.push(ex.markdown);+ } catch {+ // Examples the PM parse can't round-trip aren't valid inputs to the+ // ordinal bridge; they're covered by the corpus contract's breaker set.+ }+ }+ return examples;+}++describe('fidelity corpus', () => {+ test('resolving a derived source anchor returns its originating block', () => {+ const examples = alignedCorpus();+ expect(examples.length).toBeGreaterThan(50);+ fc.assert(+ fc.property(fc.constantFrom(...examples), fc.nat(), (markdown, n) => {+ const { doc } = snap(markdown);+ const offset = n % (markdown.length + 1);+ const derived = resolver.captureFromSource(markdown, offset);+ if (derived === null) return true;+ const resolved = resolver.resolveInSource(derived, { source: markdown, doc });+ if (resolved === null) return false;+ const reCaptured = resolver.captureFromSource(markdown, resolved.blockStart);+ return (+ reCaptured !== null &&+ reCaptured.blockIndex === derived.blockIndex &&+ resolved.confidence === 'exact'+ );+ }),+ { numRuns: 300, seed: 4242 },+ );+ });++ test('parse-time block counts align across the whole corpus', () => {+ let aligned = 0;+ const breakers: string[] = [];+ for (const ex of commonmark) {+ let pm: number;+ let mdast: number;+ try {+ pm = comparableChildCount(snap(ex.markdown).doc);+ mdast = computeSourceBlocks(ex.markdown, md).blocks.length;+ } catch {+ continue;+ }+ if (pm === mdast) aligned++;+ else breakers.push(`${ex.section}: pm=${pm} mdast=${mdast}`);+ }+ // The parse-time bridge keeps the ordinal mapping 1:1 for every corpus+ // document. The constructs that DO misalign are runtime states — the live+ // trailing-paragraph affordance and a mid-edit divergence between the two+ // representations — enumerated in the count-tripwire suite above.+ expect(aligned).toBeGreaterThan(200);+ expect(breakers).toEqual([]);+ });++ const alignedConstructs = [+ { name: 'headings and paragraphs', src: '# A\n\npara\n\n## B\n\nmore' },+ { name: 'bullet list', src: '- one\n- two\n- three' },+ { name: 'ordered list', src: '1. one\n2. two' },+ { name: 'fenced code', src: '```js\ncode\n```' },+ { name: 'blockquote', src: '> quote' },+ { name: 'thematic break', src: 'a\n\n---\n\nb' },+ ];++ test.each(alignedConstructs)('block counts align for $name', ({ src }) => {+ expect(comparableChildCount(snap(src).doc)).toBe(computeSourceBlocks(src, md).blocks.length);+ });+});diff --git a/packages/app/src/editor/mode-switch-position-resolver.ts b/packages/app/src/editor/mode-switch-position-resolver.tsnew file mode 100644index 000000000..e99c6e9a2--- /dev/null+++ b/packages/app/src/editor/mode-switch-position-resolver.ts@@ -0,0 +1,272 @@+/**+ * Cross-representation position mapping for mode switches.+ *+ * The editor renders one document through two representations — a ProseMirror+ * doc (WYSIWYG) and a `Y.Text('source')` string (frontmatter + body). A mode+ * switch must carry the user's place from one to the other, but the two use+ * different coordinate spaces and both report virtualization-estimated geometry,+ * so raw scroll position is meaningless across the flip.+ *+ * This module is the single chokepoint for that mapping: it turns a captured+ * top-level-block anchor into a resolved position in the other representation,+ * with a graded confidence, holding no document reference and performing no+ * writes. Everything it does is a pure function of the snapshots the caller+ * supplies at resolve time, so the whole feature's coordinate logic stays behind+ * this one interface — a future byte-accurate map can reimplement the two+ * methods without touching any consumer. Block-level granularity is deliberate:+ * ordinals are virtualization-independent where a pixel-proportional mapping is+ * not, and they need no per-node source-byte map to compute.+ */++import type { MarkdownManager } from '@inkeep/open-knowledge-core';+import type { Node as PmNode } from '@tiptap/pm/model';+import {+ blockIndexForLine,+ blockRangeToPositions,+ canonicalBlockKind,+ comparableChildCount,+ computeSourceBlocks,+ lineStartOffsets,+ lineToOffset,+ offsetToLine,+ type SourceBlock,+} from './block-spans';++/**+ * How much the resolver trusts a landing, most to least precise. `exact` is the+ * only grade at which an inline (within-block) refinement is trustworthy;+ * `clamped` means the block ordinal fell outside the target and the landing was+ * pulled to the nearest block, so the caller suppresses the highlight there.+ */+export type ResolveConfidence = 'exact' | 'same-type-ordinal' | 'ordinal' | 'clamped';++export const CONFIDENCE_ORDER = [+ 'exact',+ 'same-type-ordinal',+ 'ordinal',+ 'clamped',+] as const satisfies readonly ResolveConfidence[];++/**+ * A representation-neutral handle on a top-level block. The ordinal is the+ * primary key (blocks line up 1:1 across representations while the count+ * tripwire holds); `kind` and `content` let a resolve verify it landed on the+ * same thing and downgrade honestly when it did not.+ */+export interface BlockAnchor {+ /** 0-based index of the top-level block in the representation it was captured from. */+ blockIndex: number;+ /** Canonical block kind (see `canonicalBlockKind`). */+ kind: string;+ /** Block text content (markdown syntax stripped). */+ content: string;+ /**+ * Characters into the block from its start, in the capturing representation's+ * terms, for an explicit jump. Absent for a plain toggle, which is scroll-only.+ */+ selectionInBlock?: number;+}++/**+ * A resolved landing in the target coordinate space — full `Y.Text` char offsets+ * for a source landing, ProseMirror positions for a WYSIWYG landing.+ */+export interface ResolvedPosition {+ /** Start of the landed block. */+ blockStart: number;+ /** End of the landed block. */+ blockEnd: number;+ /** Landing point: the block start unless an `exact` grade refined it inline. */+ point: number;+ confidence: ResolveConfidence;+}++/**+ * The live document in both representations. The count tripwire is inherently+ * cross-representation, so every resolve needs both halves even though it only+ * lands in one. `source` is the full `Y.Text('source')` string including the+ * frontmatter region; `doc` is a read-only ProseMirror doc snapshot.+ */+export interface DocSnapshot {+ source: string;+ doc: PmNode;+}++/** Whether a capture should record an inline selection offset (jumps only). */+export interface CaptureOptions {+ refine?: boolean;+}++/**+ * Turns a block anchor captured in one representation into a graded position in+ * the other. `null` from a capture or resolve means "no anchor" — the caller+ * does nothing, reproducing the pre-feature behavior of leaving scroll where it+ * is. All source offsets crossing this boundary are full `Y.Text` offsets with+ * the frontmatter region included; PM positions cross as ProseMirror positions.+ */+export interface ModeSwitchPositionResolver {+ captureFromWysiwyg(doc: PmNode, pos: number, opts?: CaptureOptions): BlockAnchor | null;+ captureFromSource(source: string, fullOffset: number, opts?: CaptureOptions): BlockAnchor | null;+ resolveInSource(anchor: BlockAnchor, snapshot: DocSnapshot): ResolvedPosition | null;+ resolveInWysiwyg(anchor: BlockAnchor, snapshot: DocSnapshot): ResolvedPosition | null;+}++function clamp(value: number, lo: number, hi: number): number {+ return Math.max(lo, Math.min(value, hi));+}++/**+ * Whitespace-normalized text equality. Soft breaks and blank-line runs serialize+ * differently across the two representations, so a run-collapsing compare keeps+ * genuinely-identical blocks matching; erring toward a match only ever enables an+ * approximate inline refinement, never a wrong-block landing.+ */+function contentEquals(a: string, b: string): boolean {+ const norm = (s: string) => s.replace(/\s+/g, ' ').trim();+ return norm(a) === norm(b);+}++/**+ * The grade ladder. A count mismatch (the mandatory tripwire) or an+ * out-of-range ordinal caps the grade below `exact` so a structurally+ * untrustworthy ordinal never claims inline precision.+ */+function gradeFor(+ anchor: BlockAnchor,+ target: { inRange: boolean; tripwireOk: boolean; kind: string; text: string },+): ResolveConfidence {+ if (!target.inRange) return 'clamped';+ if (!target.tripwireOk) return 'ordinal';+ if (contentEquals(anchor.content, target.text)) return 'exact';+ if (anchor.kind === target.kind) return 'same-type-ordinal';+ return 'ordinal';+}++/** The per-source derivations three of the four methods below need. */+interface SourceIndex {+ blocks: SourceBlock[];+ lineStarts: number[];+}++/**+ * The default approximate resolver: ordinal capture, one positioned parse of the+ * live source at resolve time, content-equality verification, and a clamp as the+ * last resort. Small and side-effect-free by design so a byte-accurate+ * implementation can replace it behind the interface.+ */+export function createApproxResolver(md: MarkdownManager): ModeSwitchPositionResolver {+ // One mode switch calls three of the four methods below on the SAME source+ // string inside a single synchronous frame — capture, resolve, then a pin+ // re-anchor — so parsing per call means three or four full mdast parses over+ // identical bytes before the landing gets its first dispatch, all of it on the+ // main thread and all of it inside the window the settle contract exists to+ // keep short. Memoizing on the string itself keeps the derivation a pure+ // function of the snapshot: a single entry suffices because the calls are+ // consecutive, and any edit or later toggle changes the key, which both+ // invalidates the entry and releases the string it held.+ let indexedSource: string | null = null;+ let index: SourceIndex | null = null;++ function indexOf(source: string): SourceIndex {+ if (index !== null && indexedSource === source) return index;+ index = {+ blocks: computeSourceBlocks(source, md).blocks,+ lineStarts: lineStartOffsets(source),+ };+ indexedSource = source;+ return index;+ }++ return {+ captureFromWysiwyg(doc, pos, opts) {+ if (doc.childCount === 0) return null;+ const p = clamp(pos, 0, doc.content.size);+ let acc = 0;+ let blockIndex = doc.childCount - 1;+ let blockContentStart = 0;+ for (let i = 0; i < doc.childCount; i++) {+ const size = doc.child(i).nodeSize;+ if (p < acc + size) {+ blockIndex = i;+ blockContentStart = acc + 1;+ break;+ }+ acc += size;+ blockContentStart = acc + 1;+ }+ const node = doc.child(blockIndex);+ const anchor: BlockAnchor = {+ blockIndex,+ kind: canonicalBlockKind(node.type.name),+ content: node.textContent,+ };+ if (opts?.refine) anchor.selectionInBlock = Math.max(0, p - blockContentStart);+ return anchor;+ },++ captureFromSource(source, fullOffset, opts) {+ const { blocks, lineStarts: offsets } = indexOf(source);+ if (blocks.length === 0) return null;+ const offset = clamp(fullOffset, 0, source.length);+ const line = offsetToLine(offsets, offset);+ // Shared block-offset-table search: a frontmatter-region line maps to the+ // first body block (there is no block above it), so a viewport parked in+ // the FM region lands at the top of the body rather than a false match.+ const blockIndex = blockIndexForLine(blocks, line);+ if (blockIndex === null) return null;+ const block = blocks[blockIndex];+ if (!block) return null;+ const anchor: BlockAnchor = {+ blockIndex,+ kind: block.kind,+ content: block.text,+ };+ if (opts?.refine) {+ const blockStart = lineToOffset(offsets, block.start, source.length);+ anchor.selectionInBlock = Math.max(0, offset - blockStart);+ }+ return anchor;+ },++ resolveInSource(anchor, { source, doc }) {+ const { blocks, lineStarts: offsets } = indexOf(source);+ if (blocks.length === 0) return null;+ const inRange = anchor.blockIndex >= 0 && anchor.blockIndex < blocks.length;+ const tripwireOk = comparableChildCount(doc) === blocks.length;+ const idx = clamp(anchor.blockIndex, 0, blocks.length - 1);+ const block = blocks[idx];+ const blockStart = lineToOffset(offsets, block.start, source.length);+ const blockEnd = Math.min(lineToOffset(offsets, block.end + 1, source.length), source.length);+ const confidence = gradeFor(anchor, {+ inRange,+ tripwireOk,+ kind: block.kind,+ text: block.text,+ });+ let point = blockStart;+ if (confidence === 'exact' && anchor.selectionInBlock !== undefined) {+ point = clamp(blockStart + anchor.selectionInBlock, blockStart, blockEnd);+ }+ return { blockStart, blockEnd, point, confidence };+ },++ resolveInWysiwyg(anchor, { source, doc }) {+ const count = comparableChildCount(doc);+ if (count === 0) return null;+ const { blocks } = indexOf(source);+ const inRange = anchor.blockIndex >= 0 && anchor.blockIndex < count;+ const tripwireOk = count === blocks.length;+ const idx = clamp(anchor.blockIndex, 0, count - 1);+ const range = blockRangeToPositions(doc, idx, idx + 1);+ if (range === null) return null;+ const node = doc.child(idx);+ const confidence = gradeFor(anchor, {+ inRange,+ tripwireOk,+ kind: canonicalBlockKind(node.type.name),+ text: node.textContent,+ });+ return { blockStart: range.from, blockEnd: range.to, point: range.from, confidence };+ },+ };+}diff --git a/packages/app/src/editor/plugins/agent-insert-flash.ts b/packages/app/src/editor/plugins/agent-insert-flash.tsindex 3440231c5..b55383d53 100644--- a/packages/app/src/editor/plugins/agent-insert-flash.ts+++ b/packages/app/src/editor/plugins/agent-insert-flash.ts@@ -75,37 +75,12 @@ export function computeChangedRange(*/export const AGENT_INSERT_FLASH_ACTIVATION_MS = 6_000;-/**- * Map a top-level block-index range `[fromBlock, toBlock)` to a ProseMirror- * position range in `doc`, or null when empty / out of bounds.- *- * The activation-replay counterpart to `computeChangedRange`: the write has- * already applied, so there is no transaction to diff — the server stamped the- * changed block indices instead. They address PM top-level nodes directly- * (y-prosemirror mirrors the XmlFragment's children onto the PM doc), so the- * PM range is the span from the boundary before the first changed block to the- * boundary after the last.- */-export function blockRangeToPositions(- doc: PMNode,- fromBlock: number,- toBlock: number,-): { from: number; to: number } | null {- const childCount = doc.childCount;- const first = Math.max(0, Math.min(fromBlock, childCount));- const last = Math.max(first, Math.min(toBlock, childCount));- if (last <= first) return null;- let pos = 0;- for (let i = 0; i < first; i++) pos += doc.child(i).nodeSize;- const from = pos;- for (let i = first; i < last; i++) pos += doc.child(i).nodeSize;- const to = pos;- const size = doc.content.size;- const clampedFrom = Math.max(0, Math.min(from, size));- const clampedTo = Math.max(clampedFrom, Math.min(to, size));- if (clampedTo <= clampedFrom) return null;- return { from: clampedFrom, to: clampedTo };-}+// `blockRangeToPositions` lives in block-spans (the block-ordinal coordinate+// substrate) so the mode-switch resolver can reach it without importing this+// decoration plugin's module graph. Re-exported here for the agent-flash+// activation-replay path, which maps server-stamped block indices to a PM range+// as the counterpart to `computeChangedRange` above.+export { blockRangeToPositions } from '../block-spans';export function createAgentInsertFlashPlugin(): Plugin<DecorationSet> {return new Plugin<DecorationSet>({diff --git a/packages/app/src/editor/plugins/landing-flash-shared.test.ts b/packages/app/src/editor/plugins/landing-flash-shared.test.tsnew file mode 100644index 000000000..7c2e942d0--- /dev/null+++ b/packages/app/src/editor/plugins/landing-flash-shared.test.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from 'vitest';+import { clampFlashRange } from './landing-flash-shared';++describe('clampFlashRange', () => {+ test('admits a range at a precise grade', () => {+ expect(clampFlashRange(100, 10, 20, 'exact')).toEqual({ from: 10, to: 20 });+ expect(clampFlashRange(100, 10, 20, 'same-type-ordinal')).toEqual({ from: 10, to: 20 });+ expect(clampFlashRange(100, 10, 20, 'ordinal')).toEqual({ from: 10, to: 20 });+ });++ test('refuses the flash at a clamped grade', () => {+ // A clamped landing could not place the target, so a flash there would+ // assert a precision the landing does not have.+ expect(clampFlashRange(100, 10, 20, 'clamped')).toBeNull();+ });++ test('clamps a range that runs past the document end', () => {+ expect(clampFlashRange(15, 10, 9999, 'exact')).toEqual({ from: 10, to: 15 });+ });++ test('clamps a negative start to zero', () => {+ expect(clampFlashRange(100, -5, 20, 'exact')).toEqual({ from: 0, to: 20 });+ });++ test('refuses an empty range', () => {+ expect(clampFlashRange(100, 20, 20, 'exact')).toBeNull();+ expect(clampFlashRange(100, 20, 10, 'exact')).toBeNull();+ });++ test('refuses a range wholly past the document end', () => {+ // start clamps to the end, collapsing the range.+ expect(clampFlashRange(15, 40, 60, 'exact')).toBeNull();+ });+});diff --git a/packages/app/src/editor/plugins/landing-flash-shared.ts b/packages/app/src/editor/plugins/landing-flash-shared.tsnew file mode 100644index 000000000..3f32a9935--- /dev/null+++ b/packages/app/src/editor/plugins/landing-flash-shared.ts@@ -0,0 +1,36 @@+/**+ * Shared pieces of the landing flash — the transient highlight a mode-switch+ * jump paints on the range it landed on, in whichever editor received the+ * landing. The CodeMirror (source) and ProseMirror (WYSIWYG) halves are+ * independent decoration systems, so they share only this leaf: the class both+ * decorate with, and the range-admission rule both apply before dispatching.+ *+ * The class is distinct from the agent-write flash classes so its treatment can+ * diverge from the agent wash later without touching attribution; both halves+ * decorate an inline range, so a single CSS rule styles both.+ */++import type { ResolveConfidence } from '../mode-switch-position-resolver';++export const OK_LANDING_FLASH_CLASS = 'ok-landing-flash';++/**+ * Admit a landing range for a flash, or refuse it. A `clamped` grade means the+ * resolver could not place the target and fell back to a best-effort scroll, so+ * flashing there would assert a precision the landing does not have — refuse it.+ * The range is clamped to `[0, length]`; a range that collapses to empty after+ * clamping (or that arrives empty) is refused because an inline decoration over+ * a zero-width range has nothing to paint.+ */+export function clampFlashRange(+ length: number,+ from: number,+ to: number,+ grade: ResolveConfidence,+): { from: number; to: number } | null {+ if (grade === 'clamped') return null;+ const start = Math.max(0, Math.min(from, length));+ const end = Math.max(start, Math.min(to, length));+ if (end <= start) return null;+ return { from: start, to: end };+}diff --git a/packages/app/src/editor/plugins/landing-flash-source.test.ts b/packages/app/src/editor/plugins/landing-flash-source.test.tsnew file mode 100644index 000000000..2d3c36e97--- /dev/null+++ b/packages/app/src/editor/plugins/landing-flash-source.test.ts@@ -0,0 +1,136 @@+// @vitest-environment jsdom+import { EditorState, type TransactionSpec } from '@codemirror/state';+import { type DecorationSet, EditorView } from '@codemirror/view';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { FLASH_DURATION_MS } from './flash-shared';+import { OK_LANDING_FLASH_CLASS } from './landing-flash-shared';+import { flashSourceLanding, landingFlashField, landingFlashSource } from './landing-flash-source';++/**+ * A minimal EditorView surface backed by a real EditorState, so the real field+ * reducer runs on every dispatch. The flash trigger only reaches `state` and+ * `dispatch`, and the removal timer keys off the view object (a valid WeakMap+ * key), so this exercises the production path without a live DOM view.+ */+function drivenView(doc: string, selection?: { anchor: number; head?: number }) {+ let state = EditorState.create({+ doc,+ selection: selection+ ? { anchor: selection.anchor, head: selection.head ?? selection.anchor }+ : undefined,+ extensions: [landingFlashField],+ });+ const view = {+ get state() {+ return state;+ },+ dispatch(spec: TransactionSpec) {+ state = state.update(spec).state;+ },+ };+ return { view: view as unknown as EditorView, getState: () => state };+}++function ranges(set: DecorationSet): Array<{ from: number; to: number }> {+ const out: Array<{ from: number; to: number }> = [];+ const cursor = set.iter();+ while (cursor.value) {+ out.push({ from: cursor.from, to: cursor.to });+ cursor.next();+ }+ return out;+}++afterEach(() => {+ vi.useRealTimers();+});++describe('landing flash — source', () => {+ test('flashes the landed range at a precise grade', () => {+ const { view, getState } = drivenView('alpha\nbeta\ngamma');+ flashSourceLanding(view, 0, 5, 'exact');+ expect(ranges(getState().field(landingFlashField))).toEqual([{ from: 0, to: 5 }]);+ });++ test('suppresses the flash at a clamped grade', () => {+ const { view, getState } = drivenView('alpha\nbeta\ngamma');+ flashSourceLanding(view, 0, 5, 'clamped');+ expect(getState().field(landingFlashField).size).toBe(0);+ });++ test('clears the flash after the shared duration', () => {+ vi.useFakeTimers();+ const { view, getState } = drivenView('alpha\nbeta\ngamma');+ flashSourceLanding(view, 0, 5, 'exact');+ expect(getState().field(landingFlashField).size).toBe(1);+ vi.advanceTimersByTime(FLASH_DURATION_MS);+ expect(getState().field(landingFlashField).size).toBe(0);+ });++ test('maps the flash through a later document change', () => {+ const { view, getState } = drivenView('alpha\nbeta\ngamma');+ flashSourceLanding(view, 6, 10, 'exact');+ view.dispatch({ changes: { from: 0, insert: 'XX' } });+ expect(ranges(getState().field(landingFlashField))).toEqual([{ from: 8, to: 12 }]);+ });++ test('never changes the selection', () => {+ const { view, getState } = drivenView('alpha\nbeta\ngamma', { anchor: 3 });+ const before = getState().selection.main;+ flashSourceLanding(view, 6, 10, 'exact');+ const after = getState().selection.main;+ expect(after.anchor).toBe(before.anchor);+ expect(after.head).toBe(before.head);+ });++ test('clamps an out-of-range target to the document', () => {+ const { view, getState } = drivenView('alpha\nbeta\ngamma');+ flashSourceLanding(view, 0, 99999, 'exact');+ const [range] = ranges(getState().field(landingFlashField));+ expect(range?.to).toBe(getState().doc.length);+ });++ test('a superseding landing replaces the prior flash', () => {+ const { view, getState } = drivenView('alpha\nbeta\ngamma');+ flashSourceLanding(view, 0, 5, 'exact');+ flashSourceLanding(view, 6, 10, 'exact');+ expect(ranges(getState().field(landingFlashField))).toEqual([{ from: 6, to: 10 }]);+ });++ test('landingFlashSource wires the field into a state', () => {+ const state = EditorState.create({ doc: 'x', extensions: [landingFlashSource()] });+ expect(state.field(landingFlashField).size).toBe(0);+ });++ test('paints the shared landing-flash class onto the landed range in the DOM', () => {+ // Decoration ranges alone do not prove the highlight is visible: the class+ // is the contract with the stylesheet, so it is asserted on a real mounted+ // view rather than on the field's state.+ const view = new EditorView({+ state: EditorState.create({ doc: 'alpha\nbeta\ngamma', extensions: [landingFlashSource()] }),+ parent: document.body,+ });+ try {+ flashSourceLanding(view, 0, 5, 'exact');+ expect(view.dom.querySelector(`.${OK_LANDING_FLASH_CLASS}`)?.textContent).toBe('alpha');+ } finally {+ view.destroy();+ }+ });++ test('removes the flashed class from the DOM after the shared duration', () => {+ vi.useFakeTimers();+ const view = new EditorView({+ state: EditorState.create({ doc: 'alpha\nbeta\ngamma', extensions: [landingFlashSource()] }),+ parent: document.body,+ });+ try {+ flashSourceLanding(view, 0, 5, 'exact');+ expect(view.dom.querySelector(`.${OK_LANDING_FLASH_CLASS}`)).not.toBeNull();+ vi.advanceTimersByTime(FLASH_DURATION_MS);+ expect(view.dom.querySelector(`.${OK_LANDING_FLASH_CLASS}`)).toBeNull();+ } finally {+ view.destroy();+ }+ });+});diff --git a/packages/app/src/editor/plugins/landing-flash-source.ts b/packages/app/src/editor/plugins/landing-flash-source.tsnew file mode 100644index 000000000..9b3d815e8--- /dev/null+++ b/packages/app/src/editor/plugins/landing-flash-source.ts@@ -0,0 +1,90 @@+/**+ * Landing flash — Source (CodeMirror).+ *+ * A mark decoration over the range a mode-switch jump landed on, cleared after+ * one shared flash duration. Sibling to the agent-write flash, not an extension+ * of it: this fires on an explicit "view in source" landing, carries its own+ * lifetime, and reuses none of the agent-flash Y.Map observation.+ *+ * The removal timer lives on the view, not on a decoration timestamp, because+ * there is only ever one landing flash at a time (a new landing supersedes any+ * prior). The caller starts the flash once the landed range is on screen, so the+ * expiry clock measures visible time rather than dispatch-to-visible latency.+ *+ * Decoration-only: it never moves the selection or focus, so a plain toggle that+ * does not flash is unaffected and a jump's caret placement stays the caller's.+ */++import { type Extension, StateEffect, StateField } from '@codemirror/state';+import { Decoration, type DecorationSet, EditorView, ViewPlugin } from '@codemirror/view';+import type { ResolveConfidence } from '../mode-switch-position-resolver';+import { FLASH_DURATION_MS } from './flash-shared';+import { clampFlashRange, OK_LANDING_FLASH_CLASS } from './landing-flash-shared';++const addLandingFlash = StateEffect.define<{ from: number; to: number }>();+const removeLandingFlash = StateEffect.define<null>();++const landingMark = Decoration.mark({ class: OK_LANDING_FLASH_CLASS });++/** Exposed so tests can read the live decoration set from a driven state. */+export const landingFlashField = StateField.define<DecorationSet>({+ create() {+ return Decoration.none;+ },+ update(decorations, tr) {+ let next = decorations.map(tr.changes);+ for (const effect of tr.effects) {+ // A new landing replaces the prior flash rather than layering on it.+ if (effect.is(addLandingFlash)) {+ next = Decoration.set([landingMark.range(effect.value.from, effect.value.to)]);+ } else if (effect.is(removeLandingFlash)) {+ next = Decoration.none;+ }+ }+ return next;+ },+ provide: (field) => EditorView.decorations.from(field),+});++// Per-view removal timers. The cleanup plugin below cancels the pending timer on+// view teardown so it can never dispatch onto a destroyed view (which throws).+const removalTimers = new WeakMap<EditorView, ReturnType<typeof setTimeout>>();++const landingFlashCleanup = ViewPlugin.define((view) => ({+ destroy() {+ const timer = removalTimers.get(view);+ if (timer !== undefined) {+ clearTimeout(timer);+ removalTimers.delete(view);+ }+ },+}));++/**+ * Flash the landed range and schedule its removal. A `clamped` grade suppresses+ * the flash (see `clampFlashRange`). Call this when the range is on screen; the+ * expiry timer starts here.+ */+export function flashSourceLanding(+ view: EditorView,+ from: number,+ to: number,+ grade: ResolveConfidence,+): void {+ const range = clampFlashRange(view.state.doc.length, from, to, grade);+ if (!range) return;+ view.dispatch({ effects: addLandingFlash.of(range) });++ const prior = removalTimers.get(view);+ if (prior !== undefined) clearTimeout(prior);+ const timer = setTimeout(() => {+ removalTimers.delete(view);+ view.dispatch({ effects: removeLandingFlash.of(null) });+ }, FLASH_DURATION_MS);+ removalTimers.set(view, timer);+}++/** The field plus its teardown-cleanup plugin, for a full-page source editor. */+export function landingFlashSource(): Extension {+ return [landingFlashField, landingFlashCleanup];+}diff --git a/packages/app/src/editor/plugins/landing-flash-wysiwyg.test.ts b/packages/app/src/editor/plugins/landing-flash-wysiwyg.test.tsnew file mode 100644index 000000000..a252c70a0--- /dev/null+++ b/packages/app/src/editor/plugins/landing-flash-wysiwyg.test.ts@@ -0,0 +1,162 @@+// @vitest-environment jsdom+import { Schema } from '@tiptap/pm/model';+import { EditorState, TextSelection } from '@tiptap/pm/state';+import { EditorView } from '@tiptap/pm/view';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { FLASH_DURATION_MS } from './flash-shared';+import { OK_LANDING_FLASH_CLASS } from './landing-flash-shared';+import {+ createLandingFlashPlugin,+ flashWysiwygLanding,+ landingFlashKey,+} from './landing-flash-wysiwyg';++const schema = new Schema({+ nodes: {+ doc: { content: 'paragraph+' },+ paragraph: { content: 'text*', toDOM: () => ['p', 0] },+ text: {},+ },+});++const para = (text: string) => schema.node('paragraph', null, text ? [schema.text(text)] : []);+const doc = (...texts: string[]) => schema.node('doc', null, texts.map(para));++function makeState() {+ return EditorState.create({+ schema,+ doc: doc('alpha', 'omega'),+ plugins: [createLandingFlashPlugin()],+ });+}++/**+ * A minimal EditorView surface backed by a real EditorState, so the real plugin+ * reducer runs on every dispatch. The flash trigger only reaches `state` and+ * `dispatch`, and the removal timer keys off the view object.+ */+function drivenView() {+ let state = makeState();+ const view = {+ get state() {+ return state;+ },+ dispatch(tr: ReturnType<EditorState['tr']['setMeta']>) {+ state = state.apply(tr);+ },+ };+ return {+ view: view as unknown as EditorView,+ getState: () => state,+ setSelection(pos: number) {+ state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, pos)));+ },+ };+}++const flashes = (state: EditorState) => landingFlashKey.getState(state)?.find() ?? [];++afterEach(() => {+ vi.useRealTimers();+});++describe('landing flash — wysiwyg plugin reducer', () => {+ test('add meta decorates the range', () => {+ let state = makeState();+ state = state.apply(state.tr.setMeta(landingFlashKey, { add: { from: 1, to: 6 } }));+ expect(flashes(state)).toHaveLength(1);+ expect(flashes(state)[0]?.from).toBe(1);+ });++ test('clear meta removes the decoration', () => {+ let state = makeState();+ state = state.apply(state.tr.setMeta(landingFlashKey, { add: { from: 1, to: 6 } }));+ state = state.apply(state.tr.setMeta(landingFlashKey, { clear: true }));+ expect(flashes(state)).toHaveLength(0);+ });++ test('a superseding add replaces the prior range', () => {+ let state = makeState();+ state = state.apply(state.tr.setMeta(landingFlashKey, { add: { from: 1, to: 6 } }));+ state = state.apply(state.tr.setMeta(landingFlashKey, { add: { from: 8, to: 13 } }));+ const decos = flashes(state);+ expect(decos).toHaveLength(1);+ expect(decos[0]?.from).toBe(8);+ });++ test('decorations map through an unrelated document change', () => {+ let state = makeState();+ state = state.apply(state.tr.setMeta(landingFlashKey, { add: { from: 8, to: 13 } }));+ state = state.apply(state.tr.insertText('shift', 2));+ const decos = flashes(state);+ expect(decos).toHaveLength(1);+ expect(decos[0]?.from).toBe(13);+ });+});++describe('landing flash — wysiwyg trigger', () => {+ test('suppresses the flash at a clamped grade', () => {+ const { view, getState } = drivenView();+ flashWysiwygLanding(view, 1, 6, 'clamped');+ expect(flashes(getState())).toHaveLength(0);+ });++ test('flashes then clears after the shared duration', () => {+ vi.useFakeTimers();+ const { view, getState } = drivenView();+ flashWysiwygLanding(view, 1, 6, 'exact');+ expect(flashes(getState())).toHaveLength(1);+ vi.advanceTimersByTime(FLASH_DURATION_MS);+ expect(flashes(getState())).toHaveLength(0);+ });++ test('never changes the selection', () => {+ const { view, getState, setSelection } = drivenView();+ setSelection(2);+ const before = getState().selection;+ flashWysiwygLanding(view, 8, 13, 'exact');+ expect(getState().selection.eq(before)).toBe(true);+ });++ test('clamps an out-of-range target to the document', () => {+ const { view, getState } = drivenView();+ flashWysiwygLanding(view, 1, 9999, 'exact');+ const decos = flashes(getState());+ expect(decos[0]?.to).toBe(getState().doc.content.size);+ });+});++describe('landing flash — wysiwyg rendering', () => {+ /** Mount a real view so the decoration's rendered attributes are observable. */+ function mountedView(): EditorView {+ const host = document.createElement('div');+ document.body.appendChild(host);+ return new EditorView(host, { state: makeState() });+ }++ test('paints the shared landing-flash class onto the landed range in the DOM', () => {+ // Decoration ranges alone do not prove the highlight is visible: the class+ // is the contract with the stylesheet, so it is asserted on a real mounted+ // view rather than on the plugin's state.+ const view = mountedView();+ try {+ flashWysiwygLanding(view, 1, 6, 'exact');+ expect(view.dom.querySelector(`.${OK_LANDING_FLASH_CLASS}`)?.textContent).toBe('alpha');+ } finally {+ view.destroy();+ }+ });++ test('removes the flashed class from the DOM after the shared duration', () => {+ vi.useFakeTimers();+ const view = mountedView();+ try {+ flashWysiwygLanding(view, 1, 6, 'exact');+ expect(view.dom.querySelector(`.${OK_LANDING_FLASH_CLASS}`)).not.toBeNull();+ vi.advanceTimersByTime(FLASH_DURATION_MS);+ expect(view.dom.querySelector(`.${OK_LANDING_FLASH_CLASS}`)).toBeNull();+ } finally {+ view.destroy();+ }+ });+});diff --git a/packages/app/src/editor/plugins/landing-flash-wysiwyg.ts b/packages/app/src/editor/plugins/landing-flash-wysiwyg.tsnew file mode 100644index 000000000..70fd1f40f--- /dev/null+++ b/packages/app/src/editor/plugins/landing-flash-wysiwyg.ts@@ -0,0 +1,104 @@+/**+ * Landing flash — WYSIWYG (ProseMirror).+ *+ * The WYSIWYG twin of the source landing flash: a standalone inline decoration+ * over the range a mode-switch jump landed on, cleared after one shared flash+ * duration. Standalone (its own plugin key, its own lifetime) rather than an+ * extension of the agent-insert flash, which decorates agent-changed ranges on a+ * different, shorter clock.+ *+ * The removal timer lives on the view because there is only ever one landing+ * flash at a time. The caller starts the flash once the landed range is on+ * screen, so its expiry clock measures visible time, not dispatch latency.+ *+ * Decoration-only: it never moves the selection or focus.+ */++import { Extension } from '@tiptap/core';+import { Plugin, PluginKey } from '@tiptap/pm/state';+import { Decoration, DecorationSet, type EditorView } from '@tiptap/pm/view';+import type { ResolveConfidence } from '../mode-switch-position-resolver';+import { FLASH_DURATION_MS } from './flash-shared';+import { clampFlashRange, OK_LANDING_FLASH_CLASS } from './landing-flash-shared';++export const landingFlashKey = new PluginKey<DecorationSet>('okLandingFlash');++interface LandingFlashMeta {+ /** Range (current-doc coordinates) to flash, replacing any prior flash. */+ add?: { from: number; to: number };+ /** Clear the flash. */+ clear?: boolean;+}++// Per-view removal timers. The plugin's view-destroy hook cancels the pending+// timer on teardown so it can never dispatch onto a destroyed view.+const removalTimers = new WeakMap<EditorView, ReturnType<typeof setTimeout>>();++export function createLandingFlashPlugin(): Plugin<DecorationSet> {+ return new Plugin<DecorationSet>({+ key: landingFlashKey,+ state: {+ init: () => DecorationSet.empty,+ apply(tr, decorations) {+ const meta = tr.getMeta(landingFlashKey) as LandingFlashMeta | undefined;+ let next = decorations.map(tr.mapping, tr.doc);+ if (meta?.clear) next = DecorationSet.empty;+ // A new landing replaces the prior flash rather than layering on it.+ if (meta?.add && meta.add.to > meta.add.from) {+ next = DecorationSet.create(tr.doc, [+ Decoration.inline(meta.add.from, meta.add.to, { class: OK_LANDING_FLASH_CLASS }),+ ]);+ }+ return next;+ },+ },+ props: {+ decorations(state) {+ return landingFlashKey.getState(state);+ },+ },+ view(editorView) {+ return {+ destroy() {+ const timer = removalTimers.get(editorView);+ if (timer !== undefined) {+ clearTimeout(timer);+ removalTimers.delete(editorView);+ }+ },+ };+ },+ });+}++/**+ * Flash the landed range and schedule its removal. A `clamped` grade suppresses+ * the flash (see `clampFlashRange`). Call this when the range is on screen; the+ * expiry timer starts here.+ */+export function flashWysiwygLanding(+ view: EditorView,+ from: number,+ to: number,+ grade: ResolveConfidence,+): void {+ const range = clampFlashRange(view.state.doc.content.size, from, to, grade);+ if (!range) return;+ view.dispatch(view.state.tr.setMeta(landingFlashKey, { add: range }));++ const prior = removalTimers.get(view);+ if (prior !== undefined) clearTimeout(prior);+ const timer = setTimeout(() => {+ removalTimers.delete(view);+ view.dispatch(view.state.tr.setMeta(landingFlashKey, { clear: true }));+ }, FLASH_DURATION_MS);+ removalTimers.set(view, timer);+}++/** TipTap wrapper that registers the plugin on the WYSIWYG editor. */+export const LandingFlash = Extension.create({+ name: 'okLandingFlash',+ addProseMirrorPlugins() {+ return [createLandingFlashPlugin()];+ },+});diff --git a/packages/app/src/editor/scroll-restore-coordination.test.ts b/packages/app/src/editor/scroll-restore-coordination.test.tsnew file mode 100644index 000000000..97bda155f--- /dev/null+++ b/packages/app/src/editor/scroll-restore-coordination.test.ts@@ -0,0 +1,316 @@+// @vitest-environment jsdom+/**+ * Coverage for the scroll-restore coordination surface: the per-document+ * body-offset map (persistence + LRU cap), the landing-result writer, the+ * ref-counted suppression registry a landing uses to become the single scroll+ * writer, and the landing-owner registry that lets an explicit navigation take+ * that role back. The anchor-measurement primitive the writer consumes is+ * `measureAnchor`, pinned in components/scroll-restore.test.ts.+ * `writeLandingResult` builds real DOM (`document.createElement`,+ * `getBoundingClientRect`, `querySelector`), so this file opts into jsdom via+ * the per-file docblock above. It is NOT a Tier-3 React mount test — no+ * component render — so it stays `.test.ts`, not `.dom.test.tsx`.+ */++import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import {+ __resetScrollRestoreCoordination,+ acquireScrollRestoreSuppression,+ BODY_ANCHOR_ATTR,+ claimScrollerForNavigation,+ type DocScrollState,+ getDocScrollState,+ isScrollRestoreSuppressed,+ type LandingScrollOwner,+ MAX_TRACKED_DOC_SCROLL,+ registerLandingScrollOwner,+ rememberDocScrollState,+ runScrollNavigation,+ scrollFraction,+ writeLandingResult,+} from './scroll-restore-coordination';+import type { EditorModeValue } from './use-editor-mode';++// Terse builder — most persistence/LRU cases care only about the offset, so+// they leave mode/fraction at defaults.+function state(offset: number, mode: EditorModeValue = 'wysiwyg', fraction = 0): DocScrollState {+ return { offset, mode, fraction };+}++beforeEach(() => {+ __resetScrollRestoreCoordination();+});++afterEach(() => {+ __resetScrollRestoreCoordination();+ vi.restoreAllMocks();+});++// A detached element with fixed layout geometry — jsdom returns an all-zero+// rect, an empty client-rect list, and a no-op scrollTop, so the math needs+// deterministic stand-ins. `boxes` is what makes the element laid out: an+// element with none is `unmeasurable` to `measureAnchor` (display:none /+// detached), which is a real case the landing writer has to handle.+function elementAt(top: number, scrollTop = 0, boxes = 1): HTMLElement {+ const el = document.createElement('div');+ vi.spyOn(el, 'getClientRects').mockReturnValue({ length: boxes } as DOMRectList);+ vi.spyOn(el, 'getBoundingClientRect').mockReturnValue({+ top,+ bottom: top,+ left: 0,+ right: 0,+ width: 0,+ height: 0,+ x: 0,+ y: top,+ toJSON: () => ({}),+ } as DOMRect);+ Object.defineProperty(el, 'scrollTop', { configurable: true, writable: true, value: scrollTop });+ return el;+}++describe('scroll-restore state persistence', () => {+ test('a document with no remembered state reads back undefined', () => {+ expect(getDocScrollState('never-written')).toBeUndefined();+ });++ test('remembers and reads back a document offset', () => {+ rememberDocScrollState('doc', state(42));+ expect(getDocScrollState('doc')?.offset).toBe(42);+ });++ test('records the mode the position was captured in so a restore can tell same- from cross-mode', () => {+ rememberDocScrollState('doc', state(42, 'source', 0.4));+ expect(getDocScrollState('doc')?.mode).toBe('source');+ expect(getDocScrollState('doc')?.fraction).toBe(0.4);+ });++ test('a later write for the same document overwrites the earlier one', () => {+ rememberDocScrollState('doc', state(42, 'wysiwyg'));+ rememberDocScrollState('doc', state(99, 'source'));+ expect(getDocScrollState('doc')?.offset).toBe(99);+ expect(getDocScrollState('doc')?.mode).toBe('source');+ });++ test('evicts the least-recently-written document once capacity is exceeded', () => {+ for (let i = 0; i <= MAX_TRACKED_DOC_SCROLL; i++) rememberDocScrollState(`k${i}`, state(i));+ expect(getDocScrollState('k0')).toBeUndefined();+ expect(getDocScrollState(`k${MAX_TRACKED_DOC_SCROLL}`)?.offset).toBe(MAX_TRACKED_DOC_SCROLL);+ });++ test('re-writing a document refreshes its recency so it is not the next evicted', () => {+ for (let i = 0; i < MAX_TRACKED_DOC_SCROLL; i++) rememberDocScrollState(`k${i}`, state(i));+ rememberDocScrollState('k0', state(1000)); // touch the oldest → moves it to most-recent+ rememberDocScrollState('overflow', state(-1)); // one over capacity → evicts the now-oldest (k1)+ expect(getDocScrollState('k0')?.offset).toBe(1000);+ expect(getDocScrollState('k1')).toBeUndefined();+ });+});++describe('scrollFraction', () => {+ test('is the ratio of scrollTop to the scrollable range', () => {+ // range = 5000 - 1000 = 4000; 1000 / 4000 = 0.25+ expect(scrollFraction(1000, 5000, 1000)).toBe(0.25);+ });++ test('is zero when the content does not overflow (no scrollable range)', () => {+ expect(scrollFraction(0, 800, 800)).toBe(0);+ expect(scrollFraction(50, 500, 800)).toBe(0);+ });++ test('clamps into [0,1] for out-of-range inputs', () => {+ expect(scrollFraction(-100, 5000, 1000)).toBe(0);+ expect(scrollFraction(9999, 5000, 1000)).toBe(1);+ });+});++describe('writeLandingResult', () => {+ test('persists the target as a body-relative offset using an explicit anchor', () => {+ const container = elementAt(100, 50);+ const anchor = elementAt(300);+ writeLandingResult({+ docName: 'doc',+ container,+ targetScrollTop: 1000,+ mode: 'source',+ anchor,+ });+ // targetScrollTop - anchorPos(250) = 750, so a later restore at the same+ // anchor reproduces scrollTop 1000.+ expect(getDocScrollState('doc')?.offset).toBe(750);+ });++ test('stamps the mode the landing landed in', () => {+ const container = elementAt(100, 50);+ writeLandingResult({ docName: 'doc', container, targetScrollTop: 1000, mode: 'source' });+ expect(getDocScrollState('doc')?.mode).toBe('source');+ });++ test('records the landing fraction from the container scroll range', () => {+ const container = elementAt(100, 0);+ Object.defineProperty(container, 'scrollHeight', { configurable: true, value: 5000 });+ Object.defineProperty(container, 'clientHeight', { configurable: true, value: 1000 });+ writeLandingResult({ docName: 'doc', container, targetScrollTop: 1000, mode: 'source' });+ // 1000 / (5000 - 1000) = 0.25+ expect(getDocScrollState('doc')?.fraction).toBe(0.25);+ });++ test('finds the body anchor via its marker attribute when none is passed', () => {+ const container = elementAt(100, 50);+ const anchor = elementAt(300);+ anchor.setAttribute(BODY_ANCHOR_ATTR, '');+ container.appendChild(anchor);+ writeLandingResult({ docName: 'doc', container, targetScrollTop: 1000, mode: 'wysiwyg' });+ expect(getDocScrollState('doc')?.offset).toBe(750);+ });++ test('falls back to the raw target when the container has no body anchor', () => {+ const container = elementAt(100, 50);+ writeLandingResult({ docName: 'doc', container, targetScrollTop: 1000, mode: 'wysiwyg' });+ expect(getDocScrollState('doc')?.offset).toBe(1000);+ });++ test('takes the raw fallback for an anchor with no layout boxes, never its zero rect', () => {+ // A mounted-but-hidden anchor reports a rect at the viewport origin.+ // Measuring it would store `targetScrollTop - (0 - containerTop ++ // scrollTop)` — the self-amplifying offset the restore loop then feeds+ // back into itself, one frame at a time.+ const container = elementAt(100, 50);+ const hiddenAnchor = elementAt(0, 0, 0);+ writeLandingResult({+ docName: 'doc',+ container,+ targetScrollTop: 1000,+ mode: 'wysiwyg',+ anchor: hiddenAnchor,+ });+ expect(getDocScrollState('doc')?.offset).toBe(1000);+ });+});++describe('scroll-restore suppression registry', () => {+ test('a document is not suppressed until a handle is acquired', () => {+ expect(isScrollRestoreSuppressed('doc')).toBe(false);+ });++ test('acquiring a handle suppresses the document; releasing it re-enables restore', () => {+ const handle = acquireScrollRestoreSuppression('doc');+ expect(isScrollRestoreSuppressed('doc')).toBe(true);+ handle.release();+ expect(isScrollRestoreSuppressed('doc')).toBe(false);+ });++ test('overlapping holders each keep suppression until all release', () => {+ const first = acquireScrollRestoreSuppression('doc');+ const second = acquireScrollRestoreSuppression('doc');+ first.release();+ expect(isScrollRestoreSuppressed('doc')).toBe(true); // second still holds+ second.release();+ expect(isScrollRestoreSuppressed('doc')).toBe(false);+ });++ test('releasing the same handle twice does not underflow another holder', () => {+ const first = acquireScrollRestoreSuppression('doc');+ const second = acquireScrollRestoreSuppression('doc');+ first.release();+ first.release(); // idempotent — must not decrement second's hold+ expect(isScrollRestoreSuppressed('doc')).toBe(true);+ second.release();+ expect(isScrollRestoreSuppressed('doc')).toBe(false);+ });++ test('suppression is scoped per document', () => {+ const handle = acquireScrollRestoreSuppression('a');+ expect(isScrollRestoreSuppressed('a')).toBe(true);+ expect(isScrollRestoreSuppressed('b')).toBe(false);+ handle.release();+ });+});++describe('landing scroll owners and explicit navigation', () => {+ /**+ * Register a landing owner that behaves like the controller's: superseding it+ * releases its own registration. Reports how often it was superseded.+ */+ function ownLanding(docName: string, yieldsToNavigation: boolean): () => number {+ let superseded = 0;+ const registration = registerLandingScrollOwner(docName, {+ yieldsToNavigation,+ supersede: () => {+ superseded += 1;+ registration.release();+ },+ });+ return () => superseded;+ }++ test('an unowned scroller is free for a navigation', () => {+ const scroll = vi.fn();+ expect(runScrollNavigation('doc', scroll)).toBe(true);+ expect(scroll).toHaveBeenCalledTimes(1);+ });++ test('a yielding owner is superseded and the navigation runs', () => {+ const superseded = ownLanding('doc', true);+ const scroll = vi.fn();++ expect(runScrollNavigation('doc', scroll)).toBe(true);++ expect(superseded()).toBe(1);+ expect(scroll).toHaveBeenCalledTimes(1);+ // Superseding released the registration, so the next navigation is free.+ expect(claimScrollerForNavigation('doc')).toBe(true);+ expect(superseded()).toBe(1);+ });++ test('a non-yielding owner keeps the scroller and the navigation does not run', () => {+ const superseded = ownLanding('doc', false);+ const scroll = vi.fn();++ expect(runScrollNavigation('doc', scroll)).toBe(false);++ expect(superseded()).toBe(0);+ expect(scroll).not.toHaveBeenCalled();+ });++ test('overlapping yielding owners are all superseded', () => {+ const first = ownLanding('doc', true);+ const second = ownLanding('doc', true);++ expect(runScrollNavigation('doc', () => {})).toBe(true);++ expect(first()).toBe(1);+ expect(second()).toBe(1);+ });++ test('one non-yielding owner blocks the claim, superseding none of them', () => {+ // A partial pre-emption would tear down the yielding landing on behalf of a+ // navigation that then never runs.+ const yielding = ownLanding('doc', true);+ const holding = ownLanding('doc', false);++ expect(runScrollNavigation('doc', () => {})).toBe(false);++ expect(yielding()).toBe(0);+ expect(holding()).toBe(0);+ });++ test('a released owner no longer holds the scroller', () => {+ const supersede = vi.fn();+ const owner: LandingScrollOwner = { yieldsToNavigation: false, supersede };+ const registration = registerLandingScrollOwner('doc', owner);+ expect(claimScrollerForNavigation('doc')).toBe(false);++ registration.release();+ registration.release(); // idempotent++ expect(claimScrollerForNavigation('doc')).toBe(true);+ expect(supersede).not.toHaveBeenCalled();+ });++ test('ownership is scoped per document', () => {+ ownLanding('a', false);+ expect(claimScrollerForNavigation('a')).toBe(false);+ expect(claimScrollerForNavigation('b')).toBe(true);+ });+});diff --git a/packages/app/src/editor/scroll-restore-coordination.ts b/packages/app/src/editor/scroll-restore-coordination.tsnew file mode 100644index 000000000..b9ad186c1--- /dev/null+++ b/packages/app/src/editor/scroll-restore-coordination.ts@@ -0,0 +1,274 @@+/**+ * Coordination surface for the per-document scroll-restore layer.+ *+ * The scroll bookkeeping that `ScrollPreservingContainer` (EditorActivityPool)+ * uses to save and restore a document's scroll position lives here as the+ * single source of truth, so a second scroll writer — a mode-switch landing —+ * can reconcile with it instead of racing it:+ *+ * - the per-document saved-position map — a body-relative offset for a+ * same-mode restore, the mode it was captured in, and a scroll fraction for+ * a cross-mode proportional floor — plus its reader and writers,+ * - a ref-counted suppression registry that lets a landing become the single+ * scroll writer for a document while its settle window is open,+ * - the landing-owner registry and `runScrollNavigation`, the primitive every+ * explicit navigation scrolls through so it PRE-EMPTS an in-flight landing+ * instead of being erased by it.+ *+ * Keeping this state in one module — rather than duplicating it in the landing+ * controller — is what makes the reconciliation honest: both writers read and+ * write the same map, so a landing result persists through the container's+ * remount-survival restore, and a later restore reproduces the landing rather+ * than the pre-landing position.+ */++import { measureAnchor } from '@/components/scroll-restore';+import type { EditorModeValue } from './use-editor-mode';++/**+ * A document's saved scroll position, along with the editor mode it was captured+ * in and a whole-range fraction. The mode makes a restore honest: the offset+ * only maps back to the same body content in the SAME mode, because each mode's+ * geometry is different. When the document is re-activated in a different mode+ * than it was left in, the precise offset would drive the scroller against the+ * other mode's layout — so the restore falls back to `fraction` (how far through+ * the scrollable range the user was) for a proportional floor instead.+ */+export interface DocScrollState {+ /** Body-relative offset (scrollTop minus above-body anchor height). */+ offset: number;+ /** The editor mode this position was captured in. */+ mode: EditorModeValue;+ /** scrollTop as a fraction [0,1] of the scrollable range at capture time. */+ fraction: number;+}++/**+ * scrollTop expressed as a fraction of the container's scrollable range, clamped+ * to `[0,1]`. Zero when the content does not overflow (nothing to be a fraction+ * of). The mode-independent floor a cross-mode restore lands on.+ */+export function scrollFraction(+ scrollTop: number,+ scrollHeight: number,+ clientHeight: number,+): number {+ const max = scrollHeight - clientHeight;+ if (max <= 0) return 0;+ return Math.max(0, Math.min(1, scrollTop / max));+}++/**+ * Per-document saved scroll state keyed by `docName`. Two reasons it lives at+ * module scope, not in a per-instance ref:+ * 1. Survives the editor's REMOUNT on navigate-back — the fresh+ * ScrollPreservingContainer instance re-reads the same value instead of+ * losing it (the per-instance ref was the bug: a remount dropped it and+ * then re-captured churn from the resize).+ * 2. The offset is body-relative — a Properties-panel height change+ * (collapse/expand, even globally on another doc) never invalidates it,+ * because it is measured from the top of the body, not the top of the+ * scroller.+ * Same-mode restore = currentAnchor + storedOffset, so it always lands on the+ * same body content regardless of the panel's current height.+ *+ * Entries are deliberately kept PAST Activity eviction (so revisiting a+ * pooled-out doc still restores scroll), so there is no per-eviction cleanup —+ * but to keep a very long session from growing the map without bound,+ * `rememberDocScrollState` caps it at `MAX_TRACKED_DOC_SCROLL`, dropping the+ * least-recently-written entry (re-insert-on-write makes the order LRU).+ */+export const MAX_TRACKED_DOC_SCROLL = 256;+const docScrollState = new Map<string, DocScrollState>();++export function rememberDocScrollState(docName: string, state: DocScrollState): void {+ docScrollState.delete(docName); // re-insert last → LRU order for eviction+ docScrollState.set(docName, state);+ if (docScrollState.size > MAX_TRACKED_DOC_SCROLL) {+ const oldest = docScrollState.keys().next().value;+ if (oldest !== undefined) docScrollState.delete(oldest);+ }+}++/** The persisted scroll state for a document, or undefined if none. */+export function getDocScrollState(docName: string): DocScrollState | undefined {+ return docScrollState.get(docName);+}++/**+ * Attribute marking the zero-height body-top anchor inside a scroll container.+ * The container's own restore effect holds a React ref to the same node; this+ * marker lets a landing find it from a bare container element it did not mount.+ */+export const BODY_ANCHOR_ATTR = 'data-ok-body-anchor';++/**+ * Persist a landing at `targetScrollTop` so a later scroll restore for the same+ * document reproduces it. Stored body-relative (targetScrollTop minus the+ * current above-body anchor height), so it survives the editor's remount and+ * tracks a Properties-panel height change the same way a captured user scroll+ * does — writing a raw scrollTop alone would survive neither. Falls back to the+ * raw target when the container has no resolvable body anchor (a scroller+ * without the dual-editor body, e.g. a recovery panel), matching the restore's+ * own absent-anchor fallback. `mode` is the mode the landing lands in, so a later+ * re-activation in a different mode floors instead of driving this offset.+ *+ * An anchor that is mounted but generates no layout boxes takes the same raw+ * fallback rather than its zero rect: a viewport-origin measurement here would+ * write a self-amplifying offset into the very map the restore loop reads, the+ * corruption class `measureAnchor` exists to make unrepresentable. A landing+ * records only after its final snap to settled geometry, so this is a+ * degenerate path, not the normal one.+ */+export function writeLandingResult(params: {+ docName: string;+ container: HTMLElement;+ targetScrollTop: number;+ mode: EditorModeValue;+ anchor?: HTMLElement | null;+}): void {+ const anchor =+ params.anchor ?? params.container.querySelector<HTMLElement>(`[${BODY_ANCHOR_ATTR}]`);+ const measurement = measureAnchor(params.container, anchor);+ const anchorPos = measurement.kind === 'measured' ? measurement.contentPos : 0;+ rememberDocScrollState(params.docName, {+ offset: params.targetScrollTop - anchorPos,+ mode: params.mode,+ fraction: scrollFraction(+ params.targetScrollTop,+ params.container.scrollHeight,+ params.container.clientHeight,+ ),+ });+}++/**+ * Ref-counted set of documents whose scroll-restore is currently suppressed. A+ * landing acquires a handle for the whole of its settle window so the+ * container's two-stage restore stands down and the landing is the single+ * scroll writer. Ref-counting tolerates overlapping holders (a re-dispatch that+ * briefly overlaps its predecessor) without one release re-enabling the restore+ * while another landing is still open.+ */+const suppressedDocs = new Map<string, number>();++interface ScrollRestoreSuppressionHandle {+ release(): void;+}++export function acquireScrollRestoreSuppression(docName: string): ScrollRestoreSuppressionHandle {+ suppressedDocs.set(docName, (suppressedDocs.get(docName) ?? 0) + 1);+ let released = false;+ return {+ release() {+ if (released) return; // idempotent: a double release must not underflow the count+ released = true;+ const remaining = (suppressedDocs.get(docName) ?? 0) - 1;+ if (remaining > 0) suppressedDocs.set(docName, remaining);+ else suppressedDocs.delete(docName);+ },+ };+}++export function isScrollRestoreSuppressed(docName: string): boolean {+ return (suppressedDocs.get(docName) ?? 0) > 0;+}++/**+ * A landing that currently owns a document's scroller.+ *+ * Suppression alone cannot express the relationship between a landing and an+ * explicit navigation. A landing verifies its target on every layout signal and+ * treats any scrollTop it did not write as drift, so a navigation that merely+ * scrolls during the settle window is measured as drift and reset a few+ * milliseconds later — and then the erased position is persisted by the landing.+ * Standing the navigation down instead is no better: the caret still moves, so+ * the user gets a dead click on a document that quietly agrees with them. The+ * resolution is pre-emption, which needs a handle on the landing itself.+ */+export interface LandingScrollOwner {+ /**+ * Whether an explicit navigation supersedes this landing. A position-+ * preserving toggle yields: the place the user just asked for outranks the+ * place they were. A landing that is ITSELF an explicit navigation (a jump)+ * does not — it has already placed the caret, so pre-empting it halfway would+ * strand caret and viewport in different places, the very split this contract+ * exists to prevent.+ */+ yieldsToNavigation: boolean;+ /** Terminate the landing and release the scroller. */+ supersede(): void;+}++/**+ * Landings holding a document's scroller. A set rather than a single entry+ * because holders can briefly overlap (a re-dispatch that starts before its+ * predecessor is cancelled), the same overlap the suppression count tolerates.+ */+const landingScrollOwners = new Map<string, Set<LandingScrollOwner>>();++export function registerLandingScrollOwner(+ docName: string,+ owner: LandingScrollOwner,+): { release(): void } {+ const owners = landingScrollOwners.get(docName) ?? new Set<LandingScrollOwner>();+ owners.add(owner);+ landingScrollOwners.set(docName, owners);+ return {+ release() {+ const live = landingScrollOwners.get(docName);+ if (!live) return;+ live.delete(owner);+ if (live.size === 0) landingScrollOwners.delete(docName);+ },+ };+}++/**+ * Take the document's scroller for an explicit navigation, pre-empting every+ * landing that yields. Returns false when a landing that does not yield still+ * owns it, in which case the caller must not scroll — see `runScrollNavigation`,+ * which is the form to reach for. This bare form exists for the one seam that+ * cannot perform its own scroll: CodeMirror's `scrollToMatch` returns a scroll+ * effect for the search extension to dispatch rather than scrolling itself.+ */+export function claimScrollerForNavigation(docName: string): boolean {+ const owners = landingScrollOwners.get(docName);+ if (!owners) return true;+ for (const owner of owners) {+ if (!owner.yieldsToNavigation) return false;+ }+ // Snapshot first: `supersede` releases the registration, and a landing that+ // registers a successor while unwinding would otherwise be superseded in the+ // same pass by the navigation that had already claimed the scroller.+ const superseding = Array.from(owners);+ for (const owner of superseding) owner.supersede();+ return true;+}++/**+ * Run an explicit, user-initiated navigation's scroll — an outline or+ * Problems-panel row click, a find/replace match, a deep-link anchor.+ *+ * Every such navigation goes through here rather than reaching for+ * `scrollIntoView` directly, so the precedence against an in-flight landing is+ * enforced by this producer instead of by each writer remembering to ask. That+ * is the difference that matters: a writer that forgets to poll silently opts+ * out of the contract, which is how a landing came to erase the source-mode+ * Problems-row jump. Put the navigation's selection write inside `scroll` too —+ * caret and viewport should move together or not at all.+ *+ * Returns whether the navigation ran.+ */+export function runScrollNavigation(docName: string, scroll: () => void): boolean {+ if (!claimScrollerForNavigation(docName)) return false;+ scroll();+ return true;+}++/** Test-only: clear all coordination state between cases. */+export function __resetScrollRestoreCoordination(): void {+ docScrollState.clear();+ suppressedDocs.clear();+ landingScrollOwners.clear();+}diff --git a/packages/app/src/editor/source-editor-navigation.test.ts b/packages/app/src/editor/source-editor-navigation.test.tsindex 94528caab..d65b29d10 100644--- a/packages/app/src/editor/source-editor-navigation.test.ts+++ b/packages/app/src/editor/source-editor-navigation.test.ts@@ -1,14 +1,25 @@import { afterEach, describe, expect, test, vi } from 'vitest';+import * as Y from 'yjs';+import type { BlockAnchor } from './mode-switch-position-resolver';import {+ clearPendingNavigationForExitedMode,clearPendingSourceNavigation,clearPendingSourceNavigationsForTest,+ clearPendingWysiwygNavigation,+ clearPendingWysiwygNavigationsForTest,consumePendingSourceNavigation,+ consumePendingWysiwygNavigation,+ createNavigationPin,peekPendingSourceNavigation,+ peekPendingWysiwygNavigation,rememberPendingSourceNavigation,+ rememberPendingWysiwygNavigation,+ resolveNavigationPin,} from './source-editor-navigation';afterEach(() => {clearPendingSourceNavigationsForTest();+ clearPendingWysiwygNavigationsForTest();vi.useRealTimers();});@@ -58,6 +69,15 @@ describe('source-editor-navigation', () => {clearPendingSourceNavigation('doc-a');expect(consumePendingSourceNavigation('doc-a')).toBeNull();});++ test('the source store carries a selection-offset intent alongside the panel kinds', () => {+ const anchor: BlockAnchor = { blockIndex: 2, kind: 'paragraph', content: 'target' };+ rememberPendingSourceNavigation('doc-a', { kind: 'selection-offset', anchor });++ expect(peekPendingSourceNavigation('doc-a')).toEqual({ kind: 'selection-offset', anchor });+ expect(consumePendingSourceNavigation('doc-a')).toEqual({ kind: 'selection-offset', anchor });+ expect(consumePendingSourceNavigation('doc-a')).toBeNull();+ });});describe('pending-intent expiry', () => {@@ -110,3 +130,152 @@ describe('pending-intent expiry', () => {expect(consumePendingSourceNavigation('doc-a')).toEqual(lintNavigation);});});++describe('wysiwyg pending-navigation store', () => {+ const anchor: BlockAnchor = { blockIndex: 1, kind: 'heading', content: 'Section' };++ test('consume returns the pending WYSIWYG navigation once for a doc', () => {+ rememberPendingWysiwygNavigation('doc-a', { kind: 'selection-offset', anchor });++ expect(peekPendingWysiwygNavigation('doc-a')).toEqual({ kind: 'selection-offset', anchor });+ expect(consumePendingWysiwygNavigation('doc-a')).toEqual({ kind: 'selection-offset', anchor });+ expect(consumePendingWysiwygNavigation('doc-a')).toBeNull();+ });++ test('WYSIWYG navigation is doc-scoped', () => {+ const a: BlockAnchor = { blockIndex: 0, kind: 'paragraph', content: 'a' };+ const b: BlockAnchor = { blockIndex: 4, kind: 'paragraph', content: 'b' };+ rememberPendingWysiwygNavigation('doc-a', { kind: 'selection-offset', anchor: a });+ rememberPendingWysiwygNavigation('doc-b', { kind: 'selection-offset', anchor: b });++ expect(consumePendingWysiwygNavigation('doc-a')?.anchor).toEqual(a);+ expect(consumePendingWysiwygNavigation('doc-b')?.anchor).toEqual(b);+ });++ test('clearPendingWysiwygNavigation removes entry without returning it', () => {+ rememberPendingWysiwygNavigation('doc-a', { kind: 'selection-offset', anchor });+ clearPendingWysiwygNavigation('doc-a');+ expect(consumePendingWysiwygNavigation('doc-a')).toBeNull();+ });++ test('a WYSIWYG intent older than 30 seconds is discarded at consume time', () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-07-09T12:00:00.000Z'));+ rememberPendingWysiwygNavigation('doc-a', { kind: 'selection-offset', anchor });++ vi.setSystemTime(new Date('2026-07-09T12:00:30.001Z'));+ expect(consumePendingWysiwygNavigation('doc-a')).toBeNull();+ });+});++describe('mode-exit clearing', () => {+ const srcAnchor: BlockAnchor = { blockIndex: 0, kind: 'paragraph', content: 'source side' };+ const wysAnchor: BlockAnchor = { blockIndex: 0, kind: 'paragraph', content: 'wysiwyg side' };++ test('leaving source clears the source intent', () => {+ rememberPendingSourceNavigation('doc-a', { kind: 'selection-offset', anchor: srcAnchor });+ clearPendingNavigationForExitedMode('doc-a', 'source');+ expect(consumePendingSourceNavigation('doc-a')).toBeNull();+ });++ test('leaving wysiwyg clears the wysiwyg intent', () => {+ rememberPendingWysiwygNavigation('doc-a', { kind: 'selection-offset', anchor: wysAnchor });+ clearPendingNavigationForExitedMode('doc-a', 'wysiwyg');+ expect(consumePendingWysiwygNavigation('doc-a')).toBeNull();+ });++ test('leaving a mode preserves the intent queued for the mode being entered', () => {+ // A W->S flip queues a source landing while leaving the WYSIWYG view.+ // Clearing the exited (WYSIWYG) mode must not discard that queued landing,+ // otherwise the flip that just banked it would erase itself.+ rememberPendingSourceNavigation('doc-a', { kind: 'selection-offset', anchor: srcAnchor });+ clearPendingNavigationForExitedMode('doc-a', 'wysiwyg');+ expect(consumePendingSourceNavigation('doc-a')).toEqual({+ kind: 'selection-offset',+ anchor: srcAnchor,+ });+ });+});++describe('navigation pin', () => {+ // Offsets index the target word 'target' within a fixed source string.+ const SOURCE = 'hello world target here';+ const TARGET_START = SOURCE.indexOf('target');+ const TARGET_END = TARGET_START + 'target'.length;++ function seed(): { doc: Y.Doc; text: Y.Text } {+ const doc = new Y.Doc();+ const text = doc.getText('source');+ text.insert(0, SOURCE);+ return { doc, text };+ }++ test('a pin survives a remote insert before the target and tracks the moved offset', () => {+ const { doc, text } = seed();+ const pin = createNavigationPin(text, TARGET_START, TARGET_END);++ text.insert(0, 'PREFIX ');++ expect(resolveNavigationPin(pin, doc)).toBe(TARGET_START + 'PREFIX '.length);+ });++ test('a pin is lost when its target range is deleted', () => {+ const { doc, text } = seed();+ const pin = createNavigationPin(text, TARGET_START, TARGET_END);++ text.delete(TARGET_START, 'target'.length);++ expect(resolveNavigationPin(pin, doc)).toBeNull();+ });++ test('a pin is lost when a remote peer deletes the target and syncs it back', () => {+ const { doc, text } = seed();+ const pin = createNavigationPin(text, TARGET_START, TARGET_END);++ const peer = new Y.Doc();+ Y.applyUpdate(peer, Y.encodeStateAsUpdate(doc));+ peer.getText('source').delete(TARGET_START, 'target'.length);+ Y.applyUpdate(doc, Y.encodeStateAsUpdate(peer));++ expect(resolveNavigationPin(pin, doc)).toBeNull();+ });++ test('a partially-deleted target resolves to the surviving fragment', () => {+ const { doc, text } = seed();+ const pin = createNavigationPin(text, TARGET_START, TARGET_END);++ // Delete 'rget', leaving 'ta' at the original start.+ text.delete(TARGET_START + 2, 4);++ expect(resolveNavigationPin(pin, doc)).toBe(TARGET_START);+ });++ test('a pin that cannot be mapped into the document resolves to null', () => {+ const { text } = seed();+ const pin = createNavigationPin(text, TARGET_START, TARGET_END);++ // A document that never saw this pin's structure cannot resolve it.+ const other = new Y.Doc();+ other.getText('source').insert(0, SOURCE);++ expect(resolveNavigationPin(pin, other)).toBeNull();+ });++ test('creating and resolving a pin performs no mutation and opens no transaction', () => {+ const { doc, text } = seed();+ let updates = 0;+ let transactions = 0;+ doc.on('update', () => {+ updates++;+ });+ doc.on('afterTransaction', () => {+ transactions++;+ });++ const pin = createNavigationPin(text, TARGET_START, TARGET_END);+ resolveNavigationPin(pin, doc);++ expect(updates).toBe(0);+ expect(transactions).toBe(0);+ });+});diff --git a/packages/app/src/editor/source-editor-navigation.ts b/packages/app/src/editor/source-editor-navigation.tsindex 65699ca28..9978c08f1 100644--- a/packages/app/src/editor/source-editor-navigation.ts+++ b/packages/app/src/editor/source-editor-navigation.ts@@ -1,11 +1,64 @@+/**+ * Per-document pending-navigation stores: a durable "flip mode, then land here"+ * record that survives the mode swap and the target editor's (possibly lazy)+ * mount. Two stores, one per destination view — source-destined intents replay+ * when the CodeMirror view activates, WYSIWYG-destined intents when the TipTap+ * view activates. Both are in-memory, doc-scoped, consume-once, and expire on a+ * shared horizon so a much-later mode switch never replays a stale target.+ *+ * The cross-mode `selection-offset` kind additionally carries a relative-position+ * pin over the target's `Y.Text('source')` range. Y.Text is the document's+ * truth, so both directions land off the source ordinal and a single pin type+ * serves both stores. The pin lets a queued landing follow content that remote+ * peers move (or delete) during the capture-to-dispatch window instead of+ * indexing a frozen offset.+ */++import * as Y from 'yjs';import type { OutlineNavDetail } from '@/components/OutlinePanel';import type { LintNavDetail } from '@/components/ProblemsPanel';import type { RawMdxNavDetail } from '@/editor/extensions/raw-mdx-nav-event';+import type { EditorModeValue } from '@/editor/use-editor-mode';+import type { BlockAnchor } from './mode-switch-position-resolver';++/**+ * A relative-position pin over a top-level block's `Y.Text('source')` range.+ * Pinning both ends (rather than a single offset) lets resolution distinguish+ * "the target moved" from "the target was deleted": a remote edit before the+ * block shifts both ends together, while deleting the block collapses them.+ */+export interface NavigationPin {+ start: Y.RelativePosition;+ end: Y.RelativePosition;+}+/**+ * A queued cross-mode landing: a resolver block anchor plus an optional pin. The+ * anchor's ordinal is the primary key; the pin, when present, upgrades a stale+ * capture-time offset to a live one at dispatch. Absent pin means no collab+ * tracking is available and the landing rides the ordinal alone.+ *+ * `intent` distinguishes the two landing behaviors that share this machinery: a+ * position-preserving toggle (scroll-only, non-interfering) versus an explicit+ * jump (centered, caret placed, highlighted). Absent means toggle — the+ * pre-existing behavior — so a plain toggle need not spell it out.+ */+export interface SelectionOffsetNavigation {+ kind: 'selection-offset';+ intent?: 'toggle' | 'jump';+ anchor: BlockAnchor;+ pin?: NavigationPin;+}++/** Navigation intents queued for the source view (frontmatter + body). */type PendingSourceNavigation =| { kind: 'outline'; detail: OutlineNavDetail }| { kind: 'raw-mdx'; detail: RawMdxNavDetail }- | { kind: 'lint'; detail: LintNavDetail };+ | { kind: 'lint'; detail: LintNavDetail }+ | SelectionOffsetNavigation;++/** Navigation intents queued for the WYSIWYG view. */+type PendingWysiwygNavigation = SelectionOffsetNavigation;/*** Discard-at-consume horizon. The replay effect fires on every source-mode@@ -15,41 +68,107 @@ type PendingSourceNavigation =*/const PENDING_NAVIGATION_TTL_MS = 30_000;-interface PendingNavigationEntry {- navigation: PendingSourceNavigation;+interface PendingNavigationEntry<T> {+ navigation: T;rememberedAt: number;}-const pendingNavigations = new Map<string, PendingNavigationEntry>();--function liveNavigationOf(- entry: PendingNavigationEntry | undefined,-): PendingSourceNavigation | null {- if (!entry) return null;- return Date.now() - entry.rememberedAt > PENDING_NAVIGATION_TTL_MS ? null : entry.navigation;+interface PendingNavigationStore<T> {+ remember(docName: string, navigation: T): void;+ peek(docName: string): T | null;+ consume(docName: string): T | null;+ clear(docName: string): void;+ clearForTest(): void;}-export function rememberPendingSourceNavigation(- docName: string,- navigation: PendingSourceNavigation,-): void {- pendingNavigations.set(docName, { navigation, rememberedAt: Date.now() });+function createPendingNavigationStore<T>(): PendingNavigationStore<T> {+ const entries = new Map<string, PendingNavigationEntry<T>>();+ const live = (entry: PendingNavigationEntry<T> | undefined): T | null => {+ if (!entry) return null;+ return Date.now() - entry.rememberedAt > PENDING_NAVIGATION_TTL_MS ? null : entry.navigation;+ };+ return {+ remember(docName, navigation) {+ entries.set(docName, { navigation, rememberedAt: Date.now() });+ },+ peek(docName) {+ return live(entries.get(docName));+ },+ consume(docName) {+ const entry = entries.get(docName);+ entries.delete(docName);+ return live(entry);+ },+ clear(docName) {+ entries.delete(docName);+ },+ clearForTest() {+ entries.clear();+ },+ };}-export function peekPendingSourceNavigation(docName: string): PendingSourceNavigation | null {- return liveNavigationOf(pendingNavigations.get(docName));-}+const sourceNavigations = createPendingNavigationStore<PendingSourceNavigation>();+const wysiwygNavigations = createPendingNavigationStore<PendingWysiwygNavigation>();++export const rememberPendingSourceNavigation = sourceNavigations.remember;+export const peekPendingSourceNavigation = sourceNavigations.peek;+export const consumePendingSourceNavigation = sourceNavigations.consume;+export const clearPendingSourceNavigation = sourceNavigations.clear;+export const clearPendingSourceNavigationsForTest = sourceNavigations.clearForTest;-export function consumePendingSourceNavigation(docName: string): PendingSourceNavigation | null {- const entry = pendingNavigations.get(docName);- pendingNavigations.delete(docName);- return liveNavigationOf(entry);+export const rememberPendingWysiwygNavigation = wysiwygNavigations.remember;+export const peekPendingWysiwygNavigation = wysiwygNavigations.peek;+export const consumePendingWysiwygNavigation = wysiwygNavigations.consume;+export const clearPendingWysiwygNavigation = wysiwygNavigations.clear;+export const clearPendingWysiwygNavigationsForTest = wysiwygNavigations.clearForTest;++/**+ * Clear the intent destined for the view being left. On a flip, the intent for+ * the view being entered lives in the other store, so this only discards a+ * lingering target that never got a chance to replay — it never stomps the+ * landing the flip just queued.+ */+export function clearPendingNavigationForExitedMode(+ docName: string,+ exitedMode: EditorModeValue,+): void {+ if (exitedMode === 'source') {+ clearPendingSourceNavigation(docName);+ } else {+ clearPendingWysiwygNavigation(docName);+ }}-export function clearPendingSourceNavigation(docName: string): void {- pendingNavigations.delete(docName);+/**+ * Pin a block's `Y.Text('source')` char range so a queued landing can track it+ * across remote edits. Pure read of the current state — no mutation, no+ * transaction (`Y.createRelativePositionFromTypeIndex` only reads item ids).+ */+export function createNavigationPin(+ ytext: Y.Text,+ blockStart: number,+ blockEnd: number,+): NavigationPin {+ return {+ start: Y.createRelativePositionFromTypeIndex(ytext, blockStart),+ end: Y.createRelativePositionFromTypeIndex(ytext, blockEnd),+ };}-export function clearPendingSourceNavigationsForTest(): void {- pendingNavigations.clear();+/**+ * Resolve a pin against the current document, returning the live start offset of+ * the surviving target, or `null` when it can no longer be resolved. Null covers+ * both a structure that is entirely gone (Yjs cannot map the id) and a range that+ * has collapsed — the pinned block was deleted out from under the queued landing.+ * The caller falls back to the resolver's clamped grade in that case rather than+ * landing on whatever content shifted into the old offset. A pure read: no+ * mutation, no transaction.+ */+export function resolveNavigationPin(pin: NavigationPin, ydoc: Y.Doc): number | null {+ const start = Y.createAbsolutePositionFromRelativePosition(pin.start, ydoc);+ const end = Y.createAbsolutePositionFromRelativePosition(pin.end, ydoc);+ if (start === null || end === null) return null;+ if (end.index <= start.index) return null;+ return start.index;}diff --git a/packages/app/src/editor/view-in-source-event.ts b/packages/app/src/editor/view-in-source-event.tsnew file mode 100644index 000000000..3eba2513b--- /dev/null+++ b/packages/app/src/editor/view-in-source-event.ts@@ -0,0 +1,16 @@+/**+ * VIEW_IN_SOURCE_EVENT — window CustomEvent that asks the editor pane to flip a+ * document into source mode for an explicit "view in source" jump.+ *+ * The jump command banks its landing target before dispatching, then relies on+ * this event to trigger the flip; `EditorPane` owns the mode state and listens.+ * Kept as a bare signal (no target payload) because the target already lives in+ * the pending-navigation store the incoming source view replays — the same split+ * the raw-MDX navigation uses.+ */++export const VIEW_IN_SOURCE_EVENT = 'open-knowledge:view-in-source';++export interface ViewInSourceDetail {+ docName: string;+}diff --git a/packages/app/src/globals.css b/packages/app/src/globals.cssindex 9af915bd7..9c57a24b0 100644--- a/packages/app/src/globals.css+++ b/packages/app/src/globals.css@@ -510,6 +510,30 @@}}+/* Landing flash — transient highlight on the range a mode-switch jump lands on+ (landing-flash-source.ts / landing-flash-wysiwyg.ts). A dedicated class, not+ the agent-write flash, so its treatment can diverge from the agent wash later+ without touching attribution; it reuses the shared agent-flash keyframe today.+ Inline decoration in both editors, so one rule covers CodeMirror and+ ProseMirror. box-decoration-break keeps a wrapped multi-line range+ individually accented; duration matches FLASH_DURATION_MS. */+.ok-landing-flash {+ animation: agent-flash 2s var(--ease-out-strong) forwards;+ border-radius: 3px;+ box-decoration-break: clone;+ -webkit-box-decoration-break: clone;+ position: relative;+}++/* Reduced motion — static terracotta accent bar, no movement or background sweep. */+@media (prefers-reduced-motion: reduce) {+ .ok-landing-flash {+ animation: none;+ box-shadow: inset 3px 0 0 var(--color-agent);+ transition: box-shadow 2s ease;+ }+}+[data-agent-flash-state="editing"][data-agent-flash-position="append"].ProseMirror> *:nth-last-child(-n + 3),@@ -5107,6 +5131,13 @@ html.electron-mode [data-slot="sidebar-inner"] {animation-name: agent-breathing-dark;}+/* Boosted-alpha landing flash on the dark canvas (reduced motion already+ neutralizes the animation via a 0s duration, so the accent-bar fallback+ still stands). */+.dark .ok-landing-flash {+ animation-name: agent-flash-dark;+}+.dark [data-undo-state="ready"][data-undo-just-enabled="true"] {animation-name: undo-ready-dark;}diff --git a/packages/app/src/lib/command-menu-parity.test-helper.ts b/packages/app/src/lib/command-menu-parity.test-helper.tsindex 26a2a60f2..50da4028d 100644--- a/packages/app/src/lib/command-menu-parity.test-helper.ts+++ b/packages/app/src/lib/command-menu-parity.test-helper.ts@@ -24,7 +24,10 @@ export const PALETTE_COMMAND_IDS = new Set<string>([// Ids deliberately NOT palette rows — each with a stated reason.export const APP_RESERVED_IDS = new Map<string, string>([['delete', 'sidebar Trash id, distinct from the menu move-to-trash; not separately surfaced'],- ['toggle-source', 'source-mode toggle owned by the editor, not a palette action today'],+ [+ 'toggle-source',+ 'view-in-source jump dispatched by the Desktop editor context menu; reachable there, not a Cmd+K palette row',+ ],['save-version', 'deferred Project menu — not yet a shipped command anywhere'],['version-history', 'deferred Project menu — not yet a shipped command anywhere'],['focus-search', 'focus-routing id, not a user-facing command'],diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.tsindex 00b9a588e..3ed93f93b 100644--- a/packages/app/src/lib/desktop-bridge-types.ts+++ b/packages/app/src/lib/desktop-bridge-types.ts@@ -743,6 +743,7 @@ export interface OkEditorViewMenuStateSnapshot {readonly docPanelVisible?: boolean;readonly terminalVisible?: boolean;readonly terminalLive?: boolean;+ readonly canViewInSource?: boolean;}/**diff --git a/packages/app/src/lib/keyboard-shortcuts.test.ts b/packages/app/src/lib/keyboard-shortcuts.test.tsindex 0ea8c97b2..20fd4d7fd 100644--- a/packages/app/src/lib/keyboard-shortcuts.test.ts+++ b/packages/app/src/lib/keyboard-shortcuts.test.ts@@ -5,6 +5,7 @@ import {formatShortcutLabel,isEditableShortcutTarget,KEYBOARD_SHORTCUTS,+ type KeyboardShortcutId,matchesKeyboardShortcut,} from './keyboard-shortcuts';@@ -602,4 +603,70 @@ describe('keyboard shortcut registry', () => {expect(isEditableShortcutTarget({ isContentEditable: true })).toBe(true);expect(isEditableShortcutTarget({ tagName: 'BUTTON' })).toBe(false);});++ test('formats the mode-switch shortcuts per platform', () => {+ expect(formatShortcut('toggle-editor-mode', 'mac')).toBe('⌥⌘ M');+ expect(formatShortcut('toggle-editor-mode', 'windowsLinux')).toBe('Ctrl Alt M');+ expect(formatShortcut('view-source-at-cursor', 'mac')).toBe('⌥⌘ E');+ expect(formatShortcut('view-source-at-cursor', 'windowsLinux')).toBe('Ctrl Alt E');+ });++ test('registers the mode-switch commands in their shortcut-help categories', () => {+ const byId = new Map(KEYBOARD_SHORTCUTS.map((shortcut) => [shortcut.id, shortcut]));+ expect(byId.get('toggle-editor-mode')?.category).toBe('general');+ expect(byId.get('view-source-at-cursor')?.category).toBe('wysiwyg');+ });++ test('the mode-switch chords match only their own id across the whole registry', () => {+ // The matcher keys on `code`, so the produced `key` (layout-dependent when+ // Alt is held) is irrelevant here and set only to satisfy the event shape.+ const chords = [+ { id: 'toggle-editor-mode', code: 'KeyM', key: 'm' },+ { id: 'view-source-at-cursor', code: 'KeyE', key: 'e' },+ ] as const;+ for (const chord of chords) {+ const macEvent = {+ metaKey: true,+ ctrlKey: false,+ altKey: true,+ shiftKey: false,+ key: chord.key,+ code: chord.code,+ };+ const winEvent = {+ metaKey: false,+ ctrlKey: true,+ altKey: true,+ shiftKey: false,+ key: chord.key,+ code: chord.code,+ };+ for (const shortcut of KEYBOARD_SHORTCUTS) {+ // The public array widens `id` to `string`; every runtime value is a+ // registered id, so narrowing it back for the matcher lookup is sound.+ const id = shortcut.id as KeyboardShortcutId;+ expect(matchesKeyboardShortcut(macEvent, id, 'mac')).toBe(id === chord.id);+ expect(matchesKeyboardShortcut(winEvent, id, 'windowsLinux')).toBe(id === chord.id);+ }+ }+ });++ test('the mode toggle requires its Alt modifier so it never steals Cmd+M', () => {+ // Cmd+M (no Alt) is the macOS "minimize window" chord — the toggle must not+ // fire on it, nor on a bare M keypress.+ expect(+ matchesKeyboardShortcut(+ { metaKey: true, ctrlKey: false, altKey: false, key: 'm', code: 'KeyM' },+ 'toggle-editor-mode',+ 'mac',+ ),+ ).toBe(false);+ expect(+ matchesKeyboardShortcut(+ { metaKey: false, ctrlKey: false, altKey: false, key: 'm', code: 'KeyM' },+ 'toggle-editor-mode',+ 'mac',+ ),+ ).toBe(false);+ });});diff --git a/packages/app/src/lib/keyboard-shortcuts.ts b/packages/app/src/lib/keyboard-shortcuts.tsindex d3d10e8bd..b134e9e2d 100644--- a/packages/app/src/lib/keyboard-shortcuts.ts+++ b/packages/app/src/lib/keyboard-shortcuts.ts@@ -173,6 +173,24 @@ const KEYBOARD_SHORTCUT_DEFINITIONS = [},],},+ {+ // Toggles the visual/source editor and preserves scroll position both ways.+ // Follows the CmdOrCtrl+Alt+<letter> family the other view toggles use+ // (sidebar ⌥⌘S, doc panel ⌥⌘B), so it stays clear of TipTap/CodeMirror's+ // own single-modifier bindings and works from either editor.+ id: 'toggle-editor-mode',+ category: 'general',+ title: msg`Toggle source view`,+ description: msg`Switch between the visual and source editors, keeping your place.`,+ scope: msg`Editor`,+ bindings: [+ {+ mac: '⌥⌘ M',+ windowsLinux: 'Ctrl Alt M',+ match: { code: 'KeyM', anyMod: true, altKey: true, allowExtraModifiers: true },+ },+ ],+ },{id: 'toggle-terminal-panel',category: 'general',@@ -502,6 +520,23 @@ const KEYBOARD_SHORTCUT_DEFINITIONS = [},],},+ {+ // Jumps from the visual editor to the markdown behind the caret's block,+ // centered and highlighted. CmdOrCtrl+Alt+E stays clear of TipTap's ⌘E+ // inline-code binding (no Alt) and of the ⌥⌘M mode toggle above.+ id: 'view-source-at-cursor',+ category: 'wysiwyg',+ title: msg`View in source`,+ description: msg`Jump to the markdown source for the block at the cursor, centered and highlighted.`,+ scope: msg`Visual editor`,+ bindings: [+ {+ mac: '⌥⌘ E',+ windowsLinux: 'Ctrl Alt E',+ match: { code: 'KeyE', anyMod: true, altKey: true, allowExtraModifiers: true },+ },+ ],+ },{id: 'edit-with-ai',category: 'general',diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 9f7a04439..5de908694 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -1189,6 +1189,7 @@"LvdLef": ["Thanks for the feedback!"],"LwMxXg": ["Failed to open worktree."],"M-IF14": ["Report reference"],+ "M0jOcG": ["View in source markdown"],"M1OfV9": ["Next source diagnostic"],"M3ytY_": ["This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."@@ -2023,6 +2024,7 @@"blFttG": ["Search projects"],"bmC18N": ["Clearing local collaboration data for \"", ["docName"], "\" before reconnecting."],"brCtGB": ["History unavailable"],+ "buNXgr": ["Switch between the visual and source editors, keeping your place."],"bultyE": ["When enabled, the agent opens or refreshes the preview after each edit. Disable if you manage your own preview window (OK Desktop, a browser tab on another display, etc.)."],@@ -2058,6 +2060,9 @@"cRHuuI": ["Couldn't copy path"],"cRm498": ["No schema files in this project yet — create one to start validating."],"cSCbv3": ["BETA"],+ "cU-seF": [+ "Jump to the markdown source for the block at the cursor, centered and highlighted."+ ],"cUK8lW": [["conflictCount", "plural", { "one": ["#", " conflict"], "other": ["#", " conflicts"] }]],@@ -3006,6 +3011,7 @@"u7H-Wn": ["Show panel (", ["panelShortcutLabel"], ")"],"u7U_Ij": ["Link the selected text, or edit the link under the caret."],"uA_jXp": ["Switch and update branch"],+ "uBAxNB": ["Editor"],"uCaIdy": ["GitHub sign-in is missing or expired. Reconnect to resume syncing."],"uDlyqd": ["Document the architecture of this repo: create an overview page that links to a page per major module describing its responsibilities and entry points."@@ -3075,6 +3081,7 @@"vIxrEk": ["Fit width"],"vLyv1R": ["Hide"],"vPKX2i": ["In app (beta)"],+ "vPXOUw": ["Toggle source view"],"vQIVHc": ["Folder properties"],"vWc9a0": ["Type to edit; <0>⌘ Enter</0> saves, <1>Esc</1> cancels."],"vYPvPB": ["Switch project…"],@@ -3305,6 +3312,7 @@"zkz0Fg": ["Set up syncing"],"zlErBl": ["Page headings error response did not match RFC 9457"],"zo3Dl7": ["Toggle thumbnails"],+ "zq2eBA": ["View in source"],"zrP8HX": ["Frontmatter every document created from this template starts with. Values are YAML — a list is <0>[a, b]</0>; <1>{",["date"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex ce0319676..6c1b362e2 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -3512,6 +3512,10 @@ msgstr "editing [[{realCurrentDoc}]]"msgid "Editing broken MDX source: {reason}"msgstr "Editing broken MDX source: {reason}"+#: src/lib/keyboard-shortcuts.ts+msgid "Editor"+msgstr "Editor"+#: src/components/EditorModeToggle.tsxmsgid "Editor mode"msgstr "Editor mode"@@ -5140,6 +5144,10 @@ msgstr "Jump to page {pageNumber}"msgid "Jump to tab 1-8"msgstr "Jump to tab 1-8"+#: src/lib/keyboard-shortcuts.ts+msgid "Jump to the markdown source for the block at the cursor, centered and highlighted."+msgstr "Jump to the markdown source for the block at the cursor, centered and highlighted."+#: src/components/acp/ThreadHistoryMenu.tsx#: src/components/FolderOverview.tsx#: src/components/FolderTimelineCard.tsx@@ -8968,6 +8976,10 @@ msgstr "Surface"msgid "Switch and update branch"msgstr "Switch and update branch"+#: src/lib/keyboard-shortcuts.ts+msgid "Switch between the visual and source editors, keeping your place."+msgstr "Switch between the visual and source editors, keeping your place."+#: src/components/ShareBranchSwitchDialog.tsxmsgid "Switch branch"msgstr "Switch branch"@@ -9821,6 +9833,10 @@ msgstr "Toggle source comment"msgid "Toggle source tab focus mode"msgstr "Toggle source tab focus mode"+#: src/lib/keyboard-shortcuts.ts+msgid "Toggle source view"+msgstr "Toggle source view"+#: src/lib/keyboard-shortcuts.tsmsgid "Toggle strikethrough formatting."msgstr "Toggle strikethrough formatting."@@ -10250,6 +10266,14 @@ msgstr "View as text"msgid "View diff for edit {burstNumber} of {docName}"msgstr "View diff for edit {burstNumber} of {docName}"+#: src/lib/keyboard-shortcuts.ts+msgid "View in source"+msgstr "View in source"++#: src/editor/bubble-menu/ViewInSourceBubbleButton.tsx+msgid "View in source markdown"+msgstr "View in source markdown"+#: src/components/PublishToGitHubDialog.tsxmsgid "Visibility"msgstr "Visibility"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 30acd4850..26723cab5 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -1189,6 +1189,7 @@"LvdLef": ["Ţĥàńķś ƒōŕ ţĥē ƒēēďƀàćķ!"],"LwMxXg": ["Ƒàĩĺēď ţō ōƥēń ŵōŕķţŕēē."],"M-IF14": ["Ŕēƥōŕţ ŕēƒēŕēńćē"],+ "M0jOcG": ["Vĩēŵ ĩń śōũŕćē ḿàŕķďōŵń"],"M1OfV9": ["Ńēxţ śōũŕćē ďĩàĝńōśţĩć"],"M3ytY_": ["Ţĥĩś ĺōōķś ĺĩķē à ďŕĩvē ŕōōţ (ē.ĝ., Ć:\\). Śćàƒƒōĺďĩńĝ ĥēŕē ŵĩĺĺ śćàń àń ēńţĩŕē ďŕĩvē."@@ -2023,6 +2024,7 @@"blFttG": ["Śēàŕćĥ ƥŕōĴēćţś"],"bmC18N": ["Ćĺēàŕĩńĝ ĺōćàĺ ćōĺĺàƀōŕàţĩōń ďàţà ƒōŕ \"", ["docName"], "\" ƀēƒōŕē ŕēćōńńēćţĩńĝ."],"brCtGB": ["Ĥĩśţōŕŷ ũńàvàĩĺàƀĺē"],+ "buNXgr": ["Śŵĩţćĥ ƀēţŵēēń ţĥē vĩśũàĺ àńď śōũŕćē ēďĩţōŕś, ķēēƥĩńĝ ŷōũŕ ƥĺàćē."],"bultyE": ["Ŵĥēń ēńàƀĺēď, ţĥē àĝēńţ ōƥēńś ōŕ ŕēƒŕēśĥēś ţĥē ƥŕēvĩēŵ àƒţēŕ ēàćĥ ēďĩţ. Ďĩśàƀĺē ĩƒ ŷōũ ḿàńàĝē ŷōũŕ ōŵń ƥŕēvĩēŵ ŵĩńďōŵ (ŌĶ Ďēśķţōƥ, à ƀŕōŵśēŕ ţàƀ ōń àńōţĥēŕ ďĩśƥĺàŷ, ēţć.)."],@@ -2058,6 +2060,9 @@"cRHuuI": ["Ćōũĺďń'ţ ćōƥŷ ƥàţĥ"],"cRm498": ["Ńō śćĥēḿà ƒĩĺēś ĩń ţĥĩś ƥŕōĴēćţ ŷēţ — ćŕēàţē ōńē ţō śţàŕţ vàĺĩďàţĩńĝ."],"cSCbv3": ["ßĒŢÀ"],+ "cU-seF": [+ "ĵũḿƥ ţō ţĥē ḿàŕķďōŵń śōũŕćē ƒōŕ ţĥē ƀĺōćķ àţ ţĥē ćũŕśōŕ, ćēńţēŕēď àńď ĥĩĝĥĺĩĝĥţēď."+ ],"cUK8lW": [["conflictCount", "plural", { "one": ["#", " ćōńƒĺĩćţ"], "other": ["#", " ćōńƒĺĩćţś"] }]],@@ -3006,6 +3011,7 @@"u7H-Wn": ["Śĥōŵ ƥàńēĺ (", ["panelShortcutLabel"], ")"],"u7U_Ij": ["Ĺĩńķ ţĥē śēĺēćţēď ţēxţ, ōŕ ēďĩţ ţĥē ĺĩńķ ũńďēŕ ţĥē ćàŕēţ."],"uA_jXp": ["Śŵĩţćĥ àńď ũƥďàţē ƀŕàńćĥ"],+ "uBAxNB": ["Ēďĩţōŕ"],"uCaIdy": ["ĜĩţĤũƀ śĩĝń-ĩń ĩś ḿĩśśĩńĝ ōŕ ēxƥĩŕēď. Ŕēćōńńēćţ ţō ŕēśũḿē śŷńćĩńĝ."],"uDlyqd": ["Ďōćũḿēńţ ţĥē àŕćĥĩţēćţũŕē ōƒ ţĥĩś ŕēƥō: ćŕēàţē àń ōvēŕvĩēŵ ƥàĝē ţĥàţ ĺĩńķś ţō à ƥàĝē ƥēŕ ḿàĴōŕ ḿōďũĺē ďēśćŕĩƀĩńĝ ĩţś ŕēśƥōńśĩƀĩĺĩţĩēś àńď ēńţŕŷ ƥōĩńţś."@@ -3075,6 +3081,7 @@"vIxrEk": ["Ƒĩţ ŵĩďţĥ"],"vLyv1R": ["Ĥĩďē"],"vPKX2i": ["Ĩń àƥƥ (ƀēţà)"],+ "vPXOUw": ["Ţōĝĝĺē śōũŕćē vĩēŵ"],"vQIVHc": ["Ƒōĺďēŕ ƥŕōƥēŕţĩēś"],"vWc9a0": ["Ţŷƥē ţō ēďĩţ; <0>⌘ Ēńţēŕ</0> śàvēś, <1>Ēść</1> ćàńćēĺś."],"vYPvPB": ["Śŵĩţćĥ ƥŕōĴēćţ…"],@@ -3305,6 +3312,7 @@"zkz0Fg": ["Śēţ ũƥ śŷńćĩńĝ"],"zlErBl": ["Ƥàĝē ĥēàďĩńĝś ēŕŕōŕ ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ŔƑĆ 9457"],"zo3Dl7": ["Ţōĝĝĺē ţĥũḿƀńàĩĺś"],+ "zq2eBA": ["Vĩēŵ ĩń śōũŕćē"],"zrP8HX": ["Ƒŕōńţḿàţţēŕ ēvēŕŷ ďōćũḿēńţ ćŕēàţēď ƒŕōḿ ţĥĩś ţēḿƥĺàţē śţàŕţś ŵĩţĥ. Vàĺũēś àŕē ŶÀḾĹ — à ĺĩśţ ĩś <0>[à, ƀ]</0>; <1>{",["date"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 3d6b19267..4cac890fd 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -3508,6 +3508,10 @@ msgstr ""msgid "Editing broken MDX source: {reason}"msgstr ""+#: src/lib/keyboard-shortcuts.ts+msgid "Editor"+msgstr ""+#: src/components/EditorModeToggle.tsxmsgid "Editor mode"msgstr ""@@ -5136,6 +5140,10 @@ msgstr ""msgid "Jump to tab 1-8"msgstr ""+#: src/lib/keyboard-shortcuts.ts+msgid "Jump to the markdown source for the block at the cursor, centered and highlighted."+msgstr ""+#: src/components/acp/ThreadHistoryMenu.tsx#: src/components/FolderOverview.tsx#: src/components/FolderTimelineCard.tsx@@ -8964,6 +8972,10 @@ msgstr ""msgid "Switch and update branch"msgstr ""+#: src/lib/keyboard-shortcuts.ts+msgid "Switch between the visual and source editors, keeping your place."+msgstr ""+#: src/components/ShareBranchSwitchDialog.tsxmsgid "Switch branch"msgstr ""@@ -9817,6 +9829,10 @@ msgstr ""msgid "Toggle source tab focus mode"msgstr ""+#: src/lib/keyboard-shortcuts.ts+msgid "Toggle source view"+msgstr ""+#: src/lib/keyboard-shortcuts.tsmsgid "Toggle strikethrough formatting."msgstr ""@@ -10246,6 +10262,14 @@ msgstr ""msgid "View diff for edit {burstNumber} of {docName}"msgstr ""+#: src/lib/keyboard-shortcuts.ts+msgid "View in source"+msgstr ""++#: src/editor/bubble-menu/ViewInSourceBubbleButton.tsx+msgid "View in source markdown"+msgstr ""+#: src/components/PublishToGitHubDialog.tsxmsgid "Visibility"msgstr ""diff --git a/packages/app/tests/meta/tall-doc-fixture.test.ts b/packages/app/tests/meta/tall-doc-fixture.test.tsnew file mode 100644index 000000000..907d16a54--- /dev/null+++ b/packages/app/tests/meta/tall-doc-fixture.test.ts@@ -0,0 +1,98 @@+import { describe, expect, test } from 'vitest';+import {+ blockMarker,+ type GenerateTallDocOptions,+ generateTallDoc,+ SHIFTER_URL_PREFIX,+ type TallDocBlock,+ type TallDocManifest,+ type TallDocShifter,+ type TallDocShifterSpec,+} from '../stress/_helpers/tall-doc-fixture.ts';++describe('tall-doc fixture generator', () => {+ test('emits one top-level block per requested block with a unique marker', () => {+ const opts: GenerateTallDocOptions = { blockCount: 40 };+ const { markdown, manifest } = generateTallDoc(opts);+ expect(manifest.blockCount).toBe(40);+ expect(manifest.blocks).toHaveLength(40);++ const topLevelBlocks = markdown.split('\n\n');+ expect(topLevelBlocks).toHaveLength(40);++ const blocks: readonly TallDocBlock[] = manifest.blocks;+ const markers = blocks.map((b) => b.marker);+ expect(new Set(markers).size).toBe(40);+ for (const block of manifest.blocks) {+ expect(block.marker).toBe(blockMarker(block.index));+ // The marker must appear verbatim in the rendered source so an assertion+ // can locate the block by text in either editor.+ expect(markdown).toContain(block.marker);+ }+ });++ test('block markers are zero-padded and stable across regeneration', () => {+ expect(blockMarker(0)).toBe('OKBLK0000');+ expect(blockMarker(42)).toBe('OKBLK0042');+ expect(blockMarker(1234)).toBe('OKBLK1234');+ const a = generateTallDoc({ blockCount: 10 });+ const b = generateTallDoc({ blockCount: 10 });+ expect(a.markdown).toBe(b.markdown);+ });++ test('every block marker is emphasised so the rendered block has an element child', () => {+ const { markdown } = generateTallDoc({ blockCount: 5 });+ for (let i = 0; i < 5; i++) {+ expect(markdown).toContain(`**${blockMarker(i)}**`);+ }+ });++ test('positioned shifters are spliced after their block and recorded with a deterministic delay', () => {+ const specs: readonly TallDocShifterSpec[] = [+ { afterBlock: 2, delayMs: 250, heightPx: 800 },+ { afterBlock: 4 },+ ];+ const { markdown, manifest } = generateTallDoc({ blockCount: 6, shifters: specs });++ const shifters: readonly TallDocShifter[] = manifest.shifters;+ expect(shifters).toHaveLength(2);+ const [first, second] = shifters;+ expect(first?.afterBlock).toBe(2);+ expect(first?.delayMs).toBe(250);+ expect(first?.heightPx).toBe(800);+ expect(first?.url.startsWith(SHIFTER_URL_PREFIX)).toBe(true);+ // Unspecified delay/height fall back to deterministic defaults, never random.+ expect(second?.delayMs).toBeGreaterThan(0);+ expect(second?.heightPx).toBeGreaterThan(0);++ // The shifter image renders immediately after its block and before the next.+ const blockThreeStart = markdown.indexOf(blockMarker(3));+ const shifterMarkup = markdown.indexOf(`(${first?.url})`);+ const blockTwoStart = markdown.indexOf(blockMarker(2));+ expect(shifterMarkup).toBeGreaterThan(blockTwoStart);+ expect(shifterMarkup).toBeLessThan(blockThreeStart);+ });++ test('shifter block count is separate from the paragraph block count', () => {+ const { manifest } = generateTallDoc({+ blockCount: 3,+ shifters: [{ afterBlock: 0 }, { afterBlock: 1 }],+ });+ expect(manifest.blockCount).toBe(3);+ expect(manifest.blocks).toHaveLength(3);+ expect(manifest.shifters).toHaveLength(2);+ });++ test('rejects a non-positive block count rather than emitting an empty doc', () => {+ expect(() => generateTallDoc({ blockCount: 0 })).toThrow(/positive integer/);+ expect(() => generateTallDoc({ blockCount: -3 })).toThrow(/positive integer/);+ });++ test('manifest is a plain data record safe to assert against', () => {+ const { manifest } = generateTallDoc({ blockCount: 2 });+ // No functions on the manifest — tests assert on values, and the shape+ // survives a structured-clone round trip (e.g. crossing an evaluate boundary).+ const roundTripped = structuredClone(manifest) as TallDocManifest;+ expect(roundTripped).toEqual(manifest);+ });+});diff --git a/packages/app/tests/stress/_helpers/index.ts b/packages/app/tests/stress/_helpers/index.tsindex 4a6411df9..0cb262faa 100644--- a/packages/app/tests/stress/_helpers/index.ts+++ b/packages/app/tests/stress/_helpers/index.ts@@ -28,11 +28,22 @@ export {type WorkerServer,} from './fixtures.ts';export { waitForGraphSimulationSettled } from './graph.ts';+export {+ assertLanded,+ injectForcedEstimateError,+ landingMarkCount,+ readSourceCaretHead,+ readWysiwygCaretHead,+ scrollWysiwygBlockToTop,+ toggleMode,+ waitForLandingSettled,+} from './landing.ts';export {installClockAfterSync,type WaitForProviderOptions,waitForActiveProviderSynced,} from './provider.ts';+export { matchIsWithinReadableScrollport } from './scrollport.ts';export {checkCollabSync,closeServerLog,@@ -55,4 +66,5 @@ export {waitForSlashMenuFirstOption,waitForSlashMenuOpen,} from './slash-menu.ts';+export { blockMarker, generateTallDoc } from './tall-doc-fixture.ts';export { createMp3Buffer, createMp4Buffer, createPngBuffer } from './upload-fixtures.ts';diff --git a/packages/app/tests/stress/_helpers/landing.ts b/packages/app/tests/stress/_helpers/landing.tsnew file mode 100644index 000000000..f48d136e9--- /dev/null+++ b/packages/app/tests/stress/_helpers/landing.ts@@ -0,0 +1,556 @@+/**+ * End-to-end helpers for mode-switch landing assertions.+ *+ * Landing tests are worthless if they pass by accident — a missing target that+ * reads as "not visible, so skip" is a false green. Every helper here is built+ * around one rule: the thing being asserted about must be proven present before+ * any position claim is made, and its absence fails loudly. The two editors are+ * measured asymmetrically because their virtualization differs — WYSIWYG keeps+ * every block in the DOM under `content-visibility: auto` (so a landed block is+ * checked for materialization on its rendered child element, and a decoy far+ * block is checked to be non-materialized as a wrong-geometry cross-check),+ * while CodeMirror renders only the lines near the viewport (so off-viewport+ * lines have no DOM at all, and assertions go through the view's own coordinate+ * lookup, never a bounding box).+ *+ * The settle wait observes the `ok/landing/*` performance marks the landing+ * controller emits rather than sleeping, so it tracks the app's real terminal+ * signal (land or abandon) instead of a guessed duration.+ */++import { expect, type Page } from '@playwright/test';++/** The two editor modes, mirrored locally so the helper needs no app-src import. */+type LandingMode = 'wysiwyg' | 'source';++/** Where a landing is expected to place its target within the readable area. */+type LandingPlacement = 'top' | 'center';++const SCROLL_CONTAINER_SELECTOR = '[data-testid="editor-scroll-container"]';+const WYSIWYG_SELECTOR = '.ProseMirror:not(.composer-prosemirror)';+const SOURCE_SELECTOR = '.cm-editor';+const CHUNK_WRAPPER_SELECTOR = `${WYSIWYG_SELECTOR} .ok-chunk-wrapper`;+/** The toolbar overlays the top of the shared scroller; the readable area starts below it. */+const TOOLBAR_OVERLAP_PX = 56;++const MODE_RADIO_NAME: Record<LandingMode, string> = {+ wysiwyg: 'Visual editor',+ source: 'Markdown source',+};++/**+ * Click the mode toggle and wait until the target editor is mounted and+ * visible. Both editors stay in the DOM across a flip; the swap is a+ * content-visibility class change, so `toBeVisible` is the honest ready signal.+ */+export async function toggleMode(page: Page, to: LandingMode): Promise<void> {+ await page.getByRole('radio', { name: MODE_RADIO_NAME[to] }).click();+ const mounted = to === 'source' ? SOURCE_SELECTOR : WYSIWYG_SELECTOR;+ await expect(page.locator(mounted).first()).toBeVisible();+}++/** Which terminal signal a landing produced, plus its recorded payload. */+interface LandingMark {+ kind: 'land' | 'abandoned';+ grade: string;+ delta: number;+ /** Only present on an abandoned landing. */+ target?: number;+}++const LAND_MARK = 'ok/landing/land';+const ABANDON_MARK = 'ok/landing/abandoned';++/**+ * Count of terminal landing marks (`land` + `abandoned`) emitted so far. A+ * cancelled landing emits neither, by design. Snapshot this before an action+ * and pass it as `since` to `waitForLandingSettled` so a test that toggles more+ * than once waits for the NEXT landing, not a stale earlier one.+ */+export async function landingMarkCount(page: Page): Promise<number> {+ return page.evaluate(+ ([land, abandon]) =>+ performance.getEntriesByName(land).length + performance.getEntriesByName(abandon).length,+ [LAND_MARK, ABANDON_MARK] as const,+ );+}++interface RawMarkPayload {+ name: string;+ props: Record<string, string>;+}++function parseMark(raw: RawMarkPayload | null): LandingMark {+ if (!raw) {+ throw new Error('waitForLandingSettled: a terminal landing mark was counted but not readable');+ }+ const kind = raw.name === ABANDON_MARK ? 'abandoned' : 'land';+ const mark: LandingMark = {+ kind,+ grade: raw.props.grade ?? 'unknown',+ delta: Number(raw.props.delta ?? 'NaN'),+ };+ if (kind === 'abandoned') mark.target = Number(raw.props.target ?? 'NaN');+ return mark;+}++/**+ * Wait until the landing controller records a terminal mark beyond the `since`+ * baseline, then return the latest one parsed. Fails loudly if none appears in+ * time — a landing that never lands, cancels, or abandons is a defect, not a+ * pass. Reads the mark's DevTools-track properties to recover the grade, delta,+ * and (for an abandon) the target the controller stamped on it.+ */+export async function waitForLandingSettled(+ page: Page,+ opts?: { since?: number; timeout?: number },+): Promise<LandingMark> {+ const since = opts?.since ?? 0;+ await expect+ .poll(() => landingMarkCount(page), { timeout: opts?.timeout ?? 10_000 })+ .toBeGreaterThan(since);++ const raw = await page.evaluate(+ ([land, abandon]) => {+ const entries = [+ ...performance.getEntriesByName(land),+ ...performance.getEntriesByName(abandon),+ ].sort((a, b) => a.startTime - b.startTime);+ const latest = entries[entries.length - 1];+ if (!latest) return null;+ // `mark()` emits via `performance.measure(name, { detail })`, stamping the+ // payload as DevTools-track property tuples. Recover them into a record.+ const detail = (latest as PerformanceMeasure & { detail?: unknown }).detail as+ | { devtools?: { properties?: Array<[string, string]> } }+ | undefined;+ const props: Record<string, string> = {};+ for (const [k, v] of detail?.devtools?.properties ?? []) props[k] = v;+ return { name: latest.name, props };+ },+ [LAND_MARK, ABANDON_MARK] as const,+ );+ return parseMark(raw);+}++/**+ * Force the WYSIWYG chunk-height estimate to a wrong value by overriding the+ * `--ok-cv-h` custom property through a page style tag, then confirm it applies+ * at runtime. A page style tag is required: an init-script injection runs before+ * the app's own stylesheet and is overridden by it. Over-tall estimates make a+ * naive landing overshoot, which is the failure a landing test must be able to+ * provoke on demand.+ */+export async function injectForcedEstimateError(page: Page, cvHeightPx = 400): Promise<void> {+ const value = `${cvHeightPx}px`;+ await page.addStyleTag({ content: `:root{--ok-cv-h:${value};}` });+ const applied = await page.evaluate(+ ([wrapperSelector]) => {+ const root = getComputedStyle(document.documentElement).getPropertyValue('--ok-cv-h').trim();+ const wrapper = document.querySelector<HTMLElement>(wrapperSelector);+ const onWrapper = wrapper+ ? getComputedStyle(wrapper).getPropertyValue('--ok-cv-h').trim()+ : null;+ return { root, onWrapper };+ },+ [CHUNK_WRAPPER_SELECTOR] as const,+ );+ expect(applied.root, 'forced --ok-cv-h did not apply on :root at runtime').toBe(value);+ if (applied.onWrapper !== null) {+ // When a chunk wrapper exists the override must reach it (it is the actual+ // consumer of the variable) — otherwise the estimate error would be inert.+ expect(applied.onWrapper, 'forced --ok-cv-h did not inherit to the chunk wrapper').toBe(value);+ }+}++interface SourceLandingProbe {+ materialized: boolean;+ visible: boolean;+ topOffsetFromReadableTop: number;+ centerOffsetFromReadableCenter: number;+ readableHeight: number;+ caretHead: number;+}++interface WysiwygLandingProbe {+ materialized: boolean;+ visible: boolean;+ /**+ * Whether the decoy block is within the readable area. The wrong-geometry+ * cross-check is geometric, not content-visibility-based: whether Chromium+ * actually skips an off-screen chunk in a headless run is a runtime decision,+ * but an off-screen block's box is always far outside the readable band.+ */+ decoyVisible: boolean | null;+ topOffsetFromReadableTop: number;+ centerOffsetFromReadableCenter: number;+ readableHeight: number;+}++interface AssertLandedSourceOptions {+ mode: 'source';+ /** Unique text of the target block; located in the CodeMirror document. */+ targetText: string;+ placement?: LandingPlacement;+ /** Toolbar overlap; defaults to the shared 56px. */+ toolbarPx?: number;+}++interface AssertLandedWysiwygOptions {+ mode: 'wysiwyg';+ /** Marker of the block that must be landed on and materialized. */+ targetMarker: string;+ /**+ * Marker of a far block that must NOT be materialized — the wrong-geometry+ * cross-check that distinguishes a real landing from "everything rendered" or+ * a landing at the wrong end of the document.+ */+ decoyMarker?: string;+ placement?: LandingPlacement;+ toolbarPx?: number;+}++type AssertLandedOptions = AssertLandedSourceOptions | AssertLandedWysiwygOptions;++/**+ * Assert that a landing brought its target into the readable area, measured the+ * way each editor actually virtualizes. Structural absence (target text, editor+ * view, or the probe element missing) throws inside the page so the failure is+ * loud and specific; position claims are asserted from returned measurements.+ */+export async function assertLanded(page: Page, options: AssertLandedOptions): Promise<void> {+ const { placement } = options;+ const toolbarPx = options.toolbarPx ?? TOOLBAR_OVERLAP_PX;+ if (options.mode === 'source') {+ await assertLandedSource(page, options.targetText, placement, toolbarPx);+ } else {+ await assertLandedWysiwyg(+ page,+ options.targetMarker,+ options.decoyMarker,+ placement,+ toolbarPx,+ );+ }+}++async function assertLandedSource(+ page: Page,+ targetText: string,+ placement: LandingPlacement | undefined,+ toolbarPx: number,+): Promise<void> {+ const probe = await page.evaluate(+ ({ targetText, toolbarPx, scrollSelector, sourceSelector }): SourceLandingProbe => {+ const scroller = Array.from(document.querySelectorAll<HTMLElement>(scrollSelector)).find(+ (el) => el.getClientRects().length > 0,+ );+ if (!scroller) throw new Error('assertLanded(source): no visible scroll container');++ const content = Array.from(document.querySelectorAll<HTMLElement>(sourceSelector))+ .find((el) => el.getClientRects().length > 0)+ ?.querySelector('.cm-content');+ // CodeMirror attaches its view to the content DOM. Read it the way the+ // library's own `EditorView.findFromDOM` does, tolerating the field rename+ // across CodeMirror versions. A miss throws — the source oracle cannot be+ // honest without the view's coordinate lookup.+ const handle = content as+ | (Element & {+ cmTile?: { root?: { view?: unknown } };+ cmView?: { rootView?: { view?: unknown } };+ })+ | null+ | undefined;+ const view = (handle?.cmTile?.root?.view ?? handle?.cmView?.rootView?.view) as+ | {+ state: {+ doc: { toString(): string; length: number };+ selection: { main: { head: number } };+ };+ viewport: { from: number; to: number };+ coordsAtPos(pos: number): { top: number; bottom: number } | null;+ }+ | undefined;+ if (!view)+ throw new Error('assertLanded(source): no CodeMirror EditorView on the content DOM');++ const docText = view.state.doc.toString();+ const idx = docText.indexOf(targetText);+ if (idx === -1) {+ throw new Error(`assertLanded(source): target text "${targetText}" not in the document`);+ }++ const scrollRect = scroller.getBoundingClientRect();+ const readableTop = scrollRect.top + toolbarPx;+ const readableHeight = scrollRect.bottom - readableTop;+ const inViewport = idx >= view.viewport.from && idx <= view.viewport.to;+ const coords = view.coordsAtPos(idx);+ if (!inViewport || !coords) {+ return {+ materialized: false,+ visible: false,+ topOffsetFromReadableTop: Number.NaN,+ centerOffsetFromReadableCenter: Number.NaN,+ readableHeight,+ caretHead: view.state.selection.main.head,+ };+ }+ const center = (coords.top + coords.bottom) / 2;+ return {+ materialized: true,+ visible: coords.top < scrollRect.bottom && coords.bottom > readableTop,+ topOffsetFromReadableTop: coords.top - readableTop,+ centerOffsetFromReadableCenter: center - (readableTop + scrollRect.bottom) / 2,+ readableHeight,+ caretHead: view.state.selection.main.head,+ };+ },+ {+ targetText,+ toolbarPx,+ scrollSelector: SCROLL_CONTAINER_SELECTOR,+ sourceSelector: SOURCE_SELECTOR,+ },+ );++ assertPlacement('source', probe, placement);+}++async function assertLandedWysiwyg(+ page: Page,+ targetMarker: string,+ decoyMarker: string | undefined,+ placement: LandingPlacement | undefined,+ toolbarPx: number,+): Promise<void> {+ const probe = await page.evaluate(+ ({+ targetMarker,+ decoyMarker,+ toolbarPx,+ scrollSelector,+ wrapperSelector,+ }): WysiwygLandingProbe => {+ const scroller = Array.from(document.querySelectorAll<HTMLElement>(scrollSelector)).find(+ (el) => el.getClientRects().length > 0,+ );+ if (!scroller) throw new Error('assertLanded(wysiwyg): no visible scroll container');++ const wrappers = Array.from(document.querySelectorAll<HTMLElement>(wrapperSelector));+ const findWrapper = (marker: string): HTMLElement | undefined =>+ wrappers.find((w) => w.textContent?.includes(marker));++ const target = findWrapper(targetMarker);+ if (!target) {+ throw new Error(`assertLanded(wysiwyg): target block "${targetMarker}" not in the DOM`);+ }+ // Materialization is read on the wrapper's first element child, not the+ // wrapper: content-visibility skips the layout of a chunk's descendants, so+ // a skipped block's child has a zero-height box while a painted block's+ // child has a real one. The `checkVisibility` API is unreliable headless+ // (it reports a just-scrolled-in block as still skipped and an off-screen+ // one as visible), so the laid-out box height is the honest signal. A+ // wrapper with no element child means the block-shape assumption changed.+ const targetProbe = target.firstElementChild;+ if (!targetProbe) {+ throw new Error(+ `assertLanded(wysiwyg): target block "${targetMarker}" has no element child to probe`,+ );+ }+ const materialized = targetProbe.getBoundingClientRect().height > 0;++ const scrollRect = scroller.getBoundingClientRect();+ const readableTop = scrollRect.top + toolbarPx;+ const readableHeight = scrollRect.bottom - readableTop;+ const inBand = (r: DOMRect): boolean => r.top < scrollRect.bottom && r.bottom > readableTop;++ let decoyVisible: boolean | null = null;+ if (decoyMarker !== undefined) {+ const decoy = findWrapper(decoyMarker);+ if (!decoy) {+ throw new Error(`assertLanded(wysiwyg): decoy block "${decoyMarker}" not in the DOM`);+ }+ decoyVisible = inBand(decoy.getBoundingClientRect());+ }++ const rect = target.getBoundingClientRect();+ const center = rect.top + rect.height / 2;+ return {+ materialized,+ visible: inBand(rect),+ decoyVisible,+ topOffsetFromReadableTop: rect.top - readableTop,+ centerOffsetFromReadableCenter: center - (readableTop + scrollRect.bottom) / 2,+ readableHeight,+ };+ },+ {+ targetMarker,+ decoyMarker: decoyMarker ?? undefined,+ toolbarPx,+ scrollSelector: SCROLL_CONTAINER_SELECTOR,+ wrapperSelector: CHUNK_WRAPPER_SELECTOR,+ },+ );++ expect(+ probe.materialized,+ `WYSIWYG target "${targetMarker}" is content-visibility-skipped (not landed)`,+ ).toBe(true);+ if (probe.decoyVisible !== null) {+ expect(+ probe.decoyVisible,+ `WYSIWYG decoy "${decoyMarker}" is within the readable area — the landing rendered the wrong region`,+ ).toBe(false);+ }+ assertPlacement('wysiwyg', probe, placement);+}++/**+ * Assert the target is present, materialized, and within the readable area. When+ * a placement is given, additionally pin it to the top or centre of that area;+ * with no placement the check is visibility-only (the target landed on-screen,+ * without a claim about where).+ */+function assertPlacement(+ mode: LandingMode,+ probe: SourceLandingProbe | WysiwygLandingProbe,+ placement: LandingPlacement | undefined,+): void {+ expect(+ probe.materialized,+ `${mode} target is not materialized (not rendered in the viewport)`,+ ).toBe(true);+ expect(probe.visible, `${mode} target is not within the readable area after landing`).toBe(true);++ const band = probe.readableHeight;+ if (placement === 'top') {+ // The anchor block should sit near the top of the readable area, tolerating+ // block granularity (a degraded grade may land an adjacent block at the top)+ // but not a landing that leaves it at the bottom or off-screen.+ expect(+ probe.topOffsetFromReadableTop,+ `${mode} top-placed target is not near the top of the readable area`,+ ).toBeLessThan(band * 0.5);+ expect(probe.topOffsetFromReadableTop).toBeGreaterThan(-band * 0.25);+ } else if (placement === 'center') {+ expect(+ Math.abs(probe.centerOffsetFromReadableCenter),+ `${mode} center-placed target is not near the readable-area center`,+ ).toBeLessThan(band * 0.3);+ }+}++/**+ * Scroll the shared scroller so the WYSIWYG block carrying `marker` sits at the+ * top of the readable area, honoring the toolbar scroll-padding. Used to set up+ * a non-trivial landing anchor: with the block at the top, a mode flip captures+ * it as the viewport anchor.+ *+ * Convergence is required, not a single `scrollIntoView`: off-screen chunks+ * reserve an over-tall `content-visibility` estimate, so a one-shot scroll+ * overshoots and the block lands above the fold. This measures the block's real+ * rect each frame and corrects until it rests at the readable top — the same+ * measure-and-redispatch the landing controller does.+ *+ * It also holds until the block has actually painted: a chunk just scrolled into+ * view is content-visibility-skipped for a frame, and while skipped its content+ * is not laid out, so ProseMirror's `posAtCoords` finds nothing there and the+ * subsequent mode flip captures no anchor. Waiting for the child's box to gain+ * height is the paint signal.+ *+ * Reaching the top for a single frame is not enough. When the target rests at the+ * readable top, the blocks that entered the render margin just above it refine+ * their over-tall `content-visibility` estimate to real heights over the next few+ * frames, silently dragging the target upward while `scrollTop` holds. So this+ * requires the block to hold at the top across several consecutive frames before+ * returning: it re-corrects whenever a refinement knocks it off, and only reports+ * a settled viewport — the precondition a real user's flip acts on. Returns the+ * residual offset so a caller can assert it converged.+ */+export async function scrollWysiwygBlockToTop(page: Page, marker: string): Promise<number> {+ return page.evaluate(+ async ({ marker, wrapperSelector, scrollSelector, toolbarPx }) => {+ const scroller = Array.from(document.querySelectorAll<HTMLElement>(scrollSelector)).find(+ (el) => el.getClientRects().length > 0,+ );+ if (!scroller) throw new Error('scrollWysiwygBlockToTop: no visible scroll container');+ const findWrapper = (): HTMLElement | undefined =>+ Array.from(document.querySelectorAll<HTMLElement>(wrapperSelector)).find((w) =>+ w.textContent?.includes(marker),+ );+ if (!findWrapper())+ throw new Error(`scrollWysiwygBlockToTop: block "${marker}" not in the DOM`);+ const nextFrame = (): Promise<void> =>+ new Promise((resolve) => {+ requestAnimationFrame(() => resolve());+ });++ const REQUIRED_STABLE_FRAMES = 5;+ const MAX_FRAMES = 90;+ let delta = Number.POSITIVE_INFINITY;+ let stableFrames = 0;+ for (let i = 0; i < MAX_FRAMES; i++) {+ const wrapper = findWrapper();+ if (!wrapper) break;+ const readableTop = scroller.getBoundingClientRect().top + toolbarPx;+ delta = wrapper.getBoundingClientRect().top - readableTop;+ const painted = (wrapper.firstElementChild?.getBoundingClientRect().height ?? 0) > 0;+ if (Math.abs(delta) <= 2 && painted) {+ stableFrames += 1;+ if (stableFrames >= REQUIRED_STABLE_FRAMES) break;+ } else {+ stableFrames = 0;+ if (Math.abs(delta) > 2) scroller.scrollTop += delta;+ }+ await nextFrame();+ }+ return delta;+ },+ {+ marker,+ wrapperSelector: CHUNK_WRAPPER_SELECTOR,+ scrollSelector: SCROLL_CONTAINER_SELECTOR,+ toolbarPx: TOOLBAR_OVERLAP_PX,+ },+ );+}++/**+ * The CodeMirror caret head offset, read from the view's own state. Used by the+ * caret oracle: a plain toggle must leave it unchanged, a jump must place it at+ * the landed range start. Throws if the source view is not reachable.+ */+export async function readSourceCaretHead(page: Page): Promise<number> {+ return page.evaluate((sourceSelector) => {+ const content = Array.from(document.querySelectorAll<HTMLElement>(sourceSelector))+ .find((el) => el.getClientRects().length > 0)+ ?.querySelector('.cm-content');+ const handle = content as+ | (Element & {+ cmTile?: { root?: { view?: unknown } };+ cmView?: { rootView?: { view?: unknown } };+ })+ | null+ | undefined;+ const view = (handle?.cmTile?.root?.view ?? handle?.cmView?.rootView?.view) as+ | { state: { selection: { main: { head: number } } } }+ | undefined;+ if (!view) throw new Error('readSourceCaretHead: no CodeMirror EditorView on the content DOM');+ return view.state.selection.main.head;+ }, SOURCE_SELECTOR);+}++/**+ * The ProseMirror caret head, read from the active editor's own state. The+ * source-to-WYSIWYG caret oracle uses it: a plain toggle must leave the WYSIWYG+ * selection unchanged. Reads ProseMirror state, not the DOM, so it is valid even+ * while the WYSIWYG view is CSS-hidden underneath source mode (the editor stays+ * mounted across a flip). Throws if the dev-exposed editor is not reachable.+ */+export async function readWysiwygCaretHead(page: Page): Promise<number> {+ return page.evaluate(() => {+ const editor = window.__activeEditor;+ if (!editor) throw new Error('readWysiwygCaretHead: window.__activeEditor not set');+ return editor.state.selection.head;+ });+}diff --git a/packages/app/tests/stress/_helpers/scrollport.ts b/packages/app/tests/stress/_helpers/scrollport.tsnew file mode 100644index 000000000..44c180bfd--- /dev/null+++ b/packages/app/tests/stress/_helpers/scrollport.ts@@ -0,0 +1,57 @@+/**+ * Shared scrollport-containment predicate for scroll/landing e2e tests.+ *+ * The editor toolbar is absolute-positioned over the top of the shared scroller,+ * so a match sitting behind it is on-screen but not readable. This one definition+ * encodes that readable band; a per-test copy that omitted the toolbar inset+ * silently could not detect toolbar occlusion, and the two copies had already+ * drifted apart on their inset and tolerance.+ */++import type { Page } from '@playwright/test';++/** Pixels of the scrollport's top edge overlapped by the absolute toolbar. */+const TOOLBAR_OVERLAP_PX = 56;++interface ScrollportContainmentOptions {+ /** Toolbar overlap to exclude at the top of the scrollport. */+ toolbarPx?: number;+ /** Slack on each edge, absorbing sub-pixel and block-granularity rounding. */+ tolerancePx?: number;+}++/**+ * True iff the first `matchSelector` element inside the painted editor scroll+ * container sits fully within the readable band: below the toolbar overlap and+ * above the scroller's bottom edge. Returns false when the container or match is+ * absent, so a missing target never reads as "contained".+ *+ * The container is chosen by layout boxes rather than a first-match query: a+ * hidden `<Activity>` entry keeps its scroll container in the DOM, so more than+ * one can exist at once and only the painted one is the active scrollport.+ */+export async function matchIsWithinReadableScrollport(+ page: Page,+ matchSelector: string,+ { toolbarPx = TOOLBAR_OVERLAP_PX, tolerancePx = 2 }: ScrollportContainmentOptions = {},+): Promise<boolean> {+ return page.evaluate(+ ({ matchSelector, toolbarPx, tolerancePx }) => {+ const scrollContainer = Array.from(+ document.querySelectorAll('[data-testid="editor-scroll-container"]'),+ ).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ const match = scrollContainer?.querySelector(matchSelector);+ if (!scrollContainer || !(match instanceof HTMLElement)) return false;+ const scrollRect = scrollContainer.getBoundingClientRect();+ const matchRect = match.getBoundingClientRect();+ return (+ matchRect.top >= scrollRect.top + toolbarPx - tolerancePx &&+ matchRect.bottom <= scrollRect.bottom + tolerancePx+ );+ },+ { matchSelector, toolbarPx, tolerancePx },+ );+}diff --git a/packages/app/tests/stress/_helpers/tall-doc-fixture.ts b/packages/app/tests/stress/_helpers/tall-doc-fixture.tsnew file mode 100644index 000000000..7c3e07dd1--- /dev/null+++ b/packages/app/tests/stress/_helpers/tall-doc-fixture.ts@@ -0,0 +1,172 @@+/**+ * Deterministic tall-document fixture for landing tests.+ *+ * A landing assertion is only honest if the target block is far enough down a+ * genuinely virtualized document that a wrong landing leaves it off-screen (and+ * content-visibility-skipped). This generator produces such a document plus a+ * block-inventory manifest the tests assert against, so a test can seed a doc,+ * ask for "block 200", and check the landing brought exactly that block into+ * view — with no coordinate math living in the test itself.+ *+ * Determinism: content is a pure function of the requested block count and+ * shifter list. `Math.random` is not used (it is unavailable in this repo's+ * workflow sandbox and would make replay impossible); filler words are drawn+ * from a fixed table indexed by block position.+ *+ * Every block is one top-level paragraph carrying a unique marker. The marker+ * is emphasised (`**OKBLK0042**`) so the rendered `.ok-chunk-wrapper` always+ * has an element child (`<strong>`): the content-visibility skip state a+ * WYSIWYG landing assertion reads is reported on the wrapper's first element+ * child, not the wrapper itself, so a plain-text paragraph (no element child)+ * would have nothing to probe.+ */++const MARKER_PREFIX = 'OKBLK';+const MARKER_DIGITS = 4;++/** Fixed lorem table — filler is drawn from here by block index, never randomly. */+const FILLER_WORDS = [+ 'lorem',+ 'ipsum',+ 'dolor',+ 'sit',+ 'amet',+ 'consectetur',+ 'adipiscing',+ 'elit',+ 'tempor',+ 'incididunt',+ 'labore',+ 'magna',+ 'aliqua',+ 'veniam',+ 'nostrud',+ 'ullamco',+ 'laboris',+ 'aliquip',+ 'commodo',+ 'consequat',+] as const;++/**+ * The unique, greppable marker for a block index — `OKBLK0042`. Stable across+ * runs and shared by the generator, the manifest, and every assertion so a test+ * never hard-codes a marker string the generator could drift away from.+ */+export function blockMarker(index: number): string {+ return `${MARKER_PREFIX}${String(index).padStart(MARKER_DIGITS, '0')}`;+}++export interface TallDocBlock {+ /** 0-based position among the document's top-level body blocks. */+ index: number;+ /** The block's unique marker (`blockMarker(index)`). */+ marker: string;+}++export interface TallDocShifterSpec {+ /**+ * The shifter is inserted immediately after this block index, so its late+ * height growth pushes every block below it — including a landing target+ * placed further down — during the settle window.+ */+ afterBlock: number;+ /** How long the arming route holds the response before serving it. */+ delayMs?: number;+ /** Final rendered height once it resolves — the layout shift magnitude. */+ heightPx?: number;+}++export interface TallDocShifter {+ /** 0-based position among the document's shifters. */+ index: number;+ afterBlock: number;+ delayMs: number;+ heightPx: number;+ /**+ * The image src the shifter renders. An arming helper serves this path late+ * (with `delayMs`) to synthesize a deterministic async layout shift; unarmed,+ * it simply 404s and contributes no height.+ */+ url: string;+}++export interface TallDocManifest {+ /** Number of top-level paragraph blocks (excludes shifter image blocks). */+ blockCount: number;+ blocks: readonly TallDocBlock[];+ shifters: readonly TallDocShifter[];+}++export interface GenerateTallDocOptions {+ /** Number of top-level paragraph blocks to emit. */+ blockCount: number;+ /** Async layout shifters to interleave, each positioned after a block. */+ shifters?: readonly TallDocShifterSpec[];+}++const DEFAULT_SHIFTER_DELAY_MS = 300;+const DEFAULT_SHIFTER_HEIGHT_PX = 600;+/** Sentinel path prefix an arming helper matches with `page.route`. */+export const SHIFTER_URL_PREFIX = '/__ok-landing-shifter__';++function fillerFor(index: number): string {+ // Deterministic 12-word run whose starting offset rotates by block index, so+ // adjacent blocks read differently but the same index always reproduces.+ const count = 12;+ const words: string[] = [];+ for (let i = 0; i < count; i++) {+ words.push(FILLER_WORDS[(index * 7 + i * 3) % FILLER_WORDS.length] ?? 'lorem');+ }+ return words.join(' ');+}++/**+ * Build a tall markdown document and the manifest describing it. Blocks are+ * emitted in index order; each requested shifter is spliced in after its+ * `afterBlock` as its own image block. The returned markdown is ready to seed+ * through `api.seedDocs`; the manifest is what assertions target.+ */+export function generateTallDoc(options: GenerateTallDocOptions): {+ markdown: string;+ manifest: TallDocManifest;+} {+ const { blockCount } = options;+ if (!Number.isInteger(blockCount) || blockCount <= 0) {+ throw new Error(`generateTallDoc: blockCount must be a positive integer, got ${blockCount}`);+ }+ const shifterSpecs = options.shifters ?? [];++ const blocks: TallDocBlock[] = [];+ const shifters: TallDocShifter[] = [];+ const shiftersByBlock = new Map<number, TallDocShifterSpec[]>();+ for (const spec of shifterSpecs) {+ const list = shiftersByBlock.get(spec.afterBlock) ?? [];+ list.push(spec);+ shiftersByBlock.set(spec.afterBlock, list);+ }++ const segments: string[] = [];+ for (let i = 0; i < blockCount; i++) {+ const marker = blockMarker(i);+ blocks.push({ index: i, marker });+ segments.push(`**${marker}** ${fillerFor(i)}`);+ for (const spec of shiftersByBlock.get(i) ?? []) {+ const index = shifters.length;+ const shifter: TallDocShifter = {+ index,+ afterBlock: i,+ delayMs: spec.delayMs ?? DEFAULT_SHIFTER_DELAY_MS,+ heightPx: spec.heightPx ?? DEFAULT_SHIFTER_HEIGHT_PX,+ url: `${SHIFTER_URL_PREFIX}/${index}.png`,+ };+ shifters.push(shifter);+ segments.push(``);+ }+ }++ return {+ markdown: segments.join('\n\n'),+ manifest: { blockCount, blocks, shifters },+ };+}diff --git a/packages/app/tests/stress/find-replace.e2e.ts b/packages/app/tests/stress/find-replace.e2e.tsindex 59351508a..e41e36659 100644--- a/packages/app/tests/stress/find-replace.e2e.ts+++ b/packages/app/tests/stress/find-replace.e2e.ts@@ -7,7 +7,12 @@import { randomUUID } from 'node:crypto';import type { Page } from '@playwright/test';-import { expect, test, waitForActiveProviderSynced } from './_helpers';+import {+ expect,+ matchIsWithinReadableScrollport,+ test,+ waitForActiveProviderSynced,+} from './_helpers';function uniqueDocName(label: string): string {return `test-find-replace-${label}-${randomUUID().slice(0, 8)}`;@@ -28,23 +33,6 @@ function visibleScrollContainer(page: Page) {return page.locator('[data-testid="editor-scroll-container"]:visible');}-async function activeFindMatchIsInsideScrollport(page: Page): Promise<boolean> {- return page.evaluate(() => {- const scrollContainer = Array.from(- document.querySelectorAll('[data-testid="editor-scroll-container"]'),- ).find((element): element is HTMLElement => {- if (!(element instanceof HTMLElement)) return false;- return element.getClientRects().length > 0;- });- const activeMatch = scrollContainer?.querySelector('.ok-find-match-active');- if (!scrollContainer || !(activeMatch instanceof HTMLElement)) return false;-- const scrollRect = scrollContainer.getBoundingClientRect();- const matchRect = activeMatch.getBoundingClientRect();- return matchRect.top >= scrollRect.top && matchRect.bottom <= scrollRect.bottom;- });-}-async function activeElementIsEditor(page: Page): Promise<boolean> {return page.evaluate(() => document.activeElement?.classList.contains('ProseMirror') ?? false);}@@ -166,7 +154,9 @@ test('TipTap find navigation scrolls an off-screen active match into view', asyn),).toBeGreaterThan(0);- await expect.poll(() => activeFindMatchIsInsideScrollport(page)).toBe(true);+ await expect+ .poll(() => matchIsWithinReadableScrollport(page, '.ok-find-match-active'))+ .toBe(true);});test('TipTap find navigation does not show table controls inside table matches', async ({diff --git a/packages/app/tests/stress/landing-helpers.e2e.ts b/packages/app/tests/stress/landing-helpers.e2e.tsnew file mode 100644index 000000000..f41642ce7--- /dev/null+++ b/packages/app/tests/stress/landing-helpers.e2e.ts@@ -0,0 +1,122 @@+/**+ * Self-test for the landing e2e helpers.+ *+ * These helpers are the oracle every later landing test depends on, so they are+ * proven here against the real running app: a real WYSIWYG-to-source landing is+ * asserted with the source oracle; each anti-vacuity guard is shown to fail+ * loudly when its target is absent (a missing target must never read as a pass);+ * the WYSIWYG oracle is exercised with a real materialization check plus its+ * wrong-geometry cross-check; and the forced-estimate-error lever is confirmed+ * to apply at runtime. If any of these regress, the helpers stop being honest+ * and every test built on them silently weakens.+ */++import { randomUUID } from 'node:crypto';+import {+ assertLanded,+ blockMarker,+ expect,+ generateTallDoc,+ injectForcedEstimateError,+ landingMarkCount,+ readSourceCaretHead,+ scrollWysiwygBlockToTop,+ test,+ toggleMode,+ waitForActiveProviderSynced,+ waitForLandingSettled,+} from './_helpers';++const WYSIWYG = '.ProseMirror:not(.composer-prosemirror)';+const CHUNK_WRAPPER = `${WYSIWYG} .ok-chunk-wrapper`;++function docName(label: string): string {+ return `landing-helpers-${label}-${randomUUID().slice(0, 8)}`;+}++test('source oracle asserts a real WYSIWYG-to-source landing, and its guard fires on an absent target', async ({+ page,+ api,+}) => {+ const name = docName('src');+ const { markdown } = generateTallDoc({ blockCount: 400 });+ await api.seedDocs([{ name, markdown }]);+ await page.goto(`/#/${name}`);+ await waitForActiveProviderSynced(page);+ await expect(page.locator(WYSIWYG).first()).toBeVisible();++ // Put a mid-document block at the top so the flip has a non-trivial anchor to+ // preserve — a landing at scrollTop 0 would prove nothing.+ const anchorMarker = blockMarker(150);+ const settleDelta = await scrollWysiwygBlockToTop(page, anchorMarker);+ expect(+ Math.abs(settleDelta),+ 'setup scroll did not converge the anchor to the top of the readable area',+ ).toBeLessThan(40);++ const before = await landingMarkCount(page);+ await toggleMode(page, 'source');+ const mark = await waitForLandingSettled(page, { since: before });+ expect(mark.kind, `landing did not land (grade ${mark.grade})`).toBe('land');++ // The oracle: the anchor's markdown is materialized and near the top of the+ // readable area in the source view.+ await assertLanded(page, { mode: 'source', targetText: anchorMarker, placement: 'top' });++ // Non-interference: a plain toggle is scroll-only, so the source caret stays+ // at the document default rather than being placed at the landed range.+ expect(await readSourceCaretHead(page)).toBe(0);++ // Anti-vacuity: a target that is not in the document must throw, not pass.+ await expect(+ assertLanded(page, { mode: 'source', targetText: 'OKBLK-absent-marker', placement: 'top' }),+ 'source oracle silently accepted an absent target',+ ).rejects.toThrow(/not in the document/);+});++test('WYSIWYG oracle materializes the target and rejects a wrong-geometry landing, and its guard fires on an absent target', async ({+ page,+ api,+}) => {+ const name = docName('wys');+ const { markdown } = generateTallDoc({ blockCount: 400 });+ await api.seedDocs([{ name, markdown }]);+ await page.goto(`/#/${name}`);+ await waitForActiveProviderSynced(page);+ await expect(page.locator(WYSIWYG).first()).toBeVisible();++ const targetMarker = blockMarker(150);+ const decoyMarker = blockMarker(0);+ const settleDelta = await scrollWysiwygBlockToTop(page, targetMarker);+ expect(Math.abs(settleDelta), 'setup scroll did not converge the target').toBeLessThan(40);++ // The target must be materialized and on-screen; the far first block is the+ // wrong-geometry decoy that must be off-screen. No placement claim here — this+ // exercises the visibility-only form of the oracle.+ await assertLanded(page, { mode: 'wysiwyg', targetMarker, decoyMarker });++ // Anti-vacuity: a block that does not exist must throw, not pass.+ await expect(+ assertLanded(page, { mode: 'wysiwyg', targetMarker: blockMarker(9999) }),+ 'WYSIWYG oracle silently accepted an absent target',+ ).rejects.toThrow(/not in the DOM/);+});++test('forced-estimate-error injection applies the chunk-height override at runtime', async ({+ page,+ api,+}) => {+ const name = docName('cvh');+ const { markdown } = generateTallDoc({ blockCount: 120 });+ await api.seedDocs([{ name, markdown }]);+ await page.goto(`/#/${name}`);+ await waitForActiveProviderSynced(page);+ await expect(page.locator(WYSIWYG).first()).toBeVisible();+ // A chunk wrapper must exist so the override's inheritance to the real+ // consumer is what gets confirmed, not just the :root declaration.+ await expect(page.locator(CHUNK_WRAPPER).first()).toBeAttached();++ // Self-asserting: throws if --ok-cv-h does not apply on :root and inherit to+ // the chunk wrapper.+ await injectForcedEstimateError(page, 400);+});diff --git a/packages/app/tests/stress/mode-switch-landing.e2e.ts b/packages/app/tests/stress/mode-switch-landing.e2e.tsnew file mode 100644index 000000000..5a46bf63b--- /dev/null+++ b/packages/app/tests/stress/mode-switch-landing.e2e.ts@@ -0,0 +1,419 @@+/**+ * Behavior E2E for mode-switch position fidelity.+ *+ * Proves the three user-visible landing behaviors against the real running app,+ * with the caret-delta oracle as the primary assertion and geometry containment+ * as a secondary cross-check:+ *+ * - the plain WYSIWYG->source toggle preserves the topmost block and leaves the+ * target editor's selection untouched;+ * - the plain source->WYSIWYG toggle does the same in reverse;+ * - the explicit "view in source" jump from the selection bubble lands the+ * block centered with the caret placed at its source start.+ *+ * Plus the terminal-safety contract: a landing that can never settle abandons+ * within its window and stamps the abandoned mark with a target and a delta.+ *+ * Every test seeds its own uniquely-named tall document so parallel workers+ * never share a CRDT doc name, and asserts through the landing oracle in+ * `_helpers/landing.ts`, which measures each editor the way it actually+ * virtualizes and fails loudly on an absent target.+ */++import { randomUUID } from 'node:crypto';+import type { Page } from '@playwright/test';+import {+ type ApiHelpers,+ assertLanded,+ blockMarker,+ expect,+ generateTallDoc,+ landingMarkCount,+ readSourceCaretHead,+ readWysiwygCaretHead,+ scrollWysiwygBlockToTop,+ selectText,+ test,+ toggleMode,+ waitForActiveProviderSynced,+ waitForLandingSettled,+} from './_helpers';++const WYSIWYG = '.ProseMirror:not(.composer-prosemirror)';+const VIEW_IN_SOURCE_BUBBLE = 'view-in-source-bubble-button';+/**+ * The transient highlight a jump paints on the range it landed on, scoped to the+ * source editor. Restated here rather than imported from app src, like the other+ * selectors this suite uses; syntax highlighting splits the decorated range+ * across several spans, so assertions read all of them.+ */+const LANDING_FLASH = '.cm-editor .ok-landing-flash';+/** Deep enough in a 400-block doc that a wrong landing leaves it off-screen. */+const ANCHOR_INDEX = 150;++function docName(label: string): string {+ return `mode-switch-landing-${label}-${randomUUID().slice(0, 8)}`;+}++/** Seed a tall doc, open it, and wait until the WYSIWYG editor is synced + visible. */+async function openTallDoc(page: Page, api: ApiHelpers, name: string): Promise<void> {+ const { markdown } = generateTallDoc({ blockCount: 400 });+ await api.seedDocs([{ name, markdown }]);+ await page.goto(`/#/${name}`);+ await waitForActiveProviderSynced(page);+ await expect(page.locator(WYSIWYG).first()).toBeVisible();+}++/**+ * Scroll the anchor block to the top of the WYSIWYG readable area, asserting the+ * setup converged so a later landing has a real position to preserve rather than+ * scrollTop 0. The helper already holds the viewport stable across refinement+ * frames; this only pins that it got there.+ */+async function anchorAtTop(page: Page, marker: string): Promise<void> {+ const residual = await scrollWysiwygBlockToTop(page, marker);+ expect(+ Math.abs(residual),+ 'setup scroll did not converge the anchor to the top of the readable area',+ ).toBeLessThan(40);+}++/**+ * Resolve once the shared scroller's `scrollTop` has held still long enough that+ * the composer's 300ms bottom-pin window demonstrably elapsed without moving the+ * settled landing. Polls inside the page and requires consecutive unchanged+ * samples: the e2e STOP rule bans `page.waitForTimeout` as a fixed-delay+ * anti-flake smell, and stability is the property under test anyway — a fixed+ * sleep would only assume it.+ */+async function settleScrollPosition(page: Page): Promise<void> {+ await page.evaluate(+ () =>+ new Promise<void>((resolve, reject) => {+ const el = document.querySelector<HTMLElement>('[data-testid="editor-scroll-container"]');+ if (!el) {+ reject(new Error('settleScrollPosition: no editor scroll container'));+ return;+ }+ const POLL_MS = 50;+ // 600ms of stillness comfortably outlives the 300ms pin window.+ const REQUIRED_STABLE_TICKS = 12;+ const MAX_TICKS = 120; // ~6s ceiling - fail fast rather than hit Playwright's+ let last = Number.NaN;+ let stableTicks = 0;+ let totalTicks = 0;+ const tick = () => {+ totalTicks += 1;+ if (totalTicks > MAX_TICKS) {+ reject(+ new Error(+ `settleScrollPosition: scrollTop never held still for ${+ REQUIRED_STABLE_TICKS * POLL_MS+ }ms within ${MAX_TICKS * POLL_MS}ms`,+ ),+ );+ return;+ }+ const now = el.scrollTop;+ stableTicks = now === last ? stableTicks + 1 : 0;+ last = now;+ if (stableTicks >= REQUIRED_STABLE_TICKS) {+ resolve();+ return;+ }+ setTimeout(tick, POLL_MS);+ };+ setTimeout(tick, POLL_MS);+ }),+ );+}++/**+ * Continuously flip the WYSIWYG content-visibility height estimate so a pending+ * landing's target never stops moving. Every off-screen block above the target+ * re-lays-out its `--ok-cv-h` placeholder each tick, shifting the target's+ * content-space position faster than the settle quiet window closes — the "target+ * keeps moving, drift never falls under threshold" condition the abandon path is+ * defined by. Paired with `stopEstimateOscillation`.+ */+async function startEstimateOscillation(page: Page): Promise<void> {+ await page.evaluate(() => {+ const STYLE_ID = 'ok-abandon-oscillation';+ const existing = document.getElementById(STYLE_ID);+ const style = existing instanceof HTMLStyleElement ? existing : document.createElement('style');+ style.id = STYLE_ID;+ if (!existing) document.head.appendChild(style);+ let tall = false;+ const tick = (): void => {+ tall = !tall;+ style.textContent = `:root{--ok-cv-h:${tall ? 1400 : 100}px;}`;+ };+ tick();+ const win = window as unknown as { __okAbandonOsc?: number };+ win.__okAbandonOsc = window.setInterval(tick, 30);+ });+}++/**+ * Assert the landed block is highlighted right now. Reads every decorated span+ * because the source editor's syntax highlighting splits the flashed range, and+ * joins them so the assertion is about the covered text, not one fragment. The+ * computed style is read too: a decorated span the stylesheet no longer paints+ * would still be "visible" while showing the user nothing.+ */+async function expectLandingFlashOn(+ page: Page,+ marker: string,+ opts: { reducedMotion?: boolean } = {},+): Promise<void> {+ const flash = page.locator(LANDING_FLASH);+ await expect(flash.first(), 'the landed range was never highlighted').toBeVisible();+ const covered = (await flash.allTextContents()).join('');+ expect(covered, 'the landing flash covered a different block').toContain(marker);++ const style = await flash.first().evaluate((el) => {+ const computed = getComputedStyle(el);+ return { animationName: computed.animationName, boxShadow: computed.boxShadow };+ });+ if (opts.reducedMotion) {+ expect(style.animationName, 'reduced motion should not animate the flash').toBe('none');+ expect(style.boxShadow, 'reduced motion should paint the static accent bar').not.toBe('none');+ } else {+ expect(style.animationName, 'the landing flash class is not styled').not.toBe('none');+ }+}++async function stopEstimateOscillation(page: Page): Promise<void> {+ await page.evaluate(() => {+ const win = window as unknown as { __okAbandonOsc?: number };+ if (win.__okAbandonOsc !== undefined) {+ window.clearInterval(win.__okAbandonOsc);+ win.__okAbandonOsc = undefined;+ }+ document.getElementById('ok-abandon-oscillation')?.remove();+ });+}++test('plain toggle from WYSIWYG to source keeps the anchor block in view without touching the selection', async ({+ page,+ api,+}) => {+ const name = docName('w2s');+ await openTallDoc(page, api, name);++ const anchor = blockMarker(ANCHOR_INDEX);+ await anchorAtTop(page, anchor);++ const before = await landingMarkCount(page);+ await toggleMode(page, 'source');+ const mark = await waitForLandingSettled(page, { since: before });+ expect(mark.kind, `W->S toggle did not land (grade ${mark.grade})`).toBe('land');++ // Primary oracle: the plain toggle is scroll-only, so the source editor keeps+ // its own selection. Source is shown for the first time here, so its pre-flip+ // selection is the document default (head 0); a zero delta proves the landing+ // placed no caret.+ expect(await readSourceCaretHead(page), 'plain toggle moved the source selection').toBe(0);++ // Secondary: the anchor's markdown is materialized and near the top of the+ // readable area.+ await assertLanded(page, { mode: 'source', targetText: anchor, placement: 'top' });+});++test('plain toggle from source back to WYSIWYG keeps the anchor block in view without touching the selection', async ({+ page,+ api,+}) => {+ const name = docName('s2w');+ await openTallDoc(page, api, name);++ const anchor = blockMarker(ANCHOR_INDEX);+ await anchorAtTop(page, anchor);++ // Land the anchor at the source top so the direction under test (source->+ // WYSIWYG) starts from a real scrolled position rather than the document top.+ const beforeSetup = await landingMarkCount(page);+ await toggleMode(page, 'source');+ expect(+ (await waitForLandingSettled(page, { since: beforeSetup })).kind,+ 'setup W->S did not land',+ ).toBe('land');+ await assertLanded(page, { mode: 'source', targetText: anchor, placement: 'top' });++ // The WYSIWYG editor stays mounted under source mode; capture its untouched+ // selection before the flip so the oracle is a real delta, not a constant.+ const caretBefore = await readWysiwygCaretHead(page);++ const before = await landingMarkCount(page);+ await toggleMode(page, 'wysiwyg');+ const mark = await waitForLandingSettled(page, { since: before });+ expect(mark.kind, `S->W toggle did not land (grade ${mark.grade})`).toBe('land');++ // Primary oracle: the WYSIWYG selection is identical across the flip (scroll-only).+ expect(await readWysiwygCaretHead(page), 'plain toggle moved the WYSIWYG selection').toBe(+ caretBefore,+ );++ // Secondary: the anchor block landed near the WYSIWYG top and the far first+ // block (the wrong-geometry decoy) is off-screen.+ await assertLanded(page, {+ mode: 'wysiwyg',+ targetMarker: anchor,+ decoyMarker: blockMarker(0),+ placement: 'top',+ });+});++test('a second entry into source mode still holds the landing against the composer bottom-pin', async ({+ page,+ api,+}) => {+ // The first entry into source mode always landed; the SECOND one did not. A+ // deep flip momentarily clamps the shared scroller to the bottom (the outgoing+ // WYSIWYG scrollTop overshoots source's shorter content), which the composer's+ // bottom-anchored scroll pin reads as "the user is at the end" and re-pins+ // every frame for 300ms — outliving the landing and leaving the user at the+ // end of the document while the land mark still claimed a zero delta. The pin+ // now stands down for the landing's suppression window, so the assertion that+ // matters is the one AFTER the pin's window has fully elapsed.+ const name = docName('second-entry');+ await openTallDoc(page, api, name);++ const first = blockMarker(ANCHOR_INDEX);+ await anchorAtTop(page, first);+ let since = await landingMarkCount(page);+ await toggleMode(page, 'source');+ expect((await waitForLandingSettled(page, { since })).kind, 'first W->S did not land').toBe(+ 'land',+ );++ since = await landingMarkCount(page);+ await toggleMode(page, 'wysiwyg');+ await waitForLandingSettled(page, { since });++ // A different, deeper anchor so a stomped landing is unmistakable.+ const second = blockMarker(260);+ await anchorAtTop(page, second);+ since = await landingMarkCount(page);+ await toggleMode(page, 'source');+ expect((await waitForLandingSettled(page, { since })).kind, 'second W->S did not land').toBe(+ 'land',+ );++ // Outlive the 300ms pin window before asserting — the pre-fix failure only+ // materialised after the landing had already settled.+ await settleScrollPosition(page);+ await assertLanded(page, { mode: 'source', targetText: second, placement: 'top' });+});++test('view in source from the bubble menu lands the block centered with the caret at its source start', async ({+ page,+ api,+}) => {+ const name = docName('jump');+ await openTallDoc(page, api, name);++ const target = blockMarker(ANCHOR_INDEX);+ // Bring the block on-screen so its selection has a real rect for the bubble to+ // anchor to, then select its marker to raise the selection bubble.+ await anchorAtTop(page, target);+ await selectText(page, target);++ const bubble = page.getByTestId(VIEW_IN_SOURCE_BUBBLE);+ await expect(bubble, 'the View in source bubble entry did not appear on selection').toBeVisible();++ const before = await landingMarkCount(page);+ await bubble.click();+ const mark = await waitForLandingSettled(page, { since: before });+ expect(mark.kind, `jump did not land (grade ${mark.grade})`).toBe('land');++ // Secondary: the target range is centered in the readable area.+ await assertLanded(page, { mode: 'source', targetText: target, placement: 'center' });++ // Primary oracle: unlike the scroll-only toggle, the jump places the caret at+ // the landed range's start — the source block containing the marker. Caret head+ // and block bounds are read in the same full-Y.Text offset space.+ const caretHead = await readSourceCaretHead(page);+ const bounds = await page.evaluate((marker) => {+ const src = window.__activeProvider?.document?.getText('source')?.toString() ?? '';+ const markerIdx = src.indexOf(marker);+ const priorBreak = src.lastIndexOf('\n\n', markerIdx);+ return { markerIdx, blockStart: priorBreak === -1 ? 0 : priorBreak + 2 };+ }, target);++ expect(bounds.markerIdx, 'target marker not found in the source document').toBeGreaterThan(0);+ expect(caretHead, 'jump did not place a caret (still at document start)').toBeGreaterThan(0);+ expect(caretHead, 'caret landed before the target block').toBeGreaterThanOrEqual(+ bounds.blockStart,+ );+ expect(caretHead, 'caret landed past the target block start').toBeLessThanOrEqual(+ bounds.markerIdx,+ );++ // The highlight is the other half of the jump's headline behavior: the landed+ // range is flashed once it is on screen, then clears on its own.+ await expectLandingFlashOn(page, target);+ await expect(page.locator(LANDING_FLASH), 'the landing flash never cleared').toHaveCount(0, {+ timeout: 10_000,+ });+});++test('view in source still lands and flashes under reduced motion', async ({ page, api }) => {+ // Reduced motion swaps the flash animation for a static accent bar in CSS; the+ // landing itself (scroll, caret, decoration lifetime) is script-driven and must+ // be unaffected.+ await page.emulateMedia({ reducedMotion: 'reduce' });++ const name = docName('jump-reduced-motion');+ await openTallDoc(page, api, name);++ const target = blockMarker(ANCHOR_INDEX);+ await anchorAtTop(page, target);+ await selectText(page, target);++ const bubble = page.getByTestId(VIEW_IN_SOURCE_BUBBLE);+ await expect(bubble, 'the View in source bubble entry did not appear on selection').toBeVisible();++ const before = await landingMarkCount(page);+ await bubble.click();+ const mark = await waitForLandingSettled(page, { since: before });+ expect(mark.kind, `jump did not land under reduced motion (grade ${mark.grade})`).toBe('land');++ await assertLanded(page, { mode: 'source', targetText: target, placement: 'center' });+ expect(+ await readSourceCaretHead(page),+ 'jump did not place a caret under reduced motion',+ ).toBeGreaterThan(0);+ await expectLandingFlashOn(page, target, { reducedMotion: true });+});++test('a source-to-WYSIWYG landing that can never settle abandons with a target and delta', async ({+ page,+ api,+}) => {+ const name = docName('abandon');+ await openTallDoc(page, api, name);++ const anchor = blockMarker(ANCHOR_INDEX);+ await anchorAtTop(page, anchor);++ // Establish a scrolled source viewport, then queue the reverse landing.+ const beforeSetup = await landingMarkCount(page);+ await toggleMode(page, 'source');+ expect(+ (await waitForLandingSettled(page, { since: beforeSetup })).kind,+ 'setup W->S did not land',+ ).toBe('land');++ // Keep the WYSIWYG landing target moving for the whole window so it can never+ // settle; the controller must then abandon, not loop or land.+ await startEstimateOscillation(page);+ const before = await landingMarkCount(page);+ await toggleMode(page, 'wysiwyg');+ const mark = await waitForLandingSettled(page, { since: before, timeout: 6_000 });+ await stopEstimateOscillation(page);++ expect(mark.kind, 'a never-settling landing should abandon, not land').toBe('abandoned');+ expect(Number.isFinite(mark.target), 'abandoned mark is missing a numeric target').toBe(true);+ expect(Number.isFinite(mark.delta), 'abandoned mark is missing a numeric delta').toBe(true);+});diff --git a/packages/app/tests/stress/source-find-scroll.e2e.ts b/packages/app/tests/stress/source-find-scroll.e2e.tsindex af101eff7..e60f4e278 100644--- a/packages/app/tests/stress/source-find-scroll.e2e.ts+++ b/packages/app/tests/stress/source-find-scroll.e2e.ts@@ -12,9 +12,12 @@import { randomUUID } from 'node:crypto';import type { Page } from '@playwright/test';-import { expect, test, waitForActiveProviderSynced } from './_helpers';--const TOOLBAR_OVERLAP_PX = 56;+import {+ expect,+ matchIsWithinReadableScrollport,+ test,+ waitForActiveProviderSynced,+} from './_helpers';function uniqueDocName(label: string): string {return `test-source-find-${label}-${randomUUID().slice(0, 8)}`;@@ -26,29 +29,6 @@ function visibleScrollContainer(page: Page) {return page.locator('[data-testid="editor-scroll-container"]:visible');}-/**- * True iff the currently-selected CodeMirror search match is fully within the- * visible scrollport AND below the toolbar overlap zone (so it is actually- * readable, not hidden behind the absolute-positioned toolbar).- */-async function selectedSearchMatchInScrollport(page: Page): Promise<boolean> {- return page.evaluate((toolbar) => {- const scrollContainer = Array.from(- document.querySelectorAll('[data-testid="editor-scroll-container"]'),- ).find(- (element): element is HTMLElement =>- element instanceof HTMLElement && element.getClientRects().length > 0,- );- const match = scrollContainer?.querySelector('.cm-searchMatch-selected');- if (!scrollContainer || !(match instanceof HTMLElement)) return false;- const scrollRect = scrollContainer.getBoundingClientRect();- const matchRect = match.getBoundingClientRect();- return (- matchRect.top >= scrollRect.top + toolbar - 2 && matchRect.bottom <= scrollRect.bottom + 2- );- }, TOOLBAR_OVERLAP_PX);-}-test('source-mode find scrolls an off-screen match into view', async ({ page, api }) => {const docName = uniqueDocName('scroll');// Long body so the marker sits well below the fold once in source mode.@@ -105,5 +85,7 @@ test('source-mode find scrolls an off-screen match into view', async ({ page, ap),).toBeGreaterThan(0);- await expect.poll(() => selectedSearchMatchInScrollport(page)).toBe(true);+ await expect+ .poll(() => matchIsWithinReadableScrollport(page, '.cm-searchMatch-selected'))+ .toBe(true);});diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex c014b1413..8f9d95287 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,3 +1,4 @@+import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 005627195..8bfdb40cd 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,3 +1,4 @@+import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 8890f6739..c18c086d5 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 9d9c244b0..463e89595 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,3 +1,4 @@+const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.tsindex c43fdd7e7..0939885bb 100644--- a/packages/core/src/bridge/intraline-predicate.ts+++ b/packages/core/src/bridge/intraline-predicate.ts@@ -1,3 +1,4 @@+export function rawLineCounts(doc: string): Map<string, number> {const counts = new Map<string, number>();for (const line of doc.split('\n')) {diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex 251560a35..c0dc65705 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -65,6 +65,7 @@ export function tryLineLevelCombine(return { clean: true, merged };}+export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex da41900cd..d35f6b455 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,3 +1,4 @@+const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 754dc5cc2..0be5203e4 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;+interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {ignoreAttrs?: (attrKey: string) => boolean;}+/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}+export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex af20de1e2..dca644141 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,3 +1,4 @@+/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.tsindex 561415d8c..59b067531 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -810,6 +810,7 @@ interface OkEditorViewMenuStateSnapshot {readonly docPanelVisible?: boolean;readonly terminalVisible?: boolean;readonly terminalLive?: boolean;+ readonly canViewInSource?: boolean;}/**diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex 83d47404a..a363dfd54 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,3 +1,4 @@+import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.tsindex 9807a7e82..4499dbc92 100644--- a/packages/core/src/markdown/code-fence.ts+++ b/packages/core/src/markdown/code-fence.ts@@ -1,3 +1,4 @@+export function selectFenceChar(info: string): '`' | '~' {return info.includes('`') ? '~' : '`';}diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 7415c474a..34704165b 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex ece5c02a1..b6299a948 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,3 +1,4 @@+import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex 54774764a..acd398aa6 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.tsindex 43ecdc709..ba9b56384 100644--- a/packages/core/src/markdown/div-align-promoter.ts+++ b/packages/core/src/markdown/div-align-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex c7518d614..fb5ac8e8a 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,3 +1,4 @@+const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 00f5771ee..6931623c7 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}+interface GfmExample {section: string;markdown: string;@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}+interface MdxCrashEntry {id: string;input: string;@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}+export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}+export interface NgPinnedCase {id: string;name: string;@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}+export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex 8b1eb8519..daa3ef82b 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;+function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}+const WORDS = ['lorem','ipsum',@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}+type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}+function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 420dc0fe5..32c055c5b 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,6 +7,7 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';+export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 2653473da..283913255 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,3 +1,4 @@+export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex da0a81d23..5d1000cc4 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex b1f252c31..8dc3a81b5 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,3 +1,4 @@+import type { Root as HastRoot } from 'hast';import type { List, Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -85,7 +86,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified().use(rehypeParse, { fragment: true });+ const processor = unified()+ .use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 706fa9afb..994eb6917 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,3 +1,4 @@+import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex a64ecf306..bc3047bf2 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromPmMark,@@ -204,6 +205,7 @@ export class MarkdownManager {}}+const registry = createRegistry();function destructureAttrs(@@ -252,6 +254,7 @@ function destructureAttrs(return result;}+function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -271,6 +274,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}+function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -339,6 +343,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}+import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -585,6 +590,7 @@ function buildMdastToPmHandlers(}));}+if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -665,6 +671,7 @@ function buildMdastToPmHandlers(}));}+if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -943,6 +950,7 @@ function buildMdastToPmHandlers(};}+const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1068,6 +1076,7 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}+function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.tsindex fa0be9e86..b79e9aef7 100644--- a/packages/core/src/markdown/lint/applies-to.ts+++ b/packages/core/src/markdown/lint/applies-to.ts@@ -1,3 +1,4 @@+import picomatch from 'picomatch';import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsindex 312c9c74b..94b34dee1 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,3 +1,4 @@+const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set(['.markdownlint.json','.markdownlint.jsonc',diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex 3162881fc..d41c42367 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -38,6 +38,7 @@ const fullPluginShape = Object.fromEntries(LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),) as z.ZodRawShape;+export const LinterConfigSchema = z.object({enabled: z.boolean(),plugins: z.object(fullPluginShape),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex d48eea5e4..a51f2ffb0 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSettingMD013: false,};+export function resolveMarkdownlintConfig(rules: Record<string, MarkdownlintRuleSetting> | undefined,): Configuration {diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.tsindex ef478e268..9c9542661 100644--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts@@ -1,3 +1,4 @@+import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';export interface FrontmatterFieldConstraint {diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.tsindex 3871ccada..997f71794 100644--- a/packages/core/src/markdown/lint/frontmatter-validate.ts+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts@@ -1,3 +1,4 @@+import Ajv, { type ValidateFunction } from 'ajv';import Ajv2019 from 'ajv/dist/2019.js';import Ajv2020 from 'ajv/dist/2020.js';diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex ce0db23a3..e371f6a6c 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,3 +1,4 @@+import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 5e832aa19..be5871ed9 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,3 +1,4 @@+import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import {@@ -13,6 +14,7 @@ import {type MarkdownlintSlice,} from './types.ts';+const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex da6c477e9..772183427 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,3 +1,4 @@+export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];@@ -69,6 +70,7 @@ export interface FrontmatterSlice {schemas: ResolvedFrontmatterSchemaEntry[];}+interface RuleOptionSpecBase {key: string;description: string;diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex a5b511f25..bd79424c7 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex 679c72ef7..f84967798 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex 8ce2b2492..df788a80d 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,3 +1,4 @@+import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex bfd7e3109..fa3cfcd86 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 1a897fca8..17ed2b829 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 9864b3b60..7e4a9a48b 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,6 +168,7 @@ export function parseRecursive(}}+interface VFilePlace {offset?: number;start?: { offset?: number };@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}+interface Region {start: number;end: number;@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}+export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}+interface SourceBlock {src: string;start: number;@@ -452,6 +456,7 @@ function tryPerBlockFallback(};}+function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex e6ab4fd57..43d420187 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,3 +1,4 @@+export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 8bcbe2692..50d3e1314 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex 91cdf658f..ccf06e94d 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,3 +1,4 @@+import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';import { isBlankLineParagraph } from './zero-emission-blocks.ts';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex 0f399d34c..e5b4c9eba 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,3 +1,4 @@+import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- } else if (first === '[') {+ }+ else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex db10fa54b..ca225ce9b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,3 +1,4 @@+import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 34068d103..3a2524a9a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 93151d43b..2279a0189 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex 188f02d83..a0f467c42 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4ba2c3418..4e8542a21 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex 1a74b1272..a3c96b24a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex de35e7b79..e95cf43d6 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex b4be1b2ea..ffdb4d5b5 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex 3c8d88b7c..e2a96d1a7 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex cf2c9da8e..0389575ac 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,3 +1,4 @@+import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.tsindex 0dd54070e..96304e7a5 100644--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts@@ -1,3 +1,4 @@+import type { JSONContent } from '@tiptap/core';import type { Nodes } from 'mdast';import { expect } from 'vitest';diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 46cc6a074..542204403 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,3 +1,4 @@+import type { Node as PmNode } from '@tiptap/pm/model';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { PropDef, SerializeContext } from '../registry/types.ts';diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex b012a5aff..8c08b7a04 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,3 +1,4 @@+import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 7f6dfcfc3..fd22d2c7b 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,3 +1,4 @@+import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex cd245c38c..c5bfd2386 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,3 +1,4 @@+import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex d578476a7..ac9f5239b 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,3 +1,4 @@+const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex 6dad26200..afd9936fe 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {}}+const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {};}+function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};+const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 55472d8b1..45232b145 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -834,6 +834,10 @@ function attachSpellcheckMenuToWindow(win: BrowserWindow): void {});attachSpellcheckContextMenu(win.webContents, {isSpellCheckEnabled: () => appState.spellCheckEnabled,+ // The native menu attaches to every editable field in the window, so the+ // view-in-source row needs the renderer's answer for whether the jump is+ // live. Read per right-click, like the spell-check flag above.+ canViewInSource: () => editorViewMenuState.canViewInSource === true,setSpellCheckEnabled: setSpellCheckEnabledAppWide,addToDictionary: (word) => {session.defaultSession.addWordToSpellCheckerDictionary(word);@@ -843,6 +847,13 @@ function attachSpellcheckMenuToWindow(win: BrowserWindow): void {getLogger('spellcheck-menu').warn({ err, url }, 'context-menu search openExternal failed');});},+ viewInSource: () => {+ // Route to the window that was right-clicked. Guard the click→close race:+ // the menu click fires async, and a send on a destroyed webContents throws+ // and crashes main (no userland uncaughtException handler).+ if (win.isDestroyed()) return;+ sendToRenderer(win.webContents, 'ok:menu-action', 'toggle-source');+ },popMenu: (input) => {popSpellcheckMenu({ Menu, window: win }, input);},@@ -1109,9 +1120,10 @@ let editorActiveTarget: EditorActiveTargetSnapshot = { kind: null };* View-menu state pushed by the renderer via* `ok:editor:view-menu-state-changed`. Drives the View menu's checkbox* reflection for the visibility toggles and the smart-hide on Expand All /- * Collapse All. Module-scope rather than per-window for the same reason- * `editorActiveTarget` is — the menu is a singleton. Pre-push defaults- * (and their rationale) live with `createDefaultEditorViewMenuState`.+ * Collapse All, plus the editor context menu's view-in-source row. Module-scope+ * rather than per-window for the same reason `editorActiveTarget` is — the menu+ * is a singleton. Pre-push defaults (and their rationale) live with+ * `createDefaultEditorViewMenuState`.*/let editorViewMenuState: EditorViewMenuStateSnapshot = createDefaultEditorViewMenuState();diff --git a/packages/desktop/src/main/spellcheck-context-menu.ts b/packages/desktop/src/main/spellcheck-context-menu.tsindex eeaaaebbc..e774646a1 100644--- a/packages/desktop/src/main/spellcheck-context-menu.ts+++ b/packages/desktop/src/main/spellcheck-context-menu.ts@@ -2,12 +2,18 @@* Wires the native editor context menu onto a window's webContents.** The main process observes the `context-menu` event directly, so spellcheck- * params and clipboard edit flags arrive without any renderer IPC. The only- * gate is `params.isEditable`: the menu shows on any editable field and is+ * params and clipboard edit flags arrive without any renderer IPC. The gate for+ * the menu itself is `params.isEditable`: it shows on any editable field and is* suppressed everywhere else. Surfaces that own their right-click (asset chips,* file tree, editor tabs) `preventDefault()` in the renderer, which suppresses* this main-process event, so they never reach this handler.*+ * Editable, though, spans far more than the document body — the composer, a+ * rename field, any dialog input — so a row that only means something over a+ * document carries its own gate. Those read as capabilities the renderer pushes+ * and this handler samples fresh per right-click, the same shape as the+ * spell-check flag.+ ** Side-effecting capabilities (session, shell, persistence, popup) are injected* so the gate + action wiring are exercised by unit tests without mounting a* BrowserWindow; the pure template builder lives in `spellcheck-menu.ts`.@@ -49,6 +55,13 @@ export interface SpellcheckContextMenuDeps {* without re-attaching the listener.*/readonly isSpellCheckEnabled: () => boolean;+ /**+ * Whether the view-in-source jump would do anything right now — read fresh+ * per right-click, from the state the renderer pushes on every mode and+ * active-document change. Main cannot derive this: it sees an editable+ * target, not which surface the target belongs to.+ */+ readonly canViewInSource: () => boolean;/** Flip app-wide spell checking: update the live session AND persist. */readonly setSpellCheckEnabled: (enabled: boolean) => void;/**@@ -58,6 +71,9 @@ export interface SpellcheckContextMenuDeps {readonly addToDictionary: (word: string) => void;/** Hand a URL to the OS default browser (through the shared scheme gate). */readonly openExternal: (url: string) => void;+ /** Route the view-in-source jump back to the renderer over the existing+ * menu-action channel — no new IPC channel and no document text in main. */+ readonly viewInSource: () => void;/** Build + pop the native menu for the assembled template params. */readonly popMenu: (input: BuildSpellcheckMenuTemplateParams) => void;}@@ -94,10 +110,14 @@ export function attachSpellcheckContextMenu(search: (query) => {deps.openExternal(googleSearchUrl(query));},+ viewInSource: () => {+ deps.viewInSource();+ },};deps.popMenu({params,spellCheckEnabled: deps.isSpellCheckEnabled(),+ canViewInSource: deps.canViewInSource(),actions,});});diff --git a/packages/desktop/src/main/spellcheck-menu.ts b/packages/desktop/src/main/spellcheck-menu.tsindex 14416f43e..63db25024 100644--- a/packages/desktop/src/main/spellcheck-menu.ts+++ b/packages/desktop/src/main/spellcheck-menu.ts@@ -19,6 +19,13 @@* with checking off defensively (Enable row, no suggestions).* - Look Up / Search with Google: shown when there is a selection or a* flagged word to act on.+ * - View in Source: shown only when the renderer has said the jump is live+ * (`canViewInSource`) — the native menu attaches to every editable field in+ * the window, and the jump only means something over a document open in the+ * visual editor. Omitted rather than disabled: a permanently-greyed row on+ * every rename field and dialog input is worse noise than no row. The jump+ * runs in the renderer (routed over the menu-action channel), so the builder+ * reads no document content here.** Pure: `buildSpellcheckMenuTemplate` takes a params slice + the current* `spellCheckEnabled` flag + an `actions` object and returns a@@ -52,12 +59,23 @@ export interface SpellcheckMenuActions {readonly lookUp: () => void;/** Open a web search for the selection or flagged word. */readonly search: (query: string) => void;+ /** Jump to the markdown source of the right-clicked block. Routed to the+ * renderer over the menu-action channel; no document text is read in main. */+ readonly viewInSource: () => void;}export interface BuildSpellcheckMenuTemplateParams {readonly params: SpellcheckMenuParams;/** Whether spell checking is currently on (the persisted app-wide flag). */readonly spellCheckEnabled: boolean;+ /**+ * Whether the view-in-source jump is live for the focused window — the+ * renderer's own answer, since `isEditable` alone cannot tell the document+ * body from the composer, a rename field or a dialog input. Required rather+ * than defaulted so a new call site has to state it instead of silently+ * re-offering the row everywhere.+ */+ readonly canViewInSource: boolean;readonly actions: SpellcheckMenuActions;}@@ -75,10 +93,17 @@ export interface BuildSpellcheckMenuTemplateParams {const LOOKUP_LABEL_MAX = 50;const SEARCH_QUERY_MAX = 200;+/**+ * Native-menu label for the view-in-source jump. The `</>` code glyph rides the+ * label text because native menu items carry no icon field, mirroring the code+ * affordance the renderer bubble menu shows for the same command.+ */+const VIEW_IN_SOURCE_LABEL = 'View in Source Markdown';+export function buildSpellcheckMenuTemplate(input: BuildSpellcheckMenuTemplateParams,): MenuItemConstructorOptions[] {- const { params, spellCheckEnabled, actions } = input;+ const { params, spellCheckEnabled, canViewInSource, actions } = input;const { misspelledWord, dictionarySuggestions, selectionText, editFlags } = params;const editSection: MenuItemConstructorOptions[] = [];@@ -138,8 +163,22 @@ export function buildSpellcheckMenuTemplate(});}+ // Only where the jump is live. The jump is renderer-owned (routed over the+ // menu-action channel), so main reads no document text — including to decide+ // this, which is why the answer is pushed rather than computed here.+ const viewSection: MenuItemConstructorOptions[] = canViewInSource+ ? [+ {+ label: VIEW_IN_SOURCE_LABEL,+ click: () => {+ actions.viewInSource();+ },+ },+ ]+ : [];+const template: MenuItemConstructorOptions[] = [];- for (const section of [editSection, spellSection, lookupSection]) {+ for (const section of [editSection, spellSection, lookupSection, viewSection]) {if (section.length === 0) continue;if (template.length > 0) template.push({ type: 'separator' });template.push(...section);diff --git a/packages/desktop/src/main/view-menu-state.test.ts b/packages/desktop/src/main/view-menu-state.test.tsindex a69179188..756a06270 100644--- a/packages/desktop/src/main/view-menu-state.test.ts+++ b/packages/desktop/src/main/view-menu-state.test.ts@@ -130,6 +130,9 @@ describe('createDefaultEditorViewMenuState — pre-first-push menu state', () =>docPanelVisible: true,terminalVisible: false,terminalLive: false,+ // Restrictive by design: this one gates a context-menu row, and a row+ // offered before the renderer says the jump is live would do nothing.+ canViewInSource: false,});});});diff --git a/packages/desktop/src/main/view-menu-state.ts b/packages/desktop/src/main/view-menu-state.tsindex 1d076fe24..b00f847f2 100644--- a/packages/desktop/src/main/view-menu-state.ts+++ b/packages/desktop/src/main/view-menu-state.ts@@ -17,6 +17,11 @@ export function mergeViewMenuState(* Expand/Collapse rendered (no smart-hide), sidebar + doc panel assumed* visible (the common wide-window startup), terminal hidden with no live* session.+ *+ * `canViewInSource` is the one field that defaults to the RESTRICTIVE value+ * rather than the likely one: it gates a context-menu row, and a row offered+ * before the renderer has said the jump is live would silently do nothing.+ * Absent is better than inert for a row the user has to read past.*/export function createDefaultEditorViewMenuState(): EditorViewMenuStateSnapshot {return {@@ -30,6 +35,7 @@ export function createDefaultEditorViewMenuState(): EditorViewMenuStateSnapshotdocPanelVisible: true,terminalVisible: false,terminalLive: false,+ canViewInSource: false,};}diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.tsindex 2132d13f4..0350c2e08 100644--- a/packages/desktop/src/shared/bridge-contract.ts+++ b/packages/desktop/src/shared/bridge-contract.ts@@ -817,7 +817,8 @@ export type OkEditorActiveTargetSnapshot =| { readonly kind: null };/**- * Renderer → main snapshot of the View menu's checkbox + smart-hide state.+ * Renderer → main snapshot of the View menu's checkbox + smart-hide state, plus+ * the editor capabilities main's other native menus gate rows on.* Drives the macOS View menu's live `checked` reflection for "Show Hidden Files"* and the `visible: false` smart-hide on "Expand All" /* "Collapse All" so a fully-expanded tree doesn't render a no-op item.@@ -849,6 +850,12 @@ export interface OkEditorViewMenuStateSnapshot {// terminal reads `terminalLive: true, terminalVisible: false`. Drives the// Terminal menu's "Kill Terminal" enablement.readonly terminalLive?: boolean;+ // Whether the editor context menu's "View in Source" jump would do anything:+ // it reads the visual editor's caret for the active document, so it is inert+ // in source mode and with no document open. Optional + defaults false, so the+ // row stays out of the menu until the renderer says the jump is live — main+ // has no way to compute this, and must not learn about document content.+ readonly canViewInSource?: boolean;}/**diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.tsindex d7c1d9028..cadb1ea7f 100644--- a/packages/desktop/src/shared/ipc-channels.ts+++ b/packages/desktop/src/shared/ipc-channels.ts@@ -666,6 +666,7 @@ export interface EditorViewMenuStateSnapshot {readonly docPanelVisible?: boolean;readonly terminalVisible?: boolean;readonly terminalLive?: boolean;+ readonly canViewInSource?: boolean;}/**diff --git a/packages/desktop/tests/main/spellcheck-context-menu.test.ts b/packages/desktop/tests/main/spellcheck-context-menu.test.tsindex fdd0ea2b4..2d997ef79 100644--- a/packages/desktop/tests/main/spellcheck-context-menu.test.ts+++ b/packages/desktop/tests/main/spellcheck-context-menu.test.ts@@ -51,12 +51,17 @@ function makeWebContents() {};}-function makeDeps(isSpellCheckEnabled: () => boolean = () => true) {+function makeDeps(+ isSpellCheckEnabled: () => boolean = () => true,+ canViewInSource: () => boolean = () => true,+) {return {isSpellCheckEnabled,+ canViewInSource,setSpellCheckEnabled: vi.fn((_: boolean) => {}),addToDictionary: vi.fn((_: string) => {}),openExternal: vi.fn((_: string) => {}),+ viewInSource: vi.fn(() => {}),popMenu: vi.fn((_: BuildSpellcheckMenuTemplateParams) => {}),};}@@ -94,6 +99,25 @@ describe('attachSpellcheckContextMenu — spellCheckEnabled flag', () => {});});+describe('attachSpellcheckContextMenu — canViewInSource capability', () => {+ test('reads the capability fresh on each right-click', () => {+ // Same shape as the spell-check flag: the renderer pushes mode and+ // active-document changes continuously, and the menu must reflect the state+ // at THIS right-click, not the one the listener was attached under.+ const wc = makeWebContents();+ const values = [true, false];+ const deps = makeDeps(+ () => true,+ () => values.shift() ?? true,+ );+ attachSpellcheckContextMenu(wc, deps);+ wc.fire(makeParams());+ wc.fire(makeParams());+ expect(deps.popMenu.mock.calls[0]?.[0]?.canViewInSource).toBe(true);+ expect(deps.popMenu.mock.calls[1]?.[0]?.canViewInSource).toBe(false);+ });+});+describe('attachSpellcheckContextMenu — params forwarding', () => {test('popMenu receives the fired params object', () => {const wc = makeWebContents();@@ -165,4 +189,12 @@ describe('attachSpellcheckContextMenu — action wiring', () => {actions.search('a b&c');expect(deps.openExternal).toHaveBeenCalledWith('https://www.google.com/search?q=a%20b%26c');});++ test('viewInSource routes to the injected capability', () => {+ const wc = makeWebContents();+ const deps = makeDeps();+ const actions = fireAndGetActions(wc, deps, makeParams());+ actions.viewInSource();+ expect(deps.viewInSource).toHaveBeenCalledTimes(1);+ });});diff --git a/packages/desktop/tests/main/spellcheck-menu.test.ts b/packages/desktop/tests/main/spellcheck-menu.test.tsindex 979c9e072..46e190daf 100644--- a/packages/desktop/tests/main/spellcheck-menu.test.ts+++ b/packages/desktop/tests/main/spellcheck-menu.test.ts@@ -22,9 +22,15 @@ function makeActions() {setSpellCheckEnabled: vi.fn((_: boolean) => {}),lookUp: vi.fn(() => {}),search: vi.fn((_: string) => {}),+ viewInSource: vi.fn(() => {}),};}+// The view-in-source jump trails every section-composition case below, which+// all build with the jump live (`canViewInSource` defaults to true in `build`).+// Its own gate is covered by the not-live cases at the end of the describe.+const VIEW_ROW = 'View in Source Markdown';+const allEditFlags = {canCut: true,canCopy: true,@@ -46,8 +52,9 @@ function build(params: SpellcheckMenuParams,spellCheckEnabled: boolean,actions: BuildSpellcheckMenuTemplateParams['actions'],+ canViewInSource = true,): MenuItemConstructorOptions[] {- return buildSpellcheckMenuTemplate({ params, spellCheckEnabled, actions });+ return buildSpellcheckMenuTemplate({ params, spellCheckEnabled, canViewInSource, actions });}/** Project a template to a comparable shape: role, label, or separator marker. */@@ -56,9 +63,16 @@ function shapeOf(template: MenuItemConstructorOptions[]): string[] {}describe('buildSpellcheckMenuTemplate — section composition', () => {- test('editable text with no misspelling and no selection → edit roles only', () => {+ test('editable text with no misspelling and no selection → edit roles + View in Source', () => {const template = build(makeParams(), true, makeActions());- expect(shapeOf(template)).toEqual(['cut', 'copy', 'paste', 'selectAll']);+ expect(shapeOf(template)).toEqual([+ 'cut',+ 'copy',+ 'paste',+ 'selectAll',+ '[separator]',+ VIEW_ROW,+ ]);});test('edit roles respect editFlags', () => {@@ -66,7 +80,7 @@ describe('buildSpellcheckMenuTemplate — section composition', () => {editFlags: { canCut: false, canCopy: true, canPaste: true, canSelectAll: false },});const template = build(params, true, makeActions());- expect(shapeOf(template)).toEqual(['copy', 'paste']);+ expect(shapeOf(template)).toEqual(['copy', 'paste', '[separator]', VIEW_ROW]);});test('flagged word with checking on → suggestions, Add to Dictionary, Disable, Look Up, Search', () => {@@ -88,6 +102,8 @@ describe('buildSpellcheckMenuTemplate — section composition', () => {'[separator]','Look Up "teh"','Search with Google',+ '[separator]',+ VIEW_ROW,]);});@@ -105,6 +121,8 @@ describe('buildSpellcheckMenuTemplate — section composition', () => {'[separator]','Look Up "zzx"','Search with Google',+ '[separator]',+ VIEW_ROW,]);});@@ -117,6 +135,8 @@ describe('buildSpellcheckMenuTemplate — section composition', () => {'selectAll','[separator]','Enable Spell Check',+ '[separator]',+ VIEW_ROW,]);});@@ -136,6 +156,8 @@ describe('buildSpellcheckMenuTemplate — section composition', () => {'[separator]','Look Up "teh"','Search with Google',+ '[separator]',+ VIEW_ROW,]);});@@ -150,15 +172,19 @@ describe('buildSpellcheckMenuTemplate — section composition', () => {'[separator]','Look Up "hello world"','Search with Google',+ '[separator]',+ VIEW_ROW,]);});- test('no rows at all → empty template (no dangling separators)', () => {+ test('no edit/spell/lookup rows → View in Source alone (no dangling separators)', () => {+ // With the jump live and nothing else to offer, the view row is the sole+ // entry, with no leading separator.const params = makeParams({editFlags: { canCut: false, canCopy: false, canPaste: false, canSelectAll: false },});const template = build(params, true, makeActions());- expect(template).toHaveLength(0);+ expect(shapeOf(template)).toEqual([VIEW_ROW]);});test('leading section absent → no leading separator', () => {@@ -176,8 +202,64 @@ describe('buildSpellcheckMenuTemplate — section composition', () => {'[separator]','Look Up "teh"','Search with Google',+ '[separator]',+ VIEW_ROW,]);});++ test('View in Source is the last row on a fully-populated menu', () => {+ const params = makeParams({+ misspelledWord: 'teh',+ dictionarySuggestions: ['the'],+ selectionText: 'teh fox',+ });+ const template = build(params, true, makeActions());+ const shape = shapeOf(template);+ // Appended after everything else, behind its own separator.+ expect(shape.at(-1)).toBe(VIEW_ROW);+ expect(shape.at(-2)).toBe('[separator]');+ });++ // The menu attaches to every editable field in the window, and the jump only+ // means something over a document open in the visual editor. Everywhere else+ // — the composer, a rename field, a dialog input, source mode, no document —+ // the row is omitted rather than shown inert or greyed.+ test('the jump not being live omits the row, leaving the rest intact', () => {+ const params = makeParams({+ misspelledWord: 'teh',+ dictionarySuggestions: ['the'],+ selectionText: 'teh fox',+ });+ const template = build(params, true, makeActions(), false);+ expect(shapeOf(template)).toEqual([+ 'cut',+ 'copy',+ 'paste',+ 'selectAll',+ '[separator]',+ 'the',+ 'Add to Dictionary',+ 'Disable Spell Check',+ '[separator]',+ 'Look Up "teh fox"',+ 'Search with Google',+ ]);+ });++ test('the omitted row takes its separator with it', () => {+ const template = build(makeParams(), true, makeActions(), false);+ expect(shapeOf(template)).toEqual(['cut', 'copy', 'paste', 'selectAll']);+ });++ test('a capability-less field with the jump not live gets no menu rows at all', () => {+ // The case that made the row unconditional-looking: an editable target with+ // no edit flags, no misspelling and no selection. It must now come back+ // empty rather than offering a lone row that does nothing.+ const params = makeParams({+ editFlags: { canCut: false, canCopy: false, canPaste: false, canSelectAll: false },+ });+ expect(build(params, true, makeActions(), false)).toEqual([]);+ });});describe('buildSpellcheckMenuTemplate — callback dispatch', () => {@@ -220,6 +302,13 @@ describe('buildSpellcheckMenuTemplate — callback dispatch', () => {expect(actions.setSpellCheckEnabled).toHaveBeenCalledWith(true);});+ test('View in Source fires the viewInSource action', () => {+ const actions = makeActions();+ const template = build(makeParams(), true, actions);+ clickRow(template, VIEW_ROW);+ expect(actions.viewInSource).toHaveBeenCalledTimes(1);+ });+test('Look Up fires lookUp; Search fires search with the word', () => {const actions = makeActions();const params = makeParams({ selectionText: 'flow' });@@ -299,12 +388,24 @@ describe('popSpellcheckMenu', () => {popSpellcheckMenu({ Menu: { buildFromTemplate }, window: fakeWindow },- { params: makeParams(), spellCheckEnabled: true, actions: makeActions() },+ {+ params: makeParams(),+ spellCheckEnabled: true,+ canViewInSource: true,+ actions: makeActions(),+ },);expect(buildFromTemplate).toHaveBeenCalledTimes(1);const built = buildFromTemplate.mock.calls[0]?.[0];- expect(shapeOf(built ?? [])).toEqual(['cut', 'copy', 'paste', 'selectAll']);+ expect(shapeOf(built ?? [])).toEqual([+ 'cut',+ 'copy',+ 'paste',+ 'selectAll',+ '[separator]',+ VIEW_ROW,+ ]);expect(popup).toHaveBeenCalledWith({ window: fakeWindow });});@@ -314,7 +415,12 @@ describe('popSpellcheckMenu', () => {popSpellcheckMenu({ Menu: { buildFromTemplate }, window: fakeWindow },- { params: makeParams(), spellCheckEnabled: true, actions: makeActions() },+ {+ params: makeParams(),+ spellCheckEnabled: true,+ canViewInSource: true,+ actions: makeActions(),+ },);expect(buildFromTemplate).not.toHaveBeenCalled();