Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): de-flake props-toggle scroll-preserve e2e (real restore defect) (#2955)
Nick Gomez98b716b8feda
diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsxindex 15c38c049..33bc0eb86 100644--- a/packages/app/src/components/EditorActivityPool.tsx+++ b/packages/app/src/components/EditorActivityPool.tsx@@ -65,6 +65,14 @@ import { EditorSkeleton } from './EditorSkeleton';import { PageHeader } from './PageHeader';import { usePageList } from './PageListContext';import { PropertyPanel } from './PropertyPanel';+import {+ computeRestoreTarget,+ hasLandedAt,+ isExternalScroll,+ measureAnchor,+ RESTORE_BACKSTOP_MS,+ shouldRecordScrollPosition,+} from './scroll-restore';import { Button } from './ui/button';// Lazy-loaded: the skill/template identity panel (+ SkillProperties /@@ -482,24 +490,19 @@ interface ActivityEntryProps {* (re-clamping scrollTop to 0), and the editor hydrates content* asynchronously after `'create'` — neither a single synchronous write* nor a one-shot ResizeObserver retry survives that race. The poll- * ends on the first user-scroll-intent signal (wheel / touchstart) or- * a 2 s safety timeout.- */-/**- * Position of `anchor` within `container`'s scroll content (distance from the- * content top), independent of the current scroll offset. Equals the total- * height ABOVE the anchor — page header + Properties section. Returns null when- * either element is missing so callers can skip anchor compensation.+ * ends on the first user-scroll-intent signal (wheel / touchstart /+ * mousedown / keydown), on an external scrollTop write (outline click,+ * find-in-doc — anything we didn't write), or a hard wall-clock+ * backstop. There is deliberately no early "settled" finalizer: a+ * finalized restore never corrects again, so finalizing ahead of a late+ * layout shift (contended hydration, panel settle, font swap) is how+ * transient churn used to freeze into a permanently wrong position.+ *+ * Anchor measurements are validity-guarded (see scroll-restore.ts): a+ * mounted-but-hidden anchor (a Suspense fallback window during a slow+ * reveal) yields NO target for that frame rather than a degenerate+ * viewport-origin measurement that self-amplifies per applied frame.*/-function measureAnchorContentPos(- container: HTMLElement,- anchor: HTMLElement | null | undefined,-): number | null {- if (!anchor) return null;- const cTop = container.getBoundingClientRect().top;- const aTop = anchor.getBoundingClientRect().top;- return aTop - cTop + container.scrollTop;-}/*** Per-document scroll position, stored as a BODY OFFSET (scrollTop minus the@@ -599,12 +602,18 @@ function ScrollPreservingContainer({// restore-in-progress (our own writes + panel-resize adjustments).if (!isActiveRef.current || isRestoringRef.current) return;if (el.scrollTop > 0) {+ const anchor = measureAnchor(el, bodyAnchorRef?.current);+ // A hidden (zero-rect) anchor means layout is mid-transition — any+ // scroll event on such a frame is churn, not user position. Recording+ // it would corrupt the save the same way it corrupts the restore.+ if (!shouldRecordScrollPosition(anchor)) return;savedScrollTop.current = el.scrollTop;- const anchor = measureAnchorContentPos(el, bodyAnchorRef?.current);- savedAnchorPos.current = anchor;+ savedAnchorPos.current = anchor.kind === 'measured' ? anchor.contentPos : null;// Persist the body-relative offset per doc so it survives a remount and// stays valid across Properties-panel height changes.- if (anchor !== null) rememberDocScrollOffset(docName, el.scrollTop - anchor);+ if (anchor.kind === 'measured') {+ rememberDocScrollOffset(docName, el.scrollTop - anchor.contentPos);+ }}};el.addEventListener('scroll', onScroll, { passive: true });@@ -626,10 +635,23 @@ function ScrollPreservingContainer({// and does not change when scrollHeight grows inside it. Polling reads// scrollHeight directly each frame — the signal we actually need.//- // Stop conditions: wheel / touchstart from the user (unambiguous- // scroll-intent signals — click-to-place-caret produces neither), or- // a 2 s safety timeout that covers the large-doc cold-mount + CRDT- // hydration window in dev.+ // Stop conditions: user scroll intent (wheel / touchstart / mousedown on+ // the scroller for scrollbar drags / keydown for keyboard scrolling), an+ // EXTERNAL scroll write (outline-click scrollIntoView, find-in-doc — any+ // scrollTop move we didn't make; see isExternalScroll), or the+ // `RESTORE_BACKSTOP_MS` hard backstop. There is deliberately NO+ // "settled" heuristic and NO short wall-clock finalizer: both finalize+ // before a late layout shift above the body (contended hydration, panel+ // settling, font swap), and a finalized restore never corrects again —+ // 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),+ // 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+ // other browser-side scrollTop mover, and with it off, any move we+ // didn't write is a reliable takeover signal.useLayoutEffect(() => {if (!isActive) return;const el = ref.current;@@ -648,54 +670,115 @@ function ScrollPreservingContainer({savedAnchorPos.current !== null ? rawTarget - savedAnchorPos.current : null;const bodyOffset: number | null = sharedOffset ?? instanceOffset;if (rawTarget === 0 && bodyOffset === null) return; // nothing to restore- const computeTarget = (): number => {- if (bodyOffset === null) return rawTarget;- const anchor = measureAnchorContentPos(el, bodyAnchorRef?.current);- return anchor === null ? rawTarget : anchor + bodyOffset;- };+ // 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));// 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;+ // Suspend CSS scroll anchoring for the loop's lifetime (restored in+ // finish). Two agents adjusting scrollTop for the same content shifts+ // fight each other, and with anchoring off, any scrollTop move we did+ // not write is a reliable someone-else-took-over signal.+ const priorOverflowAnchor = el.style.overflowAnchor;+ el.style.overflowAnchor = 'none';const startTs = performance.now();let phase2Marked = false;+ // True once the restore has landed on target at least once (Phase 1 or+ // Phase 2) — gates the `yielded` mark so a healthy restore followed by+ // user interaction doesn't read as an incomplete one.+ let hasLandedOnce = false;// Stage 1 — synchronous best-effort write. Mark phase1-success when it// 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();- el.scrollTop = target;- if (el.scrollTop === target && el.scrollHeight > target) {- mark('ok/scroll-restore/phase1-success', {- target,- elapsedMs: performance.now() - startTs,- });+ if (target !== null) {+ el.scrollTop = target;+ if (hasLandedAt(el.scrollTop, target) && el.scrollHeight > target) {+ hasLandedOnce = true;+ mark('ok/scroll-restore/phase1-success', {+ target,+ elapsedMs: performance.now() - startTs,+ });+ }}+ // The scrollTop as we left it — the baseline the external-scroll+ // detector compares against next frame.+ let prevScrollTop = el.scrollTop;- // Stage 2 — bounded per-frame re-apply.+ // Stage 2 — per-frame tracking until user intent, external scroll, or+ // backstop.let done = false;let raf = 0;const finish = () => {if (done) return;done = true;isRestoringRef.current = false; // re-enable user-scroll capture+ el.style.overflowAnchor = priorOverflowAnchor;cancelAnimationFrame(raf);clearTimeout(safetyTimer);- el.removeEventListener('wheel', onUserInterrupt);- el.removeEventListener('touchstart', onUserInterrupt);+ el.removeEventListener('wheel', yieldToUser);+ el.removeEventListener('touchstart', yieldToUser);+ el.removeEventListener('mousedown', yieldToUser);+ el.removeEventListener('keydown', yieldToUser);+ };+ // Any user input yields, deliberately including EVERY key: once the user+ // is interacting, enforcing a restore target against them is worse than+ // a small residual offset they are already overriding. Caret-driven+ // scrolls would also be caught next frame by the external-scroll check;+ // the listeners just yield a frame sooner.+ const yieldToUser = () => {+ if (!hasLandedOnce) {+ // A restore that never landed and then yielded is otherwise+ // invisible (no phase1/phase2-success, no abandoned) — surface it so+ // operators can distinguish "user took over" from "never ran".+ mark('ok/scroll-restore/yielded', {+ reason: 'user',+ elapsedMs: performance.now() - startTs,+ finalScrollTop: el.scrollTop,+ });+ }+ finish();};- const onUserInterrupt = () => finish();- el.addEventListener('wheel', onUserInterrupt, { passive: true });- el.addEventListener('touchstart', onUserInterrupt, { passive: true });+ el.addEventListener('wheel', yieldToUser, { passive: true });+ el.addEventListener('touchstart', yieldToUser, { passive: true });+ // mousedown covers scrollbar drags (they begin with a mousedown on the+ // scroller and produce neither wheel nor touchstart); keydown covers+ // keyboard scrolling once focus is inside.+ el.addEventListener('mousedown', yieldToUser);+ el.addEventListener('keydown', yieldToUser);const tick = () => {if (done) return;+ // An UPWARD scrollTop move we didn't write = someone else owns the+ // scroll now (outline-click scrollIntoView, find-in-doc). Yield+ // immediately — enforcing a stale target over an intentional scroll is+ // worse than any restore imprecision. Downward moves are shrink-clamps+ // to re-apply over (possibly against a transient collapsed height);+ // downward user takeovers arrive via the intent listeners above.+ if (isExternalScroll(prevScrollTop, el.scrollTop)) {+ if (!hasLandedOnce) {+ mark('ok/scroll-restore/yielded', {+ reason: 'external',+ elapsedMs: performance.now() - startTs,+ finalScrollTop: el.scrollTop,+ });+ }+ finish();+ return;+ }// Recompute from the current anchor so the target follows the Properties// section as it settles to its post-toggle height (see computeTarget).+ // 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 (el.scrollTop !== target && el.scrollHeight > target) {+ if (target !== null && !hasLandedAt(el.scrollTop, target) && el.scrollHeight > target) {el.scrollTop = target;- if (el.scrollTop === target && !phase2Marked) {+ if (hasLandedAt(el.scrollTop, 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', {@@ -703,34 +786,41 @@ function ScrollPreservingContainer({elapsedMs: performance.now() - startTs,});phase2Marked = true;+ hasLandedOnce = true;}}+ prevScrollTop = el.scrollTop;raf = requestAnimationFrame(tick);};raf = requestAnimationFrame(tick);const safetyTimer = setTimeout(() => {if (done) return;- // Fire `abandoned` based on final DOM state, not a historical- // success flag. The Phase 1 sync write can land then later be- // re-clamped to 0 by the Suspense warm-fallback → real-editor- // swap; if Stage 2 doesn't recover from that re-clamp within the- // 2 s window, the final state is wrong and the production- // telemetry must surface it. Also 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). User-scroll exits via- // `onUserInterrupt → finish` which clears the timer, so a- // scroll-away cannot trigger a false `abandoned` here.- if (el.scrollTop !== target && el.scrollHeight > target) {+ // 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();+ if (+ finalTarget === null ||+ (!hasLandedAt(el.scrollTop, finalTarget) && el.scrollHeight > finalTarget)+ ) {+ // `target` stays numeric across the ok/scroll-restore family (a+ // mixed number|string field silently NaNs any numeric aggregation);+ // the unmeasurable-anchor case is carried by `anchorMeasurable`+ // with `target` omitted.mark('ok/scroll-restore/abandoned', {- target,+ ...(finalTarget !== null ? { target: finalTarget } : {}),+ anchorMeasurable: finalTarget !== null,elapsedMs: performance.now() - startTs,scrollHeight: el.scrollHeight,finalScrollTop: el.scrollTop,});}finish();- }, 2000);+ }, RESTORE_BACKSTOP_MS);return finish;}, [isActive, bodyAnchorRef, docName]);diff --git a/packages/app/src/components/scroll-restore.test.ts b/packages/app/src/components/scroll-restore.test.tsnew file mode 100644index 000000000..3bea220cb--- /dev/null+++ b/packages/app/src/components/scroll-restore.test.ts@@ -0,0 +1,157 @@+import { describe, expect, test } from 'vitest';+import {+ computeRestoreTarget,+ hasLandedAt,+ isExternalScroll,+ measureAnchor,+ SCROLL_LANDING_TOLERANCE_PX,+ shouldRecordScrollPosition,+} from './scroll-restore';++/** Minimal layout fake: only the members measureAnchor reads. */+function fakeElement(opts: { rects: number; top?: number; scrollTop?: number }): HTMLElement {+ return {+ scrollTop: opts.scrollTop ?? 0,+ getClientRects: () => ({ length: opts.rects }) as DOMRectList,+ 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 });+ expect(measureAnchor(container, null)).toEqual({ kind: 'absent' });+ expect(measureAnchor(container, undefined)).toEqual({ kind: 'absent' });+ });++ test('anchor with no layout boxes (display:none / detached) is unmeasurable, never a viewport-origin measurement', () => {+ const container = fakeElement({ rects: 1, top: 56, scrollTop: 1200 });+ const hiddenAnchor = fakeElement({ rects: 0, top: 0 });+ expect(measureAnchor(container, hiddenAnchor)).toEqual({ kind: 'unmeasurable' });+ });++ test('laid-out anchor measures its content position (aTop - cTop + scrollTop)', () => {+ const container = fakeElement({ rects: 1, top: 56, scrollTop: 1205 });+ const anchor = fakeElement({ rects: 1, top: -722.40625 });+ expect(measureAnchor(container, anchor)).toEqual({+ kind: 'measured',+ contentPos: -722.40625 - 56 + 1205,+ });+ });++ test('a zero-height anchor that IS laid out still measures (h-0 divs generate a box)', () => {+ const container = fakeElement({ rects: 1, top: 0, scrollTop: 0 });+ const anchor = fakeElement({ rects: 1, top: 350 });+ expect(measureAnchor(container, anchor)).toEqual({ kind: 'measured', contentPos: 350 });+ });+});++describe('computeRestoreTarget', () => {+ test('no saved body offset restores the raw scrollTop regardless of anchor state', () => {+ expect(computeRestoreTarget(1200, null, { kind: 'measured', contentPos: 426 })).toBe(1200);+ expect(computeRestoreTarget(1200, null, { kind: 'unmeasurable' })).toBe(1200);+ expect(computeRestoreTarget(1200, null, { kind: 'absent' })).toBe(1200);+ });++ test('measured anchor keeps the body offset constant as the height above the body changes', () => {+ // Saved at scrollTop 1200 with 426px above the body -> offset 774. After+ // the Properties panel collapses (322px less above the body), the same+ // body content sits at scrollTop 878.+ expect(computeRestoreTarget(1200, 774, { kind: 'measured', contentPos: 426 })).toBe(1200);+ expect(computeRestoreTarget(1200, 774, { kind: 'measured', contentPos: 104 })).toBe(878);+ });++ test('unmeasurable anchor yields no target (hold) — NOT scrollTop-relative feedback', () => {+ // The regression this pins: a zero-rect anchor used to degenerate into+ // `scrollTop - containerTop`, making each applied frame raise the next+ // frame's target by ~the body offset until the scroller ran away from the+ // saved position. The only safe output for a degenerate frame is null.+ expect(computeRestoreTarget(1200, 774, { kind: 'unmeasurable' })).toBeNull();+ });++ test('anchor absent from the layout falls back to the raw saved scrollTop', () => {+ expect(computeRestoreTarget(1200, 774, { kind: 'absent' })).toBe(1200);+ });++ test('a zero body offset is a real offset, not "no offset"', () => {+ // 0 is stored when the user sat exactly at the anchor position. A+ // falsy-check drift (bodyOffset === null -> !bodyOffset) would silently+ // switch these to raw-scrollTop restores.+ expect(computeRestoreTarget(1200, 0, { kind: 'measured', contentPos: 426 })).toBe(426);+ expect(computeRestoreTarget(1200, 0, { kind: 'unmeasurable' })).toBeNull();+ });+});++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 the+ // scrollTop with a garbage anchor state and corrupts the saved body+ // offset the next restore relies on.+ expect(shouldRecordScrollPosition({ kind: 'unmeasurable' })).toBe(false);+ });++ test('measured and absent frames record normally', () => {+ expect(shouldRecordScrollPosition({ kind: 'measured', contentPos: 426 })).toBe(true);+ expect(shouldRecordScrollPosition({ kind: 'absent' })).toBe(true);+ });+});++describe('isExternalScroll', () => {+ test('an unchanged (or sub-tolerance) position is not external', () => {+ expect(isExternalScroll(1200, 1200)).toBe(false);+ expect(isExternalScroll(1200, 1200.5)).toBe(false);+ });++ test('an upward move of exactly the tolerance is not external (boundary is inclusive)', () => {+ // A <= -> < equivalent mutation here would make a legitimate 1px+ // per-frame anchor correction read as a takeover and end the loop one+ // pixel short.+ expect(isExternalScroll(1200, 1200 + SCROLL_LANDING_TOLERANCE_PX)).toBe(false);+ });++ test('an upward move we did not write is external (no browser-side explanation)', () => {+ expect(isExternalScroll(1200, 2600)).toBe(true);+ expect(isExternalScroll(0, 400)).toBe(true);+ });++ test('an upward move just above the tolerance IS external', () => {+ // Pins the > side of the boundary: a > -> >= drift would misclassify a+ // legitimate 1px anchor correction as a takeover.+ expect(isExternalScroll(1200, 1200 + SCROLL_LANDING_TOLERANCE_PX + 0.001)).toBe(true);+ });++ test('downward moves are never external — they can be shrink-clamps against a TRANSIENT height', () => {+ // The regression this pins: a fresh-mount hydration collapse clamps+ // scrollTop to 0 against a momentary small scrollHeight; by the next+ // (starved) frame the height has regrown, so no comparison against the+ // CURRENT maxScroll can tell this clamp from a takeover. Treating the+ // downward move as external stranded the rename-restore at 0 in CI.+ // Downward USER takeovers are caught by the intent listeners instead.+ expect(isExternalScroll(1330, 0)).toBe(false);+ expect(isExternalScroll(1200, 300)).toBe(false);+ expect(isExternalScroll(1200, 400)).toBe(false);+ });+});++describe('hasLandedAt', () => {+ test('integer-clamped scrollTop lands on a fractional target within tolerance', () => {+ // Observed in the wild: target 882.40625, scrollTop clamped to 882.+ expect(hasLandedAt(882, 882.40625)).toBe(true);+ });++ test('positions beyond the tolerance have not landed', () => {+ expect(hasLandedAt(880, 882.40625)).toBe(false);+ expect(hasLandedAt(882 + SCROLL_LANDING_TOLERANCE_PX + 0.5, 882)).toBe(false);+ });++ test('exact landing still lands', () => {+ expect(hasLandedAt(1200, 1200)).toBe(true);+ });++ test('a delta of exactly the tolerance lands (boundary is inclusive)', () => {+ // A <= -> < mutation here would leave the loop rewriting to the backstop+ // and never emit phase2-success.+ expect(hasLandedAt(882 + SCROLL_LANDING_TOLERANCE_PX, 882)).toBe(true);+ expect(hasLandedAt(882 - SCROLL_LANDING_TOLERANCE_PX, 882)).toBe(true);+ });+});diff --git a/packages/app/src/components/scroll-restore.ts b/packages/app/src/components/scroll-restore.tsnew file mode 100644index 000000000..b6dfbf550--- /dev/null+++ b/packages/app/src/components/scroll-restore.ts@@ -0,0 +1,148 @@+/**+ * Pure decision logic for ScrollPreservingContainer's restore loop+ * (EditorActivityPool.tsx). Extracted so the geometry/finalization rules are+ * unit-testable without mounting the pool.+ *+ * The restore contract: converge the scroller on the saved BODY offset using+ * only valid layout evidence, and yield only to user intent, an external+ * scroll, or the hard backstop. Two properties are load-bearing:+ *+ * 1. A mounted-but-not-laid-out anchor (display:none — e.g. while a+ * Suspense fallback replaces the committed children during a slow+ * reveal) reports a zero rect at the viewport origin. Treating that as a+ * measurement degenerates the anchor-relative target into+ * `scrollTop + offset - containerTop`, which self-amplifies on every+ * re-apply frame (each write raises scrollTop, which raises the next+ * target) until the scroller runs away from the saved position. Such+ * frames must yield NO target (hold), not a wrong one.+ *+ * 2. `scrollTop` is device-pixel-clamped while anchor-derived targets are+ * fractional, so exact equality between them can never be reached on+ * standard-DPR displays. Landing checks need a sub-pixel tolerance or+ * the loop rewrites forever and telemetry misclassifies an on-target+ * restore as abandoned.+ */++/** Anchor layout evidence for one frame. */+export type AnchorMeasurement =+ | { kind: 'measured'; contentPos: number }+ | { kind: 'unmeasurable' }+ | { kind: 'absent' };++/**+ * Position of `anchor` within `container`'s scroll content (distance from the+ * content top, independent of the current scroll offset) — the total height+ * ABOVE the anchor: page header + Properties section.+ *+ * `absent` = no anchor in this layout (caller falls back to the raw saved+ * scrollTop, compensation delta 0). `unmeasurable` = the anchor exists but+ * generates no layout boxes this frame (display:none / detached), so there is+ * no valid measurement — callers must hold rather than compute from the zero+ * rect (property 1 above).+ */+export function measureAnchor(+ container: HTMLElement,+ anchor: HTMLElement | null | undefined,+): AnchorMeasurement {+ if (!anchor) return { kind: 'absent' };+ if (anchor.getClientRects().length === 0) return { kind: 'unmeasurable' };+ const cTop = container.getBoundingClientRect().top;+ const aTop = anchor.getBoundingClientRect().top;+ return { kind: 'measured', contentPos: aTop - cTop + container.scrollTop };+}++/**+ * The scrollTop the restore should apply this frame, or `null` to hold+ * (no valid evidence this frame — do not write).+ *+ * With no saved body offset, or with no anchor in the layout at all, the raw+ * saved scrollTop is the restore basis (legacy behavior). With a body offset+ * and a measured anchor, the target keeps the body offset constant as the+ * height above the body changes.+ */+export function computeRestoreTarget(+ rawTarget: number,+ bodyOffset: number | null,+ anchor: AnchorMeasurement,+): number | null {+ if (bodyOffset === null) return rawTarget;+ switch (anchor.kind) {+ case 'measured':+ return anchor.contentPos + bodyOffset;+ case 'absent':+ return rawTarget;+ case 'unmeasurable':+ return null;+ default:+ return assertNever(anchor);+ }+}++/**+ * 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 the+ * anchor is transiently hidden pairs the scrollTop with a missing/garbage+ * anchor measurement and corrupts the saved body offset the next restore+ * relies on.+ */+export function shouldRecordScrollPosition(anchor: AnchorMeasurement): boolean {+ switch (anchor.kind) {+ case 'measured':+ case 'absent':+ return true;+ case 'unmeasurable':+ return false;+ default:+ return assertNever(anchor);+ }+}++function assertNever(value: never): never {+ throw new Error(`Unhandled AnchorMeasurement variant: ${JSON.stringify(value)}`);+}++/**+ * Sub-pixel landing tolerance (property 2 above): browsers clamp scrollTop to+ * device pixels, so a fractional target is "reached" within one CSS pixel.+ */+export const SCROLL_LANDING_TOLERANCE_PX = 1;++export function hasLandedAt(scrollTop: number, target: number): boolean {+ return Math.abs(scrollTop - target) <= SCROLL_LANDING_TOLERANCE_PX;+}++/**+ * True when the scroller moved between our frames in a way only an external+ * scroller could produce — a programmatic scrollIntoView (outline click,+ * find-in-doc) or a user scroll not caught by the intent listeners. Such a+ * move is a "someone else owns the scroll now" signal and must end the+ * restore immediately; fighting it re-applies a stale target over an+ * intentional scroll.+ *+ * Direction is the discriminator. The browser's shrink-clamp — the one+ * non-external scrollTop mover left once the caller suspends CSS scroll+ * anchoring — can only ever move scrollTop DOWN, and it can happen against a+ * TRANSIENT height (the Suspense warm-fallback -> editor swap collapses+ * scrollHeight and re-grows it within a frame under contention), so a+ * downward move can never be attributed reliably: comparing against the+ * current maxScroll misreads a stale clamp as a takeover and strands the+ * restore at the clamped position. Downward moves are therefore treated as+ * re-clamps to re-apply over (downward USER takeovers are caught by the+ * wheel/touch/mousedown/keydown listeners). An upward move we didn't write+ * has no browser-side explanation and is external.+ */+export function isExternalScroll(prevScrollTop: number, scrollTop: number): boolean {+ return scrollTop - prevScrollTop > SCROLL_LANDING_TOLERANCE_PX;+}++/**+ * Hard wall-clock backstop for the restore loop. Not a finalizer in the+ * design sense — user intent and external scrolls are the normal exits — but+ * a guarantee that a doc whose anchor never becomes measurable again+ * re-enables user scroll capture eventually. Long deliberately: the loop+ * finalizing while layout is still churning is precisely how a transient+ * degenerate window used to freeze into a permanently wrong position, so the+ * backstop must comfortably exceed any contended hydration + panel-settle+ * window rather than approximate a typical one.+ */+export const RESTORE_BACKSTOP_MS = 10_000;diff --git a/packages/app/src/lib/perf/mark.ts b/packages/app/src/lib/perf/mark.tsindex 383b28cf3..ef7d86cd2 100644--- a/packages/app/src/lib/perf/mark.ts+++ b/packages/app/src/lib/perf/mark.ts@@ -8,7 +8,7 @@** Naming convention: `ok/<subsystem>/<event>` where subsystem is* one of `nav`, `sync`, `activity`, `render`, `editor`, `sidebar`, `outline`,- * `vitals`, `mount`, `cold`, `startup`. `validatePerfMarkName` is a dev-only lint of the+ * `vitals`, `mount`, `cold`, `startup`, `scroll-restore`. `validatePerfMarkName` is a dev-only lint of the* shape; it `console.warn`s in dev and returns silently so emission is always* best-effort.*diff --git a/packages/app/tests/stress/docs-open-scroll-restore.e2e.ts b/packages/app/tests/stress/docs-open-scroll-restore.e2e.tsindex a54a7c4c1..13780befe 100644--- a/packages/app/tests/stress/docs-open-scroll-restore.e2e.ts+++ b/packages/app/tests/stress/docs-open-scroll-restore.e2e.ts@@ -31,12 +31,13 @@* deferred reparent + ProseMirror inflations land at ~250 ms, the next* rAF tick re-applies `scrollTop = target` and emits* `ok/scroll-restore/phase2-success`. The poll detects the restored- * position well before the 2 s safety timer → PASS.+ * position well before the restore's wall-clock backstop → PASS.*- * Test polling window (450 ms) is intentionally BELOW the 2000 ms- * production safety timer that fires `ok/scroll-restore/abandoned` when- * Stage 2 never landed. A regression that breaks the rAF-poll path but- * is masked by some other late write would restore at >= 2 s with a+ * Test polling window (450 ms) is intentionally FAR BELOW the production+ * wall-clock backstop (RESTORE_BACKSTOP_MS, 10 s) that fires+ * `ok/scroll-restore/abandoned` when Stage 2 never landed. A regression+ * that breaks the rAF-poll path but is masked by some other late write+ * would restore seconds late with a* user-perceptible scroll bounce — that is a UX regression, not a* successful fallback. This test treats it as a failure to specifically* pin the rAF-poll mechanism that delivers the "no perceptible delay"@@ -213,9 +214,10 @@ test.describe('docs-open-scroll-restore — F1 RED (deterministic via portal-app).toBeGreaterThan(0);// STEP 8 — the user-facing contract: scroll position must be restored- // after the warm-reopen, well before the 2000 ms safety timer that- // production uses to abandon Stage 2 if rAF-poll never lands. Polling- // window (450 ms) is deliberately far below 2 s — the rAF-poll must do+ // after the warm-reopen, well before the wall-clock backstop+ // (RESTORE_BACKSTOP_MS) that production uses to abandon Stage 2 if+ // rAF-poll never lands. Polling window (450 ms) is deliberately far+ // below it — the rAF-poll must do// the work. Patch defers appendChild by 250 ms, so the next rAF tick// re-applies scrollTop at ~260 ms, giving ~190 ms slack within the// 450 ms window. (450 ms vs original 400 ms: the extra 50 ms absorbsdiff --git a/packages/app/tests/stress/props-toggle-scroll-preserve.e2e.ts b/packages/app/tests/stress/props-toggle-scroll-preserve.e2e.tsindex 705f0366e..b8d71c578 100644--- a/packages/app/tests/stress/props-toggle-scroll-preserve.e2e.ts+++ b/packages/app/tests/stress/props-toggle-scroll-preserve.e2e.ts@@ -13,7 +13,7 @@* to A leaves the SAME body content at the SAME viewport position, while A's* panel does reflect the shared collapse (proving the state stayed live).*/-import type { Page } from '@playwright/test';+import type { Locator, Page } from '@playwright/test';import { expect, test, waitForActiveProviderSynced } from './_helpers';async function openFromSidebar(page: Page, filename: string) {@@ -22,6 +22,40 @@ async function openFromSidebar(page: Page, filename: string) {await row.click();}+/**+ * Wait until the scroller's content height stops changing (~300ms stable,+ * bounded at ~10s). The oracle snapshot below must be taken on SETTLED+ * content: while late paragraphs are still hydrating, content growth+ * triggers browser scroll-anchoring adjustments that legitimately shift+ * scrollTop (and fire scroll events the product records as the user's+ * position). A snapshot taken mid-hydration goes stale the moment such an+ * adjustment lands — the restore then faithfully preserves the ADJUSTED+ * position, and the assertion fails by exactly the adjustment delta.+ */+async function waitForStableScrollHeight(scroller: Locator) {+ const stabilized = await scroller.evaluate(async (el) => {+ let last = -1;+ let stable = 0;+ for (let i = 0; i < 200 && stable < 6; i += 1) {+ await new Promise((r) => setTimeout(r, 50));+ if (el.scrollHeight === last) stable += 1;+ else {+ stable = 0;+ last = el.scrollHeight;+ }+ }+ return stable >= 6;+ });+ // Distinguish a timed-out stabilization from a genuine restore regression+ // in CI logs: a failure right after this warning means the snapshot below+ // may itself be unsettled (re-triage the hydration path, not the restore).+ if (!stabilized) {+ console.warn(+ '[props-toggle e2e] scrollHeight never stabilized within 10s; snapshot may be unsettled',+ );+ }+}+const FM = `---type: daily-notedescription: A description@@ -60,10 +94,12 @@ test('Properties toggle on another doc preserves scroll on return (shared + scro(el) => el.getBoundingClientRect().height,);- // Scroll doc A into its body and record the body marker's viewport position.+ // Scroll doc A into its body and record the body marker's viewport position+ // — on settled content only (see waitForStableScrollHeight).const scroller = page.getByTestId('editor-scroll-container').filter({ hasText: 'Doc A Bottom Marker' });+ await waitForStableScrollHeight(scroller);await scroller.evaluate((el) => el.scrollTo({ top: 1200, behavior: 'instant' }));const markerTopBefore = await bodyMarker(page).evaluate((el) => el.getBoundingClientRect().top);