Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): stop the agent follow-scroll hijacking a visible change (#4108)
Nick Gomeze2f881bb9544
diff --git a/.changeset/agent-follow-scroll-visible-change.md b/.changeset/agent-follow-scroll-visible-change.mdnew file mode 100644index 000000000..596d60267--- /dev/null+++ b/.changeset/agent-follow-scroll-visible-change.md@@ -0,0 +1,11 @@+---+"@inkeep/open-knowledge": patch+---++Opening a document an agent had just written no longer throws you into the middle of it.++When an agent writes a file, the editor flashes what changed and, if Follow file is on, scrolls that change into view. It picked the scroll target by taking the midpoint of the changed range. For a small edit the midpoint is the edit, so that worked. For a whole-file write, which is what creating or rewriting a file produces, the changed range is the entire document and its midpoint is just the arithmetic middle: a place where nothing in particular happened. Opening such a file within a few seconds of the write, without clicking into the editor first, scrolled you to that arbitrary spot instead of leaving you at the top.++The follow-scroll now asks whether any part of the change is already on screen, rather than whether the midpoint alone is, and it asks it against the region you can actually read: the editor's scroll container inset by the toolbar at the top and the Ask AI composer at the bottom, rather than the raw window. A change you can already see is not chased, so a whole-file write leaves your position alone, while an agent edit below the fold is still scrolled toward as it was before. How precisely that scroll lands is unchanged, and for an edit far outside the part of the document currently rendered it can still leave you well away from the edit rather than on it.++Two changes worth naming: a change that is only partly on screen is now left in place rather than recentred, and a change whose only overlap with the window sits behind the toolbar or the composer now counts as hidden rather than visible, so it is followed.diff --git a/packages/app/package.json b/packages/app/package.jsonindex 3e59fa2e2..6da6fdab5 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -29,7 +29,7 @@"measure:stress": "bash scripts/measure-stress.sh","measure:sweep": "bash scripts/measure-sweep.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts",+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/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","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/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsxindex 4ea057648..c1112ed2e 100644--- a/packages/app/src/editor/TiptapEditor.tsx+++ b/packages/app/src/editor/TiptapEditor.tsx@@ -50,6 +50,7 @@ import { mark } from '@/lib/perf';import { wrapExtensionsWithTiming } from '@/lib/perf/cold-mount-instrumentation';import { useIdentity } from '../presence/identity';import { registerEditor, unregisterEditor } from './active-editor';+import { changedRangeIsOnScreen } from './agent-follow-scroll';import { applyLintFixes } from './apply-lint-fix.ts';import { getAwarenessHeartbeat } from './awareness-heartbeat-runtime';import { buildAwarenessUser } from './awareness-user';@@ -99,6 +100,7 @@ import {} from './source-editor-navigation';import { TableCellHandles } from './table-controls/TableCellHandles';import { attachTypingBurstDetector } from './typing-burst-detector';+import { editorVisibleBand } from './utils/editor-visible-region';import { getEditorView } from './utils/get-editor-view';import { walkCurrencyExtension } from './walk-currency-extension';@@ -904,25 +906,41 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({if (!loadFollowFilePref()) return;if (document.visibilityState !== 'visible') return;if (view.hasFocus()) return;- const scrollToChange = (): void => {- const sv = liveView();- if (sv == null || sv.hasFocus() || document.visibilityState !== 'visible') return;- if (isScrollRestoreSuppressed(docName)) return;+ const elementAtPos = (sv: PMEditorView, pos: number): HTMLElement | null => {try {- const docSize = sv.state.doc.content.size;- const pos = Math.max(0, Math.min(Math.floor((from + to) / 2), docSize - 1));const domRef = sv.domAtPos(pos);const node = domRef.node;const raw =node.nodeType === Node.TEXT_NODE? node.parentElement: (node.childNodes[domRef.offset] ?? node);- const el = raw instanceof HTMLElement ? raw : (raw?.parentElement ?? null);- if (el == null) return;- const rect = el.getBoundingClientRect();- if (rect.top >= 0 && rect.bottom <= window.innerHeight) return;- el.scrollIntoView({ block: 'center', behavior: 'smooth' });- } catch {}+ return raw instanceof HTMLElement ? raw : (raw?.parentElement ?? null);+ } catch {+ return null;+ }+ };+ const scrollToChange = (): void => {+ const sv = liveView();+ if (sv == null || sv.hasFocus() || document.visibilityState !== 'visible') return;+ if (isScrollRestoreSuppressed(docName)) return;+ const docSize = sv.state.doc.content.size;+ const clamp = (pos: number): number => Math.max(0, Math.min(pos, docSize - 1));+ let start: { top: number; bottom: number };+ let end: { top: number; bottom: number };+ try {+ start = sv.coordsAtPos(clamp(from));+ end = sv.coordsAtPos(clamp(to));+ } catch {+ return;+ }+ const range = {+ top: Math.min(start.top, end.top),+ bottom: Math.max(start.bottom, end.bottom),+ };+ if (changedRangeIsOnScreen(range, editorVisibleBand(editor))) return;+ const target = elementAtPos(sv, clamp(Math.floor((from + to) / 2)));+ if (target === null) return;+ target.scrollIntoView({ block: 'center', behavior: 'smooth' });};requestAnimationFrame(scrollToChange);followUpTimers.push(diff --git a/packages/app/src/editor/agent-follow-scroll.test.ts b/packages/app/src/editor/agent-follow-scroll.test.tsnew file mode 100644index 000000000..e4ed120dd--- /dev/null+++ b/packages/app/src/editor/agent-follow-scroll.test.ts@@ -0,0 +1,58 @@+import { describe, expect, test } from 'vitest';+import { changedRangeIsOnScreen } from './agent-follow-scroll';++const REGION = { top: 56, bottom: 700 };++describe('changedRangeIsOnScreen', () => {+ test('a change spanning past both edges of the region is on screen', () => {+ expect(changedRangeIsOnScreen({ top: -12_000, bottom: 20_000 }, REGION)).toBe(true);+ });++ test('a whole-document change is on screen while the reader sits at the top', () => {+ expect(changedRangeIsOnScreen({ top: 60, bottom: 20_000 }, REGION)).toBe(true);+ });++ test('a change resting fully inside the region is on screen', () => {+ expect(changedRangeIsOnScreen({ top: 100, bottom: 140 }, REGION)).toBe(true);+ });++ test('a change below the region is not on screen', () => {+ expect(changedRangeIsOnScreen({ top: 20_000, bottom: 20_050 }, REGION)).toBe(false);+ });++ test('a change above the region is not on screen', () => {+ expect(changedRangeIsOnScreen({ top: -900, bottom: -850 }, REGION)).toBe(false);+ });++ test('a change hidden behind the toolbar band is not on screen', () => {+ expect(changedRangeIsOnScreen({ top: 10, bottom: 50 }, REGION)).toBe(false);+ });++ test('a change hidden behind the composer band is not on screen', () => {+ expect(changedRangeIsOnScreen({ top: 720, bottom: 760 }, REGION)).toBe(false);+ });++ test('a change straddling the toolbar edge is on screen', () => {+ expect(changedRangeIsOnScreen({ top: 20, bottom: 80 }, REGION)).toBe(true);+ });++ test('a change straddling the composer edge is on screen', () => {+ expect(changedRangeIsOnScreen({ top: 680, bottom: 740 }, REGION)).toBe(true);+ });++ test('a region starting at the viewport top still excludes content above it', () => {+ expect(changedRangeIsOnScreen({ top: -40, bottom: -10 }, { top: 0, bottom: 700 })).toBe(false);+ });++ test('a collapsed band stands down only for a range that straddles it', () => {+ const collapsed = { top: 300, bottom: 300 };+ expect(changedRangeIsOnScreen({ top: 280, bottom: 320 }, collapsed)).toBe(true);+ expect(changedRangeIsOnScreen({ top: 400, bottom: 450 }, collapsed)).toBe(false);+ expect(changedRangeIsOnScreen({ top: 100, bottom: 150 }, collapsed)).toBe(false);+ });++ test('unmeasurable geometry reports on-screen so the reader is never yanked on a guess', () => {+ expect(changedRangeIsOnScreen({ top: Number.NaN, bottom: Number.NaN }, REGION)).toBe(true);+ expect(changedRangeIsOnScreen({ top: 0, bottom: Number.POSITIVE_INFINITY }, REGION)).toBe(true);+ });+});diff --git a/packages/app/src/editor/agent-follow-scroll.ts b/packages/app/src/editor/agent-follow-scroll.tsnew file mode 100644index 000000000..939243b9b--- /dev/null+++ b/packages/app/src/editor/agent-follow-scroll.ts@@ -0,0 +1,9 @@+interface VerticalExtent {+ top: number;+ bottom: number;+}++export function changedRangeIsOnScreen(range: VerticalExtent, region: VerticalExtent): boolean {+ if (!Number.isFinite(range.top) || !Number.isFinite(range.bottom)) return true;+ return range.bottom > region.top && range.top < region.bottom;+}diff --git a/packages/app/src/editor/utils/editor-visible-region.dom.test.tsx b/packages/app/src/editor/utils/editor-visible-region.dom.test.tsxindex fdc9cf813..678d6cd23 100644--- a/packages/app/src/editor/utils/editor-visible-region.dom.test.tsx+++ b/packages/app/src/editor/utils/editor-visible-region.dom.test.tsx@@ -6,6 +6,7 @@ import {deriveEditorClipOptions,deriveEditorShiftOptions,deriveEditorSizeOptions,+ editorVisibleBand,} from './editor-visible-region';function renderEditorInScroller(): { editor: Editor; scroller: HTMLElement } {@@ -260,3 +261,38 @@ describe('deriveEditorSizeOptions', () => {expect(floating.style.maxWidth).toBe('');});});++function stubRect(el: HTMLElement, top: number, bottom: number): void {+ el.getBoundingClientRect = () => new DOMRect(0, top, 0, bottom - top);+}++describe('editorVisibleBand', () => {+ test('keeps both insets for a pre-mount editor', () => {+ document.documentElement.style.setProperty('--ask-composer-height', `${COMPOSER_HEIGHT_PX}px`);+ const band = editorVisibleBand(preMountEditor());+ expect(band.top).toBe(TOOLBAR_HEIGHT);+ expect(band.bottom).toBe(window.innerHeight - COMPOSER_HEIGHT_PX);+ });++ test('insets the container box by the toolbar and composer bands', () => {+ const { editor, scroller } = renderEditorInScroller();+ stubRect(scroller, 0, 800);+ document.documentElement.style.setProperty('--ask-composer-height', `${COMPOSER_HEIGHT_PX}px`);+ const band = editorVisibleBand(editor);+ expect(band.top).toBe(TOOLBAR_HEIGHT);+ expect(band.bottom).toBe(800 - COMPOSER_HEIGHT_PX);+ });++ test('collapses rather than inverting when the insets exceed the pane', () => {+ const { editor, scroller } = renderEditorInScroller();+ stubRect(scroller, 0, 200);+ document.documentElement.style.setProperty('--ask-composer-height', `${COMPOSER_HEIGHT_PX}px`);+ document.documentElement.style.setProperty(+ '--conflict-footer-height',+ `${CONFLICT_FOOTER_HEIGHT_PX}px`,+ );+ const band = editorVisibleBand(editor);+ expect(band.bottom).toBeGreaterThanOrEqual(band.top);+ expect(band.bottom).toBe(band.top);+ });+});diff --git a/packages/app/src/editor/utils/editor-visible-region.ts b/packages/app/src/editor/utils/editor-visible-region.tsindex bf00528b8..aaa73ea15 100644--- a/packages/app/src/editor/utils/editor-visible-region.ts+++ b/packages/app/src/editor/utils/editor-visible-region.ts@@ -77,6 +77,13 @@ export function deriveEditorClipOptions(editor: Editor): () => EditorClipOptions};}+export function editorVisibleBand(editor: Editor): { top: number; bottom: number } {+ const { boundary, padding } = deriveEditorClipOptions(editor)();+ const box = boundary?.getBoundingClientRect() ?? { top: 0, bottom: window.innerHeight };+ const top = box.top + padding.top;+ return { top, bottom: Math.max(top, box.bottom - padding.bottom) };+}+function resolveRegionBoundary(editor: Editor): Element | null {return getEditorView(editor)?.dom.closest('.editor-doc-scroll') ?? null;}diff --git a/packages/app/tests/stress/_helpers/index.ts b/packages/app/tests/stress/_helpers/index.tsindex e06d3ef84..6c562c2b3 100644--- a/packages/app/tests/stress/_helpers/index.ts+++ b/packages/app/tests/stress/_helpers/index.ts@@ -24,6 +24,7 @@ export {readSourceCaretHead,readWysiwygCaretHead,scrollWysiwygBlockToTop,+ TOOLBAR_OVERLAP_PX,toggleMode,waitForLandingSettled,} from './landing.ts';diff --git a/packages/app/tests/stress/_helpers/landing.ts b/packages/app/tests/stress/_helpers/landing.tsindex 220b601c1..5417dcf19 100644--- a/packages/app/tests/stress/_helpers/landing.ts+++ b/packages/app/tests/stress/_helpers/landing.ts@@ -8,7 +8,7 @@ const SCROLL_CONTAINER_SELECTOR = '[data-testid="editor-scroll-container"]';const WYSIWYG_SELECTOR = '.ProseMirror:not(.composer-prosemirror)';const SOURCE_SELECTOR = '.cm-editor';const CHUNK_WRAPPER_SELECTOR = `${WYSIWYG_SELECTOR} .ok-chunk-wrapper`;-const TOOLBAR_OVERLAP_PX = 56;+export const TOOLBAR_OVERLAP_PX = 56;const MODE_RADIO_NAME: Record<LandingMode, string> = {wysiwyg: 'Visual editor',diff --git a/packages/app/tests/stress/_helpers/scrollport.ts b/packages/app/tests/stress/_helpers/scrollport.tsindex 77b3f1583..39a007f93 100644--- a/packages/app/tests/stress/_helpers/scrollport.ts+++ b/packages/app/tests/stress/_helpers/scrollport.ts@@ -1,6 +1,5 @@import type { Page } from '@playwright/test';--const TOOLBAR_OVERLAP_PX = 56;+import { TOOLBAR_OVERLAP_PX } from './landing.ts';interface ScrollportContainmentOptions {toolbarPx?: number;diff --git a/packages/app/tests/stress/agent-follow-scroll.e2e.ts b/packages/app/tests/stress/agent-follow-scroll.e2e.tsnew file mode 100644index 000000000..1c0eaf340--- /dev/null+++ b/packages/app/tests/stress/agent-follow-scroll.e2e.ts@@ -0,0 +1,217 @@+import { randomUUID } from 'node:crypto';+import type { Page } from '@playwright/test';+import {+ type ApiHelpers,+ blockMarker,+ expect,+ generateTallDoc,+ scrollWysiwygBlockToTop,+ TOOLBAR_OVERLAP_PX,+ test,+ waitForActiveProviderSynced,+} from './_helpers';++const WYSIWYG = '.ProseMirror:not(.composer-prosemirror)';+const FLASH = '.ok-agent-insert-flash';+const EDGE_EPSILON_PX = 3;+const BLOCK_COUNT = 400;+const READING_AT = 150;+const OFFSCREEN_EDIT_AT = 320;+const LANDING_TOLERANCE_BLOCKS = 120;+const SEED_STUB = 'seed';++type FlashWindow = {+ __okFlashSeen?: boolean;+ __okRearmFlashWatch?: () => void;+ __okReadableFlash?: () => boolean;+};++function docName(label: string): string {+ return `agent-follow-scroll-${label}-${randomUUID().slice(0, 8)}`;+}++function bumpBlock(markdown: string, marker: string): string {+ const needle = `**${marker}** `;+ const at = markdown.indexOf(needle);+ if (at === -1) throw new Error(`bumpBlock: ${marker} not found`);+ const charAt = at + needle.length;+ const swapped = markdown[charAt] === markdown[charAt].toUpperCase() ? 'x' : 'X';+ return `${markdown.slice(0, charAt)}${swapped}${markdown.slice(charAt + 1)}`;+}++async function watchFlash(page: Page): Promise<void> {+ await page.addInitScript(() => {+ const w = window as unknown as FlashWindow;+ w.__okFlashSeen = false;+ const readableFlash = (): boolean => {+ const clip = Array.from(+ document.querySelectorAll<HTMLElement>('[data-testid="editor-scroll-container"]'),+ ).find((el) => el.getClientRects().length > 0);+ return clip?.querySelector('.ok-agent-insert-flash') != null;+ };+ w.__okReadableFlash = readableFlash;+ const options = {+ subtree: true,+ childList: true,+ attributes: true,+ attributeFilter: ['class'],+ };+ const observer = new MutationObserver(() => {+ if (!readableFlash()) return;+ w.__okFlashSeen = true;+ observer.disconnect();+ });+ w.__okRearmFlashWatch = () => observer.observe(document, options);+ observer.observe(document, options);+ });+}++async function openTallDoc(+ page: Page,+ api: ApiHelpers,+ name: string,+): Promise<{ markdown: string }> {+ const { markdown } = generateTallDoc({ blockCount: BLOCK_COUNT });+ const warmName = `${name}-warm`;+ await api.seedDocs([+ { name, markdown: SEED_STUB },+ { name: warmName, markdown: SEED_STUB },+ ]);+ await api.testReset(warmName);+ await watchFlash(page);++ await page.goto(`/#/${warmName}`);+ await waitForActiveProviderSynced(page);+ await expect(page.locator(WYSIWYG).first()).toBeVisible();++ await armFlashWatch(page);+ await api.writeAsAgent(warmName, `${SEED_STUB} warm`, {+ agentId: 'warm-agent',+ agentName: 'WarmAgent',+ });+ await drainFlash(page, 'the warm document');++ await armFlashWatch(page);+ await api.writeAsAgent(name, markdown, { agentId: 'seed-agent', agentName: 'SeedAgent' });+ await page.goto(`/#/${name}`);+ await waitForActiveProviderSynced(page);+ await expect(page.locator(WYSIWYG).first()).toBeVisible();+ return { markdown };+}++async function topReadableMarker(page: Page): Promise<string | null> {+ return page.evaluate(+ ([insetPx, epsilonPx]) => {+ const clip = Array.from(+ document.querySelectorAll<HTMLElement>('[data-testid="editor-scroll-container"]'),+ ).find((el) => el.getClientRects().length > 0);+ if (clip === undefined) return null;+ const clipRect = clip.getBoundingClientRect();+ const readableTop = clipRect.top + insetPx;+ for (const w of Array.from(clip.querySelectorAll<HTMLElement>('.ok-chunk-wrapper'))) {+ if (w.getClientRects().length === 0) continue;+ const r = w.getBoundingClientRect();+ if (r.bottom > readableTop + epsilonPx && r.top < clipRect.bottom) {+ return (w.textContent ?? '').match(/OKBLK\d+/)?.[0] ?? null;+ }+ }+ return null;+ },+ [TOOLBAR_OVERLAP_PX, EDGE_EPSILON_PX] as const,+ );+}++function markerIndex(marker: string | null): number {+ return marker === null ? Number.NaN : Number(marker.replace('OKBLK', ''));+}++async function armFlashWatch(page: Page): Promise<void> {+ await expect(+ page.locator(FLASH),+ 'a prior agent-flash decoration was still attached when the watch re-armed',+ ).toHaveCount(0);+ await page.evaluate(() => {+ const w = window as unknown as FlashWindow;+ const rearm = w.__okRearmFlashWatch;+ if (rearm === undefined)+ throw new Error('armFlashWatch: the flash watcher was never installed');+ w.__okFlashSeen = false;+ rearm();+ });+}++async function drainFlash(page: Page, subject: string): Promise<void> {+ await expect+ .poll(+ async () =>+ page.evaluate(() => {+ const w = window as unknown as FlashWindow;+ const readable = w.__okReadableFlash;+ if (readable === undefined)+ throw new Error('drainFlash: the flash watcher was never installed');+ return w.__okFlashSeen === true && !readable();+ }),+ { message: `the agent-flash replay for ${subject} never both fired and cleared` },+ )+ .toBe(true);+}++test('opening a document an agent just wrote leaves the reader at the top', async ({+ page,+ api,+}) => {+ const name = docName('open-after-write');+ await openTallDoc(page, api, name);++ await drainFlash(page, 'the document under test');++ expect(+ await topReadableMarker(page),+ 'opening a freshly agent-written document scrolled the reader into its middle',+ ).toBe(blockMarker(0));+});++test('a document-spanning agent write leaves a reader where they already were', async ({+ page,+ api,+}) => {+ const name = docName('spanning');+ const { markdown } = await openTallDoc(page, api, name);+ await drainFlash(page, 'the document under test');++ await scrollWysiwygBlockToTop(page, blockMarker(READING_AT));+ const before = await topReadableMarker(page);+ expect(before, 'setup did not park the reader on the anchor block').toBe(blockMarker(READING_AT));++ await armFlashWatch(page);+ const spanning = bumpBlock(bumpBlock(markdown, blockMarker(0)), blockMarker(BLOCK_COUNT - 1));+ await api.writeAsAgent(name, spanning, { agentId: 'follow-probe', agentName: 'FollowProbe' });++ await drainFlash(page, 'the document under test');++ const after = await topReadableMarker(page);+ expect(after, `a whole-document agent write scrolled the reader from ${before} to ${after}`).toBe(+ before,+ );+});++test('an agent write below the fold is still followed toward', async ({ page, api }) => {+ const name = docName('offscreen');+ const { markdown } = await openTallDoc(page, api, name);+ await drainFlash(page, 'the document under test');++ await scrollWysiwygBlockToTop(page, blockMarker(0));+ expect(await topReadableMarker(page), 'setup did not park the reader at the top').toBe(+ blockMarker(0),+ );++ const edited = bumpBlock(markdown, blockMarker(OFFSCREEN_EDIT_AT));+ await api.writeAsAgent(name, edited, { agentId: 'follow-probe', agentName: 'FollowProbe' });++ await expect+ .poll(async () => Math.abs(markerIndex(await topReadableMarker(page)) - OFFSCREEN_EDIT_AT), {+ message:+ 'the follow-scroll did not bring the reader near the off-screen agent write; the received value is how many blocks it missed by',+ })+ .toBeLessThanOrEqual(LANDING_TOLERANCE_BLOCKS);+});