Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): reveal CodeMirror carets under Ask AI (PRD-8625) (#4365)
serafin-garcia0e57a5487dd5
diff --git a/.changeset/composer-open-reveals-the-caret.md b/.changeset/composer-open-reveals-the-caret.mdnew file mode 100644index 000000000..7411e36c5--- /dev/null+++ b/.changeset/composer-open-reveals-the-caret.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++The line your cursor is on is scrolled clear of the Ask AI composer whenever the composer comes back over a document. That is bringing it back from its status-bar badge or with the Ask AI keyboard shortcut, and closing the terminal, the agents panel, or a diff view so the composer returns over the document you were reading. Pressing the shortcut while the composer is already up focuses it without moving the page.++Only the visual editor used to do this. The clearance now also holds in markdown source mode, in any file the editor opens in a text view (`.ts`, `.py`, `.json`, `.yaml`, `.txt` and the rest), and in a `.mmd` or `.mermaid` diagram's source pane, where the cursor used to end up buried under the composer.++Switching documents or editor surfaces while the composer is already open leaves the scroll position alone. A document you come back to opens where you left it, and switching between the visual editor and markdown source lands where the mode switch puts you rather than being pulled to the cursor.diff --git a/packages/app/package.json b/packages/app/package.jsonindex b1dfb78b8..09efd2350 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -29,7 +29,7 @@"measure:stress": "bash scripts/measure-stress.sh","measure:sweep": "bash scripts/measure-sweep.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/list-item-drag.e2e.ts tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts",+ "test:e2e": "playwright test tests/stress/list-item-drag.e2e.ts tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts tests/stress/theme-fade.e2e.ts tests/stress/theme-color-conversion.e2e.ts tests/stress/composer-open-caret-reveal.e2e.ts tests/stress/spellcheck-browser-absence.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox","test:visual": "playwright test --config playwright.visual.config.ts","test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",diff --git a/packages/app/src/components/BottomComposer.dom.test.tsx b/packages/app/src/components/BottomComposer.dom.test.tsxindex da9b0b4cf..aa878de1e 100644--- a/packages/app/src/components/BottomComposer.dom.test.tsx+++ b/packages/app/src/components/BottomComposer.dom.test.tsx@@ -1,16 +1,13 @@+import type { EditorView as CodeMirrorView } from '@codemirror/view';import * as actualLinguiMacro from '@lingui/react/macro';import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import {- type ReactNode,- type Ref,- StrictMode,- useEffect,- useImperativeHandle,- useRef,-} from 'react';+import type { Editor } from '@tiptap/core';+import { type ReactNode, type Ref, useEffect, useImperativeHandle, useRef } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import type { ComposerMentionInputHandle } from '@/editor/ComposerMentionInput';+import { FULL_PAGE_CM_HOST_SELECTORS, type FullPageCmHost } from '@/editor/document-scrollports';+import type { EditorSurface } from '@/editor/selection-stats';import { reloadEnabledAgentsFromStorage } from '@/lib/acp/enabled-agents';import {getDefaultRegisteredAgent,@@ -251,13 +248,18 @@ const ALL_INSTALLED: Record<string, { installed: boolean | null }> = {async function renderComposer(docName = 'notes',- extra: Partial<{ dismissed: boolean; onDismiss: () => void; onReopen: () => void }> = {},+ props: Partial<{ dismissed: boolean; onDismiss: () => void; onReopen: () => void }> = {},+ options: { strict?: boolean; surface?: EditorSurface } = {},) {const { BottomComposer } = await import('./BottomComposer');const { TooltipProvider } = await import('@/components/ui/tooltip');- return render(<BottomComposer docName={docName} surface="wysiwyg" {...extra} />, {- wrapper: TooltipProvider,- });+ return render(+ <BottomComposer docName={docName} surface={options.surface ?? 'wysiwyg'} {...props} />,+ {+ reactStrictMode: options.strict,+ wrapper: TooltipProvider,+ },+ );}async function renderComposerWithTerminal(@@ -428,12 +430,7 @@ describe('BottomComposer (shell behavior)', () => {});test('mounting never steals focus, even under StrictMode effect double-invoke', async () => {- const { BottomComposer } = await import('./BottomComposer');- render(- <StrictMode>- <BottomComposer docName="notes" surface="wysiwyg" />- </StrictMode>,- );+ await renderComposer('notes', {}, { strict: true });expect(document.activeElement).not.toBe(getInput());});@@ -1203,6 +1200,24 @@ describe('BottomComposer (dismiss / reopen)', () => {expect(onReopen).toHaveBeenCalledTimes(1);});++ test('⇧⌘L reads the current dismissed state, so a dismiss on a live instance still reopens', async () => {+ const onReopen = vi.fn(() => {});+ const { BottomComposer } = await import('./BottomComposer');+ const { rerender } = await renderComposer('notes', { onReopen });++ rerender(<BottomComposer docName="notes" surface="wysiwyg" onReopen={onReopen} dismissed />);+ dispatchOpenAskAiShortcut();++ expect(+ onReopen,+ 'the open-Ask-AI subscription has no deps, so it is built once at mount and never rebuilt, ' ++ 'and dismissing returns null only after every hook has run, which keeps that one ' ++ 'subscription alive on the same instance. Reading `dismissed` and `onReopen` out of the ' ++ 'mount closure instead of at call time would route a post-dismiss ⇧⌘L to the focus ' ++ 'branch, where the input ref is already null, and the composer would never reopen',+ ).toHaveBeenCalledTimes(1);+ });});describe('BottomComposer (conflict footer stacking)', () => {@@ -1350,11 +1365,31 @@ describe('BottomComposer (queued-comments chip lifecycle)', () => {});describe('BottomComposer (end-of-document scroll compensation)', () => {+ const PORT_BOTTOM = 700;+ const CARD_TOP = 600;+ const CARET_INSIDE_THE_GAP = 700;+ const CARET_INSIDE_THE_GAP_AFTER_A_REVEAL = 900;const planted: HTMLElement[] = [];+ const registered: Array<{ docName: string; editor: Editor }> = [];+ const registeredCmViews: Array<{ docName: string; view: CodeMirrorView }> = [];- function plantScrollport(scrollTop: number): { el: HTMLElement; writes: number[] } {- const el = document.createElement('div');- el.className = 'editor-doc-scroll';+ async function registerCaseEditor(docName: string, editor: Editor): Promise<void> {+ const { registerEditor } = await import('@/editor/active-editor');+ registerEditor(docName, editor);+ registered.push({ docName, editor });+ }++ async function registerCaseCmView(+ docName: string,+ host: FullPageCmHost,+ view: CodeMirrorView,+ ): Promise<void> {+ const { registerFullPageCmView } = await import('@/editor/full-page-cm-views');+ registerFullPageCmView(docName, view, host);+ registeredCmViews.push({ docName, view });+ }++ function trackScroll(el: HTMLElement, scrollTop: number): number[] {const writes: number[] = [];let current = scrollTop;Object.defineProperty(el, 'scrollHeight', { value: 1000, configurable: true });@@ -1367,11 +1402,39 @@ describe('BottomComposer (end-of-document scroll compensation)', () => {writes.push(next);},});+ el.getBoundingClientRect = () => new DOMRect(0, 0, 0, PORT_BOTTOM);+ return writes;+ }++ function plantScrollport(scrollTop: number): { el: HTMLElement; writes: number[] } {+ const el = document.createElement('div');+ el.className = 'editor-doc-scroll';+ const writes = trackScroll(el, scrollTop);document.body.appendChild(el);planted.push(el);return { el, writes };}+ function plantCmScrollport(+ host: FullPageCmHost,+ scrollTop: number,+ ): { scroller: HTMLElement; writes: number[] } {+ const outer = document.createElement('div');+ outer.className = 'editor-doc-scroll';+ const selector = FULL_PAGE_CM_HOST_SELECTORS[host];+ const hostEl = document.createElement('div');+ if (selector.startsWith('[')) hostEl.setAttribute(selector.slice(1, -1), '');+ else hostEl.className = selector.slice(1);+ const scroller = document.createElement('div');+ scroller.className = 'cm-scroller';+ const writes = trackScroll(scroller, scrollTop);+ hostEl.append(scroller);+ outer.append(hostEl);+ document.body.append(outer);+ planted.push(outer);+ return { scroller, writes };+ }+function plantPortal(attributes: Record<string, string>): HTMLElement {const portal = document.createElement('div');for (const [name, value] of Object.entries(attributes)) portal.setAttribute(name, value);@@ -1384,20 +1447,46 @@ describe('BottomComposer (end-of-document scroll compensation)', () => {}let nowSpy: ReturnType<typeof vi.spyOn> | null = null;+ let realGetBoundingClientRect: (this: Element) => DOMRect;++ function giveTheCardALayoutBox(): void {+ realGetBoundingClientRect = Element.prototype.getBoundingClientRect;+ Element.prototype.getBoundingClientRect = function (this: Element): DOMRect {+ return this.matches('[data-testid="ask-ai-composer-card"]')+ ? new DOMRect(0, CARD_TOP, 0, PORT_BOTTOM - CARD_TOP)+ : realGetBoundingClientRect.call(this);+ };+ }const nextFrame = () =>act(async () => {await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));});- beforeEach(() => {+ beforeEach(async () => {+ const { __resetScrollRestoreCoordination } = await import(+ '@/editor/scroll-restore-coordination'+ );+ __resetScrollRestoreCoordination();nowSpy = vi.spyOn(performance, 'now').mockReturnValue(0);+ giveTheCardALayoutBox();});- afterEach(() => {+ afterEach(async () => {+ Element.prototype.getBoundingClientRect = realGetBoundingClientRect;vi.useRealTimers();nowSpy?.mockRestore();nowSpy = null;+ const { unregisterEditor } = await import('@/editor/active-editor');+ for (const { docName, editor } of registered.splice(0)) unregisterEditor(docName, editor);+ const { unregisterFullPageCmView } = await import('@/editor/full-page-cm-views');+ for (const { docName, view } of registeredCmViews.splice(0)) {+ unregisterFullPageCmView(docName, view);+ }+ const { __resetScrollRestoreCoordination } = await import(+ '@/editor/scroll-restore-coordination'+ );+ __resetScrollRestoreCoordination();for (const el of planted.splice(0)) el.remove();});@@ -1427,6 +1516,301 @@ describe('BottomComposer (end-of-document scroll compensation)', () => {).toHaveLength(0);});+ function caretEditorStub(port: { el: HTMLElement }, caretDocY: number): Editor {+ const dom = document.createElement('div');+ port.el.appendChild(dom);+ dom.getClientRects = () => [new DOMRect(0, 0, 0, 18)] as unknown as DOMRectList;+ return {+ isDestroyed: false,+ editorView: {+ dom,+ state: { selection: { head: 1 } },+ coordsAtPos: () => ({+ top: caretDocY - port.el.scrollTop - 18,+ bottom: caretDocY - port.el.scrollTop,+ left: 0,+ right: 0,+ }),+ },+ } as unknown as Editor;+ }++ function caretCmViewStub(scroller: HTMLElement, caretDocY: number): CodeMirrorView {+ return {+ scrollDOM: scroller,+ state: { selection: { main: { head: 1 } } },+ coordsAtPos: () => ({+ top: caretDocY - scroller.scrollTop - 18,+ bottom: caretDocY - scroller.scrollTop,+ left: 0,+ right: 0,+ }),+ } as unknown as CodeMirrorView;+ }++ test('reveals the caret when the composer opens and leaves the scrollport alone on a document switch', async () => {+ const { BottomComposer } = await import('./BottomComposer');+ const port = plantScrollport(100);+ const opened = caretEditorStub(port, CARET_INSIDE_THE_GAP);+ const switchedTo = caretEditorStub(port, CARET_INSIDE_THE_GAP_AFTER_A_REVEAL);+ await registerCaseEditor('opened-doc', opened);+ await registerCaseEditor('switched-doc', switchedTo);++ const { rerender } = await renderComposer('opened-doc', {}, { strict: true });+ await nextFrame();+ await nextFrame();++ expect(+ port.writes,+ 'the composer arriving over the document is the transition this reveal exists for. This ' ++ 'case renders with `reactStrictMode` because the reveal effect schedules a frame its own ' ++ 'cleanup cancels: a double-invoked mount has to re-schedule and still reveal',+ ).not.toHaveLength(0);++ const afterOpen = port.writes.length;+ rerender(<BottomComposer docName="switched-doc" surface="wysiwyg" />);+ await nextFrame();+ await nextFrame();++ expect(+ port.writes.length,+ 'switching documents under an already-mounted, already-open composer is not the card ' ++ 'arriving over a caret. Scrolling `.editor-doc-scroll` here is a delta ' ++ 'ScrollPreservingContainer did not write, so it reads as an external scroll and abandons ' ++ 'the restore it is mid-way through. The reveal effect keys on `dismissed` alone so a ' ++ 'switch never re-runs it. `switched-doc` deliberately carries a caret BELOW the ' ++ 'occlusion line the first reveal left behind, so widening those dependencies produces a ' ++ 'write and reds this assertion. Give both stubs the same caret and it passes either way',+ ).toBe(afterOpen);+ });++ test('a document switch inside the pending reveal frame reveals neither document', async () => {+ const { BottomComposer } = await import('./BottomComposer');+ const port = plantScrollport(100);+ await registerCaseEditor('arrived-over-doc', caretEditorStub(port, CARET_INSIDE_THE_GAP));+ await registerCaseEditor(+ 'switched-under-doc',+ caretEditorStub(port, CARET_INSIDE_THE_GAP_AFTER_A_REVEAL),+ );++ const { rerender } = await renderComposer('arrived-over-doc');+ rerender(<BottomComposer docName="switched-under-doc" surface="wysiwyg" />);+ await nextFrame();+ await nextFrame();++ expect(+ port.writes,+ 'the reveal reads the card geometry a frame after the effect schedules it, and a switch ' ++ 'inside that window re-aims it: the frame was scheduled for the document the card ' ++ 'arrived over, and the document under the card is now a different one. Revealing either ' ++ 'scrolls `.editor-doc-scroll` during the switch restore, which is the write the ' ++ 'doc-switch case above exists to forbid',+ ).toHaveLength(0);+ });++ test('a surface toggle under a mounted composer reveals neither surface', async () => {+ const { BottomComposer } = await import('./BottomComposer');+ const wysiwygPort = plantScrollport(100);+ const cmPort = plantCmScrollport('textDocEditor', 100);+ await registerCaseEditor('toggled-doc', caretEditorStub(wysiwygPort, CARET_INSIDE_THE_GAP));+ await registerCaseCmView(+ 'toggled-doc',+ 'textDocEditor',+ caretCmViewStub(cmPort.scroller, CARET_INSIDE_THE_GAP),+ );++ const { rerender } = await renderComposer('toggled-doc');+ await nextFrame();+ await nextFrame();+ const afterOpen = wysiwygPort.writes.length;++ rerender(<BottomComposer docName="toggled-doc" surface="source" />);+ await nextFrame();+ await nextFrame();++ expect(+ cmPort.writes,+ 'toggling into source mode under an already-open card is not the card arriving. ' ++ 'mode-switch-landing owns where the source view lands, and a reveal firing here writes a ' ++ 'scroll delta that landing did not make. The reveal effect keys on `dismissed` alone so ' ++ 'the toggle never re-runs it, and adding `effectiveSurface` back to those dependencies ' ++ 'produces a write here',+ ).toHaveLength(0);+ expect(wysiwygPort.writes.length).toBe(afterOpen);+ });++ test('a surface toggle inside the pending reveal frame reveals neither surface', async () => {+ const { BottomComposer } = await import('./BottomComposer');+ const wysiwygPort = plantScrollport(100);+ const cmPort = plantCmScrollport('textDocEditor', 100);+ await registerCaseEditor('mid-frame-doc', caretEditorStub(wysiwygPort, CARET_INSIDE_THE_GAP));+ await registerCaseCmView(+ 'mid-frame-doc',+ 'textDocEditor',+ caretCmViewStub(cmPort.scroller, CARET_INSIDE_THE_GAP),+ );++ const { rerender } = await renderComposer('mid-frame-doc');+ rerender(<BottomComposer docName="mid-frame-doc" surface="source" />);+ await nextFrame();+ await nextFrame();++ expect(+ wysiwygPort.writes,+ 'the frame was scheduled for the surface the card arrived over, and the surface under the ' ++ 'card is now a different one. Dropping the surface half of the in-frame staleness check ' ++ 'lets that frame reveal the visual editor caret while the document is painting its ' ++ 'source view',+ ).toHaveLength(0);+ expect(cmPort.writes).toHaveLength(0);+ });++ test('reveals the caret on a CodeMirror surface, not only in the visual editor', async () => {+ const port = plantCmScrollport('textDocEditor', 100);+ await registerCaseCmView(+ 'text-doc',+ 'textDocEditor',+ caretCmViewStub(port.scroller, CARET_INSIDE_THE_GAP),+ );++ await renderComposer('text-doc', {}, { surface: 'source' });+ await nextFrame();+ await nextFrame();++ expect(+ port.writes,+ 'the component has to forward the surface it was given rather than reveal only on ' ++ 'wysiwyg. Restoring a wysiwyg-only guard here leaves every CodeMirror surface with the ' ++ 'caret under the card, which is the bug, and the module-level caret-reveal tests cannot ' ++ 'see it because they call the module directly',+ ).not.toHaveLength(0);+ });++ test('a CodeMirror host that registers after the arrival frame is not chased', async () => {+ const port = plantCmScrollport('textDocEditor', 100);++ await renderComposer('late-host-doc', {}, { surface: 'source' });+ await nextFrame();+ await nextFrame();++ await registerCaseCmView(+ 'late-host-doc',+ 'textDocEditor',+ caretCmViewStub(port.scroller, CARET_INSIDE_THE_GAP),+ );+ await nextFrame();+ await nextFrame();++ expect(+ port.writes,+ 'a lazily loaded text or Mermaid host can finish mounting after the one reveal frame. ' ++ 'Leaving that arrival alone is deliberate. All three full-page CodeMirror hosts build ' ++ 'their EditorView with no selection, so a view that registers this late has its caret ' ++ 'at position 0, which a bottom-anchored card cannot occlude. Subscribing to ' ++ 'subscribeFullPageCmViewRegistry to retry would turn the one-shot reveal into a ' ++ 'deferred write against a scrollport that mode-switch landing or scroll restore is ' ++ 'still placing, which is the write the document-switch cases above and the ' ++ 'yielded-frame cases below forbid. The stub caret here sits inside the gap, so a retry ' ++ 'implementation reds this',+ ).toHaveLength(0);+ });++ test('a remount with the composer still open reveals again', async () => {+ const port = plantScrollport(100);+ const editor = caretEditorStub(port, CARET_INSIDE_THE_GAP);+ await registerCaseEditor('remounted-doc', editor);++ const { unmount } = await renderComposer('remounted-doc', {}, { strict: true });+ await nextFrame();+ await nextFrame();+ expect(port.writes).not.toHaveLength(0);++ unmount();+ port.el.scrollTop = 100;+ const beforeRemount = port.writes.length;++ await renderComposer('remounted-doc', {}, { strict: true });+ await nextFrame();+ await nextFrame();++ expect(+ port.writes.length,+ 'the composer unmounts whenever the terminal or agents column opens, so closing one puts ' ++ 'the card back over a document it never left. That is the card arriving, not a switch ' ++ 'underneath a mounted one, so a fresh mount reveals again',+ ).toBeGreaterThan(beforeRemount);+ });++ test('a reveal frame yields to a held scroll suppression, and a reopen recovers it', async () => {+ const { acquireScrollRestoreSuppression } = await import(+ '@/editor/scroll-restore-coordination'+ );+ const { BottomComposer } = await import('./BottomComposer');+ const port = plantScrollport(100);+ const editor = caretEditorStub(port, CARET_INSIDE_THE_GAP);+ await registerCaseEditor('held-doc', editor);+ const held = acquireScrollRestoreSuppression('held-doc', 'navigation');++ const { rerender } = await renderComposer('held-doc', {}, { strict: true });+ await nextFrame();+ await nextFrame();++ expect(+ port.writes,+ 'a landing or a navigation seam owns the scrollport while it holds a suppression, and it ' ++ 'will place the document itself. The reveal has to yield rather than fight it',+ ).toHaveLength(0);++ held.release();+ rerender(<BottomComposer docName="held-doc" surface="wysiwyg" dismissed />);+ await nextFrame();+ rerender(<BottomComposer docName="held-doc" surface="wysiwyg" />);+ await nextFrame();+ await nextFrame();++ expect(+ port.writes,+ 'yielding costs the caret its reveal for that arrival, so it stays where the seam left it ' ++ 'until the card arrives again. Closing and reopening flips `dismissed`, which is the ' ++ 'only dependency the reveal effect has, so it re-runs and reveals',+ ).not.toHaveLength(0);+ });++ test('a reveal frame that yielded does not fire on the next document switch', async () => {+ const { acquireScrollRestoreSuppression } = await import(+ '@/editor/scroll-restore-coordination'+ );+ const { BottomComposer } = await import('./BottomComposer');+ const port = plantScrollport(100);+ const yielded = caretEditorStub(port, CARET_INSIDE_THE_GAP);+ const switchedTo = caretEditorStub(port, CARET_INSIDE_THE_GAP_AFTER_A_REVEAL);+ await registerCaseEditor('yielded-doc', yielded);+ await registerCaseEditor('after-yield-doc', switchedTo);+ const held = acquireScrollRestoreSuppression('yielded-doc', 'navigation');++ const { rerender } = await renderComposer('yielded-doc', {}, { strict: true });+ await nextFrame();+ await nextFrame();+ expect(+ port.writes,+ 'precondition: the frame has to reach the held suppression and yield, or the switch ' ++ 'below measures a latch that was never at risk',+ ).toHaveLength(0);++ held.release();+ rerender(<BottomComposer docName="after-yield-doc" surface="wysiwyg" />);+ await nextFrame();+ await nextFrame();++ expect(+ port.writes,+ 'a frame that yielded to a seam must not be retried on the next document switch, or the ' ++ 'reveal lands against a scrollport ScrollPreservingContainer is restoring and the ' ++ 'restore is abandoned. The effect does not re-run on a switch, so a yield costs that ' ++ 'arrival its reveal and nothing carries over',+ ).toHaveLength(0);+ });+test('stops clamping once the 300ms compensation budget is spent', async () => {const atEnd = plantScrollport(380);diff --git a/packages/app/src/components/BottomComposer.tsx b/packages/app/src/components/BottomComposer.tsxindex 7f034fa35..8cdcc458d 100644--- a/packages/app/src/components/BottomComposer.tsx+++ b/packages/app/src/components/BottomComposer.tsx@@ -2,9 +2,8 @@import { type TargetData, TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';import { Plural, Trans, useLingui } from '@lingui/react/macro';-import type { EditorView } from '@tiptap/pm/view';import { ArrowUpRight, ChevronDown, TextQuote, X } from 'lucide-react';-import { useEffect, useRef, useState } from 'react';+import { useEffect, useEffectEvent, useRef, useState } from 'react';import { toast } from 'sonner';import {composeCommentBatchInstruction,@@ -33,17 +32,13 @@ import {import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';import { Button } from '@/components/ui/button';import { Spinner } from '@/components/ui/spinner';-import { getEditorForDoc } from '@/editor/active-editor';import {type ComposerAttachmentDropPolicy,ComposerMentionInput,type ComposerMentionInputHandle,} from '@/editor/ComposerMentionInput';-import {- DOCUMENT_SCROLL_HOST_SELECTOR,- documentScrollports,- isPinnedToEnd,-} from '@/editor/document-scrollports';+import { revealCaretAboveComposerCard } from '@/editor/caret-reveal';+import { documentScrollports, isPinnedToEnd } from '@/editor/document-scrollports';import type { SuggestionPopupLabel } from '@/editor/extensions/suggestion-floating-ui';import { isScrollRestoreSuppressed } from '@/editor/scroll-restore-coordination';import {@@ -54,7 +49,6 @@ import {} from '@/editor/selection-context';import type { EditorSurface } from '@/editor/selection-stats';import { useComposerAttachments } from '@/editor/use-composer-attachments';-import { getEditorView } from '@/editor/utils/get-editor-view';import { useConflictComposerPrefill } from '@/hooks/use-conflict-composer-prefill';import { useReducedMotion } from '@/hooks/use-reduced-motion';import { useSelectionContext } from '@/hooks/use-selection-context';@@ -141,22 +135,13 @@ export const COMPOSER_SUGGESTION_POPUP_LABELS = ['composer-mention','composer-slash',] as const satisfies readonly SuggestionPopupLabel[];+const ASK_COMPOSER_HEIGHT_RESERVE_PX = 56;+const COMPOSER_PORTAL_SELECTOR = [...COMPOSER_SUGGESTION_POPUP_LABELS.map((label) => `[data-suggestion-popup="${label}"]`),`[${COMPOSER_PORTAL_ATTRIBUTE}]`,].join(',');-function safeCaretCoords(- view: EditorView,- pos: number,-): ReturnType<EditorView['coordsAtPos']> | null {- try {- return view.coordsAtPos(pos);- } catch {- return null;- }-}-export function BottomComposer({docName,surface,@@ -217,7 +202,6 @@ export function BottomComposer({useEffect(() => {if (folderMode || docName == null) return;const root = document.documentElement;- let caretFrame: number | null = null;const followBottom = () => {clampRef.current?.();if (isScrollRestoreSuppressed(docName)) return;@@ -264,24 +248,6 @@ export function BottomComposer({};frame = requestAnimationFrame(step);};- const revealCaret = () => {- if (effectiveSurface !== 'wysiwyg') return;- caretFrame = requestAnimationFrame(() => {- caretFrame = null;- if (isScrollRestoreSuppressed(docName)) return;- const editor = getEditorForDoc(docName);- const box = cardRef.current;- if (!editor || editor.isDestroyed || !box) return;- const view = getEditorView(editor);- if (!view) return;- const caret = safeCaretCoords(view, view.state.selection.head);- if (caret === null) return;- const overlap = caret.bottom - (box.getBoundingClientRect().top - 28);- if (overlap <= 0) return;- const scroller = view.dom.closest(DOCUMENT_SCROLL_HOST_SELECTOR);- if (scroller instanceof HTMLElement) scroller.scrollTop += overlap;- });- };const card = cardRef.current;if (dismissed || !card) {followBottom();@@ -292,33 +258,58 @@ export function BottomComposer({}const apply = () => {followBottom();- root.style.setProperty('--ask-composer-height', `${card.offsetHeight + 56}px`);+ root.style.setProperty(+ '--ask-composer-height',+ `${card.offsetHeight + ASK_COMPOSER_HEIGHT_RESERVE_PX}px`,+ );};apply();- revealCaret();const observer = new ResizeObserver(apply);observer.observe(card);return () => {observer.disconnect();- if (caretFrame !== null) cancelAnimationFrame(caretFrame);- caretFrame = null;followBottom();root.style.removeProperty('--ask-composer-height');};- }, [dismissed, effectiveSurface, docName, folderMode]);+ }, [dismissed, docName, folderMode]);- const dismissedRef = useRef(dismissed);- const onReopenRef = useRef(onReopen);- useEffect(() => {- dismissedRef.current = dismissed;- onReopenRef.current = onReopen;+ const openAndFocus = useEffectEvent(() => {+ if (dismissed) onReopen?.();+ else inputRef.current?.focus();});+ const readPaintedOver = useEffectEvent(() => ({+ docName: activeDocOrNull,+ effectiveSurface,+ }));++ useEffect(() => {+ if (dismissed) return;+ const arrivedOver = readPaintedOver();+ const arrivedOverDoc = arrivedOver.docName;+ if (arrivedOverDoc == null) return;+ const arrivedOverSurface = arrivedOver.effectiveSurface;+ const frame = requestAnimationFrame(() => {+ const paintedOver = readPaintedOver();+ if (+ paintedOver.docName !== arrivedOverDoc ||+ paintedOver.effectiveSurface !== arrivedOverSurface+ ) {+ return;+ }+ if (isScrollRestoreSuppressed(arrivedOverDoc)) return;+ const card = cardRef.current;+ if (!card) return;+ revealCaretAboveComposerCard({+ docName: arrivedOverDoc,+ surface: arrivedOverSurface,+ card,+ });+ });+ return () => cancelAnimationFrame(frame);+ }, [dismissed]);+useEffect(() => {- const openAndFocus = () => {- if (dismissedRef.current) onReopenRef.current?.();- else inputRef.current?.focus();- };return subscribeToOpenAskAiComposer(openAndFocus);}, []);diff --git a/packages/app/src/components/MermaidDocEditor.dom.test.tsx b/packages/app/src/components/MermaidDocEditor.dom.test.tsxindex e908872c9..80a2cb18a 100644--- a/packages/app/src/components/MermaidDocEditor.dom.test.tsx+++ b/packages/app/src/components/MermaidDocEditor.dom.test.tsx@@ -5,6 +5,11 @@ import { afterEach, describe, expect, test, vi } from 'vitest';import { Awareness } from 'y-protocols/awareness';import * as Y from 'yjs';import { FULL_PAGE_CM_HOST_SELECTORS } from '@/editor/document-scrollports';+import {+ getFullPageCmEntryForDoc,+ getMarkdownSourceViewForDoc,+ unregisterFullPageCmView,+} from '@/editor/full-page-cm-views';import { renderLinguiTemplate } from '@/test-utils/lingui-mock';vi.doMock('@lingui/react/macro', () => ({@@ -22,27 +27,106 @@ vi.doMock('@/editor/components/Mermaid', () => ({const { MermaidDocEditor } = await import('./MermaidDocEditor');-afterEach(cleanup);+const DOC_NAME = 'diagram.mmd';++const HOST_SELECTOR = FULL_PAGE_CM_HOST_SELECTORS.mermaidDocEditor;++function mountMermaidDocEditor(isSourceMode: boolean): {+ container: HTMLElement;+ unmount: () => void;+ dispose: () => void;+} {+ const document = new Y.Doc();+ const awareness = new Awareness(document);+ const provider = {+ document,+ awareness,+ on() {},+ off() {},+ } as unknown as HocuspocusProvider;+ const { container, unmount } = render(+ <MermaidDocEditor docName={DOC_NAME} provider={provider} isSourceMode={isSourceMode} />,+ );+ return {+ container,+ unmount,+ dispose: () => {+ awareness.destroy();+ document.destroy();+ },+ };+}++afterEach(() => {+ cleanup();+ const entry = getFullPageCmEntryForDoc(DOC_NAME);+ if (entry) unregisterFullPageCmView(DOC_NAME, entry.view);+});describe('MermaidDocEditor host contract', () => {test('renders the host attribute used by the composer-inset selector', () => {- const document = new Y.Doc();- const awareness = new Awareness(document);- const provider = {- document,- awareness,- on() {},- off() {},- } as unknown as HocuspocusProvider;+ const { container, unmount, dispose } = mountMermaidDocEditor(false);- const { container, unmount } = render(- <MermaidDocEditor docName="diagram.mmd" provider={provider} isSourceMode={false} />,- );+ expect(container.querySelector(HOST_SELECTOR)).not.toBeNull();++ unmount();+ dispose();+ });- expect(container.querySelector(FULL_PAGE_CM_HOST_SELECTORS.mermaidDocEditor)).not.toBeNull();+ test('registers its source pane CodeMirror under the mermaidDocEditor host in source mode', () => {+ const { container, unmount, dispose } = mountMermaidDocEditor(true);++ const entry = getFullPageCmEntryForDoc(DOC_NAME);++ expect(+ entry,+ 'a mermaid doc in source mode that registers nothing is unreachable from the composer caret ' ++ 'reveal, so opening the composer over a mid-document caret buries it',+ ).not.toBeNull();+ expect(entry?.host).toBe('mermaidDocEditor');+ expect(+ entry?.view.scrollDOM,+ 'the registered view must be the CodeMirror the source pane mounted, and its scrollDOM must ' ++ 'be the element the mermaidDocEditor scrollport selector matches',+ ).toBe(container.querySelector(`${HOST_SELECTOR} .cm-scroller`));unmount();- awareness.destroy();- document.destroy();+ dispose();+ });++ test('leaves the markdown source-editor accessor empty in source mode', () => {+ const { unmount, dispose } = mountMermaidDocEditor(true);++ expect(+ getMarkdownSourceViewForDoc(DOC_NAME),+ 'a mermaid source pane holds no markdown, so the markdown outline and landing resolvers must ' ++ 'not find it here',+ ).toBeNull();++ unmount();+ dispose();+ });++ test('registers nothing in diagram mode, where there is no caret to reveal', () => {+ const { unmount, dispose } = mountMermaidDocEditor(false);++ expect(getFullPageCmEntryForDoc(DOC_NAME)).toBeNull();++ unmount();+ dispose();+ });++ test('unregisters its source pane CodeMirror when it unmounts', () => {+ const { unmount, dispose } = mountMermaidDocEditor(true);+ expect(getFullPageCmEntryForDoc(DOC_NAME)).not.toBeNull();++ unmount();++ expect(+ getFullPageCmEntryForDoc(DOC_NAME),+ 'a registration that outlives its view leaves the reveal scrolling a destroyed CodeMirror',+ ).toBeNull();++ dispose();});});diff --git a/packages/app/src/components/MermaidDocEditor.tsx b/packages/app/src/components/MermaidDocEditor.tsxindex 669da2203..17848e13b 100644--- a/packages/app/src/components/MermaidDocEditor.tsx+++ b/packages/app/src/components/MermaidDocEditor.tsx@@ -18,6 +18,7 @@ import type * as Y from 'yjs';import { propEditorHighlight } from '@/editor/components/CodeMirrorPropInput';import { type MermaidSourceBinding, MermaidView } from '@/editor/components/Mermaid';import { okCmTheme } from '@/editor/extensions/cm-theme';+import { registerFullPageCmView, unregisterFullPageCmView } from '@/editor/full-page-cm-views';import { isOverlayLayerOpen } from '@/lib/overlay-layers';import { acquireDocUndoManager } from './doc-undo-manager';@@ -54,10 +55,12 @@ export function replaceYText(ytext: Y.Text, next: string, origin?: unknown): voi}function MermaidSourcePane({+ docName,ytext,provider,undoManager,}: {+ docName: string;ytext: Y.Text;provider: HocuspocusProvider;undoManager: Y.UndoManager;@@ -84,8 +87,12 @@ function MermaidSourcePane({}),parent: el,});- return () => view.destroy();- }, [ytext, provider, resolvedTheme, undoManager]);+ registerFullPageCmView(docName, view, 'mermaidDocEditor');+ return () => {+ unregisterFullPageCmView(docName, view);+ view.destroy();+ };+ }, [docName, ytext, provider, resolvedTheme, undoManager]);return <div ref={containerRef} className="h-full min-h-0 overflow-auto" />;}@@ -166,6 +173,7 @@ export function acquireMermaidUndoManager(}export function MermaidDocEditor({+ docName,provider,isSourceMode,}: {@@ -219,7 +227,12 @@ export function MermaidDocEditor({><div className="min-h-0 flex-1 overflow-hidden">{isSourceMode ? (- <MermaidSourcePane ytext={ytext} provider={provider} undoManager={undoManager} />+ <MermaidSourcePane+ docName={docName}+ ytext={ytext}+ provider={provider}+ undoManager={undoManager}+ />) : (<div className="flex h-full min-h-0 flex-col p-3"><MermaidView chart={source} editBinding={editBinding} className="min-h-0 flex-1" />diff --git a/packages/app/src/components/TextDocEditor.dom.test.tsx b/packages/app/src/components/TextDocEditor.dom.test.tsxnew file mode 100644index 000000000..0fd3fdd21--- /dev/null+++ b/packages/app/src/components/TextDocEditor.dom.test.tsx@@ -0,0 +1,117 @@+import type { HocuspocusProvider } from '@hocuspocus/provider';+import * as actualLinguiMacro from '@lingui/react/macro';+import { cleanup, render } from '@testing-library/react';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { Awareness } from 'y-protocols/awareness';+import * as Y from 'yjs';+import { FULL_PAGE_CM_HOST_SELECTORS } from '@/editor/document-scrollports';+import {+ getFullPageCmEntryForDoc,+ getMarkdownSourceViewForDoc,+ unregisterFullPageCmView,+} from '@/editor/full-page-cm-views';+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';++vi.doMock('@lingui/react/macro', () => ({+ ...actualLinguiMacro,+ useLingui: () => ({ t: renderLinguiTemplate }),+}));++vi.doMock('next-themes', () => ({+ useTheme: () => ({ resolvedTheme: 'light' }),+}));++const { TextDocEditor } = await import('./TextDocEditor');++const DOC_NAME = 'notes/scratch.txt';++const HOST_SELECTOR = FULL_PAGE_CM_HOST_SELECTORS.textDocEditor;++function mountTextDocEditor(): {+ container: HTMLElement;+ unmount: () => void;+ dispose: () => void;+} {+ const document = new Y.Doc();+ const awareness = new Awareness(document);+ const provider = {+ document,+ awareness,+ on() {},+ off() {},+ } as unknown as HocuspocusProvider;+ const { container, unmount } = render(<TextDocEditor docName={DOC_NAME} provider={provider} />);+ return {+ container,+ unmount,+ dispose: () => {+ awareness.destroy();+ document.destroy();+ },+ };+}++afterEach(() => {+ cleanup();+ const entry = getFullPageCmEntryForDoc(DOC_NAME);+ if (entry) unregisterFullPageCmView(DOC_NAME, entry.view);+});++describe('TextDocEditor host contract', () => {+ test('renders the host attribute used by the composer-inset selector', () => {+ const { container, unmount, dispose } = mountTextDocEditor();++ expect(container.querySelector(HOST_SELECTOR)).not.toBeNull();++ unmount();+ dispose();+ });++ test('registers its CodeMirror under the textDocEditor host while it is mounted', () => {+ const { container, unmount, dispose } = mountTextDocEditor();++ const entry = getFullPageCmEntryForDoc(DOC_NAME);++ expect(+ entry,+ 'an editable text doc that registers nothing is unreachable from the composer caret reveal, ' ++ 'so opening the composer over a mid-document caret buries it',+ ).not.toBeNull();+ expect(entry?.host).toBe('textDocEditor');+ expect(+ entry?.view.scrollDOM,+ 'the registered view must be the CodeMirror this component mounted, and its scrollDOM must ' ++ 'be the element the textDocEditor scrollport selector matches',+ ).toBe(container.querySelector(`${HOST_SELECTOR} .cm-scroller`));++ unmount();+ dispose();+ });++ test('leaves the markdown source-editor accessor empty', () => {+ const { unmount, dispose } = mountTextDocEditor();++ expect(+ getMarkdownSourceViewForDoc(DOC_NAME),+ 'a text doc CodeMirror holds no markdown, so the markdown outline and landing resolvers must ' ++ 'not find it here',+ ).toBeNull();++ unmount();+ dispose();+ });++ test('unregisters its CodeMirror when it unmounts', () => {+ const { unmount, dispose } = mountTextDocEditor();+ expect(getFullPageCmEntryForDoc(DOC_NAME)).not.toBeNull();++ unmount();++ expect(+ getFullPageCmEntryForDoc(DOC_NAME),+ 'a registration that outlives its view leaves the reveal scrolling a destroyed CodeMirror',+ ).toBeNull();++ dispose();+ });+});diff --git a/packages/app/src/components/TextDocEditor.tsx b/packages/app/src/components/TextDocEditor.tsxindex ef30f1a75..f13913137 100644--- a/packages/app/src/components/TextDocEditor.tsx+++ b/packages/app/src/components/TextDocEditor.tsx@@ -19,6 +19,7 @@ import { useEffect, useRef } from 'react';import { yCollab } from 'y-codemirror.next';import { propEditorHighlight } from '@/editor/components/CodeMirrorPropInput';import { okCmTheme } from '@/editor/extensions/cm-theme';+import { registerFullPageCmView, unregisterFullPageCmView } from '@/editor/full-page-cm-views';import { acquireDocUndoManager } from './doc-undo-manager';import { loadCodeMirrorLanguageForExtension } from './text-viewer-languages';@@ -71,6 +72,7 @@ export function TextDocEditor({}),parent: el,});+ registerFullPageCmView(docName, view, 'textDocEditor');let disposed = false;const extension = extensionOf(docName) || null;if (extension) {@@ -84,6 +86,7 @@ export function TextDocEditor({}return () => {disposed = true;+ unregisterFullPageCmView(docName, view);view.destroy();};}, [ytext, provider, resolvedTheme, docName, undoManager]);diff --git a/packages/app/src/editor/SourceEditor.dom.test.tsx b/packages/app/src/editor/SourceEditor.dom.test.tsxindex d64c59005..1f55115f4 100644--- a/packages/app/src/editor/SourceEditor.dom.test.tsx+++ b/packages/app/src/editor/SourceEditor.dom.test.tsx@@ -15,6 +15,7 @@ import {} from '@/components/OutlinePanel';import { LINT_NAV_EVENT, type LintNavDetail } from '@/components/ProblemsPanel';import { FULL_PAGE_CM_HOST_SELECTORS } from '@/editor/document-scrollports';+import { getFullPageCmEntryForDoc } from '@/editor/full-page-cm-views';import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';import { evictCmEditor } from './editor-cache';import type { LandingHandle } from './landing-controller';@@ -151,6 +152,28 @@ describe('SourceEditor host contract', () => {expect(container.querySelector(FULL_PAGE_CM_HOST_SELECTORS.sourceEditor)).not.toBeNull();});++ test('registers its CodeMirror under the sourceEditor host while it is mounted', async () => {+ const docName = 'source-full-page-cm-host';+ const { provider, ytext } = makeProvider(docName);+ const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);++ await findCmContent(container);+ const entry = getFullPageCmEntryForDoc(docName);++ expect(+ entry?.host,+ 'the host this component records is what picks its scrollport, and `sourceEditor` is the ' ++ 'only one that resolves through an ANCESTOR. Recording any other host sends the caret ' ++ 'reveal at this surface own `.cm-scroller`, which never scrolls, and drops markdown out ' ++ 'of `getMarkdownSourceViewForDoc` so the outline and the mode-switch landing anchor go ' ++ 'with it',+ ).toBe('sourceEditor');+ expect(+ entry?.view.scrollDOM,+ 'the registered view must be the CodeMirror this component mounted',+ ).toBe(container.querySelector(`${FULL_PAGE_CM_HOST_SELECTORS.sourceEditor} .cm-scroller`));+ });});describe('SourceEditor word-wrap preference wiring', () => {diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsxindex 4bd29fd2e..0e8efa211 100644--- a/packages/app/src/editor/SourceEditor.tsx+++ b/packages/app/src/editor/SourceEditor.tsx@@ -28,9 +28,9 @@ import { useConfigContext } from '@/lib/config-provider';import { emitDiagnosticBreadcrumb } from '@/lib/diagnostic-breadcrumb';import { editorToolbarOverlapPx } from '@/lib/editor-toolbar-overlap';import { claimNoteWindowInitialFocus } from '@/lib/note-window-focus';-import { registerSourceView, unregisterSourceView } from './active-source-view';import { createSourceClipboardExtension } from './clipboard/index.ts';import { type CmCacheEntry, mountCmEditor, parkCmEditor } from './editor-cache';+import { registerFullPageCmView, unregisterFullPageCmView } from './full-page-cm-views';import { useDocLintConfig } from './lint-config-client';import { startSourceLanding } from './mode-switch-landing';import { getMountId } from './mount-id-registry';@@ -79,7 +79,7 @@ function cleanupSourceEditorEntry(docName: string, entry: CmCacheEntry): void {try {parkCmEditor(entry);} finally {- unregisterSourceView(docName, entry.view);+ unregisterFullPageCmView(docName, entry.view);}}}@@ -291,7 +291,7 @@ export function SourceEditor({cmEntryRef.current = entry;viewRef.current = entry.view;setSourceViewUndoFlipActive(entry.view, isSourceModeActive);- registerSourceView(docName, entry.view);+ registerFullPageCmView(docName, entry.view, 'sourceEditor');if (claimNoteWindowInitialFocus()) entry.view.focus();} catch (err) {console.error('[SourceEditor] mountCmEditor failed', err);diff --git a/packages/app/src/editor/active-source-view.test.ts b/packages/app/src/editor/active-source-view.test.tsdeleted file mode 100644index 78e6a2976..000000000--- a/packages/app/src/editor/active-source-view.test.ts+++ /dev/null@@ -1,131 +0,0 @@-import type { EditorView } from '@codemirror/view';-import { afterEach, describe, expect, test } from 'vitest';-import {- getSourceViewForDoc,- registerSourceView,- subscribeSourceViewRegistry,- unregisterSourceView,-} from './active-source-view';--const fakeView = (id: string): EditorView => ({ __id: id }) as unknown as EditorView;--const TOUCHED_DOCS = ['doc-a', 'doc-b', 'doc-remounted'];--describe('active-source-view registry', () => {- afterEach(() => {- for (const docName of TOUCHED_DOCS) {- const current = getSourceViewForDoc(docName);- if (current) unregisterSourceView(docName, current);- }- });-- test('hands back the view registered for a docName', () => {- const view = fakeView('a');-- registerSourceView('doc-a', view);-- expect(getSourceViewForDoc('doc-a')).toBe(view);- });-- test('reports null for a docName with no mounted view', () => {- expect(getSourceViewForDoc('doc-a')).toBeNull();- });-- test('unregisters the matching view', () => {- const view = fakeView('a');- registerSourceView('doc-a', view);-- unregisterSourceView('doc-a', view);-- expect(getSourceViewForDoc('doc-a')).toBeNull();- });-- test('a stale unregister does not evict the live successor', () => {- const previous = fakeView('previous');- const current = fakeView('current');- registerSourceView('doc-remounted', previous);- registerSourceView('doc-remounted', current);-- unregisterSourceView('doc-remounted', previous);-- expect(getSourceViewForDoc('doc-remounted')).toBe(current);- });-- test('the most recent registration wins for one docName', () => {- const first = fakeView('first');- const second = fakeView('second');-- registerSourceView('doc-a', first);- registerSourceView('doc-a', second);-- expect(getSourceViewForDoc('doc-a')).toBe(second);- });-- test('keeps document names isolated', () => {- const viewA = fakeView('a');- const viewB = fakeView('b');- registerSourceView('doc-a', viewA);- registerSourceView('doc-b', viewB);-- unregisterSourceView('doc-a', viewA);-- expect(getSourceViewForDoc('doc-a')).toBeNull();- expect(getSourceViewForDoc('doc-b')).toBe(viewB);- });-- test('notifies subscribers when a view mounts and when it unmounts', () => {- const view = fakeView('a');- let notifications = 0;- const unsubscribe = subscribeSourceViewRegistry(() => {- notifications++;- });-- registerSourceView('doc-a', view);- expect(notifications).toBe(1);-- unregisterSourceView('doc-a', view);- expect(notifications).toBe(2);-- unsubscribe();- });-- test('stops notifying after unsubscribe', () => {- let notifications = 0;- const unsubscribe = subscribeSourceViewRegistry(() => {- notifications++;- });-- unsubscribe();- registerSourceView('doc-a', fakeView('a'));-- expect(notifications).toBe(0);- });-- test('does not notify when a stale unregister changes nothing', () => {- const previous = fakeView('previous');- const current = fakeView('current');- registerSourceView('doc-remounted', previous);- registerSourceView('doc-remounted', current);- let notifications = 0;- const unsubscribe = subscribeSourceViewRegistry(() => {- notifications++;- });-- unregisterSourceView('doc-remounted', previous);-- expect(notifications).toBe(0);- unsubscribe();- });-- test('notifies every subscriber', () => {- const seen: string[] = [];- const unsubscribeFirst = subscribeSourceViewRegistry(() => seen.push('first'));- const unsubscribeSecond = subscribeSourceViewRegistry(() => seen.push('second'));-- registerSourceView('doc-a', fakeView('a'));-- expect(seen).toEqual(['first', 'second']);- unsubscribeFirst();- unsubscribeSecond();- });-});diff --git a/packages/app/src/editor/active-source-view.ts b/packages/app/src/editor/active-source-view.tsdeleted file mode 100644index d16e1eb22..000000000--- a/packages/app/src/editor/active-source-view.ts+++ /dev/null@@ -1,31 +0,0 @@-import type { EditorView } from '@codemirror/view';--const sourceViews = new Map<string, EditorView>();-const listeners = new Set<() => void>();--function notifyListeners(): void {- for (const listener of listeners) listener();-}--export function registerSourceView(docName: string, view: EditorView): void {- sourceViews.set(docName, view);- notifyListeners();-}--export function unregisterSourceView(docName: string, view: EditorView): void {- if (sourceViews.get(docName) === view) {- sourceViews.delete(docName);- notifyListeners();- }-}--export function getSourceViewForDoc(docName: string): EditorView | null {- return sourceViews.get(docName) ?? null;-}--export function subscribeSourceViewRegistry(listener: () => void): () => void {- listeners.add(listener);- return () => {- listeners.delete(listener);- };-}diff --git a/packages/app/src/editor/caret-reveal.dom.test.ts b/packages/app/src/editor/caret-reveal.dom.test.tsnew file mode 100644index 000000000..6476c3ced--- /dev/null+++ b/packages/app/src/editor/caret-reveal.dom.test.ts@@ -0,0 +1,541 @@+import type { EditorView } from '@codemirror/view';+import type { Editor } from '@tiptap/core';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { getCollector } from '../lib/perf/collector';+import type { PerfMark } from '../lib/perf/types';+import { getEditorForDoc, registerEditor, unregisterEditor } from './active-editor';+import {+ __caretRevealTargetFor,+ CARET_REVEAL_GAP_PX,+ revealCaretAboveComposerCard,+} from './caret-reveal';+import {+ DOCUMENT_SCROLL_HOST_CLASS,+ FULL_PAGE_CM_HOST_SELECTORS,+ FULL_PAGE_CM_SCROLLPORTS,+ type FullPageCmHost,+} from './document-scrollports';+import {+ getFullPageCmEntryForDoc,+ registerFullPageCmView,+ unregisterFullPageCmView,+} from './full-page-cm-views';++const FULL_PAGE_CM_HOSTS = Object.keys(FULL_PAGE_CM_HOST_SELECTORS) as FullPageCmHost[];++const DOC_NAME = 'caret-reveal-doc';++const CARET_BOTTOM = 620;+const LINE_HEIGHT = 18;+const RESTING_SCROLL_TOP = 1000;+const SELECTION_HEAD = 41;+const PORT_BOTTOM_BELOW_THE_CARD = 2000;+const COORDS_FAILED_MARK = 'ok/caret-reveal/coords-failed';+const WYSIWYG_COORDS_THROW_MESSAGE = 'no position for the given offset';+const SOURCE_COORDS_THROW_MESSAGE = `Invalid position ${SELECTION_HEAD} in document of length 0`;++function rectAt(bottom: number): { top: number; bottom: number; left: number; right: number } {+ return { top: bottom - LINE_HEIGHT, bottom, left: 0, right: 0 };+}++function stubPortRect(element: HTMLElement, bottom: number): void {+ element.getBoundingClientRect = () => new DOMRect(0, 0, 0, bottom);+}++function stubLaidOut(element: HTMLElement): void {+ element.getClientRects = () => [new DOMRect(0, 0, 0, LINE_HEIGHT)] as unknown as DOMRectList;+}++const CARD_HEIGHT = 120;++function cardAt(top: number): HTMLElement {+ const element = document.createElement('div');+ element.getBoundingClientRect = () => new DOMRect(0, top, 0, CARD_HEIGHT);+ return element;+}++function mountCmHost(+ host: FullPageCmHost,+ portBottom = PORT_BOTTOM_BELOW_THE_CARD,+): { outer: HTMLElement; scroller: HTMLElement } {+ const outer = document.createElement('div');+ outer.className = DOCUMENT_SCROLL_HOST_CLASS;+ const selector = FULL_PAGE_CM_HOST_SELECTORS[host];+ const hostEl = document.createElement('div');+ if (selector.startsWith('[')) hostEl.setAttribute(selector.slice(1, -1), '');+ else hostEl.className = selector.slice(1);+ const scroller = document.createElement('div');+ scroller.className = 'cm-scroller';+ hostEl.append(scroller);+ outer.append(hostEl);+ document.body.append(outer);+ stubPortRect(outer, portBottom);+ stubPortRect(scroller, portBottom);+ return { outer, scroller };+}++function mountWysiwygHost({ laidOut = true } = {}): { outer: HTMLElement; dom: HTMLElement } {+ const outer = document.createElement('div');+ outer.className = DOCUMENT_SCROLL_HOST_CLASS;+ const dom = document.createElement('div');+ dom.className = 'ProseMirror';+ outer.append(dom);+ document.body.append(outer);+ stubPortRect(outer, PORT_BOTTOM_BELOW_THE_CARD);+ if (laidOut) stubLaidOut(dom);+ return { outer, dom };+}++function cmViewStub(+ scroller: HTMLElement,+ caretBottom: number | null | 'throws',+ reads: number[] = [],+): EditorView {+ return {+ scrollDOM: scroller,+ state: { selection: { main: { head: SELECTION_HEAD } } },+ coordsAtPos: (pos: number) => {+ reads.push(pos);+ if (caretBottom === 'throws') throw new RangeError(SOURCE_COORDS_THROW_MESSAGE);+ return caretBottom === null ? null : rectAt(caretBottom);+ },+ } as unknown as EditorView;+}++function tiptapEditorStub(+ dom: HTMLElement,+ caretBottom: number | 'throws',+ reads: number[] = [],+): Editor {+ return {+ isDestroyed: false,+ editorView: {+ dom,+ state: { selection: { head: SELECTION_HEAD } },+ coordsAtPos: (pos: number) => {+ reads.push(pos);+ if (caretBottom === 'throws') throw new RangeError(WYSIWYG_COORDS_THROW_MESSAGE);+ return rectAt(caretBottom);+ },+ },+ } as unknown as Editor;+}++function markNamed(name: string): PerfMark | undefined {+ return getCollector()+ ?.marks.toArray()+ .find((m) => m.name === name);+}++beforeEach(() => {+ getCollector()?.reset();+});++afterEach(() => {+ const entry = getFullPageCmEntryForDoc(DOC_NAME);+ if (entry) unregisterFullPageCmView(DOC_NAME, entry.view);+ const editor = getEditorForDoc(DOC_NAME);+ if (editor) unregisterEditor(DOC_NAME, editor);+ document.body.replaceChildren();+});++describe('__caretRevealTargetFor resolves a caret source and a scrollport for every surface the composer paints over', () => {+ test.each(FULL_PAGE_CM_HOSTS)('source mode on the %s host resolves both halves', (host) => {+ const { scroller } = mountCmHost(host);+ const reads: number[] = [];+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM, reads), host);++ const target = __caretRevealTargetFor(DOC_NAME, 'source');++ expect(+ target,+ `\`${host}\` is a registered full-page CodeMirror host, so the composer caret reveal must ` ++ 'resolve a caret source AND a scrollport for it. A host that resolves nothing is a ' ++ 'surface the card silently buries, which is exactly this bug',+ ).not.toBeNull();+ expect(target?.caretBottom).toBe(CARET_BOTTOM);+ expect(+ reads,+ 'the caret rect must be read at the selection head, not at a fixed or stale position',+ ).toEqual([SELECTION_HEAD]);+ expect(+ target?.scrollport,+ `the scrollport must be the element \`FULL_PAGE_CM_SCROLLPORTS.${host}\` names, resolved ` ++ 'from this host own scrollDOM',+ ).toBe(scroller.closest(FULL_PAGE_CM_SCROLLPORTS[host]));+ });++ test('markdown source mode resolves the outer document scroller, not its own cm-scroller', () => {+ const { outer, scroller } = mountCmHost('sourceEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'sourceEditor');++ const target = __caretRevealTargetFor(DOC_NAME, 'source');++ expect(+ target?.scrollport,+ 'the source editor cm-scroller reserves the composer inset but never scrolls: the outer ' ++ '`.editor-doc-scroll` does. Delegating uniformly to the CodeMirror that owns the caret ' ++ 'picks the wrong element here, which is why this host resolves through an ANCESTOR',+ ).toBe(outer);+ expect(target?.scrollport).not.toBe(scroller);+ });++ test('wysiwyg resolves through the registered TipTap editor and the document scroll host', () => {+ const { outer, dom } = mountWysiwygHost();+ const reads: number[] = [];+ registerEditor(DOC_NAME, tiptapEditorStub(dom, CARET_BOTTOM, reads));++ const target = __caretRevealTargetFor(DOC_NAME, 'wysiwyg');++ expect(target?.caretBottom).toBe(CARET_BOTTOM);+ expect(target?.scrollport).toBe(outer);+ expect(reads).toEqual([SELECTION_HEAD]);+ });++ test('wysiwyg resolves nothing from a CodeMirror registered for the same document', () => {+ const { scroller } = mountCmHost('mermaidDocEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'mermaidDocEditor');++ expect(+ __caretRevealTargetFor(DOC_NAME, 'wysiwyg'),+ 'a mermaid doc in diagram mode reports the wysiwyg surface while its only registered view is ' ++ 'a CodeMirror. There is no caret in diagram mode, so the reveal must resolve nothing rather ' ++ 'than reach across surfaces',+ ).toBeNull();+ });++ test('the frontmatter surface resolves nothing even while a source view is registered', () => {+ const { scroller } = mountCmHost('sourceEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'sourceEditor');++ expect(+ __caretRevealTargetFor(DOC_NAME, 'frontmatter'),+ '`editingSurfaceFor` only ever yields wysiwyg or source, so the composer never reports this ' ++ 'surface. The arm exists so a fourth `EditorSurface` cannot compile without a decision',+ ).toBeNull();+ });++ test('resolves nothing for a destroyed TipTap editor still sitting in the registry', () => {+ const { dom } = mountWysiwygHost();+ registerEditor(DOC_NAME, {+ ...tiptapEditorStub(dom, CARET_BOTTOM),+ isDestroyed: true,+ } as unknown as Editor);++ expect(+ __caretRevealTargetFor(DOC_NAME, 'wysiwyg'),+ 'a recycled editor outlives its registry entry, and reading coordinates off a destroyed ' ++ 'ProseMirror view is what this gate exists to prevent',+ ).toBeNull();+ });++ test('resolves nothing for a registered TipTap editor that paints no layout box', () => {+ const { dom } = mountWysiwygHost({ laidOut: false });+ registerEditor(DOC_NAME, tiptapEditorStub(dom, CARET_BOTTOM));++ expect(+ __caretRevealTargetFor(DOC_NAME, 'wysiwyg'),+ 'a ProseMirror still in the registry and still in the document, but superseded so it lays ' ++ 'out no box, reports caret coordinates against a viewport it no longer occupies. ' ++ 'Scrolling a live scrollport by that overlap moves the surface the user IS looking at to ' ++ 'chase a caret nobody can see',+ ).toBeNull();++ stubLaidOut(dom);++ expect(+ __caretRevealTargetFor(DOC_NAME, 'wysiwyg')?.caretBottom,+ 'the same editor, registry entry and scrollport must resolve once the host paints a box, ' ++ 'or the assertion above would hold for some reason other than the absent layout',+ ).toBe(CARET_BOTTOM);+ });++ test('resolves nothing while the TipTap editor has not mounted its ProseMirror view', () => {+ mountWysiwygHost();+ registerEditor(DOC_NAME, { isDestroyed: false } as unknown as Editor);++ expect(+ __caretRevealTargetFor(DOC_NAME, 'wysiwyg'),+ 'TipTap exposes no `editorView` until ProseMirror mounts, and the reveal runs from a ' ++ 'requestAnimationFrame that can land inside that window',+ ).toBeNull();+ });++ test('resolves nothing for a document with no registered view on either registry', () => {+ mountCmHost('textDocEditor');+ mountWysiwygHost();++ expect(__caretRevealTargetFor(DOC_NAME, 'source')).toBeNull();+ expect(__caretRevealTargetFor(DOC_NAME, 'wysiwyg')).toBeNull();+ });++ test('resolves nothing when the view cannot report caret coordinates', () => {+ const { scroller } = mountCmHost('textDocEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, null), 'textDocEditor');++ expect(__caretRevealTargetFor(DOC_NAME, 'source')).toBeNull();+ });++ test('resolves nothing, and does not throw, when a coordsAtPos read throws', () => {+ const { dom } = mountWysiwygHost();+ registerEditor(DOC_NAME, tiptapEditorStub(dom, 'throws'));++ expect(+ () => __caretRevealTargetFor(DOC_NAME, 'wysiwyg'),+ 'ProseMirror `coordsAtPos` throws rather than returning null for an unmapped position, and ' ++ 'this runs inside a requestAnimationFrame where an escaping throw is unhandled',+ ).not.toThrow();+ expect(__caretRevealTargetFor(DOC_NAME, 'wysiwyg')).toBeNull();+ expect(+ markNamed(COORDS_FAILED_MARK)?.properties,+ 'swallowing the throw is what keeps the frame alive, so this mark is the only trace the ' ++ 'degradation leaves. Without it a caret that has silently stopped revealing reads exactly ' ++ 'like one that never needed revealing, and a trace naming neither the document nor the ' ++ 'arm it failed on cannot separate this ProseMirror read from the three CodeMirror hosts ' ++ 'the same mark also covers',+ ).toEqual({+ docName: DOC_NAME,+ surface: 'wysiwyg',+ message: WYSIWYG_COORDS_THROW_MESSAGE,+ });++ getCollector()?.reset();+ registerEditor(DOC_NAME, tiptapEditorStub(dom, CARET_BOTTOM));++ expect(__caretRevealTargetFor(DOC_NAME, 'wysiwyg')?.caretBottom).toBe(CARET_BOTTOM);+ expect(+ markNamed(COORDS_FAILED_MARK),+ 'a read that resolves must leave the mark absent, or the assertion above would also hold ' ++ 'for a build that marks unconditionally',+ ).toBeUndefined();+ });++ test('resolves nothing, and does not throw, when a source mode coordsAtPos read throws', () => {+ const { scroller } = mountCmHost('textDocEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, 'throws'), 'textDocEditor');++ expect(+ () => __caretRevealTargetFor(DOC_NAME, 'source'),+ 'CodeMirror `coordsAtPos` reaches `state.doc.lineAt(pos)` once the view resolves a ' ++ 'non-empty rect, and `lineAt` throws a RangeError for a position past the document ' ++ 'length rather than returning null. This arm runs from the same requestAnimationFrame ' ++ 'as the wysiwyg one, where an escaping throw is unhandled',+ ).not.toThrow();+ expect(__caretRevealTargetFor(DOC_NAME, 'source')).toBeNull();+ expect(+ markNamed(COORDS_FAILED_MARK)?.properties,+ 'both arms reach this one catch, so the surface the mark records is the only thing that ' ++ 'tells a CodeMirror failure apart from a ProseMirror one. Naming the wrong arm here still ' ++ 'typechecks, and it sends triage to a view type that never ran',+ ).toEqual({+ docName: DOC_NAME,+ surface: 'source',+ message: SOURCE_COORDS_THROW_MESSAGE,+ });+ });++ test('resolves nothing when the host sits outside its scrollport', () => {+ const orphan = document.createElement('div');+ orphan.className = 'cm-scroller';+ document.body.append(orphan);+ registerFullPageCmView(DOC_NAME, cmViewStub(orphan, CARET_BOTTOM), 'textDocEditor');++ expect(__caretRevealTargetFor(DOC_NAME, 'source')).toBeNull();+ });+});++describe('revealCaretAboveComposerCard scrolls exactly the overlap the card creates', () => {+ test('scrolls a buried caret line clear of the card', () => {+ const { scroller } = mountCmHost('textDocEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'textDocEditor');+ scroller.scrollTop = RESTING_SCROLL_TOP;+ const cardTop = CARET_BOTTOM - 10;++ revealCaretAboveComposerCard({+ docName: DOC_NAME,+ surface: 'source',+ card: cardAt(cardTop),+ });++ expect(scroller.scrollTop).toBe(+ RESTING_SCROLL_TOP + (CARET_BOTTOM - (cardTop - CARET_REVEAL_GAP_PX)),+ );+ });++ test('markdown source mode scrolls the outer document scroller and leaves its cm-scroller alone', () => {+ const { outer, scroller } = mountCmHost('sourceEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'sourceEditor');+ outer.scrollTop = RESTING_SCROLL_TOP;+ scroller.scrollTop = RESTING_SCROLL_TOP;+ const cardTop = CARET_BOTTOM - 10;++ revealCaretAboveComposerCard({ docName: DOC_NAME, surface: 'source', card: cardAt(cardTop) });++ expect(outer.scrollTop).toBe(+ RESTING_SCROLL_TOP + (CARET_BOTTOM - (cardTop - CARET_REVEAL_GAP_PX)),+ );+ expect(+ scroller.scrollTop,+ 'scrolling the source editor own cm-scroller moves nothing on screen: the outer ' ++ '`.editor-doc-scroll` is the element that scrolls this surface',+ ).toBe(RESTING_SCROLL_TOP);+ });++ test('leaves the caret alone when it already clears the card by exactly the reveal gap', () => {+ const { scroller } = mountCmHost('textDocEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'textDocEditor');+ scroller.scrollTop = RESTING_SCROLL_TOP;++ revealCaretAboveComposerCard({+ docName: DOC_NAME,+ surface: 'source',+ card: cardAt(CARET_BOTTOM + CARET_REVEAL_GAP_PX),+ });++ expect(scroller.scrollTop).toBe(RESTING_SCROLL_TOP);+ });++ test('scrolls by one pixel when the caret sits one pixel inside the reveal gap', () => {+ const { scroller } = mountCmHost('textDocEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'textDocEditor');+ scroller.scrollTop = RESTING_SCROLL_TOP;++ revealCaretAboveComposerCard({+ docName: DOC_NAME,+ surface: 'source',+ card: cardAt(CARET_BOTTOM + CARET_REVEAL_GAP_PX - 1),+ });++ expect(+ scroller.scrollTop,+ 'CARET_REVEAL_GAP_PX is the clearance the caret line must keep above the card, not a ' ++ 'threshold the overlap has to exceed before anything happens',+ ).toBe(RESTING_SCROLL_TOP + 1);+ });++ test('leaves the caret alone when it already paints well above the card', () => {+ const { scroller } = mountCmHost('textDocEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'textDocEditor');+ scroller.scrollTop = RESTING_SCROLL_TOP;++ revealCaretAboveComposerCard({+ docName: DOC_NAME,+ surface: 'source',+ card: cardAt(CARET_BOTTOM + 400),+ });++ expect(scroller.scrollTop).toBe(RESTING_SCROLL_TOP);+ });++ test('leaves the scrollport untouched once the document has no registered view', () => {+ const { scroller } = mountCmHost('textDocEditor');+ const view = cmViewStub(scroller, CARET_BOTTOM);+ const cardTop = CARET_BOTTOM - 10;+ registerFullPageCmView(DOC_NAME, view, 'textDocEditor');+ scroller.scrollTop = RESTING_SCROLL_TOP;++ revealCaretAboveComposerCard({ docName: DOC_NAME, surface: 'source', card: cardAt(cardTop) });++ expect(+ scroller.scrollTop,+ 'this same scrollport, card and caret must move while a view IS registered, or the no-op ' ++ 'assertion below would hold for the wrong reason',+ ).toBeGreaterThan(RESTING_SCROLL_TOP);++ unregisterFullPageCmView(DOC_NAME, view);+ scroller.scrollTop = RESTING_SCROLL_TOP;++ revealCaretAboveComposerCard({ docName: DOC_NAME, surface: 'source', card: cardAt(cardTop) });++ expect(scroller.scrollTop).toBe(RESTING_SCROLL_TOP);+ });++ test('leaves the scrollport untouched when the view cannot report caret coordinates', () => {+ const { scroller } = mountCmHost('textDocEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, null), 'textDocEditor');+ scroller.scrollTop = RESTING_SCROLL_TOP;++ revealCaretAboveComposerCard({+ docName: DOC_NAME,+ surface: 'source',+ card: cardAt(CARET_BOTTOM - 10),+ });++ expect(scroller.scrollTop).toBe(RESTING_SCROLL_TOP);+ });++ test('clears the scrollport own bottom edge when the host inset lifts it above the card', () => {+ const hostRoutePortBottom = CARET_BOTTOM - 40;+ const { scroller } = mountCmHost('mermaidDocEditor', hostRoutePortBottom);+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'mermaidDocEditor');+ scroller.scrollTop = RESTING_SCROLL_TOP;+ const cardTop = hostRoutePortBottom + 48;++ revealCaretAboveComposerCard({+ docName: DOC_NAME,+ surface: 'source',+ card: cardAt(cardTop),+ });++ expect(+ scroller.scrollTop,+ 'the mermaid host reserves the composer band on its own border box, so its cm-scroller ' ++ 'stops 48px ABOVE the card. Clearing the card top alone parks the caret line in the ' ++ 'clipped strip between the two, where it paints nothing',+ ).toBe(RESTING_SCROLL_TOP + (CARET_BOTTOM - (hostRoutePortBottom - CARET_REVEAL_GAP_PX)));+ });++ test('leaves a scrollport with no layout box untouched', () => {+ const { scroller } = mountCmHost('textDocEditor', 0);+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'textDocEditor');+ scroller.scrollTop = RESTING_SCROLL_TOP;++ revealCaretAboveComposerCard({+ docName: DOC_NAME,+ surface: 'source',+ card: cardAt(CARET_BOTTOM + 400),+ });++ expect(+ scroller.scrollTop,+ 'a scrollport laid out with no height reports a bottom edge at the TOP of the viewport, and ' ++ '`Math.min` picks it as the occlusion line. That inverts the clamp: a caret painting well ' ++ 'clear of the card yields the maximum possible overlap instead of none. Reaching that ' ++ 'state through `display: none` would be harmless, because CSSOM View makes the `scrollTop` ' ++ 'setter a no-op for an element with no associated box. A collapsed but boxed scrollport ' ++ 'has no such protection',+ ).toBe(RESTING_SCROLL_TOP);+ });++ test('leaves the scrollport untouched when the card has no layout box', () => {+ const { scroller } = mountCmHost('textDocEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'textDocEditor');+ scroller.scrollTop = RESTING_SCROLL_TOP;+ const boxless = document.createElement('div');+ boxless.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);++ revealCaretAboveComposerCard({ docName: DOC_NAME, surface: 'source', card: boxless });++ expect(+ scroller.scrollTop,+ 'a card with no layout box reports a top of 0, which `Math.min` then takes as the occlusion ' ++ 'line for ANY scrollport. The overlap is positive for every caret below -CARET_REVEAL_GAP_PX ' ++ 'and no later exit can catch it, so this is the same inversion as the scrollport case and ' ++ 'is answered by the same rule',+ ).toBe(RESTING_SCROLL_TOP);+ });++ test('leaves the frontmatter surface untouched', () => {+ const { outer, scroller } = mountCmHost('sourceEditor');+ registerFullPageCmView(DOC_NAME, cmViewStub(scroller, CARET_BOTTOM), 'sourceEditor');+ outer.scrollTop = RESTING_SCROLL_TOP;++ revealCaretAboveComposerCard({+ docName: DOC_NAME,+ surface: 'frontmatter',+ card: cardAt(CARET_BOTTOM - 10),+ });++ expect(outer.scrollTop).toBe(RESTING_SCROLL_TOP);+ });+});diff --git a/packages/app/src/editor/caret-reveal.ts b/packages/app/src/editor/caret-reveal.tsnew file mode 100644index 000000000..e17db990d--- /dev/null+++ b/packages/app/src/editor/caret-reveal.ts@@ -0,0 +1,112 @@+import { mark } from '@/lib/perf';+import { getVisibleEditorForDoc } from './active-editor';+import { DOCUMENT_SCROLL_HOST_SELECTOR, FULL_PAGE_CM_SCROLLPORTS } from './document-scrollports';+import { getFullPageCmEntryForDoc } from './full-page-cm-views';+import type { EditorSurface } from './selection-stats';+import { getEditorView } from './utils/get-editor-view';++export const CARET_REVEAL_GAP_PX = 28;++export interface CaretRevealTarget {+ caretBottom: number;+ scrollport: HTMLElement;+}++interface CaretCoordsSource {+ coordsAtPos(pos: number): { bottom: number } | null;+}++function safeCaretCoords(+ docName: string,+ surface: EditorSurface,+ view: CaretCoordsSource,+ pos: number,+): { bottom: number } | null {+ try {+ return view.coordsAtPos(pos);+ } catch (err) {+ mark('ok/caret-reveal/coords-failed', {+ docName,+ surface,+ message: err instanceof Error ? err.message : String(err),+ });+ return null;+ }+}++function scrollportFor(from: Element, selector: string): HTMLElement | null {+ const scrollport = from.closest(selector);+ return scrollport instanceof HTMLElement ? scrollport : null;+}++function targetFrom(+ docName: string,+ surface: EditorSurface,+ view: CaretCoordsSource,+ pos: number,+ from: Element,+ selector: string,+): CaretRevealTarget | null {+ const caret = safeCaretCoords(docName, surface, view, pos);+ if (caret === null) return null;+ const scrollport = scrollportFor(from, selector);+ return scrollport === null ? null : { caretBottom: caret.bottom, scrollport };+}++export function __caretRevealTargetFor(+ docName: string,+ surface: EditorSurface,+): CaretRevealTarget | null {+ switch (surface) {+ case 'wysiwyg': {+ const editor = getVisibleEditorForDoc(docName);+ if (!editor) return null;+ const view = getEditorView(editor);+ if (!view) return null;+ return targetFrom(+ docName,+ surface,+ view,+ view.state.selection.head,+ view.dom,+ DOCUMENT_SCROLL_HOST_SELECTOR,+ );+ }+ case 'source': {+ const entry = getFullPageCmEntryForDoc(docName);+ if (!entry) return null;+ const { view, host } = entry;+ return targetFrom(+ docName,+ surface,+ view,+ view.state.selection.main.head,+ view.scrollDOM,+ FULL_PAGE_CM_SCROLLPORTS[host],+ );+ }+ case 'frontmatter':+ return null;+ }+}++export function revealCaretAboveComposerCard({+ docName,+ surface,+ card,+}: {+ docName: string;+ surface: EditorSurface;+ card: HTMLElement;+}): void {+ const cardBox = card.getBoundingClientRect();+ if (cardBox.height === 0) return;+ const target = __caretRevealTargetFor(docName, surface);+ if (target === null) return;+ const port = target.scrollport.getBoundingClientRect();+ if (port.height === 0) return;+ const occlusionTop = Math.min(cardBox.top, port.bottom);+ const overlap = target.caretBottom - (occlusionTop - CARET_REVEAL_GAP_PX);+ if (overlap <= 0) return;+ target.scrollport.scrollTop += overlap;+}diff --git a/packages/app/src/editor/document-scrollports.dom.test.ts b/packages/app/src/editor/document-scrollports.dom.test.tsindex 6e9516322..ae3d03866 100644--- a/packages/app/src/editor/document-scrollports.dom.test.ts+++ b/packages/app/src/editor/document-scrollports.dom.test.ts@@ -1,15 +1,20 @@import { afterEach, describe, expect, test } from 'vitest';import {+ DOCUMENT_SCROLLPORT_SELECTORS,documentScrollports,FULL_PAGE_CM_HOST_SELECTORS,+ FULL_PAGE_CM_SCROLLPORTS,+ type FullPageCmHost,isPinnedToEnd,SCROLL_PIN_SLACK_PX,} from './document-scrollports';+const FULL_PAGE_CM_HOSTS = Object.keys(FULL_PAGE_CM_HOST_SELECTORS) as FullPageCmHost[];+function buildEditorTree(): {outer: HTMLElement;conflictScroller: HTMLElement;- hostScrollers: Record<keyof typeof FULL_PAGE_CM_HOST_SELECTORS, HTMLElement>;+ hostScrollers: Record<FullPageCmHost, HTMLElement>;codeBlockScroller: HTMLElement;} {const container = document.createElement('div');@@ -128,3 +133,67 @@ describe('isPinnedToEnd decides which scrollports the composer may re-clamp', ()expect(isPinnedToEnd(withGeometry(scrollHeight, clientHeight, scrollTop))).toBe(expected);});});++describe('FULL_PAGE_CM_SCROLLPORTS names the element each full-page CodeMirror host actually scrolls', () => {+ test('every registered full-page CodeMirror host has a scrollport entry', () => {+ expect(+ Object.keys(FULL_PAGE_CM_SCROLLPORTS).sort(),+ 'a host registered in FULL_PAGE_CM_HOST_SELECTORS with no scrollport entry is a surface the ' ++ 'composer can paint over and never scroll, which is the whole shape of this bug',+ ).toEqual([...FULL_PAGE_CM_HOSTS].sort());+ });++ test('every scrollport entry is one of the selectors documentScrollports already queries', () => {+ expect(+ DOCUMENT_SCROLLPORT_SELECTORS,+ 'the caret reveal must scroll an element that also reserves the composer inset. A scrollport ' ++ 'outside this list reserves no inset, so scrolling it puts the caret line under the card again',+ ).toEqual(expect.arrayContaining(Object.values(FULL_PAGE_CM_SCROLLPORTS)));+ });++ test.each(FULL_PAGE_CM_HOSTS)(+ 'the %s scrollport resolves from that host cm-scroller onto an enumerated scrollport',+ (host) => {+ const { hostScrollers } = buildEditorTree();++ const resolved = hostScrollers[host].closest(FULL_PAGE_CM_SCROLLPORTS[host]);++ expect(+ resolved,+ `\`FULL_PAGE_CM_SCROLLPORTS.${host}\` must resolve from this host own \`scrollDOM\` via ` ++ '`closest`. Resolving to nothing leaves the reveal with no element to scroll',+ ).not.toBeNull();+ expect(documentScrollports()).toContain(resolved);+ },+ );++ test('markdown source mode falls through its own non-scrolling cm-scroller to the outer document scroller', () => {+ const { outer, hostScrollers } = buildEditorTree();++ const resolved = hostScrollers.sourceEditor.closest(FULL_PAGE_CM_SCROLLPORTS.sourceEditor);++ expect(+ resolved,+ 'the source editor `.cm-scroller` reserves the composer inset on its `.cm-content` but never ' ++ 'scrolls: the outer `.editor-doc-scroll` does. This host is why the table names a ' ++ 'scrollport per host instead of assuming every full-page CodeMirror scrolls itself',+ ).toBe(outer);+ expect(resolved).not.toBe(hostScrollers.sourceEditor);+ });++ test.each(['textDocEditor', 'mermaidDocEditor'] as const)(+ 'the %s host resolves to its own cm-scroller, not to the outer document scroller',+ (host) => {+ const { outer, hostScrollers } = buildEditorTree();++ const resolved = hostScrollers[host].closest(FULL_PAGE_CM_SCROLLPORTS[host]);++ expect(resolved).toBe(hostScrollers[host]);+ expect(+ resolved,+ `\`${host}\` scrolls itself. Resolving it to the outer document scroller would scroll an ` ++ 'element that is not moving under the caret',+ ).not.toBe(outer);+ },+ );+});diff --git a/packages/app/src/editor/document-scrollports.ts b/packages/app/src/editor/document-scrollports.tsindex ba083d1b5..33ac3d9da 100644--- a/packages/app/src/editor/document-scrollports.ts+++ b/packages/app/src/editor/document-scrollports.ts@@ -4,6 +4,8 @@ export const FULL_PAGE_CM_HOST_SELECTORS = {textDocEditor: '[data-text-doc-editor]',} as const;+export type FullPageCmHost = keyof typeof FULL_PAGE_CM_HOST_SELECTORS;+export const SCROLL_PIN_SLACK_PX = 40;export const DOCUMENT_SCROLL_HOST_CLASS = 'editor-doc-scroll';@@ -19,6 +21,23 @@ export const DOCUMENT_SCROLLPORT_SELECTORS = [`${FULL_PAGE_CM_HOST_SELECTORS.textDocEditor} .cm-scroller`,] as const;+export type DocumentScrollportSelector = (typeof DOCUMENT_SCROLLPORT_SELECTORS)[number];++type ScrollportForHost = {+ [H in FullPageCmHost]: H extends 'sourceEditor'+ ? typeof DOCUMENT_SCROLL_HOST_SELECTOR+ : Extract<+ DocumentScrollportSelector,+ `${(typeof FULL_PAGE_CM_HOST_SELECTORS)[H]} .cm-scroller`+ >;+};++export const FULL_PAGE_CM_SCROLLPORTS = {+ mermaidDocEditor: `${FULL_PAGE_CM_HOST_SELECTORS.mermaidDocEditor} .cm-scroller`,+ sourceEditor: DOCUMENT_SCROLL_HOST_SELECTOR,+ textDocEditor: `${FULL_PAGE_CM_HOST_SELECTORS.textDocEditor} .cm-scroller`,+} as const satisfies ScrollportForHost;+const DOCUMENT_SCROLLPORT_SELECTOR = DOCUMENT_SCROLLPORT_SELECTORS.join(', ');export function documentScrollports(): readonly HTMLElement[] {diff --git a/packages/app/src/editor/editor-cache.test.ts b/packages/app/src/editor/editor-cache.test.tsindex b089588a4..b10a67471 100644--- a/packages/app/src/editor/editor-cache.test.ts+++ b/packages/app/src/editor/editor-cache.test.ts@@ -5,7 +5,6 @@ import type { Editor } from '@tiptap/core';import { yUndoPluginKey } from '@tiptap/y-tiptap';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import * as Y from 'yjs';-import { getSourceViewForDoc, registerSourceView } from './active-source-view';import {__consumeRenameSnapshot,__getActivityMountList,@@ -36,6 +35,7 @@ import {type TiptapCacheEntry,VIEW_COUNT_CACHE_THRESHOLD,} from './editor-cache';+import { getMarkdownSourceViewForDoc, registerFullPageCmView } from './full-page-cm-views';import {__mountPromiseCacheSize,__mountPromiseSettled,@@ -1139,12 +1139,12 @@ describe('CM6 cache — lifecycle', () => {container: h.container as unknown as HTMLElement,factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,});- registerSourceView(h.docName, entry.view);- expect(getSourceViewForDoc(h.docName)).toBe(entry.view);+ registerFullPageCmView(h.docName, entry.view, 'sourceEditor');+ expect(getMarkdownSourceViewForDoc(h.docName)).toBe(entry.view);expect(evictCmEditor(h.docName)).toBe(true);- expect(getSourceViewForDoc(h.docName)).toBeNull();+ expect(getMarkdownSourceViewForDoc(h.docName)).toBeNull();});test('5 park-mount cycles work for CM6', () => {diff --git a/packages/app/src/editor/editor-cache.ts b/packages/app/src/editor/editor-cache.tsindex 611c2f783..e345bd386 100644--- a/packages/app/src/editor/editor-cache.ts+++ b/packages/app/src/editor/editor-cache.ts@@ -22,7 +22,7 @@ import { yUndoPluginKey } from '@tiptap/y-tiptap';import type * as Y from 'yjs';import { mark } from '@/lib/perf';import { readNumericOverride } from '@/lib/perf/env-override';-import { unregisterSourceView } from './active-source-view';+import { unregisterFullPageCmView } from './full-page-cm-views';import { getMountId } from './mount-id-registry';import { invalidateMountPromise } from './mount-promise';import { scrollSuppressionHolder } from './scroll-restore-coordination';@@ -657,7 +657,7 @@ export function evictCmEditor(docName: string): boolean {const entry = cmCache.get(docName);if (!entry) return false;- unregisterSourceView(docName, entry.view);+ unregisterFullPageCmView(docName, entry.view);try {entry.view.destroy();diff --git a/packages/app/src/editor/full-page-cm-views.test.ts b/packages/app/src/editor/full-page-cm-views.test.tsnew file mode 100644index 000000000..adee33e94--- /dev/null+++ b/packages/app/src/editor/full-page-cm-views.test.ts@@ -0,0 +1,221 @@+import type { EditorView } from '@codemirror/view';+import { afterEach, describe, expect, test } from 'vitest';+import { FULL_PAGE_CM_HOST_SELECTORS, type FullPageCmHost } from './document-scrollports';+import {+ getFullPageCmEntryForDoc,+ getMarkdownSourceViewForDoc,+ registerFullPageCmView,+ subscribeFullPageCmViewRegistry,+ unregisterFullPageCmView,+} from './full-page-cm-views';++const fakeView = (id: string): EditorView => ({ __id: id }) as unknown as EditorView;++const FULL_PAGE_CM_HOSTS = Object.keys(FULL_PAGE_CM_HOST_SELECTORS) as FullPageCmHost[];++const HOST_DOC = 'doc-host-discrimination';++const TOUCHED_DOCS = ['doc-a', 'doc-b', 'doc-remounted'];++describe('full-page-cm-views registry', () => {+ afterEach(() => {+ for (const docName of TOUCHED_DOCS) {+ const entry = getFullPageCmEntryForDoc(docName);+ if (entry) unregisterFullPageCmView(docName, entry.view);+ }+ });++ test('hands back the view registered for a docName', () => {+ const view = fakeView('a');++ registerFullPageCmView('doc-a', view, 'sourceEditor');++ expect(getMarkdownSourceViewForDoc('doc-a')).toBe(view);+ });++ test('reports null for a docName with no mounted view', () => {+ expect(getMarkdownSourceViewForDoc('doc-a')).toBeNull();+ });++ test('unregisters the matching view', () => {+ const view = fakeView('a');+ registerFullPageCmView('doc-a', view, 'sourceEditor');++ unregisterFullPageCmView('doc-a', view);++ expect(getMarkdownSourceViewForDoc('doc-a')).toBeNull();+ });++ test('a stale unregister does not evict the live successor', () => {+ const previous = fakeView('previous');+ const current = fakeView('current');+ registerFullPageCmView('doc-remounted', previous, 'sourceEditor');+ registerFullPageCmView('doc-remounted', current, 'sourceEditor');++ unregisterFullPageCmView('doc-remounted', previous);++ expect(getMarkdownSourceViewForDoc('doc-remounted')).toBe(current);+ });++ test('the most recent registration wins for one docName', () => {+ const first = fakeView('first');+ const second = fakeView('second');++ registerFullPageCmView('doc-a', first, 'sourceEditor');+ registerFullPageCmView('doc-a', second, 'sourceEditor');++ expect(getMarkdownSourceViewForDoc('doc-a')).toBe(second);+ });++ test('keeps document names isolated', () => {+ const viewA = fakeView('a');+ const viewB = fakeView('b');+ registerFullPageCmView('doc-a', viewA, 'sourceEditor');+ registerFullPageCmView('doc-b', viewB, 'sourceEditor');++ unregisterFullPageCmView('doc-a', viewA);++ expect(getMarkdownSourceViewForDoc('doc-a')).toBeNull();+ expect(getMarkdownSourceViewForDoc('doc-b')).toBe(viewB);+ });++ test('notifies subscribers when a view mounts and when it unmounts', () => {+ const view = fakeView('a');+ let notifications = 0;+ const unsubscribe = subscribeFullPageCmViewRegistry(() => {+ notifications++;+ });++ registerFullPageCmView('doc-a', view, 'sourceEditor');+ expect(notifications).toBe(1);++ unregisterFullPageCmView('doc-a', view);+ expect(notifications).toBe(2);++ unsubscribe();+ });++ test('stops notifying after unsubscribe', () => {+ let notifications = 0;+ const unsubscribe = subscribeFullPageCmViewRegistry(() => {+ notifications++;+ });++ unsubscribe();+ registerFullPageCmView('doc-a', fakeView('a'), 'sourceEditor');++ expect(notifications).toBe(0);+ });++ test('does not notify when a stale unregister changes nothing', () => {+ const previous = fakeView('previous');+ const current = fakeView('current');+ registerFullPageCmView('doc-remounted', previous, 'sourceEditor');+ registerFullPageCmView('doc-remounted', current, 'sourceEditor');+ let notifications = 0;+ const unsubscribe = subscribeFullPageCmViewRegistry(() => {+ notifications++;+ });++ unregisterFullPageCmView('doc-remounted', previous);++ expect(notifications).toBe(0);+ unsubscribe();+ });++ test('notifies every subscriber', () => {+ const seen: string[] = [];+ const unsubscribeFirst = subscribeFullPageCmViewRegistry(() => seen.push('first'));+ const unsubscribeSecond = subscribeFullPageCmViewRegistry(() => seen.push('second'));++ registerFullPageCmView('doc-a', fakeView('a'), 'sourceEditor');++ expect(seen).toEqual(['first', 'second']);+ unsubscribeFirst();+ unsubscribeSecond();+ });+});++describe('full-page-cm-views discriminates the host a registered CodeMirror belongs to', () => {+ afterEach(() => {+ const entry = getFullPageCmEntryForDoc(HOST_DOC);+ if (entry) unregisterFullPageCmView(HOST_DOC, entry.view);+ });++ test('reports null for a docName with no mounted view', () => {+ expect(getFullPageCmEntryForDoc(HOST_DOC)).toBeNull();+ });++ test.each(FULL_PAGE_CM_HOSTS)(+ 'hands back a view registered under the %s host together with that host',+ (host) => {+ const view = fakeView(host);++ registerFullPageCmView(HOST_DOC, view, host);++ expect(+ getFullPageCmEntryForDoc(HOST_DOC),+ `the registry must hand \`${host}\` back paired with the view it was given, so the caret ` ++ 'reveal can pick that host scrollport. Which components actually register which host is ' ++ 'a producer contract, pinned one component at a time in the three host-contract tests',+ ).toEqual({ view, host });+ },+ );++ test('the markdown source-editor accessor answers for a source-editor registration', () => {+ const view = fakeView('markdown');++ registerFullPageCmView(HOST_DOC, view, 'sourceEditor');++ expect(getMarkdownSourceViewForDoc(HOST_DOC)).toBe(view);+ });++ test.each(FULL_PAGE_CM_HOSTS.filter((host) => host !== 'sourceEditor'))(+ 'the markdown source-editor accessor stays empty for a %s registration',+ (host) => {+ registerFullPageCmView(HOST_DOC, fakeView(host), host);++ expect(+ getMarkdownSourceViewForDoc(HOST_DOC),+ `\`getMarkdownSourceViewForDoc\` means "the markdown source editor for this doc" to its existing ` ++ `consumers. Widening it to answer for \`${host}\` would hand the markdown outline and ` ++ 'landing resolvers a CodeMirror holding a different language',+ ).toBeNull();+ },+ );++ test('re-registering a document under a different host replaces the recorded host', () => {+ const markdownView = fakeView('markdown');+ const textDocView = fakeView('text-doc');+ registerFullPageCmView(HOST_DOC, markdownView, 'sourceEditor');++ registerFullPageCmView(HOST_DOC, textDocView, 'textDocEditor');++ expect(getFullPageCmEntryForDoc(HOST_DOC)).toEqual({+ view: textDocView,+ host: 'textDocEditor',+ });+ expect(getMarkdownSourceViewForDoc(HOST_DOC)).toBeNull();+ });++ test('unregistering clears both accessors', () => {+ const view = fakeView('markdown');+ registerFullPageCmView(HOST_DOC, view, 'sourceEditor');++ unregisterFullPageCmView(HOST_DOC, view);++ expect(getFullPageCmEntryForDoc(HOST_DOC)).toBeNull();+ expect(getMarkdownSourceViewForDoc(HOST_DOC)).toBeNull();+ });++ test('a stale unregister does not evict the live successor or its host', () => {+ const previous = fakeView('previous');+ const current = fakeView('current');+ registerFullPageCmView(HOST_DOC, previous, 'sourceEditor');+ registerFullPageCmView(HOST_DOC, current, 'textDocEditor');++ unregisterFullPageCmView(HOST_DOC, previous);++ expect(getFullPageCmEntryForDoc(HOST_DOC)).toEqual({ view: current, host: 'textDocEditor' });+ });+});diff --git a/packages/app/src/editor/full-page-cm-views.ts b/packages/app/src/editor/full-page-cm-views.tsnew file mode 100644index 000000000..8e991dabd--- /dev/null+++ b/packages/app/src/editor/full-page-cm-views.ts@@ -0,0 +1,46 @@+import type { EditorView } from '@codemirror/view';+import type { FullPageCmHost } from './document-scrollports';++export interface FullPageCmEntry {+ view: EditorView;+ host: FullPageCmHost;+}++const cmViewsByDoc = new Map<string, FullPageCmEntry>();+const listeners = new Set<() => void>();++function notifyListeners(): void {+ for (const listener of listeners) listener();+}++export function registerFullPageCmView(+ docName: string,+ view: EditorView,+ host: FullPageCmHost,+): void {+ cmViewsByDoc.set(docName, { view, host });+ notifyListeners();+}++export function unregisterFullPageCmView(docName: string, view: EditorView): void {+ if (cmViewsByDoc.get(docName)?.view === view) {+ cmViewsByDoc.delete(docName);+ notifyListeners();+ }+}++export function getMarkdownSourceViewForDoc(docName: string): EditorView | null {+ const entry = cmViewsByDoc.get(docName);+ return entry?.host === 'sourceEditor' ? entry.view : null;+}++export function getFullPageCmEntryForDoc(docName: string): FullPageCmEntry | null {+ return cmViewsByDoc.get(docName) ?? null;+}++export function subscribeFullPageCmViewRegistry(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}diff --git a/packages/app/src/editor/mode-switch-landing.test.ts b/packages/app/src/editor/mode-switch-landing.test.tsindex 079f2b362..6ad78764b 100644--- a/packages/app/src/editor/mode-switch-landing.test.ts+++ b/packages/app/src/editor/mode-switch-landing.test.ts@@ -10,7 +10,7 @@ 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 { registerFullPageCmView, unregisterFullPageCmView } from './full-page-cm-views.ts';import {buildSourceLandingNav,buildWysiwygLandingNav,@@ -413,7 +413,7 @@ describe('captureModeSwitchAnchor', () => {[{ 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);+ registerFullPageCmView('doc-fwd', view, 'sourceEditor');try {captureModeSwitchAnchor({ from: 'source', to: 'wysiwyg', docName: 'doc-fwd', ytext });const nav = peekPendingWysiwygNavigation('doc-fwd');@@ -421,7 +421,7 @@ describe('captureModeSwitchAnchor', () => {expect(nav?.anchor.content).toBe('target para');expect(peekPendingSourceNavigation('doc-fwd')).toBeNull();} finally {- unregisterSourceView('doc-fwd', view);+ unregisterFullPageCmView('doc-fwd', view);container.remove();}});diff --git a/packages/app/src/editor/mode-switch-landing.ts b/packages/app/src/editor/mode-switch-landing.tsindex b82e6ca85..4f28edb4b 100644--- a/packages/app/src/editor/mode-switch-landing.ts+++ b/packages/app/src/editor/mode-switch-landing.ts@@ -6,8 +6,8 @@ import type { EditorView as ProseMirrorView } from '@tiptap/pm/view';import type * as Y from 'yjs';import { editorToolbarOverlapPx } from '@/lib/editor-toolbar-overlap';import { getEditorForDoc } from './active-editor';-import { getSourceViewForDoc } from './active-source-view';import { visibleEditorScrollContainer } from './editor-cache';+import { getMarkdownSourceViewForDoc } from './full-page-cm-views';import { type LandingHandle, startLanding, type TargetMetrics } from './landing-controller';import {createApproxResolver,@@ -231,7 +231,7 @@ function captureWysiwygToSource(docName: string, ytext: Y.Text): void {}function captureSourceToWysiwyg(docName: string, ytext: Y.Text): void {- const view = getSourceViewForDoc(docName);+ const view = getMarkdownSourceViewForDoc(docName);if (!view) return;const container = findScrollContainer();if (!container) return;diff --git a/packages/app/src/globals.composer-inset-cascade.test.ts b/packages/app/src/globals.composer-inset-cascade.test.tsindex abba2e467..9a023a05c 100644--- a/packages/app/src/globals.composer-inset-cascade.test.ts+++ b/packages/app/src/globals.composer-inset-cascade.test.ts@@ -5,7 +5,10 @@ import {CONFLICT_SCROLLPORT_SELECTOR,DOCUMENT_SCROLL_HOST_SELECTOR,DOCUMENT_SCROLLPORT_SELECTORS,+ type DocumentScrollportSelector,FULL_PAGE_CM_HOST_SELECTORS,+ FULL_PAGE_CM_SCROLLPORTS,+ type FullPageCmHost,} from './editor/document-scrollports';import {type CssBlock,@@ -29,16 +32,12 @@ const INSET_VAR_ALLOWED_OUTSIDE_GLOBALS_CSS = [type InsetKind = 'content' | 'host';-type FullPageCmHostKey = keyof typeof FULL_PAGE_CM_HOST_SELECTORS;--type DocumentScrollportSelector = (typeof DOCUMENT_SCROLLPORT_SELECTORS)[number];--interface FullPageCmSurface {+interface FullPageCmInsetSurface {component: string;insetKind: InsetKind;}-const FULL_PAGE_CM_SURFACES: Readonly<Record<FullPageCmHostKey, FullPageCmSurface>> = {+const FULL_PAGE_CM_SURFACES: Readonly<Record<FullPageCmHost, FullPageCmInsetSurface>> = {textDocEditor: { component: 'components/TextDocEditor.tsx', insetKind: 'content' },sourceEditor: { component: 'editor/SourceEditor.tsx', insetKind: 'content' },mermaidDocEditor: { component: 'components/MermaidDocEditor.tsx', insetKind: 'host' },@@ -46,7 +45,7 @@ const FULL_PAGE_CM_SURFACES: Readonly<Record<FullPageCmHostKey, FullPageCmSurfacconst FULL_PAGE_CM_SURFACE_CASES = Object.entries(FULL_PAGE_CM_SURFACES).map(([host, surface]) => ({...surface,- hostSelector: FULL_PAGE_CM_HOST_SELECTORS[host as FullPageCmHostKey],+ hostSelector: FULL_PAGE_CM_HOST_SELECTORS[host as FullPageCmHost],}));interface ComposerInsetRule {@@ -62,15 +61,15 @@ const COMPOSER_INSET_RULES: readonly ComposerInsetRule[] = [},{prelude: `${FULL_PAGE_CM_HOST_SELECTORS.sourceEditor} .cm-content`,- scrollport: DOCUMENT_SCROLL_HOST_SELECTOR,+ scrollport: FULL_PAGE_CM_SCROLLPORTS.sourceEditor,},{prelude: `${FULL_PAGE_CM_HOST_SELECTORS.textDocEditor} .cm-content`,- scrollport: `${FULL_PAGE_CM_HOST_SELECTORS.textDocEditor} .cm-scroller`,+ scrollport: FULL_PAGE_CM_SCROLLPORTS.textDocEditor,},{prelude: FULL_PAGE_CM_HOST_SELECTORS.mermaidDocEditor,- scrollport: `${FULL_PAGE_CM_HOST_SELECTORS.mermaidDocEditor} .cm-scroller`,+ scrollport: FULL_PAGE_CM_SCROLLPORTS.mermaidDocEditor,},{ prelude: CONFLICT_SCROLLPORT_SELECTOR, scrollport: CONFLICT_SCROLLPORT_SELECTOR },{diff --git a/packages/app/src/hooks/useActiveHeading.source-mode.dom.test.tsx b/packages/app/src/hooks/useActiveHeading.source-mode.dom.test.tsxindex 9f290ca85..3130899aa 100644--- a/packages/app/src/hooks/useActiveHeading.source-mode.dom.test.tsx+++ b/packages/app/src/hooks/useActiveHeading.source-mode.dom.test.tsx@@ -3,10 +3,10 @@ import type { EditorView } from '@codemirror/view';import { act, cleanup, renderHook, waitFor } from '@testing-library/react';import { afterEach, describe, expect, test } from 'vitest';import {- getSourceViewForDoc,- registerSourceView,- unregisterSourceView,-} from '../editor/active-source-view';+ getMarkdownSourceViewForDoc,+ registerFullPageCmView,+ unregisterFullPageCmView,+} from '../editor/full-page-cm-views';import { useActiveHeading } from './useActiveHeading';const DOC_NAME = 'source-mode-guard-doc';@@ -56,8 +56,8 @@ function mountHeading(slug: string, top: number): void {afterEach(() => {cleanup();- const registered = getSourceViewForDoc(DOC_NAME);- if (registered) unregisterSourceView(DOC_NAME, registered);+ const registered = getMarkdownSourceViewForDoc(DOC_NAME);+ if (registered) unregisterFullPageCmView(DOC_NAME, registered);document.body.replaceChildren();});@@ -77,7 +77,7 @@ describe('useActiveHeading (source mode)', () => {});test('reports no active heading for a document with no headings', () => {- registerSourceView(DOC_NAME, stubView());+ registerFullPageCmView(DOC_NAME, stubView(), 'sourceEditor');const { result } = renderHook(() =>useActiveHeading([], { isSourceMode: true, docName: DOC_NAME }),@@ -93,7 +93,7 @@ describe('useActiveHeading (source mode)', () => {expect(result.current).toBeUndefined();act(() => {- registerSourceView(DOC_NAME, stubView());+ registerFullPageCmView(DOC_NAME, stubView(), 'sourceEditor');});await waitFor(() => {@@ -102,7 +102,7 @@ describe('useActiveHeading (source mode)', () => {});test('measures a view that was already registered at render time', () => {- registerSourceView(DOC_NAME, stubView());+ registerFullPageCmView(DOC_NAME, stubView(), 'sourceEditor');const { result } = renderHook(() =>useActiveHeading(SLUGS, { isSourceMode: true, docName: DOC_NAME }),@@ -113,14 +113,14 @@ describe('useActiveHeading (source mode)', () => {test('returns to no answer when the view unregisters', async () => {const view = stubView();- registerSourceView(DOC_NAME, view);+ registerFullPageCmView(DOC_NAME, view, 'sourceEditor');const { result } = renderHook(() =>useActiveHeading(SLUGS, { isSourceMode: true, docName: DOC_NAME }),);expect(result.current).toBe('alpha');act(() => {- unregisterSourceView(DOC_NAME, view);+ unregisterFullPageCmView(DOC_NAME, view);});await waitFor(() => {@@ -129,7 +129,11 @@ describe('useActiveHeading (source mode)', () => {});test('selects the last heading scrolled above the viewport when none is in the top half', () => {- registerSourceView(DOC_NAME, geometryStub(-2 * MID_Y, [-2 * MID_Y, -0.1 * MID_Y, 1.5 * MID_Y]));+ registerFullPageCmView(+ DOC_NAME,+ geometryStub(-2 * MID_Y, [-2 * MID_Y, -0.1 * MID_Y, 1.5 * MID_Y]),+ 'sourceEditor',+ );const { result } = renderHook(() =>useActiveHeading(SLUGS, { isSourceMode: true, docName: DOC_NAME }),@@ -139,7 +143,11 @@ describe('useActiveHeading (source mode)', () => {});test('prefers a heading in the viewport top half over one already scrolled past', () => {- registerSourceView(DOC_NAME, geometryStub(-2 * MID_Y, [-2 * MID_Y, -0.1 * MID_Y, 0.5 * MID_Y]));+ registerFullPageCmView(+ DOC_NAME,+ geometryStub(-2 * MID_Y, [-2 * MID_Y, -0.1 * MID_Y, 0.5 * MID_Y]),+ 'sourceEditor',+ );const { result } = renderHook(() =>useActiveHeading(SLUGS, { isSourceMode: true, docName: DOC_NAME }),@@ -149,7 +157,11 @@ describe('useActiveHeading (source mode)', () => {});test('resolves heading elements in WYSIWYG mode even while a source view is registered', () => {- registerSourceView(DOC_NAME, geometryStub(-2 * MID_Y, [-2 * MID_Y, -0.1 * MID_Y, 0.5 * MID_Y]));+ registerFullPageCmView(+ DOC_NAME,+ geometryStub(-2 * MID_Y, [-2 * MID_Y, -0.1 * MID_Y, 0.5 * MID_Y]),+ 'sourceEditor',+ );mountHeading('alpha', MID_Y - 10);mountHeading('beta', MID_Y + 600);mountHeading('gamma', MID_Y + 900);diff --git a/packages/app/src/hooks/useActiveHeading.ts b/packages/app/src/hooks/useActiveHeading.tsindex 9930ef587..b4c86fa58 100644--- a/packages/app/src/hooks/useActiveHeading.ts+++ b/packages/app/src/hooks/useActiveHeading.ts@@ -1,6 +1,9 @@import type { EditorView } from '@codemirror/view';import { useEffect, useRef, useState, useSyncExternalStore } from 'react';-import { getSourceViewForDoc, subscribeSourceViewRegistry } from '@/editor/active-source-view';+import {+ getMarkdownSourceViewForDoc,+ subscribeFullPageCmViewRegistry,+} from '@/editor/full-page-cm-views';import { sourceHeadingLines } from '@/editor/source-heading-lines';function domHeadingTop(slug: string): number | null {@@ -31,8 +34,8 @@ export function useActiveHeading(const rafRef = useRef<number | null>(null);const sourceView = useSyncExternalStore(- subscribeSourceViewRegistry,- () => (docName ? getSourceViewForDoc(docName) : null),+ subscribeFullPageCmViewRegistry,+ () => (docName ? getMarkdownSourceViewForDoc(docName) : null),() => null,);diff --git a/packages/app/src/lib/perf/mark-bundled-tracks.test.ts b/packages/app/src/lib/perf/mark-bundled-tracks.test.tsindex 336428a8f..3c4a48647 100644--- a/packages/app/src/lib/perf/mark-bundled-tracks.test.ts+++ b/packages/app/src/lib/perf/mark-bundled-tracks.test.ts@@ -54,6 +54,18 @@ describe('marks routed into diagnostic bundles', () => {expect(parsed()).toEqual([{ event: 'ok/scroll-restore/phase1-success' }]);});+ test('the caret-reveal coords failure carries the document and the surface into the breadcrumb', () => {+ const { parsed } = captureBreadcrumbs();+ mark('ok/caret-reveal/coords-failed', { docName: 'notes/tall', surface: 'wysiwyg' });+ expect(parsed()).toEqual([+ {+ event: 'ok/caret-reveal/coords-failed',+ docName: 'notes/tall',+ surface: 'wysiwyg',+ },+ ]);+ });+test('an unlisted track writes no breadcrumb', () => {const { spy } = captureBreadcrumbs();mark('ok/nav/hash-change', { docName: 'notes/a' });@@ -72,8 +84,8 @@ describe('marks routed into diagnostic bundles', () => {expect(names).toContain('ok/nav/hash-change');});- test('the allowlist holds exactly the one family that is safe to write per emission', () => {- expect([...BUNDLED_TRACKS]).toEqual(['ok/scroll-restore']);+ test('the allowlist holds exactly the families that are safe to write per emission', () => {+ expect([...BUNDLED_TRACKS]).toEqual(['ok/caret-reveal', 'ok/scroll-restore']);});test('membership is by whole track, so a lookalike prefix does not opt in', () => {diff --git a/packages/app/src/lib/perf/mark.ts b/packages/app/src/lib/perf/mark.tsindex 30710d239..79c38bec5 100644--- a/packages/app/src/lib/perf/mark.ts+++ b/packages/app/src/lib/perf/mark.ts@@ -4,7 +4,10 @@ import type { DevToolsTrackEntry, PerfMarkDetail } from './types';const NAME_RE = /^ok\/[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/;-export const BUNDLED_TRACKS: ReadonlySet<string> = new Set(['ok/scroll-restore']);+export const BUNDLED_TRACKS: ReadonlySet<string> = new Set([+ 'ok/caret-reveal',+ 'ok/scroll-restore',+]);export function validatePerfMarkName(name: string): boolean {return NAME_RE.test(name);diff --git a/packages/app/tests/stress/composer-open-caret-reveal.e2e.ts b/packages/app/tests/stress/composer-open-caret-reveal.e2e.tsnew file mode 100644index 000000000..cc80f59be--- /dev/null+++ b/packages/app/tests/stress/composer-open-caret-reveal.e2e.ts@@ -0,0 +1,622 @@+import { randomUUID } from 'node:crypto';+import { writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { Page } from '@playwright/test';+import { CARET_REVEAL_GAP_PX } from '../../src/editor/caret-reveal';+import {+ FULL_PAGE_CM_HOST_SELECTORS,+ FULL_PAGE_CM_SCROLLPORTS,+ type FullPageCmHost,+ SCROLL_PIN_SLACK_PX,+} from '../../src/editor/document-scrollports';+import { expect, test, toggleMode } from './_helpers';++const COMPOSER_CARD = '[data-testid="bottom-composer"] > div';+const WYSIWYG_SCROLLPORT = '[data-testid="editor-scroll-container"]';+const WYSIWYG_BODY = '.editor-doc-scroll .ProseMirror:not(.composer-prosemirror)';+const WYSIWYG_LINE = `${WYSIWYG_BODY} > *`;+const SOURCE_SCROLLPORT = `${FULL_PAGE_CM_HOST_SELECTORS.sourceEditor} .cm-scroller`;+const SOURCE_LINE = `${FULL_PAGE_CM_HOST_SELECTORS.sourceEditor} .cm-content .cm-line`;+const TEXT_DOC_CONTENT = `${FULL_PAGE_CM_HOST_SELECTORS.textDocEditor} .cm-content`;+const TEXT_DOC_LINE = `${TEXT_DOC_CONTENT} .cm-line`;+const MERMAID_HOST = FULL_PAGE_CM_HOST_SELECTORS.mermaidDocEditor;+const MERMAID_CONTENT = `${MERMAID_HOST} .cm-content`;+const MERMAID_LINE = `${MERMAID_CONTENT} .cm-line`;++const LINE_COUNT = 600;+const CARET_LINE_FRACTION = 0.45;+const NEAR_END_ROOM_PX = 64;++const CASE_TIMEOUT_MS = 180_000;+const FIRST_PAINT_TIMEOUT_MS = 30_000;+const MODE_SWITCH_TIMEOUT_MS = 10_000;+const POLL_TIMEOUT_MS = 20_000;+const SETTLE_INTERVALS_MS = [150, 150, 200, 200, 300, 300, 500] as const;++const settleIntervals = (): number[] => [...SETTLE_INTERVALS_MS];+const UNPAINTED_TOLERANCE_MS = 2_500;++const markdownBody = Array.from(+ { length: LINE_COUNT },+ (_, index) => `Paragraph number ${index}.`,+).join('\n\n');++function textDocBody(): string {+ return `${Array.from(+ { length: LINE_COUNT },+ (_, index) => `export const l${index} = ${index};`,+ ).join('\n')}\n`;+}++function mermaidDocBody(): string {+ return `${['graph TD']+ .concat(Array.from({ length: LINE_COUNT }, (_, index) => ` n${index} --> n${index + 1}`))+ .join('\n')}\n`;+}++interface Surface {+ readonly label: string;+ readonly lineSelector: string;+ readonly scrollportSelector: string;+}++const CM_SURFACES: Record<FullPageCmHost, Surface> = {+ sourceEditor: {+ label: 'markdown source mode',+ lineSelector: SOURCE_LINE,+ scrollportSelector: FULL_PAGE_CM_SCROLLPORTS.sourceEditor,+ },+ textDocEditor: {+ label: 'editable text doc',+ lineSelector: TEXT_DOC_LINE,+ scrollportSelector: FULL_PAGE_CM_SCROLLPORTS.textDocEditor,+ },+ mermaidDocEditor: {+ label: 'mermaid doc source mode',+ lineSelector: MERMAID_LINE,+ scrollportSelector: FULL_PAGE_CM_SCROLLPORTS.mermaidDocEditor,+ },+};++const WYSIWYG_SURFACE: Surface = {+ label: 'markdown WYSIWYG',+ lineSelector: WYSIWYG_LINE,+ scrollportSelector: WYSIWYG_SCROLLPORT,+};++interface LineGeometry {+ readonly text: string;+ readonly top: number;+ readonly bottom: number;+ readonly left: number;+ readonly portBottom: number;+ readonly scrollTop: number;+ readonly scrollMax: number;+}++interface CaseResult {+ readonly label: string;+ readonly scrollportSelector: string;+ readonly caretText: string;+ readonly composerHeight: number;+ readonly cardTop: number;+ readonly before: LineGeometry;+ readonly after: LineGeometry;+}++const occlusionTopOf = (result: CaseResult): number =>+ Math.min(result.cardTop, result.after.portBottom);++const occlusionClearanceOf = (result: CaseResult): number =>+ occlusionTopOf(result) - result.after.bottom;++async function readComposerHeight(page: Page): Promise<number> {+ return page.evaluate(() =>+ Number.parseFloat(+ getComputedStyle(document.documentElement).getPropertyValue('--ask-composer-height') || '0',+ ),+ );+}++async function readCardTop(page: Page): Promise<number> {+ return page.evaluate((selector) => {+ const card = document.querySelector(selector);+ if (!(card instanceof HTMLElement)) throw new Error('the Ask AI composer card is not painted');+ return card.getBoundingClientRect().top;+ }, COMPOSER_CARD);+}++async function waitForComposerPublished(page: Page): Promise<void> {+ await expect(page.locator(COMPOSER_CARD).first()).toBeVisible({ timeout: POLL_TIMEOUT_MS });+ await expect+ .poll(() => readComposerHeight(page), {+ message:+ 'the composer never published --ask-composer-height, so the card reserves no band and ' ++ 'every clearance assertion below would measure a layout nothing was ever painted over',+ timeout: POLL_TIMEOUT_MS,+ })+ .toBeGreaterThan(0);+}++async function forceScrollToFraction(+ page: Page,+ surface: Surface,+ fraction: number,+): Promise<void> {+ let previous = Number.NaN;+ await expect+ .poll(+ async () => {+ const scrollTop = await page.evaluate(+ ([selector, ratio]) => {+ const scrollport = document.querySelector(selector as string);+ if (!(scrollport instanceof HTMLElement)) {+ throw new Error(`no painted scrollport matched ${selector}`);+ }+ const target = Math.round(+ (scrollport.scrollHeight - scrollport.clientHeight) * (ratio as number),+ );+ if (Math.abs(scrollport.scrollTop - target) >= 1) scrollport.scrollTop = target;+ return scrollport.scrollTop;+ },+ [surface.scrollportSelector, fraction] as const,+ );+ const settled = Number.isFinite(previous) && Math.abs(previous - scrollTop) < 1;+ previous = scrollTop;+ return settled;+ },+ {+ message:+ `${surface.label}: ${surface.scrollportSelector} never came to rest mid-document, so ` ++ 'the caret could not be placed away from the scroll end this case is defined to avoid',+ timeout: POLL_TIMEOUT_MS,+ intervals: settleIntervals(),+ },+ )+ .toBe(true);+}++async function findCaretCandidateLine(+ page: Page,+ surface: Surface,+ belowY: number,+): Promise<LineGeometry | null> {+ return page.evaluate(+ ([lineSelector, scrollportSelector, threshold]) => {+ const scrollport = document.querySelector(scrollportSelector as string);+ if (!(scrollport instanceof HTMLElement)) {+ throw new Error(`no painted scrollport matched ${scrollportSelector}`);+ }+ const portBox = scrollport.getBoundingClientRect();+ const painted = [...document.querySelectorAll<HTMLElement>(lineSelector as string)].filter(+ (element) => element.closest('.ok-mode-hidden') === null,+ );+ const textOf = (element: HTMLElement): string => element.textContent ?? '';+ const occurrences = new Map<string, number>();+ for (const element of painted) {+ occurrences.set(textOf(element), (occurrences.get(textOf(element)) ?? 0) + 1);+ }+ const candidate = painted+ .map((element) => ({ element, rect: element.getBoundingClientRect() }))+ .filter((entry) => entry.rect.top >= portBox.top && entry.rect.bottom <= portBox.bottom)+ .filter((entry) => textOf(entry.element).trim().length > 0)+ .filter((entry) => occurrences.get(textOf(entry.element)) === 1)+ .filter((entry) => entry.rect.bottom > (threshold as number))+ .at(-1);+ if (candidate === undefined) return null;+ return {+ text: textOf(candidate.element),+ top: candidate.rect.top,+ bottom: candidate.rect.bottom,+ left: candidate.rect.left,+ portBottom: portBox.bottom,+ scrollTop: scrollport.scrollTop,+ scrollMax: scrollport.scrollHeight - scrollport.clientHeight,+ };+ },+ [surface.lineSelector, surface.scrollportSelector, belowY] as const,+ );+}++async function waitForCaretCandidateLine(+ page: Page,+ surface: Surface,+ belowY: number,+): Promise<LineGeometry> {+ const missing =+ `${surface.label}: no uniquely identifiable painted line matching ${surface.lineSelector} ` ++ `sits below y=${belowY}, so this surface has no line for the reopened card to bury and the ` ++ 'case would pass without the composer ever having occluded anything';+ let candidate: LineGeometry | null = null;+ await expect+ .poll(+ async () => {+ candidate = await findCaretCandidateLine(page, surface, belowY);+ return candidate !== null;+ },+ {+ message:+ `${missing}. CodeMirror paints only its own viewport, so a scrollport that has just ` ++ 'jumped mid-document settles its scrollTop before the lines for the new region exist. ' ++ 'Selecting the candidate on the first look reads that gap as a surface with nothing to ' ++ 'bury, which is why this retries rather than throwing on one frame. The line is ' ++ 'captured in the generator rather than re-read after it, so the geometry the caret ' ++ 'click uses is the one that satisfied the poll',+ timeout: POLL_TIMEOUT_MS,+ intervals: settleIntervals(),+ },+ )+ .toBe(true);+ if (candidate === null) throw new Error(missing);+ return candidate;+}++async function findLineByText(+ page: Page,+ surface: Surface,+ text: string,+): Promise<LineGeometry | null> {+ return page.evaluate(+ ([lineSelector, scrollportSelector, wanted]) => {+ const scrollport = document.querySelector(scrollportSelector);+ if (!(scrollport instanceof HTMLElement)) {+ throw new Error(`no painted scrollport matched ${scrollportSelector}`);+ }+ const match = [...document.querySelectorAll<HTMLElement>(lineSelector)]+ .filter((element) => element.closest('.ok-mode-hidden') === null)+ .find((element) => (element.textContent ?? '') === wanted);+ if (match === undefined) return null;+ const rect = match.getBoundingClientRect();+ return {+ text: wanted,+ top: rect.top,+ bottom: rect.bottom,+ left: rect.left,+ portBottom: scrollport.getBoundingClientRect().bottom,+ scrollTop: scrollport.scrollTop,+ scrollMax: scrollport.scrollHeight - scrollport.clientHeight,+ };+ },+ [surface.lineSelector, surface.scrollportSelector, text] as const,+ );+}++async function readLineByText(+ page: Page,+ surface: Surface,+ text: string,+ phase: string,+): Promise<LineGeometry> {+ const found = await findLineByText(page, surface, text);+ if (found === null) {+ throw new Error(+ `${surface.label}: the caret line "${text}" is no longer painted ${phase}, so the surface ` ++ 'scrolled it far enough out of view that virtualization dropped it',+ );+ }+ return found;+}++async function waitForLineSettled(+ page: Page,+ surface: Surface,+ text: string,+ phase: string,+): Promise<LineGeometry> {+ let previous: LineGeometry | undefined;+ let firstMissAt: number | null = null;+ await expect+ .poll(+ async () => {+ const current = await findLineByText(page, surface, text);+ if (current === null) {+ previous = undefined;+ firstMissAt ??= Date.now();+ if (Date.now() - firstMissAt > UNPAINTED_TOLERANCE_MS) {+ await readLineByText(page, surface, text, phase);+ }+ return false;+ }+ firstMissAt = null;+ const settled =+ previous !== undefined &&+ Math.abs(previous.bottom - current.bottom) < 0.5 &&+ Math.abs(previous.scrollTop - current.scrollTop) < 0.5;+ previous = current;+ return settled;+ },+ {+ message:+ `${surface.label}: the caret line "${text}" never stopped moving ${phase}. A transient ` ++ 'frame where CodeMirror has recycled the line out of its rendered range reads as unsettled ' ++ 'rather than throwing, because `expect.poll` awaits its generator OUTSIDE the try that ' ++ 'decides whether to keep polling, so a throw here would end the test instead of ' ++ `retrying. Once the line has been unpainted for ${UNPAINTED_TOLERANCE_MS}ms the ` ++ 'absence is no longer transient and the strict read rethrows its virtualization ' ++ 'diagnostic, so a line the reveal scrolled out of the rendered range fails with that ' ++ 'message rather than waiting out this timeout with this one. The budget is elapsed ' ++ 'time rather than a poll count so it cannot drift when the interval tuple or the ' ++ "runner's schedule changes. The " ++ 'intervals are handed out per poll because the runner consumes the array it is given, ' ++ 'so a shared one would make that budget depend on how many polls ran before this one',+ timeout: POLL_TIMEOUT_MS,+ intervals: settleIntervals(),+ },+ )+ .toBe(true);+ return readLineByText(page, surface, text, phase);+}++async function forceScrollToRoomFromEnd(page: Page, surface: Surface, room: number): Promise<void> {+ let previous = Number.NaN;+ await expect+ .poll(+ async () => {+ const scrollTop = await page.evaluate(+ ([selector, gap]) => {+ const scrollport = document.querySelector(selector as string);+ if (!(scrollport instanceof HTMLElement)) {+ throw new Error(`no painted scrollport matched ${selector}`);+ }+ const target = Math.round(+ scrollport.scrollHeight - scrollport.clientHeight - (gap as number),+ );+ if (Math.abs(scrollport.scrollTop - target) >= 1) scrollport.scrollTop = target;+ return scrollport.scrollTop;+ },+ [surface.scrollportSelector, room] as const,+ );+ const settled = Number.isFinite(previous) && Math.abs(previous - scrollTop) < 1;+ previous = scrollTop;+ return settled;+ },+ {+ message:+ `${surface.label}: ${surface.scrollportSelector} never came to rest ${room}px from its ` ++ 'scroll end, so the caret could not be placed in the near-end band this case covers',+ timeout: POLL_TIMEOUT_MS,+ intervals: settleIntervals(),+ },+ )+ .toBe(true);+}++async function runNearScrollEndCase(page: Page, surface: Surface): Promise<CaseResult> {+ await waitForComposerPublished(page);+ const bandTop = await readCardTop(page);+ const composerHeight = await readComposerHeight(page);++ await page.getByTestId('ask-ai-collapse').click();+ await expect(page.getByTestId('ask-ai-reopen-badge')).toBeVisible();+ await expect(page.locator(COMPOSER_CARD)).toHaveCount(0);++ await forceScrollToRoomFromEnd(page, surface, NEAR_END_ROOM_PX);+ const candidate = await waitForCaretCandidateLine(page, surface, bandTop - CARET_REVEAL_GAP_PX);+ await page.mouse.click(candidate.left + 8, (candidate.top + candidate.bottom) / 2);+ await waitForLineSettled(page, surface, candidate.text, 'after the caret click');+ await forceScrollToRoomFromEnd(page, surface, NEAR_END_ROOM_PX);+ const before = await waitForLineSettled(+ page,+ surface,+ candidate.text,+ 'after the scroll was placed near the end',+ );++ await page.getByTestId('ask-ai-reopen-badge').click();+ await waitForComposerPublished(page);+ const after = await waitForLineSettled(+ page,+ surface,+ candidate.text,+ 'after the composer reopened',+ );++ return {+ label: surface.label,+ scrollportSelector: surface.scrollportSelector,+ caretText: candidate.text,+ composerHeight,+ cardTop: await readCardTop(page),+ before,+ after,+ };+}++function assertCaretRevealedNearTheScrollEnd(result: CaseResult): void {+ const roomBefore = result.before.scrollMax - result.before.scrollTop;+ expect(+ roomBefore,+ `${result.label}: precondition, the caret has to sit outside the ${SCROLL_PIN_SLACK_PX}px pin ` ++ 'band, or followBottom would have collected this scrollport before the reveal ran and this ' ++ 'case would be the composer-growth invariant instead',+ ).toBeGreaterThan(SCROLL_PIN_SLACK_PX);+ expect(+ roomBefore,+ `${result.label}: precondition, the scrollport has to sit within one composer height of its ` ++ 'end, or this would not exercise the near-end behavior',+ ).toBeLessThan(result.composerHeight);+ expect(+ result.before.bottom,+ `${result.label}: precondition, the caret line has to sit inside the clearance the reveal ` ++ 'promises, or nothing needed revealing and the assertion below would pass vacuously',+ ).toBeGreaterThan(occlusionTopOf(result) - CARET_REVEAL_GAP_PX);+ expect(+ result.before.bottom - result.after.bottom,+ `${describeCase(result)}\n near the scroll end the caret line already paints a few pixels ` ++ 'above the occlusion line, so a positive clearance alone would hold with no reveal at all. ' ++ 'The reveal has to have moved the line',+ ).toBeGreaterThan(0);+ expect(occlusionClearanceOf(result), describeCase(result)).toBeGreaterThan(0);+}++async function runComposerOpenCase(page: Page, surface: Surface): Promise<CaseResult> {+ await waitForComposerPublished(page);+ const bandTop = await readCardTop(page);++ await page.getByTestId('ask-ai-collapse').click();+ await expect(page.getByTestId('ask-ai-reopen-badge')).toBeVisible();+ await expect(page.locator(COMPOSER_CARD)).toHaveCount(0);++ await forceScrollToFraction(page, surface, CARET_LINE_FRACTION);+ const candidate = await waitForCaretCandidateLine(page, surface, bandTop);+ await page.mouse.click(candidate.left + 8, (candidate.top + candidate.bottom) / 2);+ const before = await waitForLineSettled(page, surface, candidate.text, 'after the caret click');++ await page.getByTestId('ask-ai-reopen-badge').click();+ await waitForComposerPublished(page);+ const after = await waitForLineSettled(+ page,+ surface,+ candidate.text,+ 'after the composer reopened',+ );++ return {+ label: surface.label,+ scrollportSelector: surface.scrollportSelector,+ caretText: candidate.text,+ composerHeight: await readComposerHeight(page),+ cardTop: await readCardTop(page),+ before,+ after,+ };+}++function describeCase(result: CaseResult): string {+ return [+ `[${result.label}] opening the Ask AI composer must scroll the caret line clear of the card`,+ ` scrollport ${result.scrollportSelector}`,+ ` caret line "${result.caretText}"`,+ ` composer height ${result.composerHeight}`,+ ` card top ${result.cardTop.toFixed(1)}`,+ ` scrollport bottom ${result.before.portBottom.toFixed(1)} -> ${result.after.portBottom.toFixed(1)}`,+ ` occlusion top ${occlusionTopOf(result).toFixed(1)} (the higher of the card top and the scrollport bottom)`,+ ` line bottom ${result.before.bottom.toFixed(1)} -> ${result.after.bottom.toFixed(1)} (moved ${(result.after.bottom - result.before.bottom).toFixed(1)})`,+ ` scroll ${result.before.scrollTop.toFixed(1)} -> ${result.after.scrollTop.toFixed(1)} (of max ${result.after.scrollMax.toFixed(1)})`,+ ` occlusion clearance ${occlusionClearanceOf(result).toFixed(1)} (positive = the caret line paints above BOTH)`,+ ].join('\n');+}++function assertCaretRevealed(result: CaseResult): void {+ expect(+ result.before.scrollMax - result.before.scrollTop,+ `${result.label}: precondition, ${result.scrollportSelector} must sit well away from its ` ++ 'scroll end, or followBottom would re-pin it and this case would be about the ' ++ 'composer-growth invariant instead of the composer-open reveal',+ ).toBeGreaterThan(SCROLL_PIN_SLACK_PX);+ expect(+ result.before.bottom,+ `${result.label}: precondition, with the composer collapsed the caret line has to sit below ` ++ 'the line the reopened card occludes, or nothing needed revealing and the assertion below ' ++ 'would pass vacuously. Measured against the occlusion line rather than the card top so a ' ++ 'host whose scrollport is clipped ABOVE the card can express its clip-only case',+ ).toBeGreaterThan(occlusionTopOf(result) - CARET_REVEAL_GAP_PX);+ expect(occlusionClearanceOf(result), describeCase(result)).toBeGreaterThan(0);+ expect(+ result.after.scrollMax - result.after.scrollTop,+ `${result.label}: precondition, the reveal has to leave ${result.scrollportSelector} outside ` ++ 'the pin band. Inside it the write clamps at the scroll end, followBottom then finds the ' ++ 'scrollport pinned and carries it to the growing end, and the caret rises far past the ' ++ 'reveal gap — so the upper bound below would red naming the reveal for a scroll ' ++ 'followBottom made',+ ).toBeGreaterThan(SCROLL_PIN_SLACK_PX);+ expect(+ occlusionClearanceOf(result),+ `${describeCase(result)}\n the reveal must lift the caret line just clear of the occlusion ` ++ 'line, not jump the document: a clearance far above the reveal gap means the scroll ' ++ 'overshot and took the reader somewhere they did not ask to go',+ ).toBeLessThanOrEqual(CARET_REVEAL_GAP_PX + (result.after.bottom - result.after.top));+}++test.describe('opening the Ask AI composer reveals the caret it would otherwise bury', () => {+ test.setTimeout(CASE_TIMEOUT_MS);++ test('markdown in WYSIWYG mode reveals the caret the reopened card covers', async ({+ page,+ api,+ }) => {+ const docName = `composer-open-caret-wysiwyg-${randomUUID().slice(0, 8)}`;+ await api.seedDocs([{ name: `${docName}.md`, markdown: markdownBody }]);++ await page.goto(`/#/${docName}`);+ await expect(page.locator(WYSIWYG_BODY).first()).toBeVisible({+ timeout: FIRST_PAINT_TIMEOUT_MS,+ });++ assertCaretRevealed(await runComposerOpenCase(page, WYSIWYG_SURFACE));+ });++ test('markdown in source mode reveals the caret the reopened card covers', async ({+ page,+ api,+ }) => {+ const docName = `composer-open-caret-source-${randomUUID().slice(0, 8)}`;+ await api.seedDocs([{ name: `${docName}.md`, markdown: markdownBody }]);++ await page.goto(`/#/${docName}`);+ await expect(page.locator(WYSIWYG_BODY).first()).toBeVisible({+ timeout: FIRST_PAINT_TIMEOUT_MS,+ });+ await toggleMode(page, 'source');+ await expect(+ page.locator(SOURCE_SCROLLPORT).first(),+ 'the markdown doc never entered source mode after toggleMode, so the CodeMirror lines this ' ++ 'case measures would be absent and the caret would be placed in the WYSIWYG body instead',+ ).toBeVisible({ timeout: MODE_SWITCH_TIMEOUT_MS });++ assertCaretRevealed(await runComposerOpenCase(page, CM_SURFACES.sourceEditor));+ });++ test('an editable text doc reveals the caret the reopened card covers', async ({+ page,+ workerServer,+ }) => {+ const docName = `composer-open-caret-text-${randomUUID().slice(0, 8)}.ts`;+ writeFileSync(join(workerServer.contentDir, docName), textDocBody(), 'utf-8');++ await page.goto(`/#/${docName}`);+ await expect(page.locator(TEXT_DOC_CONTENT).first()).toBeVisible({+ timeout: FIRST_PAINT_TIMEOUT_MS,+ });++ assertCaretRevealed(await runComposerOpenCase(page, CM_SURFACES.textDocEditor));+ });++ test('a caret near the scroll end still clears the reopened card', async ({+ page,+ workerServer,+ }) => {+ const docName = `composer-open-caret-near-end-${randomUUID().slice(0, 8)}.ts`;+ writeFileSync(join(workerServer.contentDir, docName), textDocBody(), 'utf-8');++ await page.goto(`/#/${docName}`);+ await expect(page.locator(TEXT_DOC_CONTENT).first()).toBeVisible({+ timeout: FIRST_PAINT_TIMEOUT_MS,+ });++ assertCaretRevealedNearTheScrollEnd(+ await runNearScrollEndCase(page, CM_SURFACES.textDocEditor),+ );+ });++ test('a mermaid doc in source mode reveals the caret the reopened card covers', async ({+ page,+ workerServer,+ }) => {+ const docName = `composer-open-caret-mermaid-${randomUUID().slice(0, 8)}.mmd`;+ writeFileSync(join(workerServer.contentDir, docName), mermaidDocBody(), 'utf-8');++ await page.goto(`/#/${docName}`);+ await expect(page.locator(MERMAID_HOST).first()).toBeVisible({+ timeout: FIRST_PAINT_TIMEOUT_MS,+ });+ await toggleMode(page, 'source');+ await expect(+ page.locator(MERMAID_CONTENT).first(),+ 'the mermaid doc never mounted its source-mode CodeMirror content after toggleMode, so the ' ++ 'scrollport this case measures would be absent',+ ).toBeVisible({ timeout: MODE_SWITCH_TIMEOUT_MS });++ assertCaretRevealed(await runComposerOpenCase(page, CM_SURFACES.mermaidDocEditor));+ });+});