Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): scroll restore strands doc beyond real content (PRD-8046) (#3580)
Andrew Mikofalvy5389d42ccd8c
diff --git a/packages/app/package.json b/packages/app/package.jsonindex 8faa37e56..1627d6842 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -27,7 +27,7 @@"measure:stress": "bash scripts/measure-stress.sh","measure:sweep": "bash scripts/measure-sweep.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/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/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts",+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/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/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox","test:visual": "playwright test --config playwright.visual.config.ts","test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsxindex 01f9c681d..14913c51c 100644--- a/packages/app/src/components/EditorActivityPool.tsx+++ b/packages/app/src/components/EditorActivityPool.tsx@@ -85,10 +85,13 @@ import { PageHeader } from './PageHeader';import { usePageList } from './PageListContext';import { PropertyPanel } from './PropertyPanel';import {+ clampTargetToContent,computeRestoreTarget,hasLandedAt,+ hasRestoreRunway,isExternalScroll,measureAnchor,+ measureContentExtent,RESTORE_BACKSTOP_MS,shouldRecordScrollPosition,} from './scroll-restore';@@ -782,8 +785,8 @@ export function ScrollPreservingContainer({// from warm-fallback to real-editor will collapse scrollHeight// transiently and re-clamp scrollTop to 0.// 2. Bounded per-frame poll that re-applies scrollTop whenever the- // browser has clamped it below target AND scrollHeight is- // sufficient. Survives the warm-fallback → real-editor swap by+ // browser has clamped it below target AND the document extends far+ // enough to hold it. Survives the warm-fallback → real-editor swap by// re-applying after content hydrates back to full height.//// rAF-poll, not ResizeObserver: `ResizeObserver(el)` observes the@@ -802,7 +805,9 @@ export function ScrollPreservingContainer({// that is exactly how transient churn froze into a permanently wrong// position. Tracking until someone else takes over the scroll is the// contract ("the same body content at the same viewport position"). Cost:- // a few rect reads per frame (getClientRects + two getBoundingClientRect),+ // a few rect reads per frame (getClientRects + two getBoundingClientRect ++ // one per TOP-LEVEL editing surface — nested contenteditable atoms are+ // excluded by ancestry before any rect read),// cheap while layout is clean — reads only force reflow after a write.//// CSS scroll anchoring is suspended while the loop runs: it is the one@@ -857,10 +862,33 @@ export function ScrollPreservingContainer({savedAnchorPos.current !== null ? rawTarget - savedAnchorPos.current : null;const bodyOffset: number | null = sharedOffset ?? instanceOffset;if (rawTarget === 0 && bodyOffset === null) return; // nothing to restore- // Null = no valid layout evidence this frame (anchor mounted but hidden,- // e.g. a Suspense fallback window) — hold: no write this frame.- const computeTarget = (): number | null =>- computeRestoreTarget(rawTarget, bodyOffset, measureAnchor(el, bodyAnchorRef?.current));+ // One frame's layout evidence: where to land, and how far the document+ // actually reaches. A null target = no valid evidence this frame (anchor+ // mounted but hidden, e.g. a Suspense fallback window) — hold: no write.+ //+ // The target is bounded by measured content rather than trusted outright.+ // A saved offset describes the layout it was saved in; a rebuilt content+ // DOM re-estimates its `content-visibility` chunks and can be a fraction+ // of that height, leaving the offset past everything real — and+ // scrollHeight, the only runway evidence available before, counts+ // absolutely positioned chrome, so it will happily confirm a landing on+ // nothing. Measuring per frame (not once at setup) is what makes the+ // bound converge: the extent starts collapsed and grows as chunks+ // materialize under the viewport, so the target climbs back toward the+ // saved offset instead of freezing at the first frame's geometry.+ const measureFrame = (): { target: number | null; contentBottom: number | null } => {+ const contentBottom = measureContentExtent(el);+ const target = computeRestoreTarget(+ rawTarget,+ bodyOffset,+ measureAnchor(el, bodyAnchorRef?.current),+ );+ return {+ target:+ target === null ? null : clampTargetToContent(target, contentBottom, el.clientHeight),+ contentBottom,+ };+ };// Suppress scroll capture while we drive the restore — our own writes and// the panel-resize adjustments would otherwise be recorded as user scroll.isRestoringRef.current = true;@@ -882,13 +910,16 @@ export function ScrollPreservingContainer({// lands AND content is sized; do NOT short-circuit: the Suspense// warm-fallback → real-editor swap can still collapse scrollHeight and// re-clamp scrollTop, so Stage 2's poll must remain armed.- let target = computeTarget();- if (target !== null) {- el.scrollTop = target;- if (hasLandedAt(el.scrollTop, target) && el.scrollHeight > target) {+ let frame = measureFrame();+ if (frame.target !== null) {+ el.scrollTop = frame.target;+ if (+ hasLandedAt(el.scrollTop, frame.target) &&+ hasRestoreRunway(frame.target, frame.contentBottom, el.scrollHeight)+ ) {hasLandedOnce = true;mark('ok/scroll-restore/phase1-success', {- target,+ target: frame.target,elapsedMs: performance.now() - startTs,});}@@ -974,18 +1005,22 @@ export function ScrollPreservingContainer({return;}// Recompute from the current anchor so the target follows the Properties- // section as it settles to its post-toggle height (see computeTarget).+ // section as it settles to its post-toggle height (see measureFrame).// A null target is a degenerate frame (anchor hidden): hold — writing// through invalid evidence is how a transient hidden window used to// become a permanently wrong scroll position.- target = computeTarget();- if (target !== null && !hasLandedAt(el.scrollTop, target) && el.scrollHeight > target) {- el.scrollTop = target;- if (hasLandedAt(el.scrollTop, target) && !phase2Marked) {+ frame = measureFrame();+ if (+ frame.target !== null &&+ !hasLandedAt(el.scrollTop, frame.target) &&+ hasRestoreRunway(frame.target, frame.contentBottom, el.scrollHeight)+ ) {+ el.scrollTop = frame.target;+ if (hasLandedAt(el.scrollTop, frame.target) && !phase2Marked) {// At-most-once per restore session: phase2-success fires on the// first re-apply that lands, not every frame thereafter.mark('ok/scroll-restore/phase2-success', {- target,+ target: frame.target,elapsedMs: performance.now() - startTs,});phase2Marked = true;@@ -999,16 +1034,20 @@ export function ScrollPreservingContainer({const safetyTimer = setTimeout(() => {if (done) return;// Fire `abandoned` based on final DOM state, not a historical success- // flag. Gated on `scrollHeight > target` so we don't emit `abandoned`- // when the doc legitimately shrunk below the saved target (content- // changed; restoration was not possible). A null target here means the- // anchor never became measurable again — that IS abandonment. User- // scroll exits via `yieldToUser → finish` which clears the timer,- // so a scroll-away cannot trigger a false `abandoned`.- const finalTarget = computeTarget();+ // flag. The final target is content-clamped, so a doc that shrank below+ // the saved offset yields a REACHABLE target at the new content bottom:+ // landing there counts as restored, not landing is genuine abandonment,+ // and the runway check only suppresses the mark when no document exists+ // below the target at all. A null target here means the anchor never+ // became measurable again — that IS abandonment. User scroll exits via+ // `yieldToUser → finish` which clears the timer, so a scroll-away+ // cannot trigger a false `abandoned`.+ const final = measureFrame();+ const finalTarget = final.target;if (finalTarget === null ||- (!hasLandedAt(el.scrollTop, finalTarget) && el.scrollHeight > finalTarget)+ (!hasLandedAt(el.scrollTop, finalTarget) &&+ hasRestoreRunway(finalTarget, final.contentBottom, el.scrollHeight))) {// `target` stays numeric across the ok/scroll-restore family (a// mixed number|string field silently NaNs any numeric aggregation);diff --git a/packages/app/src/components/scroll-restore.test.ts b/packages/app/src/components/scroll-restore.test.tsindex 3bea220cb..02cff6aec 100644--- a/packages/app/src/components/scroll-restore.test.ts+++ b/packages/app/src/components/scroll-restore.test.ts@@ -1,9 +1,12 @@import { describe, expect, test } from 'vitest';import {+ clampTargetToContent,computeRestoreTarget,hasLandedAt,+ hasRestoreRunway,isExternalScroll,measureAnchor,+ measureContentExtent,SCROLL_LANDING_TOLERANCE_PX,shouldRecordScrollPosition,} from './scroll-restore';@@ -17,6 +20,34 @@ function fakeElement(opts: { rects: number; top?: number; scrollTop?: number }):} as unknown as HTMLElement;}+/** Minimal layout fake for one of the scroller's editing surfaces. */+function fakeSurface(opts: { bottom: number; rects?: number }): Element {+ return {+ getClientRects: () => ({ length: opts.rects ?? 1 }) as DOMRectList,+ getBoundingClientRect: () => ({ bottom: opts.bottom }) as DOMRect,+ } as unknown as Element;+}++/**+ * Scroller fake. `scrollHeight` is deliberately settable and deliberately+ * inconsistent with the surfaces: the whole point of measuring the editing+ * surface is that scrollHeight can describe space the document does not+ * occupy.+ */+function fakeScroller(opts: {+ top?: number;+ scrollTop?: number;+ scrollHeight?: number;+ surfaces: Element[];+}): HTMLElement {+ return {+ scrollTop: opts.scrollTop ?? 0,+ scrollHeight: opts.scrollHeight ?? 0,+ querySelectorAll: () => opts.surfaces,+ getBoundingClientRect: () => ({ top: opts.top ?? 0 }) as DOMRect,+ } as unknown as HTMLElement;+}+describe('measureAnchor', () => {test('absent anchor (null / undefined) reports absent', () => {const container = fakeElement({ rects: 1, top: 56, scrollTop: 1200 });@@ -82,6 +113,136 @@ describe('computeRestoreTarget', () => {});});+describe('measureContentExtent', () => {+ test('a container with no editing surface has no measurable extent', () => {+ // A Suspense skeleton or warm fallback: no evidence, so callers keep+ // whatever behavior they had rather than clamping against nothing.+ expect(measureContentExtent(fakeScroller({ surfaces: [] }))).toBeNull();+ });++ test('measures the surface bottom into scroll coordinates (bottom - containerTop + scrollTop)', () => {+ const scroller = fakeScroller({+ top: 56,+ scrollTop: 9471,+ surfaces: [fakeSurface({ bottom: 631 })],+ });+ expect(measureContentExtent(scroller)).toBe(631 - 56 + 9471);+ });++ test('takes the lowest surface, not the last one', () => {+ const scroller = fakeScroller({+ surfaces: [+ fakeSurface({ bottom: 400 }),+ fakeSurface({ bottom: 10132 }),+ fakeSurface({ bottom: 0 }),+ ],+ });+ expect(measureContentExtent(scroller)).toBe(10132);+ });++ test('a surface with no layout boxes contributes nothing, not a zero rect', () => {+ // The hidden half of a dual-mounted document reports a rect at the+ // viewport origin, which as an extent would clamp every restore to the+ // top of the page. Same hazard as an unmeasurable anchor.+ const scroller = fakeScroller({+ top: 56,+ scrollTop: 1000,+ surfaces: [fakeSurface({ bottom: 5000 }), fakeSurface({ bottom: 0, rects: 0 })],+ });+ expect(measureContentExtent(scroller)).toBe(5000 - 56 + 1000);+ });++ test('a container whose surfaces are all unlaid-out reports no extent', () => {+ const scroller = fakeScroller({ surfaces: [fakeSurface({ bottom: 0, rects: 0 })] });+ expect(measureContentExtent(scroller)).toBeNull();+ });++ test('a surface nested inside another surface contributes nothing (atom node views)', () => {+ // contenteditable=false atoms (wiki-link chips, embeds) match the selector+ // but sit inside the real editing surface; ancestry excludes them so a+ // chip-dense document costs one rect read, not one per atom.+ const nested = {+ ...fakeSurface({ bottom: 99_999 }),+ parentElement: { closest: () => ({}) as Element } as unknown as HTMLElement,+ } as unknown as Element;+ const scroller = fakeScroller({ surfaces: [fakeSurface({ bottom: 10132 }), nested] });+ expect(measureContentExtent(scroller)).toBe(10132);+ });++ test('never falls back to scrollHeight — that is the polluted quantity', () => {+ // The bug shape: absolutely positioned chrome parked deep in the scroller+ // keeps scrollHeight stretched thousands of pixels past a document that+ // re-rendered much shorter. A helper that consulted scrollHeight here+ // would hand the restore back the same phantom runway it is meant to+ // withhold.+ const scroller = fakeScroller({+ scrollHeight: 38944,+ surfaces: [fakeSurface({ bottom: 10132 })],+ });+ expect(measureContentExtent(scroller)).toBe(10132);+ });+});++describe('clampTargetToContent', () => {+ test('a target inside the content is untouched', () => {+ expect(clampTargetToContent(1200, 48046, 631)).toBe(1200);+ });++ test('a target past the content is pulled back to the last full viewport of content', () => {+ // The reported bug: an offset saved against 48,046px of materialized+ // content, re-applied to a layout that re-rendered at 10,132px.+ expect(clampTargetToContent(38313, 10132, 631)).toBe(10132 - 631);+ });++ test('content shorter than the viewport clamps to the top, never below zero', () => {+ expect(clampTargetToContent(38313, 447, 631)).toBe(0);+ expect(clampTargetToContent(0, 0, 631)).toBe(0);+ });++ test('an unmeasurable extent leaves the target alone', () => {+ // Nothing measured is not evidence of a short document; clamping on it+ // would strand a healthy restore at 0.+ expect(clampTargetToContent(38313, null, 631)).toBe(38313);+ });++ test('the bound is inclusive — a target exactly one viewport above the content bottom stands', () => {+ // A <= -> < drift here would shave a pixel off every restore that lands+ // at the very end of a document.+ expect(clampTargetToContent(9501, 10132, 631)).toBe(9501);+ });++ test('clamping only ever lowers a target', () => {+ expect(clampTargetToContent(200, 48046, 631)).toBe(200);+ expect(clampTargetToContent(0, 48046, 631)).toBe(0);+ });+});++describe('hasRestoreRunway', () => {+ test('content below the target is runway', () => {+ expect(hasRestoreRunway(9501, 10132, 10132)).toBe(true);+ });++ test('scrollable space that is not content is NOT runway', () => {+ // Overlay chrome can stretch scrollHeight far past the document (38,944+ // vs content ending at 10,132) — a runway check that trusted scrollHeight+ // would approve a target 28,000px past real content and let the restore+ // mark that landing a success.+ expect(hasRestoreRunway(38313, 10132, 38944)).toBe(false);+ });++ test('an unmeasurable extent falls back to scrollHeight', () => {+ expect(hasRestoreRunway(1200, null, 5000)).toBe(true);+ expect(hasRestoreRunway(1200, null, 900)).toBe(false);+ });++ test('a target exactly at the content bottom has no runway (boundary is exclusive)', () => {+ // The boundary is exclusive (`>`): a document that shrank to exactly the+ // target has no document below it, which is "restoration was not+ // possible", not an abandoned restore.+ expect(hasRestoreRunway(10132, 10132, 10132)).toBe(false);+ });+});+describe('shouldRecordScrollPosition', () => {test('a scroll event on an unmeasurable-anchor frame must NOT be recorded', () => {// The save-side twin of the restore-side hold: recording pairs thediff --git a/packages/app/src/components/scroll-restore.ts b/packages/app/src/components/scroll-restore.tsindex b6dfbf550..b698584d7 100644--- a/packages/app/src/components/scroll-restore.ts+++ b/packages/app/src/components/scroll-restore.ts@@ -21,6 +21,14 @@* standard-DPR displays. Landing checks need a sub-pixel tolerance or* the loop rewrites forever and telemetry misclassifies an on-target* restore as abandoned.+ *+ * 3. A scroller's `scrollHeight` is not a statement about the document.+ * Absolutely positioned chrome inside it counts toward the scrollable+ * overflow region, so scrollHeight can describe space no content+ * occupies — and a saved offset measured against a taller earlier layout+ * lands in exactly that space. Targets and the runway checks that gate+ * them must be bounded by measured content, or a restore can "succeed"+ * onto a blank viewport and then defend that position.*//** Anchor layout evidence for one frame. */@@ -78,6 +86,106 @@ export function computeRestoreTarget(}}+/**+ * The editing surfaces whose boxes describe the document. Both ProseMirror's+ * `view.dom` and CodeMirror's `.cm-content` carry the attribute, so no+ * per-mode knowledge is needed. The scroll-coordinate conversion below is+ * exact for the modes whose surface is laid out by THIS scroller (WYSIWYG,+ * full-page source — CM6 there renders at content height with no internal+ * scrollport). Diff, standalone Mermaid, and standalone text docs mount+ * `.cm-content` behind their own overflow pane inside the scroller, where the+ * conversion would mix the outer scrollTop with an inner-positioned rect —+ * inert today because the outer scroller cannot overflow in those modes, so+ * the clamp is unreachable there.+ *+ * Load-bearing exclusion: overlay chrome mounted inside the scroller (the+ * block drag handle, selection indicators) must NOT carry `contenteditable` —+ * an overlay that gained the attribute would re-enter this measurement and+ * re-open the phantom-space hazard the selector exists to exclude.+ */+const CONTENT_SURFACE_SELECTOR = '[contenteditable]';++/**+ * Bottom of `container`'s document content, in the container's scroll+ * coordinates (distance from the top of the scrollable content), or `null`+ * when no editing surface is laid out in it this frame.+ *+ * Neither of the two obvious measurements works here (property 3 above):+ *+ * - `scrollHeight` is the polluted quantity, at every level. It counts the+ * scrollable overflow of absolutely positioned chrome, so the scroller AND+ * every wrapper between it and the document report the same inflated+ * height.+ * - the container's own children are height-constrained wrappers (`h-full`+ * on the editor column), and the document overflows them. Their boxes+ * describe the viewport, not the document — measuring them would clamp+ * every restore to roughly the top of the page.+ *+ * The editing surface is the one box that both encloses the document and+ * excludes the chrome, because that chrome is mounted as its SIBLING rather+ * than inside it, and `getBoundingClientRect` reports an element's own border+ * box. A surface with no boxes (a hidden mode's editor, a skipped subtree)+ * contributes nothing rather than a zero rect at the viewport origin — the+ * same hazard as an unmeasurable anchor — and a frame with no surface at all+ * (a Suspense skeleton or warm fallback) yields `null` so callers hold their+ * previous behavior instead of clamping against content they cannot see.+ */+export function measureContentExtent(container: HTMLElement): number | null {+ const containerTop = container.getBoundingClientRect().top;+ const { scrollTop } = container;+ let contentBottom: number | null = null;+ for (const surface of Array.from(container.querySelectorAll(CONTENT_SURFACE_SELECTOR))) {+ // `[contenteditable]` also matches the contenteditable=false atom node+ // views nested inside an editing surface (wiki-link chips, embeds, image+ // widgets) — in-flow boxes that can never extend below their surface's+ // bottom. Skipping them by ancestry keeps the per-frame cost at one rect+ // read per top-level surface instead of one per atom in a chip-dense doc.+ if (surface.parentElement?.closest(CONTENT_SURFACE_SELECTOR)) continue;+ if (surface.getClientRects().length === 0) continue;+ const bottom = surface.getBoundingClientRect().bottom - containerTop + scrollTop;+ if (contentBottom === null || bottom > contentBottom) contentBottom = bottom;+ }+ return contentBottom;+}++/**+ * `target` bounded so the viewport it produces still sits over real content.+ *+ * This is what the browser already does to an over-large `scrollTop` write —+ * clamp it to `scrollHeight - clientHeight` — minus the chrome that inflates+ * `scrollHeight`. On a document whose geometry has not changed the bound is+ * the identity: an offset the user could reach when it was saved is still+ * reachable. It only bites once the content that offset was measured against+ * is gone, which is precisely when landing on it would show nothing.+ *+ * An unmeasurable extent leaves the target alone; the caller's own runway+ * check falls back to `scrollHeight` in that case rather than clamping+ * against a measurement we do not have.+ */+export function clampTargetToContent(+ target: number,+ contentBottom: number | null,+ clientHeight: number,+): number {+ if (contentBottom === null) return target;+ return Math.min(target, Math.max(0, contentBottom - clientHeight));+}++/**+ * Whether the layout can actually hold `target` — whether there is document+ * below it, not merely scrollable space. Gates the success marks (a scrollTop+ * that equals its target only because both were clamped to 0 is not a restore)+ * and the re-apply write (nothing to reach). Falls back to `scrollHeight` only+ * when no content extent could be measured.+ */+export function hasRestoreRunway(+ target: number,+ contentBottom: number | null,+ scrollHeight: number,+): boolean {+ return (contentBottom ?? scrollHeight) > target;+}+/*** Whether a scroll event's position is safe to record as the user's saved* position. The save-side twin of the restore-side hold: recording while thediff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsxindex c0065f9cd..98da8f319 100644--- a/packages/app/src/editor/TiptapEditor.tsx+++ b/packages/app/src/editor/TiptapEditor.tsx@@ -1033,6 +1033,31 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({};}, [editor]);+ // Hide the block drag handle when this editor leaves the screen. The handle+ // is an absolutely positioned overlay DragHandlePlugin mounts outside React,+ // and flipping an `<Activity>` to hidden (`display: none`) does not reach the+ // plugin's own hide paths, so it survives parked at the last hovered block.+ // On the way back the content DOM is rebuilt with every content-visibility+ // chunk re-estimated much shorter, and a handle left at pre-rebuild+ // coordinates stretches the scroller into scrollable space that holds no+ // content. Effects unmount on Activity hide, so this cleanup IS the+ // deactivation hook for Activity hide, pool recycle, and unmount. The one+ // display path it cannot reach is a WYSIWYG<->source mode flip (a CSS-only+ // class swap; the chrome stays mounted) — containment there comes from the+ // `.ok-mode-hidden` pane rule in globals.css, whose content-visibility+ // bounds the hidden pane's layout, this overlay included.+ // `hideDragHandle` is the plugin's own transaction meta: it hides the+ // element and clears the node it tracks, which additionally disarms the+ // plugin's reposition path during the rebuild.+ useEffect(() => {+ return () => {+ // `editor.commands` reaches through `editor.view`, a throwing proxy+ // until ProseMirror mounts (same guard as this file's other view users).+ if (editor.isDestroyed || !getEditorView(editor)) return;+ editor.commands.setMeta('hideDragHandle', true);+ };+ }, [editor]);+// A user edit promotes this doc's preview tab to permanent. Listens for the// content change rather than the keystroke: arrow keys, Escape and Cmd+C all// reach the DOM handlers above but leave the document untouched, and a tabdiff --git a/packages/app/src/globals.css b/packages/app/src/globals.cssindex 67f95ff41..c34342c73 100644--- a/packages/app/src/globals.css+++ b/packages/app/src/globals.css@@ -2426,10 +2426,26 @@ body[data-editor-tab-dragging] * {outline-offset: 2px;}-/* Visibility fade — DragHandlePlugin sets inline visibility: hidden */+/* Visibility fade — DragHandlePlugin sets inline visibility: hidden.+ The hidden handle stays in layout and keeps whatever inline top/left+ floating-ui last wrote for it, so a handle parked against a deep block goes+ on stretching the scroller's scrollHeight after the content beneath it+ shrinks (a rebuilt content DOM re-estimates every content-visibility chunk+ much shorter). That surplus is scrollable but holds nothing, which is how a+ restored offset can park the viewport on blank space. Pinning the hidden+ handle to the container origin keeps chrome inside the content by+ construction; `!important` because the plugin writes those offsets inline.+ `visibility` must stay the hiding mechanism — the plugin's reveal path+ measures the handle's box via floating-ui (the position write lands a+ microtask after the reveal), and `display: none` would zero the dimensions+ that measurement needs. */.ok-block-controls[style*="visibility: hidden"],.ok-block-controls[style*="visibility:hidden"] {opacity: 0;+ /* biome-ignore lint/complexity/noImportantStyles: the plugin writes top/left as inline styles, which no selector specificity can outrank. */+ top: 0 !important;+ /* biome-ignore lint/complexity/noImportantStyles: same inline-style override as `top` above. */+ left: 0 !important;}/* Dark mode */diff --git a/packages/app/tests/stress/tab-close-scroll-restore.e2e.ts b/packages/app/tests/stress/tab-close-scroll-restore.e2e.tsnew file mode 100644index 000000000..4785cf1ec--- /dev/null+++ b/packages/app/tests/stress/tab-close-scroll-restore.e2e.ts@@ -0,0 +1,582 @@+/**+ * Pins the editor scroller's geometry contract: scrollable space must correspond+ * to real document content, so any offset the app restores or preserves lands the+ * viewport on content that exists in the *current* layout.+ *+ * Two production mechanisms make that contract easy to break, and both are+ * exercised here:+ *+ * 1. Every top-level block renders inside a `content-visibility: auto` wrapper+ * whose skipped-state height is a flat estimate. A document whose blocks are+ * much taller than that estimate collapses to a fraction of its materialized+ * height whenever its content DOM is rebuilt — which is what returning to a+ * document after closing a sibling tab does. An offset captured against the+ * materialized geometry then points far past the real content.+ *+ * 2. The block drag handle (`.ok-block-controls`) is an absolutely positioned+ * overlay inside the scroller. floating-ui parks it at the last hovered+ * block, and it is "hidden" with `visibility: hidden` — which keeps it in+ * layout. A handle parked against a deep block keeps stretching the+ * scroller's `scrollHeight` after the content beneath it shrinks, so the+ * browser never clamps `scrollTop` back onto content.+ *+ * Every assertion therefore derives "real content extent" from the `.ProseMirror`+ * element's box, never from `scrollHeight` — `scrollHeight` is exactly the+ * quantity overlay chrome pollutes, so an assertion built on it cannot see the+ * failure. Exact restored offsets are deliberately NOT asserted: estimate-driven+ * displacement is a separate, milder defect, and pinning pixel values here would+ * make this file fail for the wrong reason.+ *+ * Not covered here: the same contract is reachable by shrinking a live document+ * from the agent-write API, but a full-body `position: 'replace'` measurably+ * resets the scroller to 0 and repositions the drag handle onto the new content,+ * so that path does not strand the viewport and a test built on it would pass+ * against the broken build.+ *+ * Content presence is measured by hit-testing (`document.elementFromPoint`)+ * rather than by sweeping block rects: a `content-visibility: auto` subtree+ * reports an empty rect while skipped, and a rect sweep forces style/layout work+ * that can perturb the very geometry under test. Hits must land on a strict+ * descendant of `.ProseMirror` — a hit on `.ProseMirror` itself is inter-block+ * whitespace whose `textContent` is the whole document, which would report+ * painted content for an entirely blank band.+ *+ * Invocation (bug-specific gate):+ * cd public/open-knowledge/packages/app && \+ * pnpm exec playwright test tests/stress/tab-close-scroll-restore.e2e.ts \+ * --workers=1 --retries=0+ */++import type { Page } from '@playwright/test';+import { type ApiHelpers, expect, test, waitForActiveProviderSynced } from './_helpers';++/**+ * Height of the absolute EditorToolbar overlapping the top of the scrollport+ * (`pt-14` on the scroll container). Content behind it is on screen but not+ * readable, so both the paint probes and the "viewport top" scroll coordinate+ * step in past it.+ */+const TOOLBAR_INSET_PX = 56;++/** Evenly spaced vertical hit tests across the readable band. */+const PAINT_PROBE_COUNT = 10;++/**+ * Slack allowed above the document's own bottom padding before extra scrollable+ * space counts as phantom. Legitimate late layout drift is tens of pixels; the+ * overlay-manufactured runway this file guards against is thousands, so the gap+ * is wide enough that no realistic padding change turns the assertion brittle.+ */+const PHANTOM_RUNWAY_TOLERANCE_PX = 64;++// --- fixture ---------------------------------------------------------------++const FILLER_WORDS = [+ 'lorem',+ 'ipsum',+ 'dolor',+ 'sit',+ 'amet',+ 'consectetur',+ 'adipiscing',+ 'elit',+ 'tempor',+ 'incididunt',+ 'labore',+ 'magna',+ 'aliqua',+ 'veniam',+ 'nostrud',+] as const;++/**+ * Words per block. ~220 renders each paragraph several hundred pixels tall at the+ * 1280x720 test viewport — several times the flat skipped-state estimate, which is+ * the precondition for the geometry collapse this file exercises. A fixture of+ * near-estimate-height blocks (tables, one-liners) does NOT reproduce it.+ */+const WORDS_PER_BLOCK = 220;+const SECTION_COUNT = 12;+const BLOCKS_PER_SECTION = 8;++function blockMarker(index: number): string {+ return `MK${String(index).padStart(4, '0')}`;+}++function fillerFor(index: number): string {+ const words: string[] = [];+ for (let i = 0; i < WORDS_PER_BLOCK; i++) {+ words.push(FILLER_WORDS[(index * 7 + i * 3) % FILLER_WORDS.length] ?? 'lorem');+ }+ return words.join(' ');+}++/**+ * Tall-block document. Every body paragraph carries a wiki link to `linkTo`, so a+ * deep scroll always leaves at least one chip inside the readable band — the+ * scenario asserts that as a precondition rather than falling back to a synthetic+ * navigation, which would skip the user's actual journey. `bottomMarker` is+ * per-document so a readiness gate can never match a different document that+ * happens to share this fixture's shape.+ */+function buildTallBlockDoc({+ linkTo,+ bottomMarker,+}: {+ linkTo: string;+ bottomMarker: string;+}): string {+ const lines: string[] = ['# Progress Log', ''];+ let index = 0;+ for (let section = 1; section <= SECTION_COUNT; section++) {+ lines.push(`## ${blockMarker(index++)} Section ${section}`, '');+ for (let block = 0; block < BLOCKS_PER_SECTION; block++) {+ const marker = blockMarker(index++);+ lines.push(`${marker} ${fillerFor(section * 5 + block)} see [[${linkTo}]] for detail.`, '');+ }+ }+ lines.push(`## ${blockMarker(index)} Bottom Marker Heading`, '', `${bottomMarker} end.`, '');+ return lines.join('\n');+}++// --- measurement -----------------------------------------------------------++interface ScrollportGeometry {+ scrollTop: number;+ scrollHeight: number;+ clientHeight: number;+ /** Top of the real document content, in the scroller's scroll coordinates. */+ contentTop: number;+ /** Bottom of the real document content, in the scroller's scroll coordinates. */+ contentBottom: number;+ /** Top edge of the readable band, in scroll coordinates. */+ viewportTop: number;+ /** Hit tests across the readable band that landed on painted document text. */+ paintedProbes: number;+ probeCount: number;+ /** The block drag-handle overlay, when one is mounted in this scroller. */+ blockControls: { top: number; bottom: number; visibility: string } | null;+}++/**+ * Read the painted editor scrollport's geometry. The painted container is chosen+ * by layout box rather than first match: a hidden `<Activity>` entry keeps its+ * scroll container in the DOM, so several can coexist and only the painted one is+ * the active scrollport.+ */+async function readScrollportGeometry(page: Page): Promise<ScrollportGeometry> {+ const geometry = await page.evaluate(+ ({ toolbarPx, probeCount }) => {+ const scroller = Array.from(+ document.querySelectorAll('[data-testid="editor-scroll-container"]'),+ ).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ if (!scroller) return null;+ const prose = scroller.querySelector('.ProseMirror:not(.composer-prosemirror)');+ if (!(prose instanceof HTMLElement)) return null;++ const scrollTop = scroller.scrollTop;+ const scrollerRect = scroller.getBoundingClientRect();+ const proseRect = prose.getBoundingClientRect();+ const toScrollCoords = (viewportY: number) => viewportY - scrollerRect.top + scrollTop;++ const bandTop = scrollerRect.top + toolbarPx;+ const bandHeight = scrollerRect.bottom - bandTop;+ let paintedProbes = 0;+ for (let i = 0; i < probeCount; i++) {+ const y = bandTop + (bandHeight * (i + 0.5)) / probeCount;+ const hit = document.elementFromPoint(scrollerRect.left + scrollerRect.width / 2, y);+ if (+ hit instanceof Element &&+ hit !== prose &&+ prose.contains(hit) &&+ (hit.textContent ?? '').trim().length > 0+ ) {+ paintedProbes += 1;+ }+ }++ const controls = scroller.querySelector('.ok-block-controls');+ const controlsRect =+ controls instanceof HTMLElement ? controls.getBoundingClientRect() : null;+ const controlsVisibility =+ controls instanceof HTMLElement ? getComputedStyle(controls).visibility : null;++ return {+ scrollTop: Math.round(scrollTop),+ scrollHeight: Math.round(scroller.scrollHeight),+ clientHeight: Math.round(scroller.clientHeight),+ contentTop: Math.round(toScrollCoords(proseRect.top)),+ contentBottom: Math.round(toScrollCoords(proseRect.bottom)),+ viewportTop: Math.round(scrollTop + toolbarPx),+ paintedProbes,+ probeCount,+ blockControls:+ controlsRect && controlsVisibility+ ? {+ top: Math.round(toScrollCoords(controlsRect.top)),+ bottom: Math.round(toScrollCoords(controlsRect.bottom)),+ visibility: controlsVisibility,+ }+ : null,+ };+ },+ { toolbarPx: TOOLBAR_INSET_PX, probeCount: PAINT_PROBE_COUNT },+ );+ if (!geometry) {+ throw new Error(+ 'no painted editor scroll container with a ProseMirror body — the editor never rendered',+ );+ }+ return geometry;+}++function describeGeometry(label: string, geometry: ScrollportGeometry): string {+ return `${label}: scrollTop=${geometry.scrollTop} scrollHeight=${geometry.scrollHeight} clientHeight=${geometry.clientHeight} content=[${geometry.contentTop}, ${geometry.contentBottom}] viewportTop=${geometry.viewportTop} painted=${geometry.paintedProbes}/${geometry.probeCount} blockControls=${JSON.stringify(geometry.blockControls)}`;+}++/**+ * Wait until the painted editor's text contains `needle`. Reads `textContent`+ * rather than asserting visibility because a `content-visibility: auto` subtree+ * scrolled out of view reports an empty box — a visibility gate would time out on+ * exactly the stranded state under test and mask the real assertion.+ */+async function waitForPaintedDocText(page: Page, needle: string, timeout = 30_000): Promise<void> {+ await expect+ .poll(+ () =>+ page.evaluate((text) => {+ const scroller = Array.from(+ document.querySelectorAll('[data-testid="editor-scroll-container"]'),+ ).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ const prose = scroller?.querySelector('.ProseMirror:not(.composer-prosemirror)');+ return (prose?.textContent ?? '').includes(text);+ }, needle),+ { timeout, message: `painted editor never showed "${needle}"` },+ )+ .toBe(true);+}++/**+ * Let the renderer advance `frames` animation frames. The restore loop under+ * test schedules its writes on requestAnimationFrame, so frames — not+ * wall-clock sleeps, which the E2E STOP rules ban — are the honest unit for+ * "give the app time to process what just happened": counting frames+ * guarantees the loop actually had turns, where a sleep only guarantees time+ * passed.+ */+async function awaitAnimationFrames(page: Page, frames: number): Promise<void> {+ await page.evaluate(+ (n) =>+ new Promise<void>((resolve) => {+ let remaining = n;+ const tick = () => {+ remaining -= 1;+ if (remaining <= 0) {+ resolve();+ return;+ }+ requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+ }),+ frames,+ );+}++/**+ * Resolve once `scrollTop` holds still for `quietMs`, or `timeoutMs` elapses.+ * Assertions run against a settled scroller so a transient pre-restore frame+ * (which briefly shows content before the restore writes its target) can never+ * be mistaken for a healthy landing. `timeoutMs` stays well below the restore+ * loop's wall-clock backstop: the contract is that the restore lands on content,+ * not that abandoning it eventually does. The quiet-period detection runs+ * in-page on requestAnimationFrame — the same scheduler the restore loop writes+ * from — so "no movement for quietMs" is measured frame-accurately.+ */+async function waitForScrollSettled(+ page: Page,+ { quietMs = 700, timeoutMs = 4_000 }: { quietMs?: number; timeoutMs?: number } = {},+): Promise<void> {+ await page.evaluate(+ (args) =>+ new Promise<void>((resolve) => {+ const readScrollTop = () => {+ const scroller = Array.from(+ document.querySelectorAll('[data-testid="editor-scroll-container"]'),+ ).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ return scroller ? Math.round(scroller.scrollTop) : null;+ };+ const started = performance.now();+ let last = readScrollTop();+ let quietSince = performance.now();+ const tick = () => {+ const now = performance.now();+ const current = readScrollTop();+ if (current !== last) {+ last = current;+ quietSince = now;+ }+ if (now - quietSince >= args.quietMs || now - started >= args.timeoutMs) {+ resolve();+ return;+ }+ requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+ }),+ { quietMs, timeoutMs },+ );+}++/** Wheel-scroll deep into the document, then back off the very bottom. */+async function scrollDeep(page: Page, { down = 30, up = 4 } = {}): Promise<void> {+ for (let i = 0; i < down; i++) {+ await page.mouse.wheel(0, 900);+ // A few frames per tick lets layout + the scroll listener process each+ // wheel event before the next lands (the save path records per event).+ await awaitAnimationFrames(page, 4);+ }+ // Backing off the last screens keeps "it merely stayed pinned at the maximum"+ // from being an alternative explanation for any end-of-document result.+ for (let i = 0; i < up; i++) {+ await page.mouse.wheel(0, -900);+ await awaitAnimationFrames(page, 4);+ }+ await waitForScrollSettled(page);+}++/**+ * Move the pointer over the block under the middle of the readable band so the+ * drag handle is positioned against deep content, and assert the affordance+ * actually mounted. Without that check a fixture or hover-path change would+ * silently disarm the overlay half of the scenario and leave the test passing on+ * a still-broken build.+ */+async function hoverDeepBlock(page: Page): Promise<void> {+ const box = await page.getByTestId('editor-scroll-container').first().boundingBox();+ if (!box) throw new Error('editor scroll container has no layout box');+ const x = box.x + box.width / 2;+ const y = box.y + TOOLBAR_INSET_PX + (box.height - TOOLBAR_INSET_PX) / 2;+ // Two moves: the drag-handle plugin positions off pointer movement, so a single+ // move landing on the same coordinate the wheel left the pointer at is a no-op.+ await page.mouse.move(x, y - 40);+ await page.mouse.move(x, y);++ await expect+ .poll(+ () =>+ page.evaluate(() => {+ const scroller = Array.from(+ document.querySelectorAll('[data-testid="editor-scroll-container"]'),+ ).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ const element = scroller?.querySelector('.ok-block-controls');+ if (!(element instanceof HTMLElement)) return 'absent';+ return getComputedStyle(element).visibility;+ }),+ {+ timeout: 5_000,+ message:+ 'the block drag handle never became visible while hovering a block — the overlay was never positioned against deep content, so this run does not exercise the stale-overlay path; re-check editor/extensions/drag-handle.ts',+ },+ )+ .toBe('visible');+}++async function openFromSidebar(page: Page, filename: string): Promise<void> {+ const row = page.getByRole('treeitem', { name: filename, exact: true });+ await expect(row).toBeVisible();+ await row.click();+}++/**+ * Index of the first wiki-link chip sitting wholly inside the readable band, or+ * -1. Chips inside a skipped `content-visibility: auto` chunk report an empty+ * rect, so a zero-area rect is treated as "not in the band" rather than as a+ * position. Measured against the scroller's own rect, not the window viewport:+ * the scrollport sits below the tab strip, so window coordinates would clip the+ * wrong band.+ */+async function findWikiLinkInBand(page: Page): Promise<{ total: number; index: number }> {+ return page.evaluate((toolbarPx) => {+ const scroller = Array.from(+ document.querySelectorAll('[data-testid="editor-scroll-container"]'),+ ).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ const chips = Array.from(document.querySelectorAll('[data-wiki-link]'));+ if (!scroller) return { total: chips.length, index: -1 };+ const scrollerRect = scroller.getBoundingClientRect();+ const bandTop = scrollerRect.top + toolbarPx + 8;+ const bandBottom = scrollerRect.bottom - 8;+ for (let i = 0; i < chips.length; i++) {+ const rect = chips[i]?.getBoundingClientRect();+ if (!rect || rect.width <= 0 || rect.height <= 0) continue;+ if (rect.top >= bandTop && rect.bottom <= bandBottom)+ return { total: chips.length, index: i };+ }+ return { total: chips.length, index: -1 };+ }, TOOLBAR_INSET_PX);+}++/**+ * Nudge the scroller until a wiki link the user could actually see is in the+ * readable band, and return its index. Nudging is bounded and small (well under+ * one block height) so the document stays deep-scrolled; navigating some other+ * way would move the source document's scroll position and stop reproducing the+ * journey under test.+ */+async function scrollUntilWikiLinkInBand(page: Page): Promise<number> {+ let found = await findWikiLinkInBand(page);+ for (let nudge = 0; nudge < 10 && found.index < 0; nudge++) {+ await page.mouse.wheel(0, 160);+ await awaitAnimationFrames(page, 12);+ found = await findWikiLinkInBand(page);+ }+ expect(+ found.index,+ `no wiki-link chip inside the readable band after the deep scroll (${found.total} chips in the document) — the fixture no longer places a link in reach of the viewport`,+ ).toBeGreaterThanOrEqual(0);+ return found.index;+}++/**+ * Assert the readable viewport intersects real document content: text is painted+ * in the band, and the band's top edge sits at or above the content's bottom in+ * scroll coordinates. Both are read from the `.ProseMirror` box, never from+ * `scrollHeight`.+ */+function expectViewportOnContent(geometry: ScrollportGeometry, label: string): void {+ expect(+ geometry.viewportTop,+ `${label} — the viewport is parked past the end of the document: ${describeGeometry(label, geometry)}`,+ ).toBeLessThanOrEqual(geometry.contentBottom);+ expect(+ geometry.paintedProbes,+ `${label} — the viewport shows no document text: ${describeGeometry(label, geometry)}`,+ ).toBeGreaterThan(0);+}++/**+ * Drive the reported journey once and hand back the three geometries the+ * contracts are read from: the freshly opened document, the deep-scrolled+ * position the user navigates away from, and the position they return to.+ */+async function runTabCloseReturnScenario(+ page: Page,+ api: ApiHelpers,+ { docName, siblingName }: { docName: string; siblingName: string },+): Promise<{+ cold: ScrollportGeometry;+ beforeNav: ScrollportGeometry;+ afterReturn: ScrollportGeometry;+}> {+ const bottomMarker = `ZZBOTTOM-${docName}-ZZ`;+ const siblingMarker = `ZZSIBLING-${siblingName}-ZZ`;+ await api.seedDocs([+ { name: docName, markdown: buildTallBlockDoc({ linkTo: siblingName, bottomMarker }) },+ { name: siblingName, markdown: `# Sibling Target\n\nShort sibling body. ${siblingMarker}` },+ ]);++ await page.goto('/');+ await openFromSidebar(page, `${docName}.md`);+ await waitForActiveProviderSynced(page);+ await waitForPaintedDocText(page, bottomMarker);+ await waitForScrollSettled(page);++ // Read the freshly opened geometry before anything parks the drag handle:+ // whatever scrollable space sits past the content bottom here is the+ // document's own bottom padding, which makes the phantom-runway bound+ // self-calibrating against padding changes.+ const cold = await readScrollportGeometry(page);+ console.log(describeGeometry('cold-open', cold));++ await page.getByTestId('editor-scroll-container').first().hover();+ await scrollDeep(page);+ // Settle on a position where a link is reachable BEFORE parking the drag+ // handle, so the recorded pre-navigation geometry is the position the user+ // actually navigates away from.+ const chipIndex = await scrollUntilWikiLinkInBand(page);+ await hoverDeepBlock(page);++ const beforeNav = await readScrollportGeometry(page);+ console.log(describeGeometry('before-nav', beforeNav));+ expect(+ beforeNav.scrollTop,+ 'the wheel scroll did not reach deep content — the fixture is no longer tall enough to exercise the geometry collapse',+ ).toBeGreaterThan(5_000);+ expectViewportOnContent(beforeNav, 'before-nav');++ await page.locator('[data-wiki-link]').nth(chipIndex).click();+ await waitForPaintedDocText(page, siblingMarker);++ const tab = page.locator(`[data-editor-tab-id*="${siblingName}"]`).first();+ await tab.hover();+ await tab.getByTestId('editor-tab-close-button').first().click();+ await waitForPaintedDocText(page, bottomMarker);+ await waitForScrollSettled(page);++ const afterReturn = await readScrollportGeometry(page);+ console.log(describeGeometry('after-return', afterReturn));+ return { cold, beforeNav, afterReturn };+}++test.describe('editor scroll geometry tracks real document content', () => {+ test('PRD-8046: returning to a tall document after closing a sibling tab shows content', async ({+ page,+ api,+ }) => {+ test.setTimeout(150_000);+ const { afterReturn } = await runTabCloseReturnScenario(page, api, {+ docName: 'tall-progress-log',+ siblingName: 'tall-progress-sibling',+ });++ expectViewportOnContent(afterReturn, 'after-return');++ // The restore loop re-applies its target for several seconds; a landing that+ // is only briefly correct is still the bug, so re-check once the loop has had+ // time to move the viewport again. 90 animation frames (~1.5s at 60fps) is+ // the frame-accurate form: the loop's re-apply writes are rAF-scheduled, so+ // counting frames guarantees it had that many turns.+ await awaitAnimationFrames(page, 90);+ const settled = await readScrollportGeometry(page);+ console.log(describeGeometry('after-return+1.5s', settled));+ expectViewportOnContent(settled, 'after-return+1.5s (stability re-check)');+ });++ test('PRD-6953: editor chrome adds no scrollable space past the end of the document', async ({+ page,+ api,+ }) => {+ test.setTimeout(150_000);+ const { cold, afterReturn } = await runTabCloseReturnScenario(page, api, {+ docName: 'runway-progress-log',+ siblingName: 'runway-progress-sibling',+ });++ const baselineOverhang = Math.max(0, cold.scrollHeight - cold.contentBottom);+ // Scrollable space may legitimately reach the scrollport's own height even+ // for a document shorter than one screen; past that, only the document's own+ // bottom padding is allowed.+ const allowedScrollHeight =+ Math.max(afterReturn.clientHeight, afterReturn.contentBottom + baselineOverhang) ++ PHANTOM_RUNWAY_TOLERANCE_PX;+ expect(+ afterReturn.scrollHeight,+ `scrollable space extends past the document: ${describeGeometry('after-return', afterReturn)} (bottom padding baseline ${baselineOverhang}px). Editor chrome must not keep the scroller stretched past the content it sits over — the extra space is what lets a restored offset park the viewport on nothing.`,+ ).toBeLessThanOrEqual(allowedScrollHeight);+ });+});