Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): keep the end-of-document line visible as the Ask AI composer grows (PRD-8578) (#4272)

serafin-garcia18fa0057df3a
diff --git a/.changeset/composer-growth-keeps-last-line-visible.md b/.changeset/composer-growth-keeps-last-line-visible.md
new file mode 100644
index 000000000..aa00307c8
--- /dev/null
+++ b/.changeset/composer-growth-keeps-last-line-visible.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+The Ask AI composer no longer covers the last line of a document as it grows.
+
+Typing a long prompt at the end of any file the editor opens in a text view (`.ts`, `.py`, `.json`, `.yaml`, `.txt` and the rest), or of a `.mmd` or `.mermaid` diagram in source mode, used to let the growing composer cover the line the caret was on. The composer reserved room at the bottom of those editors but the scroll position did not follow it, so the last line slid underneath. It now stays above the composer.
diff --git a/packages/app/package.json b/packages/app/package.json
index e014a6c1f..3fd81d389 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-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts",
+ "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-collapse-persistence.e2e.ts tests/stress/file-tree-fractional-zoom.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/source-undo-mode-flip.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/agent-follow-scroll.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/cv-auto-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts tests/stress/skills-sidebar-open.e2e.ts tests/stress/trailing-affordance.e2e.ts tests/stress/text-doc-composer-inset.e2e.ts tests/stress/agents-settings-accessible-names.e2e.ts tests/stress/composer-growth-eof-reveal.e2e.ts",
"test:e2e:install-browsers": "playwright install chromium webkit firefox",
"test:visual": "playwright test --config playwright.visual.config.ts",
"test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",
diff --git a/packages/app/src/components/BottomComposer.dom.test.tsx b/packages/app/src/components/BottomComposer.dom.test.tsx
index 231f8e0dd..da9b0b4cf 100644
--- a/packages/app/src/components/BottomComposer.dom.test.tsx
+++ b/packages/app/src/components/BottomComposer.dom.test.tsx
@@ -240,6 +240,7 @@ vi.doMock('@/comments/comment-chips', async () => {
const FIRST_SUGGESTION = /Research the extinction of flightless birds/i;
const DEFAULT_AGENT_NAME = VISIBLE_TARGETS[0]?.displayName;
+const EXPECTED_COMPOSER_POPUP_LABELS = ['composer-mention', 'composer-slash'] as const;
const ALL_INSTALLED: Record<string, { installed: boolean | null }> = {
'claude-cowork': { installed: false },
@@ -573,6 +574,22 @@ describe('BottomComposer (dispatch + picker + sticky default)', () => {
expect(dispatchCalls[0]?.target).toBe('codex');
});
+ test('the agent menu carries the marker the scroll clamp treats as composer-owned', async () => {
+ const user = userEvent.setup();
+ await renderComposer();
+
+ await user.click(screen.getByTestId('ask-ai-agent-trigger'));
+ const menu = await screen.findByTestId('ask-ai-agent-menu');
+
+ expect(
+ menu.closest('[data-composer-portal]'),
+ 'the menu is a Radix popper that renders outside the card, so the clamp cannot recognise ' +
+ 'it by containment and matches this marker instead. Matching the generic ' +
+ '[data-radix-popper-content-wrapper] instead would exempt every popper in the app, so the ' +
+ "composer's own menu has to be marked at the call site",
+ ).not.toBeNull();
+ });
+
test('picking an in-app agent launches a thread and persists the choice', async () => {
registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
const user = userEvent.setup();
@@ -1331,3 +1348,321 @@ describe('BottomComposer (queued-comments chip lifecycle)', () => {
expect(screen.getByRole('button', { name: DETACH })).toBeTruthy();
});
});
+
+describe('BottomComposer (end-of-document scroll compensation)', () => {
+ const planted: HTMLElement[] = [];
+
+ function plantScrollport(scrollTop: number): { el: HTMLElement; writes: number[] } {
+ const el = document.createElement('div');
+ el.className = 'editor-doc-scroll';
+ const writes: number[] = [];
+ let current = scrollTop;
+ Object.defineProperty(el, 'scrollHeight', { value: 1000, configurable: true });
+ Object.defineProperty(el, 'clientHeight', { value: 600, configurable: true });
+ Object.defineProperty(el, 'scrollTop', {
+ configurable: true,
+ get: () => current,
+ set: (next: number) => {
+ current = next;
+ writes.push(next);
+ },
+ });
+ document.body.appendChild(el);
+ planted.push(el);
+ return { el, writes };
+ }
+
+ function plantPortal(attributes: Record<string, string>): HTMLElement {
+ const portal = document.createElement('div');
+ for (const [name, value] of Object.entries(attributes)) portal.setAttribute(name, value);
+ const row = document.createElement('button');
+ row.type = 'button';
+ portal.appendChild(row);
+ document.body.appendChild(portal);
+ planted.push(portal);
+ return row;
+ }
+
+ let nowSpy: ReturnType<typeof vi.spyOn> | null = null;
+
+ const nextFrame = () =>
+ act(async () => {
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ });
+
+ beforeEach(() => {
+ nowSpy = vi.spyOn(performance, 'now').mockReturnValue(0);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ nowSpy?.mockRestore();
+ nowSpy = null;
+ for (const el of planted.splice(0)) el.remove();
+ });
+
+ test('clamps only the scrollport the reader had already parked at its end', async () => {
+ const nearEnd = plantScrollport(380);
+ const midDocument = plantScrollport(100);
+
+ await renderComposer();
+ await nextFrame();
+
+ expect(
+ nearEnd.writes,
+ 'a reader already at the end of the document has to be carried down as the card grows, ' +
+ 'which is the whole compensation this component performs',
+ ).not.toHaveLength(0);
+ expect(
+ nearEnd.el.scrollTop,
+ 'the clamp target is `scrollHeight - clientHeight`, 1000 - 600 here, and the reader started ' +
+ 'at 380 — inside the 40px slack but not at the end. Writing back the position already ' +
+ 'held under-clamps by the difference, which the e2e oracle tolerates up to the resting ' +
+ 'clearance',
+ ).toBe(400);
+ expect(
+ midDocument.writes,
+ 'a scrollport parked mid-document must be left alone. Dropping the pinned filter turns ' +
+ 'every composer resize into a scroll-jack to the end of every enumerated surface',
+ ).toHaveLength(0);
+ });
+
+ test('stops clamping once the 300ms compensation budget is spent', async () => {
+ const atEnd = plantScrollport(380);
+
+ await renderComposer();
+ await nextFrame();
+ const beforeDeadline = atEnd.writes.length;
+ expect(beforeDeadline).not.toBe(0);
+
+ nowSpy?.mockReturnValue(301);
+ await nextFrame();
+ await nextFrame();
+
+ expect(
+ atEnd.writes.length,
+ 'without the elapsed-time exit the compensator stops being a burst that tracks one card ' +
+ 'resize and becomes a permanent clamp, holding every pinned scrollport at its end for the ' +
+ 'life of the mount and fighting every programmatic scroll that fires none of the four ' +
+ 'cancel events — CodeMirror reveal, outline navigation, find-jump, scroll restore',
+ ).toBe(beforeDeadline);
+ });
+
+ const CANCEL_EVENTS = [
+ ['keydown', (target: HTMLElement) => fireEvent.keyDown(target, { key: 'PageUp' })],
+ ['mousedown', (target: HTMLElement) => fireEvent.mouseDown(target)],
+ ['wheel', (target: HTMLElement) => fireEvent.wheel(target, { deltaY: 64 })],
+ ['touchstart', (target: HTMLElement) => fireEvent.touchStart(target)],
+ ] as const;
+
+ test.each(CANCEL_EVENTS)(
+ 'a %s outside the card cancels the clamp, one inside it does not',
+ async (eventName, fire) => {
+ const atEnd = plantScrollport(400);
+
+ await renderComposer();
+ await nextFrame();
+ const beforeInside = atEnd.writes.length;
+ expect(beforeInside).not.toBe(0);
+
+ fire(getInput());
+ await nextFrame();
+ expect(
+ atEnd.writes.length,
+ `driving the composer is what grows the card, so a ${eventName} inside it must not stop ` +
+ 'the clamp that tracks the growth',
+ ).toBeGreaterThan(beforeInside);
+
+ const beforeOutside = atEnd.writes.length;
+ fire(document.body);
+ await nextFrame();
+ await nextFrame();
+ expect(
+ atEnd.writes.length,
+ `a ${eventName} outside the card is the reader taking over the scroll, so without it in ` +
+ 'the cancel set the clamp fights them for the rest of its 300ms budget',
+ ).toBe(beforeOutside);
+ },
+ );
+
+ test.each(CANCEL_EVENTS)(
+ 'a %s in a composer-owned portal keeps the clamp, the same event in a document popup cancels it',
+ async (eventName, fire) => {
+ const atEnd = plantScrollport(400);
+ const composerPortalRow = plantPortal({
+ 'data-radix-popper-content-wrapper': '',
+ 'data-composer-portal': '',
+ });
+ const documentPopupRow = plantPortal({ 'data-suggestion-popup': 'tag-suggestion' });
+
+ await renderComposer();
+ await nextFrame();
+ const beforePortal = atEnd.writes.length;
+ expect(beforePortal).not.toBe(0);
+
+ fire(composerPortalRow);
+ await nextFrame();
+ expect(
+ atEnd.writes.length,
+ `the composer's own agent menu is portalled out of the card, so a ${eventName} inside it ` +
+ 'is still the author driving the composer and must not stop the clamp that tracks the ' +
+ 'growth that click causes',
+ ).toBeGreaterThan(beforePortal);
+
+ const beforeDocumentPopup = atEnd.writes.length;
+ fire(documentPopupRow);
+ await nextFrame();
+ await nextFrame();
+ expect(
+ atEnd.writes.length,
+ `a ${eventName} in the document body's own tag/slash/wiki-link popup is the reader ` +
+ 'working in the document, not in the composer. Matching bare [data-suggestion-popup] ' +
+ 'or bare [data-radix-popper-content-wrapper] exempts every popup and every Radix ' +
+ 'surface in the app, so the clamp keeps forcing pinned scrollports to their end while ' +
+ 'the reader interacts with something else entirely',
+ ).toBe(beforeDocumentPopup);
+ },
+ );
+
+ test('the composer portal exemption covers exactly the popups the composer owns', async () => {
+ const { COMPOSER_SUGGESTION_POPUP_LABELS } = await import('./BottomComposer');
+ expect(
+ [...COMPOSER_SUGGESTION_POPUP_LABELS].toSorted(),
+ 'this list is the whole definition of which suggestion popups the clamp treats as the ' +
+ "author's own surface. Dropping a member silently reclassifies a popup the composer owns " +
+ 'as a foreign surface, so picking a row in it cancels the clamp and drops the last line ' +
+ 'back under the growing card. The per-label cases below also cover that direction. Each ' +
+ 'row still plants its own popup, so dropping a member from production reds there too. ' +
+ 'What only this equality catches is production growing past this expectation, which then ' +
+ 'gets no case of its own, and this expectation shrinking below production. An edit that ' +
+ 'drops a label from both lists at once is invisible to both, which is why membership ' +
+ 'stays a judgment call',
+ ).toEqual([...EXPECTED_COMPOSER_POPUP_LABELS].toSorted());
+ });
+
+ test.each(EXPECTED_COMPOSER_POPUP_LABELS)(
+ 'a mousedown in the %s popup keeps the clamp, because the composer owns that popup',
+ async (label) => {
+ const atEnd = plantScrollport(400);
+ const composerPopupRow = plantPortal({ 'data-suggestion-popup': label });
+
+ await renderComposer();
+ await nextFrame();
+ const before = atEnd.writes.length;
+ expect(before).not.toBe(0);
+
+ fireEvent.mouseDown(composerPopupRow);
+ await nextFrame();
+ await nextFrame();
+ expect(
+ atEnd.writes.length,
+ `the ${label} popup is the composer's own suggestion menu, portalled to the body rather ` +
+ 'than nested in the card, so picking a row in it is the author driving the composer. ' +
+ 'A selector fragment that no longer matches this label silently reclassifies a popup ' +
+ 'the composer owns as a foreign surface and cancels the clamp on the click that grows ' +
+ 'the card',
+ ).toBeGreaterThan(before);
+ },
+ );
+
+ test('a dep change mid-burst supersedes the in-flight clamp instead of stacking a second loop on it', async () => {
+ const atEnd = plantScrollport(400);
+ const { BottomComposer } = await import('./BottomComposer');
+ const { rerender } = await renderComposer();
+ await nextFrame();
+ expect(atEnd.writes.length).not.toBe(0);
+
+ rerender(<BottomComposer docName="notes" surface="wysiwyg" dismissed />);
+ await nextFrame();
+
+ const beforeSettleFrame = atEnd.writes.length;
+ await nextFrame();
+ expect(
+ atEnd.writes.length - beforeSettleFrame,
+ 'React tears the old effect down before it sets the new one up, and the destructor runs a ' +
+ 'settle pass for the collapsing card. If the disposal token lives inside the effect ' +
+ 'callback the incoming run starts blind to that settle pass, so dismiss, reopen, a ' +
+ 'markdown-mode toggle and a document switch each leave a second per-frame writer and a ' +
+ 'second set of four window listeners on the same scrollport. The token has to outlive a ' +
+ 'single effect run for the incoming run to supersede the outgoing one',
+ ).toBe(1);
+ });
+
+ test('unmounting supersedes the in-flight clamp instead of stacking a second loop on it', async () => {
+ const atEnd = plantScrollport(400);
+
+ const { unmount } = await renderComposer();
+ await nextFrame();
+ expect(atEnd.writes.length).not.toBe(0);
+
+ unmount();
+ await nextFrame();
+
+ const beforeSettleFrame = atEnd.writes.length;
+ await nextFrame();
+ expect(
+ atEnd.writes.length - beforeSettleFrame,
+ 'the destructor runs a settle pass for the collapsing card, so it must first dispose the ' +
+ 'burst it is replacing. Without a shared disposal token both loops keep writing, so every ' +
+ 'unmount and every coalesced resize adds another window listener set and another writer ' +
+ 'to the same scrollport',
+ ).toBe(1);
+
+ nowSpy?.mockReturnValue(301);
+ await nextFrame();
+ const afterDeadline = atEnd.writes.length;
+ await nextFrame();
+ expect(
+ atEnd.writes.length,
+ 'the post-unmount settle pass is a burst like any other, so it has to stop writing at the ' +
+ 'same 300ms deadline rather than owning the scrollport for the life of the page',
+ ).toBe(afterDeadline);
+ });
+
+ test('unmounting a dismissed composer releases the settle clamp instead of leaving it ownerless', async () => {
+ const atEnd = plantScrollport(400);
+ const { BottomComposer } = await import('./BottomComposer');
+ const { rerender, unmount } = await renderComposer();
+ await nextFrame();
+ rerender(<BottomComposer docName="notes" surface="wysiwyg" dismissed />);
+ await nextFrame();
+ unmount();
+ await nextFrame();
+ const afterUnmount = atEnd.writes.length;
+ await nextFrame();
+ await nextFrame();
+ expect(
+ atEnd.writes.length,
+ 'the collapsed branch installs a clamp of its own, four window listeners, a per-frame ' +
+ 'writer and a 400ms backstop, so unmounting out of it has to release the token. Without ' +
+ 'a destructor the burst keeps pinning live document scrollports after the component is gone',
+ ).toBe(afterUnmount);
+ });
+
+ test('the 400ms backstop tears the clamp down when the elapsed-time deadline never arms', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ const atEnd = plantScrollport(400);
+
+ await renderComposer();
+ await nextFrame();
+ expect(atEnd.writes.length).not.toBe(0);
+
+ act(() => {
+ vi.advanceTimersByTime(400);
+ });
+
+ const afterBackstop = atEnd.writes.length;
+ await nextFrame();
+ await nextFrame();
+ expect(
+ atEnd.writes.length,
+ 'the elapsed-time deadline only arms once the clock advances, and a clock that never ' +
+ 'advances is exactly the case where a frozen tab, a paused debugger or a machine that ' +
+ 'stops painting leaves the burst alive. The 400ms timer is the wall-clock backstop that ' +
+ 'ends it anyway, so without it the four window listeners and the per-frame writer outlive ' +
+ 'the card resize they were installed for. This case holds performance.now at 0 so the ' +
+ 'deadline arm cannot fire, and fakes only setTimeout and clearTimeout so that jsdom, ' +
+ 'which drives requestAnimationFrame off setInterval, keeps producing real frames',
+ ).toBe(afterBackstop);
+ });
+});
diff --git a/packages/app/src/components/BottomComposer.tsx b/packages/app/src/components/BottomComposer.tsx
index 78581fe3a..7f034fa35 100644
--- a/packages/app/src/components/BottomComposer.tsx
+++ b/packages/app/src/components/BottomComposer.tsx
@@ -2,6 +2,7 @@
import { type TargetData, TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
+import type { EditorView } from '@tiptap/pm/view';
import { ArrowUpRight, ChevronDown, TextQuote, X } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
@@ -38,6 +39,12 @@ import {
ComposerMentionInput,
type ComposerMentionInputHandle,
} from '@/editor/ComposerMentionInput';
+import {
+ DOCUMENT_SCROLL_HOST_SELECTOR,
+ documentScrollports,
+ isPinnedToEnd,
+} from '@/editor/document-scrollports';
+import type { SuggestionPopupLabel } from '@/editor/extensions/suggestion-floating-ui';
import { isScrollRestoreSuppressed } from '@/editor/scroll-restore-coordination';
import {
lightRenderMarkdownPreview,
@@ -47,6 +54,7 @@ import {
} from '@/editor/selection-context';
import type { EditorSurface } from '@/editor/selection-stats';
import { useComposerAttachments } from '@/editor/use-composer-attachments';
+import { getEditorView } from '@/editor/utils/get-editor-view';
import { useConflictComposerPrefill } from '@/hooks/use-conflict-composer-prefill';
import { useReducedMotion } from '@/hooks/use-reduced-motion';
import { useSelectionContext } from '@/hooks/use-selection-context';
@@ -127,6 +135,28 @@ function useRotatingSuggestion(
return { text: phrases[safeIndex] ?? '', visible };
}
+const COMPOSER_PORTAL_ATTRIBUTE = 'data-composer-portal';
+const COMPOSER_PORTAL_ATTRIBUTES = { [COMPOSER_PORTAL_ATTRIBUTE]: '' } as const;
+export const COMPOSER_SUGGESTION_POPUP_LABELS = [
+ 'composer-mention',
+ 'composer-slash',
+] as const satisfies readonly SuggestionPopupLabel[];
+const COMPOSER_PORTAL_SELECTOR = [
+ ...COMPOSER_SUGGESTION_POPUP_LABELS.map((label) => `[data-suggestion-popup="${label}"]`),
+ `[${COMPOSER_PORTAL_ATTRIBUTE}]`,
+].join(',');
+
+function safeCaretCoords(
+ view: EditorView,
+ pos: number,
+): ReturnType<EditorView['coordsAtPos']> | null {
+ try {
+ return view.coordsAtPos(pos);
+ } catch {
+ return null;
+ }
+}
+
export function BottomComposer({
docName,
surface,
@@ -164,6 +194,7 @@ export function BottomComposer({
inputRef,
);
const cardRef = useRef<HTMLDivElement>(null);
+ const clampRef = useRef<(() => void) | null>(null);
const [initialDraftDoc] = useState(() => getComposerDraft().doc ?? undefined);
@@ -186,56 +217,78 @@ export function BottomComposer({
useEffect(() => {
if (folderMode || docName == null) return;
const root = document.documentElement;
+ let caretFrame: number | null = null;
const followBottom = () => {
+ clampRef.current?.();
if (isScrollRestoreSuppressed(docName)) return;
- const pinned = [...document.querySelectorAll<HTMLElement>('.editor-doc-scroll')].filter(
- (el) => {
- const max = el.scrollHeight - el.clientHeight;
- return max > 0 && el.scrollTop >= max - 40;
- },
- );
+ const pinned = documentScrollports().filter(isPinnedToEnd);
if (pinned.length === 0) return;
let cancelled = false;
- const cancel = () => {
+ let frame: number | null = null;
+ let backstop: ReturnType<typeof setTimeout> | null = null;
+ const cancelIfOutsideCard = (event: Event) => {
+ const target = event.target as Node | null;
+ if (target === null) return;
+ if (cardRef.current?.contains(target)) return;
+ if (target instanceof Element && target.closest(COMPOSER_PORTAL_SELECTOR) !== null) return;
+ cancelled = true;
+ };
+ const dispose = () => {
cancelled = true;
+ if (frame !== null) cancelAnimationFrame(frame);
+ frame = null;
+ if (backstop !== null) clearTimeout(backstop);
+ backstop = null;
+ window.removeEventListener('wheel', cancelIfOutsideCard);
+ window.removeEventListener('touchstart', cancelIfOutsideCard);
+ window.removeEventListener('mousedown', cancelIfOutsideCard);
+ window.removeEventListener('keydown', cancelIfOutsideCard);
+ if (clampRef.current === dispose) clampRef.current = null;
};
- window.addEventListener('wheel', cancel, { passive: true });
- window.addEventListener('touchstart', cancel, { passive: true });
+ clampRef.current = dispose;
+ window.addEventListener('wheel', cancelIfOutsideCard, { passive: true });
+ window.addEventListener('touchstart', cancelIfOutsideCard, { passive: true });
+ window.addEventListener('mousedown', cancelIfOutsideCard);
+ window.addEventListener('keydown', cancelIfOutsideCard);
+ backstop = setTimeout(dispose, 400);
const start = performance.now();
const step = () => {
+ frame = null;
if (isScrollRestoreSuppressed(docName)) cancelled = true;
if (cancelled || performance.now() - start >= 300) {
- window.removeEventListener('wheel', cancel);
- window.removeEventListener('touchstart', cancel);
+ dispose();
return;
}
for (const el of pinned) el.scrollTop = el.scrollHeight - el.clientHeight;
- requestAnimationFrame(step);
+ frame = requestAnimationFrame(step);
};
- requestAnimationFrame(step);
+ frame = requestAnimationFrame(step);
};
const revealCaret = () => {
- if (surface !== 'wysiwyg') return;
- requestAnimationFrame(() => {
+ if (effectiveSurface !== 'wysiwyg') return;
+ caretFrame = requestAnimationFrame(() => {
+ caretFrame = null;
if (isScrollRestoreSuppressed(docName)) return;
const editor = getEditorForDoc(docName);
const box = cardRef.current;
if (!editor || editor.isDestroyed || !box) return;
- try {
- const view = editor.view;
- const caret = view.coordsAtPos(editor.state.selection.head);
- const overlap = caret.bottom - (box.getBoundingClientRect().top - 28);
- if (overlap <= 0) return;
- const scroller = view.dom.closest('.editor-doc-scroll');
- if (scroller instanceof HTMLElement) scroller.scrollTop += overlap;
- } catch {}
+ const view = getEditorView(editor);
+ if (!view) return;
+ const caret = safeCaretCoords(view, view.state.selection.head);
+ if (caret === null) return;
+ const overlap = caret.bottom - (box.getBoundingClientRect().top - 28);
+ if (overlap <= 0) return;
+ const scroller = view.dom.closest(DOCUMENT_SCROLL_HOST_SELECTOR);
+ if (scroller instanceof HTMLElement) scroller.scrollTop += overlap;
});
};
const card = cardRef.current;
if (dismissed || !card) {
followBottom();
root.style.removeProperty('--ask-composer-height');
- return;
+ return () => {
+ clampRef.current?.();
+ };
}
const apply = () => {
followBottom();
@@ -247,10 +300,12 @@ export function BottomComposer({
observer.observe(card);
return () => {
observer.disconnect();
+ if (caretFrame !== null) cancelAnimationFrame(caretFrame);
+ caretFrame = null;
followBottom();
root.style.removeProperty('--ask-composer-height');
};
- }, [dismissed, surface, docName, folderMode]);
+ }, [dismissed, effectiveSurface, docName, folderMode]);
const dismissedRef = useRef(dismissed);
const onReopenRef = useRef(onReopen);
@@ -765,7 +820,7 @@ export function BottomComposer({
</span>
{selectionExpanded && pinnedPreview !== '' ? (
<p
- className="max-h-24 w-full basis-full overflow-y-auto whitespace-pre-wrap text-2xs text-muted-foreground/80 subtle-scrollbar"
+ className="max-h-24 w-full basis-full overflow-y-auto overscroll-contain whitespace-pre-wrap text-2xs text-muted-foreground/80 subtle-scrollbar"
data-testid="composer-selection-preview"
>
{pinnedPreview}
@@ -836,7 +891,7 @@ export function BottomComposer({
onMentionsChange={setInlineMentions}
onSubmit={submit}
initialDoc={initialDraftDoc}
- className="max-h-[200px] overflow-y-auto text-base md:text-sm"
+ className="max-h-[200px] overflow-y-auto overscroll-contain text-base md:text-sm"
/>
{}
{isEmpty ? (
@@ -917,6 +972,7 @@ export function BottomComposer({
)}
</p>
}
+ menuAttributes={COMPOSER_PORTAL_ATTRIBUTES}
triggerAriaLabel={t`Choose agent`}
testIds={{
primary: 'ask-ai-send',
diff --git a/packages/app/src/components/ConflictView.dom.test.tsx b/packages/app/src/components/ConflictView.dom.test.tsx
index a03d381dd..5cd0752b4 100644
--- a/packages/app/src/components/ConflictView.dom.test.tsx
+++ b/packages/app/src/components/ConflictView.dom.test.tsx
@@ -5,6 +5,7 @@ import { act, cleanup, render, screen } from '@testing-library/react';
import axe from 'axe-core';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, test, vi } from 'vitest';
+import { documentScrollports } from '@/editor/document-scrollports';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
vi.doMock('@lingui/react/macro', () => ({
@@ -547,3 +548,23 @@ describe('ConflictView — word-level highlighting inside conflicts', () => {
expect(await spanCount(2, true)).toBe(0);
});
});
+
+describe('ConflictView scroll compensation', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('the conflict scroller is enumerated by the Ask AI composer scroll compensator', async () => {
+ await renderConflictView();
+
+ const scroller = document.querySelector('.conflict-view');
+ expect(scroller).not.toBeNull();
+ expect(
+ documentScrollports(),
+ 'the composer re-clamps the scrollports `documentScrollports` returns, and it finds this ' +
+ 'one by class name alone. Renaming the wrapper here drops a live inset surface from that ' +
+ 'set, burying the last hunks and their inline Accept/Reject controls under the card with ' +
+ 'every other test still green',
+ ).toContain(scroller);
+ });
+});
diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsx
index f4395a1c8..ed19f6fbe 100644
--- a/packages/app/src/components/EditorActivityPool.tsx
+++ b/packages/app/src/components/EditorActivityPool.tsx
@@ -23,6 +23,7 @@ import {
import { createPortal } from 'react-dom';
import { Spinner } from '@/components/ui/spinner';
import { type PoolEntrySnapshot, useDocumentContext } from '@/editor/DocumentContext';
+import { DOCUMENT_SCROLL_HOST_CLASS } from '@/editor/document-scrollports';
import { peekRenameSnapshot, setActivityMountList } from '@/editor/editor-cache';
import { isSystemDoc } from '@/editor/is-system-doc';
import { clearMountId, getMountId, setMountId } from '@/editor/mount-id-registry';
@@ -637,7 +638,7 @@ export function ScrollPreservingContainer({
ref={ref}
data-testid="editor-scroll-container"
className={cn(
- 'editor-doc-scroll subtle-scrollbar h-full overflow-y-auto',
+ `${DOCUMENT_SCROLL_HOST_CLASS} subtle-scrollbar h-full overflow-y-auto`,
isNoteWindow() || !hasToolbar ? 'pt-0 scroll-pt-0' : 'pt-14 scroll-pt-14',
)}
style={{ overflowAnchor: 'auto' }}
diff --git a/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx b/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx
new file mode 100644
index 000000000..fd4f15082
--- /dev/null
+++ b/packages/app/src/components/EditorArea.composer-surface.dom.test.tsx
@@ -0,0 +1,176 @@
+import { cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { ConfigProvider } from '@/lib/config-provider';
+
+type EditorMode = 'wysiwyg' | 'source';
+
+function docCtxFor(docName: string) {
+ return {
+ activeDocName: docName,
+ activeProvider: { configuration: { name: docName } } as never,
+ activeTarget: { kind: 'doc' as const, target: docName, docName },
+ activeNewTabId: null,
+ recycleDocument: () => {},
+ closeActivityPanel: () => {},
+ docPanelMode: 'timeline',
+ docPanelAgentId: null,
+ docPanelExpandSignal: 0,
+ };
+}
+
+let docCtx: ReturnType<typeof docCtxFor> = docCtxFor('notes/example.ts');
+let selectionStatsSurfaces: string[] = [];
+
+vi.doMock('@/lib/perf', () => ({
+ mark: () => {},
+ ProfilerBoundary: ({ children }: { children: ReactNode }) => children,
+}));
+vi.doMock('@/components/PropertyContext', () => ({
+ PropertyProvider: ({ children }: { children: ReactNode }) => children,
+ useProperties: () => ({ requestAddProperty: () => {} }),
+}));
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => docCtx,
+ useDocumentTransition: () => ({ openDocumentTransition: null }),
+ isBlobRunnerNewTabId: () => false,
+}));
+vi.doMock('@/hooks/use-document-stats', () => ({ useDocumentStats: () => null }));
+vi.doMock('@/hooks/use-selection-stats', () => ({
+ useSelectionStats: (_activeDocName: string | null, surface: string) => {
+ selectionStatsSurfaces.push(surface);
+ return null;
+ },
+}));
+vi.doMock('@/hooks/use-lifecycle-status', () => ({ useLifecycleStatus: () => 'ready' }));
+vi.doMock('@/presence/use-sync-status', () => ({ useSyncStatus: () => 'synced' }));
+vi.doMock('@/lib/use-settings-route', () => ({
+ useSettingsRoute: () => ({ open: false, close: () => {} }),
+ SETTINGS_OPEN_HASH: '#settings',
+ isSettingsShortcut: () => false,
+}));
+vi.doMock('@/components/settings/SettingsDialogShell', () => ({
+ SettingsDialogShell: () => <div data-testid="settings-shell" />,
+}));
+vi.doMock('@/components/EditorSkeleton', () => ({
+ EditorSkeleton: () => <div data-testid="editor-skeleton" />,
+}));
+vi.doMock('@/components/EmptyEditorState', () => ({
+ EmptyEditorState: () => <div data-testid="empty-editor-state" />,
+}));
+vi.doMock('./TerminalDock', () => ({
+ TerminalDock: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+vi.doMock('./EditorWorkspace', () => ({
+ EditorWorkspace: ({
+ renderPane,
+ }: {
+ renderPane: (context: {
+ pane: { id: string };
+ isFocused: boolean;
+ activityDocName: string | null;
+ }) => ReactNode;
+ }) =>
+ renderPane({
+ pane: { id: 'pane-test' },
+ isFocused: true,
+ activityDocName: null,
+ }),
+}));
+vi.doMock('react-resizable-panels', () => ({
+ usePanelRef: () => ({ current: { collapse: () => {}, expand: () => {} } }),
+ useGroupRef: () => ({ current: { getLayout: () => [], setLayout: () => {} } }),
+}));
+vi.doMock('@/components/ui/resizable', () => ({
+ ResizablePanelGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ ResizablePanel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ ResizableHandle: () => <div />,
+}));
+vi.doMock('./EditorActivityPool', () => ({
+ EditorActivityPool: () => <div data-testid="editor-pool" />,
+}));
+vi.doMock('@/editor/find-replace/FindReplaceController', () => ({
+ FindReplaceController: () => null,
+}));
+vi.doMock('./EditorToolbar', () => ({
+ EditorToolbar: () => <div data-testid="editor-toolbar" />,
+}));
+vi.doMock('./EditorFooter', () => ({ EditorFooter: () => <div data-testid="editor-footer" /> }));
+vi.doMock('./editor-area-overlay', () => ({ shouldPaintOverlay: () => false }));
+vi.doMock('@/components/DocPanel', () => ({ DocPanel: () => <div data-testid="doc-panel" /> }));
+vi.doMock('./BottomComposer', () => ({
+ BottomComposer: ({ surface }: { surface?: string }) => (
+ <div data-testid="bottom-composer" data-surface={surface ?? ''} />
+ ),
+}));
+
+const { EditorArea } = await import('./EditorArea');
+
+function renderEditorArea(editorMode: EditorMode) {
+ return render(
+ <ConfigProvider collabUrl={null}>
+ <EditorArea
+ editorMode={editorMode}
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ />
+ </ConfigProvider>,
+ );
+}
+
+function composerSurfaceFor(docName: string, editorMode: EditorMode): string {
+ cleanup();
+ docCtx = docCtxFor(docName);
+ renderEditorArea(editorMode);
+ return screen.getByTestId('bottom-composer').getAttribute('data-surface') ?? '';
+}
+
+function footerSelectionSurfaceFor(docName: string, editorMode: EditorMode): string {
+ cleanup();
+ docCtx = docCtxFor(docName);
+ selectionStatsSurfaces = [];
+ renderEditorArea(editorMode);
+ const surface = selectionStatsSurfaces.at(-1);
+ if (surface === undefined) throw new Error('EditorArea never asked for selection stats');
+ return surface;
+}
+
+describe('EditorArea derives an editing surface from the document, not the markdown mode toggle', () => {
+ beforeEach(() => cleanup());
+ afterEach(() => cleanup());
+
+ test('a markdown document takes its composer surface from the mode toggle', () => {
+ expect(composerSurfaceFor('notes/example', 'wysiwyg')).toBe('wysiwyg');
+ expect(composerSurfaceFor('notes/example', 'source')).toBe('source');
+ });
+
+ test('a markdown document takes its selection-stats surface from the mode toggle', () => {
+ expect(footerSelectionSurfaceFor('notes/example', 'wysiwyg')).toBe('wysiwyg');
+ expect(footerSelectionSurfaceFor('notes/example', 'source')).toBe('source');
+ });
+
+ test('an editable text doc gets one composer surface whichever way the toggle is left', () => {
+ const underWysiwyg = composerSurfaceFor('notes/example.ts', 'wysiwyg');
+ const underSource = composerSurfaceFor('notes/example.ts', 'source');
+
+ const message =
+ 'a .ts file is edited in CodeMirror whatever the markdown mode toggle says, so the surface ' +
+ 'handed to the composer has to be the CodeMirror one under either toggle position. Got ' +
+ `"${underWysiwyg}" under wysiwyg and "${underSource}" under source`;
+ expect(underWysiwyg, message).toBe('source');
+ expect(underSource, message).toBe('source');
+ });
+
+ test('an editable text doc gets one selection-stats surface whichever way the toggle is left', () => {
+ const underWysiwyg = footerSelectionSurfaceFor('notes/example.ts', 'wysiwyg');
+ const underSource = footerSelectionSurfaceFor('notes/example.ts', 'source');
+
+ const message =
+ 'the footer reads selection stats under a surface key, and for a .ts file that key has to ' +
+ 'be the CodeMirror one under either toggle position. Got ' +
+ `"${underWysiwyg}" under wysiwyg and "${underSource}" under source`;
+ expect(underWysiwyg, message).toBe('source');
+ expect(underSource, message).toBe('source');
+ });
+});
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index 31e576797..21e6c7a45 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -51,6 +51,7 @@ import {
import { FindReplaceController } from '@/editor/find-replace/FindReplaceController';
import { useDocLintConfig } from '@/editor/lint-config-client';
import { mountPromiseHasResolved } from '@/editor/mount-promise';
+import { editingSurfaceFor } from '@/editor/selection-stats';
import { syncPromiseHasResolved } from '@/editor/sync-promise';
import {
partitionFrontmatterProblems,
@@ -304,10 +305,8 @@ function EditorAreaInner({
} = useDocumentContext();
const { openDocumentTransition } = useDocumentTransition();
const stats = useDocumentStats(activeProvider, activeDocName);
- const selectionStats = useSelectionStats(
- activeDocName,
- editorMode === 'source' ? 'source' : 'wysiwyg',
- );
+ const editingSurface = editingSurfaceFor(activeDocName, editorMode);
+ const selectionStats = useSelectionStats(activeDocName, editingSurface);
const [everHadProvider, setEverHadProvider] = useState(false);
useEffect(() => {
if (activeProvider != null && !everHadProvider) setEverHadProvider(true);
@@ -1132,7 +1131,7 @@ function EditorAreaInner({
{showBottomComposer ? (
<BottomComposer
docName={activeDocName}
- surface={isSourceMode ? 'source' : 'wysiwyg'}
+ surface={editingSurface}
dismissed={composerDismissed}
onDismiss={() => setComposerDismissed(true)}
onReopen={() => setComposerDismissed(false)}
diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsx
index 098c080fd..eaf7690a6 100644
--- a/packages/app/src/components/EditorPane.tsx
+++ b/packages/app/src/components/EditorPane.tsx
@@ -22,6 +22,7 @@ import { RAW_MDX_NAV_EVENT, type RawMdxNavDetail } from '@/editor/extensions/raw
import { captureModeSwitchAnchor, requestViewInSource } from '@/editor/mode-switch-landing';
import { requestPreviewTabPromotion } from '@/editor/preview-tab-promotion';
import { getSelectionContext, subscribeSelectionContext } from '@/editor/selection-context';
+import { editingSurfaceFor } from '@/editor/selection-stats';
import { rememberPendingSourceNavigation } from '@/editor/source-editor-navigation';
import { type EditorModeValue, useEditorMode } from '@/editor/use-editor-mode';
import { VIEW_IN_SOURCE_EVENT, type ViewInSourceDetail } from '@/editor/view-in-source-event';
@@ -179,6 +180,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
useConfigContext();
const { activeDocName, activeProvider } = useDocumentContext();
+ const editingSurface = editingSurfaceFor(activeDocName, editorMode);
const autoSyncOnboardingVariant = resolveAutoSyncOnboarding({
autoSyncOnboardingDismissed,
@@ -204,7 +206,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
function sendSelectionToTerminal(newTab: boolean, target?: 'agents'): boolean {
if (activeDocName == null) return false;
- const snapshot = getSelectionContext(activeDocName, editorMode);
+ const snapshot = getSelectionContext(activeDocName, editingSurface);
const selectionMarkdown = snapshot?.markdown ?? '';
if (selectionMarkdown.trim() === '') return false;
const staged = `${composeTerminalSelectionPaste(activeDocName, selectionMarkdown)}\n\n`;
@@ -334,7 +336,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
let last: boolean | null = null;
const publish = () => {
const snapshot =
- activeDocName === null ? null : getSelectionContext(activeDocName, editorMode);
+ activeDocName === null ? null : getSelectionContext(activeDocName, editingSurface);
const hasEditorSelection = (snapshot?.markdown ?? '').trim() !== '';
if (hasEditorSelection === last) return;
last = hasEditorSelection;
@@ -343,7 +345,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
};
publish();
return subscribeSelectionContext(publish);
- }, [activeDocName, editorMode]);
+ }, [activeDocName, editingSurface]);
useEffect(() => {
if (noteWindow) {
diff --git a/packages/app/src/components/MermaidDocEditor.dom.test.tsx b/packages/app/src/components/MermaidDocEditor.dom.test.tsx
index 5a620f60a..e908872c9 100644
--- a/packages/app/src/components/MermaidDocEditor.dom.test.tsx
+++ b/packages/app/src/components/MermaidDocEditor.dom.test.tsx
@@ -4,7 +4,7 @@ import { cleanup, render } from '@testing-library/react';
import { afterEach, describe, expect, test, vi } from 'vitest';
import { Awareness } from 'y-protocols/awareness';
import * as Y from 'yjs';
-import { FULL_PAGE_CM_HOST_SELECTORS } from '@/globals-css.test-helper';
+import { FULL_PAGE_CM_HOST_SELECTORS } from '@/editor/document-scrollports';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
vi.doMock('@lingui/react/macro', () => ({
diff --git a/packages/app/src/components/handoff/AgentSplitButton.tsx b/packages/app/src/components/handoff/AgentSplitButton.tsx
index 994ba9047..bb1f4790f 100644
--- a/packages/app/src/components/handoff/AgentSplitButton.tsx
+++ b/packages/app/src/components/handoff/AgentSplitButton.tsx
@@ -60,6 +60,7 @@ export function AgentSplitButton({
menuLeading,
onMenuOpenChange,
menuAlign = 'end',
+ menuAttributes,
triggerAriaLabel,
testIds,
}: {
@@ -77,6 +78,7 @@ export function AgentSplitButton({
menuLeading?: ReactNode;
onMenuOpenChange?: (open: boolean) => void;
menuAlign?: 'start' | 'end';
+ menuAttributes?: Readonly<{ 'data-composer-portal'?: string }>;
triggerAriaLabel: string;
testIds: AgentSplitButtonTestIds;
}) {
@@ -117,6 +119,7 @@ export function AgentSplitButton({
align={menuAlign}
className="max-h-80 min-w-[200px]"
data-testid={testIds.menu}
+ {...menuAttributes}
>
{}
{menuLeading ? (
diff --git a/packages/app/src/editor/SourceEditor.dom.test.tsx b/packages/app/src/editor/SourceEditor.dom.test.tsx
index 6d6827c10..d64c59005 100644
--- a/packages/app/src/editor/SourceEditor.dom.test.tsx
+++ b/packages/app/src/editor/SourceEditor.dom.test.tsx
@@ -14,7 +14,7 @@ import {
type OutlineNavDetail,
} from '@/components/OutlinePanel';
import { LINT_NAV_EVENT, type LintNavDetail } from '@/components/ProblemsPanel';
-import { FULL_PAGE_CM_HOST_SELECTORS } from '@/globals-css.test-helper';
+import { FULL_PAGE_CM_HOST_SELECTORS } from '@/editor/document-scrollports';
import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
import { evictCmEditor } from './editor-cache';
import type { LandingHandle } from './landing-controller';
diff --git a/packages/app/src/editor/document-scrollports.dom.test.ts b/packages/app/src/editor/document-scrollports.dom.test.ts
new file mode 100644
index 000000000..6e9516322
--- /dev/null
+++ b/packages/app/src/editor/document-scrollports.dom.test.ts
@@ -0,0 +1,130 @@
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ documentScrollports,
+ FULL_PAGE_CM_HOST_SELECTORS,
+ isPinnedToEnd,
+ SCROLL_PIN_SLACK_PX,
+} from './document-scrollports';
+
+function buildEditorTree(): {
+ outer: HTMLElement;
+ conflictScroller: HTMLElement;
+ hostScrollers: Record<keyof typeof FULL_PAGE_CM_HOST_SELECTORS, HTMLElement>;
+ codeBlockScroller: HTMLElement;
+} {
+ const container = document.createElement('div');
+
+ const outer = document.createElement('div');
+ outer.className = 'editor-doc-scroll';
+ container.appendChild(outer);
+
+ const makeHost = (selector: string) => {
+ const host = document.createElement('div');
+ if (selector.startsWith('[')) host.setAttribute(selector.slice(1, -1), '');
+ else host.className = selector.slice(1);
+ const scroller = document.createElement('div');
+ scroller.className = 'cm-scroller';
+ host.appendChild(scroller);
+ outer.appendChild(host);
+ return scroller;
+ };
+
+ const hostScrollers = {
+ mermaidDocEditor: makeHost(FULL_PAGE_CM_HOST_SELECTORS.mermaidDocEditor),
+ sourceEditor: makeHost(FULL_PAGE_CM_HOST_SELECTORS.sourceEditor),
+ textDocEditor: makeHost(FULL_PAGE_CM_HOST_SELECTORS.textDocEditor),
+ };
+
+ const conflictScroller = document.createElement('div');
+ conflictScroller.className = 'conflict-view';
+ outer.appendChild(conflictScroller);
+
+ const codeBlock = document.createElement('div');
+ codeBlock.className = 'node-codeBlock';
+ const codeBlockScroller = document.createElement('div');
+ codeBlockScroller.className = 'cm-scroller';
+ codeBlock.appendChild(codeBlockScroller);
+ outer.appendChild(codeBlock);
+
+ document.body.appendChild(container);
+ return { outer, conflictScroller, hostScrollers, codeBlockScroller };
+}
+
+function withGeometry(scrollHeight: number, clientHeight: number, scrollTop: number): HTMLElement {
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'scrollHeight', { value: scrollHeight, configurable: true });
+ Object.defineProperty(el, 'clientHeight', { value: clientHeight, configurable: true });
+ Object.defineProperty(el, 'scrollTop', { value: scrollTop, configurable: true });
+ return el;
+}
+
+afterEach(() => {
+ document.body.replaceChildren();
+});
+
+describe('documentScrollports enumerates every surface that reserves the composer inset', () => {
+ test('returns the outer document scroller, the conflict scroller and each scrolling host scroller', () => {
+ const { outer, conflictScroller, hostScrollers } = buildEditorTree();
+
+ const found = documentScrollports();
+
+ expect(found).toContain(outer);
+ expect(
+ found,
+ 'the conflict surface reserves --ask-composer-height on its own overflow-y-auto scroller, ' +
+ 'so leaving it out buries the last hunk and its Accept/Reject controls under the card',
+ ).toContain(conflictScroller);
+ expect(found, 'mermaidDocEditor scrollport must be enumerated').toContain(
+ hostScrollers.mermaidDocEditor,
+ );
+ expect(found, 'textDocEditor scrollport must be enumerated').toContain(
+ hostScrollers.textDocEditor,
+ );
+ expect(found).toHaveLength(4);
+ });
+
+ test('leaves out the source editor scroller, which reserves the inset but never scrolls', () => {
+ const { hostScrollers } = buildEditorTree();
+
+ expect(
+ documentScrollports(),
+ '`.source-editor` is deliberately absent from `DOCUMENT_SCROLLPORT_SELECTORS`: it ' +
+ 'reserves the composer inset on its `.cm-content`, but the outer ' +
+ '`.editor-doc-scroll` is what scrolls, so enumerating it would add an element ' +
+ '`isPinnedToEnd` can never accept. jsdom does no layout, so this tier can only pin ' +
+ 'the selector-list decision. The layout premise behind it is owned by the ' +
+ '`markdown in source mode` case in tests/stress/composer-growth-eof-reveal.e2e.ts, ' +
+ 'which measures the real geometry',
+ ).not.toContain(hostScrollers.sourceEditor);
+ });
+
+ test('ignores a CodeMirror scroller that belongs to no registered host', () => {
+ const { codeBlockScroller } = buildEditorTree();
+
+ expect(documentScrollports()).not.toContain(codeBlockScroller);
+ });
+
+ test('returns an element matching two selectors exactly once', () => {
+ const host = document.createElement('div');
+ host.setAttribute('data-text-doc-editor', '');
+ const scroller = document.createElement('div');
+ scroller.className = 'cm-scroller editor-doc-scroll';
+ host.appendChild(scroller);
+ document.body.appendChild(host);
+
+ expect(documentScrollports().filter((el) => el === scroller)).toHaveLength(1);
+ });
+});
+
+describe('isPinnedToEnd decides which scrollports the composer may re-clamp', () => {
+ test.each([
+ ['resting exactly at its scroll end', 1000, 600, 400, true],
+ ['parked inside the slack above the end', 1000, 600, 400 - (SCROLL_PIN_SLACK_PX - 1), true],
+ ['parked exactly at the far edge of the slack', 1000, 600, 400 - SCROLL_PIN_SLACK_PX, true],
+ ['parked one pixel above the slack', 1000, 600, 400 - (SCROLL_PIN_SLACK_PX + 1), false],
+ ['reading the middle of a long document', 1000, 600, 0, false],
+ ['unable to scroll at all', 600, 600, 0, false],
+ ] as const)('%s', (_label, scrollHeight, clientHeight, scrollTop, expected) => {
+ expect(isPinnedToEnd(withGeometry(scrollHeight, clientHeight, scrollTop))).toBe(expected);
+ });
+});
diff --git a/packages/app/src/editor/document-scrollports.ts b/packages/app/src/editor/document-scrollports.ts
new file mode 100644
index 000000000..ba083d1b5
--- /dev/null
+++ b/packages/app/src/editor/document-scrollports.ts
@@ -0,0 +1,31 @@
+export const FULL_PAGE_CM_HOST_SELECTORS = {
+ mermaidDocEditor: '[data-mermaid-doc-editor]',
+ sourceEditor: '.source-editor',
+ textDocEditor: '[data-text-doc-editor]',
+} as const;
+
+export const SCROLL_PIN_SLACK_PX = 40;
+
+export const DOCUMENT_SCROLL_HOST_CLASS = 'editor-doc-scroll';
+
+export const DOCUMENT_SCROLL_HOST_SELECTOR = `.${DOCUMENT_SCROLL_HOST_CLASS}`;
+
+export const CONFLICT_SCROLLPORT_SELECTOR = '.conflict-view';
+
+export const DOCUMENT_SCROLLPORT_SELECTORS = [
+ DOCUMENT_SCROLL_HOST_SELECTOR,
+ CONFLICT_SCROLLPORT_SELECTOR,
+ `${FULL_PAGE_CM_HOST_SELECTORS.mermaidDocEditor} .cm-scroller`,
+ `${FULL_PAGE_CM_HOST_SELECTORS.textDocEditor} .cm-scroller`,
+] as const;
+
+const DOCUMENT_SCROLLPORT_SELECTOR = DOCUMENT_SCROLLPORT_SELECTORS.join(', ');
+
+export function documentScrollports(): readonly HTMLElement[] {
+ return [...document.querySelectorAll<HTMLElement>(DOCUMENT_SCROLLPORT_SELECTOR)];
+}
+
+export function isPinnedToEnd(el: HTMLElement): boolean {
+ const max = el.scrollHeight - el.clientHeight;
+ return max > 0 && el.scrollTop >= max - SCROLL_PIN_SLACK_PX;
+}
diff --git a/packages/app/src/editor/extensions/suggestion-floating-ui.ts b/packages/app/src/editor/extensions/suggestion-floating-ui.ts
index 00ad5fbe2..dfa5fce22 100644
--- a/packages/app/src/editor/extensions/suggestion-floating-ui.ts
+++ b/packages/app/src/editor/extensions/suggestion-floating-ui.ts
@@ -72,9 +72,16 @@ function applyColumnCount(popup: HTMLDivElement, regionWidth: number | null): vo
popup.toggleAttribute('data-suggestion-narrow', regionWidth < SUGGESTION_TWO_COLUMN_MIN_PX);
}
+export type SuggestionPopupLabel =
+ | 'composer-mention'
+ | 'composer-slash'
+ | 'slash-command'
+ | 'tag-suggestion'
+ | 'wiki-link-suggestion';
+
export function createSuggestionPopup(
getCurrentProps: () => SuggestionProps<unknown> | null,
- label: string,
+ label: SuggestionPopupLabel,
{ clipToEditorPane = false }: { clipToEditorPane?: boolean } = {},
): {
popup: HTMLDivElement;
diff --git a/packages/app/src/editor/selection-stats.test.ts b/packages/app/src/editor/selection-stats.test.ts
index 2ddc3f468..755c52cc8 100644
--- a/packages/app/src/editor/selection-stats.test.ts
+++ b/packages/app/src/editor/selection-stats.test.ts
@@ -2,6 +2,7 @@ import type { EditorView } from '@codemirror/view';
import type { Editor } from '@tiptap/core';
import { describe, expect, test } from 'vitest';
import {
+ editingSurfaceFor,
getSelectionStats,
publishSelectionStats,
selectionStatsFromSource,
@@ -139,3 +140,20 @@ describe('selectionStatsFromSource', () => {
expect(stats?.words).toBe(2);
});
});
+
+describe('editingSurfaceFor derives the editing surface from the document', () => {
+ test.each([
+ ['notes/example', 'wysiwyg', 'wysiwyg'],
+ ['notes/example', 'source', 'source'],
+ ['notes/example.md', 'wysiwyg', 'wysiwyg'],
+ ['notes/example.ts', 'wysiwyg', 'source'],
+ ['notes/example.ts', 'source', 'source'],
+ ['notes/data.json', 'wysiwyg', 'source'],
+ ['diagram.mmd', 'wysiwyg', 'wysiwyg'],
+ ['diagram.mmd', 'source', 'source'],
+ [null, 'wysiwyg', 'wysiwyg'],
+ [null, 'source', 'source'],
+ ] as const)('%s under the %s toggle edits on the %s surface', (docName, mode, expected) => {
+ expect(editingSurfaceFor(docName, mode)).toBe(expected);
+ });
+});
diff --git a/packages/app/src/editor/selection-stats.ts b/packages/app/src/editor/selection-stats.ts
index c420b7487..437899974 100644
--- a/packages/app/src/editor/selection-stats.ts
+++ b/packages/app/src/editor/selection-stats.ts
@@ -1,11 +1,20 @@
import type { EditorView } from '@codemirror/view';
+import { isEditableTextDocFile } from '@inkeep/open-knowledge-core';
import type { Editor } from '@tiptap/core';
import { computeSelectionStats, type DocumentStats } from '@/lib/document-stats';
+import type { EditorModeValue } from './use-editor-mode';
export const SELECTION_STATS_DEBOUNCE_MS = 120;
export type EditorSurface = 'wysiwyg' | 'source' | 'frontmatter';
+export function editingSurfaceFor(
+ docName: string | null,
+ editorMode: EditorModeValue,
+): EditorSurface {
+ return docName !== null && isEditableTextDocFile(docName) ? 'source' : editorMode;
+}
+
const statsByDocSurface = new Map<string, DocumentStats>();
const listeners = new Set<() => void>();
diff --git a/packages/app/src/editor/utils/editor-visible-region.ts b/packages/app/src/editor/utils/editor-visible-region.ts
index 7b3d92254..1a52c55f1 100644
--- a/packages/app/src/editor/utils/editor-visible-region.ts
+++ b/packages/app/src/editor/utils/editor-visible-region.ts
@@ -1,5 +1,6 @@
import type { DetectOverflowOptions, MiddlewareState, ShiftOptions } from '@floating-ui/dom';
import type { Editor } from '@tiptap/react';
+import { DOCUMENT_SCROLL_HOST_SELECTOR } from '@/editor/document-scrollports';
import { editorToolbarOverlapPx } from '@/lib/editor-toolbar-overlap';
import { getEditorView } from './get-editor-view';
@@ -55,7 +56,7 @@ export function editorVisibleBand(editor: Editor): { top: number; bottom: number
}
function resolveRegionBoundary(editor: Editor): Element | null {
- return getEditorView(editor)?.dom.closest('.editor-doc-scroll') ?? null;
+ return getEditorView(editor)?.dom.closest(DOCUMENT_SCROLL_HOST_SELECTOR) ?? null;
}
export const SELECTION_SURFACE_GAP_PX = 8;
diff --git a/packages/app/src/globals-css.test-helper.test.ts b/packages/app/src/globals-css.test-helper.test.ts
index 63d90874c..72803dcb8 100644
--- a/packages/app/src/globals-css.test-helper.test.ts
+++ b/packages/app/src/globals-css.test-helper.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, test } from 'vitest';
-import { blankComments } from './globals-css.test-helper';
+import {
+ blankComments,
+ collectBlocks,
+ normalizeSelector,
+ splitSelectorList,
+} from './globals-css.test-helper';
describe('globals.css comment stripping', () => {
test('a `/*` inside a quoted at-rule argument does not open a comment', () => {
@@ -27,3 +32,75 @@ describe('globals.css comment stripping', () => {
expect(blankComments(css).split('\n').length).toBe(css.split('\n').length);
});
});
+
+describe('globals.css block scanning', () => {
+ test('an at-rule nested inside a style rule keeps both preludes and their own declarations', () => {
+ const blocks = collectBlocks(
+ '.surface { color: red; @media (min-width: 40rem) { padding-bottom: 1px; } }',
+ );
+ expect(
+ blocks.map((block) => block.prelude),
+ 'the leaf-only regex this scanner replaces (`/([^{}]+)\\{([^{}]*)\\}/g`) cannot see past one ' +
+ 'brace level, so it reads the whole outer prelude plus the nested at-rule as one selector ' +
+ 'string and never reports `.surface` at all. A guard built on that reading attributes a ' +
+ 'nested declaration to nothing and passes silently',
+ ).toEqual(['@media (min-width: 40rem)', '.surface']);
+ expect(
+ blocks.find((block) => block.prelude === '@media (min-width: 40rem)')?.declarations,
+ ).toContain('padding-bottom: 1px');
+ expect(
+ blocks.find((block) => block.prelude === '.surface')?.declarations,
+ 'a declaration written before the nested at-rule belongs to the outer rule, not to the ' +
+ 'at-rule that follows it',
+ ).toContain('color: red');
+ });
+
+ test('a brace inside a quoted attribute selector does not open or close a block', () => {
+ const blocks = collectBlocks('[data-state="}"] .child { padding-bottom: 2px; }');
+ expect(
+ blocks.map((block) => block.prelude),
+ 'the `}` lives inside a quoted attribute value, so it is a literal character rather than a ' +
+ 'block terminator. A scanner that counts it closes the rule early and loses every ' +
+ 'declaration after it',
+ ).toEqual(['[data-state="}"] .child']);
+ expect(blocks[0]?.declarations).toContain('padding-bottom: 2px');
+ });
+
+ test('a comma inside brackets or parentheses does not split the selector list', () => {
+ expect(
+ splitSelectorList('[data-keys="a,b"], :is(.one, .two) .child, .last'),
+ 'only top-level commas separate selectors. Splitting on a comma nested in an attribute ' +
+ 'value or a functional pseudo-class yields selector fragments that match nothing, so a ' +
+ 'set-equality guard built on them reports a phantom difference or, worse, silently agrees',
+ ).toEqual(['[data-keys="a,b"]', ':is(.one, .two) .child', '.last']);
+ });
+
+ test('a selector split across lines normalizes to its single-space form', () => {
+ expect(
+ normalizeSelector('.outer\n .inner'),
+ 'globals.css wraps long selectors, and the tables these are compared against are written on ' +
+ 'one line. Without this collapse the two spellings of one selector never compare equal',
+ ).toBe('.outer .inner');
+ });
+
+ test('a brace inside a comment cannot forge a block, whether or not the caller pre-blanks', () => {
+ const raw = '.surface { /* opens { here */ padding-bottom: 3px; }';
+ expect(
+ collectBlocks(raw).map((block) => block.prelude),
+ 'the scanner consumes comments itself rather than making every caller remember to, which is ' +
+ 'where CSS Syntax L3 puts it (section 4.3.1, "consume a token", begins by consuming ' +
+ 'comments). Without that the brace inside the comment opens a block, `.surface` never ' +
+ 'closes, and the scanner reports the comment text as a selector: against globals.css that ' +
+ 'read yields 319 blocks instead of 745 and 23 inset-bearing selectors instead of 7, 16 of ' +
+ 'them comment prose',
+ ).toEqual(['.surface']);
+ expect(
+ collectBlocks(blankComments(raw)),
+ 'blanking overwrites a comment in place with whitespace rather than splicing it out, so ' +
+ 'the second pass finds no `/*` where the comment was and none newly joined across its ' +
+ 'seam, and the `/*` that survive inside strings are skipped by both passes alike. That ' +
+ 'is what makes it idempotent, and it is why a caller that pre-blanks gets ' +
+ 'byte-identical output to one that does not',
+ ).toEqual(collectBlocks(raw));
+ });
+});
diff --git a/packages/app/src/globals-css.test-helper.ts b/packages/app/src/globals-css.test-helper.ts
index 095a8c968..b64877a33 100644
--- a/packages/app/src/globals-css.test-helper.ts
+++ b/packages/app/src/globals-css.test-helper.ts
@@ -3,12 +3,6 @@ import { join } from 'node:path';
const GLOBALS_CSS_PATH = join(import.meta.dirname, 'globals.css');
-export const FULL_PAGE_CM_HOST_SELECTORS = {
- mermaidDocEditor: '[data-mermaid-doc-editor]',
- sourceEditor: '.source-editor',
- textDocEditor: '[data-text-doc-editor]',
-} as const;
-
export function blankComments(css: string): string {
let out = '';
let quote: string | null = null;
@@ -45,6 +39,84 @@ export function blankComments(css: string): string {
return out;
}
+export interface CssBlock {
+ prelude: string;
+ declarations: string;
+ ancestors: readonly string[];
+}
+
+export function collectBlocks(css: string): CssBlock[] {
+ const source = blankComments(css);
+ const blocks: CssBlock[] = [];
+ const open: CssBlock[] = [];
+ let segment = '';
+ let quote: string | null = null;
+ for (let i = 0; i < source.length; i++) {
+ const ch = source[i];
+ if (quote) {
+ segment += ch;
+ if (ch === '\\') {
+ segment += source[i + 1] ?? '';
+ i++;
+ } else if (ch === quote) quote = null;
+ continue;
+ }
+ if (ch === '"' || ch === "'") {
+ quote = ch;
+ segment += ch;
+ continue;
+ }
+ if (ch === '{') {
+ open.push({
+ prelude: segment.trim(),
+ declarations: '',
+ ancestors: open.map((block) => block.prelude),
+ });
+ segment = '';
+ continue;
+ }
+ if (ch === '}') {
+ const done = open.pop();
+ if (done) {
+ done.declarations += segment;
+ blocks.push(done);
+ }
+ segment = '';
+ continue;
+ }
+ if (ch === ';') {
+ const enclosing = open.at(-1);
+ if (enclosing) enclosing.declarations += `${segment};`;
+ segment = '';
+ continue;
+ }
+ segment += ch;
+ }
+ return blocks;
+}
+
+export function normalizeSelector(selector: string): string {
+ return selector.trim().replace(/\s+/g, ' ');
+}
+
+export function splitSelectorList(prelude: string): string[] {
+ const parts: string[] = [];
+ let depth = 0;
+ let current = '';
+ for (const ch of prelude) {
+ if (ch === '(' || ch === '[') depth++;
+ else if (ch === ')' || ch === ']') depth--;
+ if (ch === ',' && depth === 0) {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += ch;
+ }
+ parts.push(current);
+ return parts.map(normalizeSelector).filter((part) => part.length > 0);
+}
+
export function readGlobalsCssRaw(): string {
return readFileSync(GLOBALS_CSS_PATH, 'utf-8');
}
diff --git a/packages/app/src/globals.composer-inset-cascade.test.ts b/packages/app/src/globals.composer-inset-cascade.test.ts
index 2a3faa01c..abba2e467 100644
--- a/packages/app/src/globals.composer-inset-cascade.test.ts
+++ b/packages/app/src/globals.composer-inset-cascade.test.ts
@@ -2,39 +2,80 @@ import { readdirSync, readFileSync } from 'node:fs';
import { join, relative, sep } from 'node:path';
import { describe, expect, test } from 'vitest';
import {
+ CONFLICT_SCROLLPORT_SELECTOR,
+ DOCUMENT_SCROLL_HOST_SELECTOR,
+ DOCUMENT_SCROLLPORT_SELECTORS,
FULL_PAGE_CM_HOST_SELECTORS,
+} from './editor/document-scrollports';
+import {
+ type CssBlock,
+ collectBlocks,
readGlobalsCssWithoutComments,
+ splitSelectorList,
} from './globals-css.test-helper';
const SRC_ROOT = import.meta.dirname;
const RESET_PRELUDE = '.cm-editor .cm-content';
-const INSET_VALUE = 'var(--ask-composer-height';
+const INSET_VAR = '--ask-composer-height';
+
+const INSET_VALUE = `var(${INSET_VAR}`;
+
+const INSET_VAR_ALLOWED_OUTSIDE_GLOBALS_CSS = [
+ 'components/BottomComposer.tsx',
+ 'editor/utils/editor-visible-region.ts',
+] as const;
type InsetKind = 'content' | 'host';
+type FullPageCmHostKey = keyof typeof FULL_PAGE_CM_HOST_SELECTORS;
+
+type DocumentScrollportSelector = (typeof DOCUMENT_SCROLLPORT_SELECTORS)[number];
+
interface FullPageCmSurface {
component: string;
- hostSelector: string;
insetKind: InsetKind;
}
-const FULL_PAGE_CM_SURFACES: readonly FullPageCmSurface[] = [
+const FULL_PAGE_CM_SURFACES: Readonly<Record<FullPageCmHostKey, FullPageCmSurface>> = {
+ textDocEditor: { component: 'components/TextDocEditor.tsx', insetKind: 'content' },
+ sourceEditor: { component: 'editor/SourceEditor.tsx', insetKind: 'content' },
+ mermaidDocEditor: { component: 'components/MermaidDocEditor.tsx', insetKind: 'host' },
+};
+
+const FULL_PAGE_CM_SURFACE_CASES = Object.entries(FULL_PAGE_CM_SURFACES).map(([host, surface]) => ({
+ ...surface,
+ hostSelector: FULL_PAGE_CM_HOST_SELECTORS[host as FullPageCmHostKey],
+}));
+
+interface ComposerInsetRule {
+ prelude: string;
+ scrollport: DocumentScrollportSelector;
+}
+
+const COMPOSER_INSET_RULES: readonly ComposerInsetRule[] = [
+ { prelude: DOCUMENT_SCROLL_HOST_SELECTOR, scrollport: DOCUMENT_SCROLL_HOST_SELECTOR },
+ {
+ prelude: `${DOCUMENT_SCROLL_HOST_SELECTOR} :is(.ProseMirror, .cm-content)`,
+ scrollport: DOCUMENT_SCROLL_HOST_SELECTOR,
+ },
{
- component: 'components/TextDocEditor.tsx',
- hostSelector: FULL_PAGE_CM_HOST_SELECTORS.textDocEditor,
- insetKind: 'content',
+ prelude: `${FULL_PAGE_CM_HOST_SELECTORS.sourceEditor} .cm-content`,
+ scrollport: DOCUMENT_SCROLL_HOST_SELECTOR,
},
{
- component: 'editor/SourceEditor.tsx',
- hostSelector: FULL_PAGE_CM_HOST_SELECTORS.sourceEditor,
- insetKind: 'content',
+ prelude: `${FULL_PAGE_CM_HOST_SELECTORS.textDocEditor} .cm-content`,
+ scrollport: `${FULL_PAGE_CM_HOST_SELECTORS.textDocEditor} .cm-scroller`,
},
{
- component: 'components/MermaidDocEditor.tsx',
- hostSelector: FULL_PAGE_CM_HOST_SELECTORS.mermaidDocEditor,
- insetKind: 'host',
+ prelude: FULL_PAGE_CM_HOST_SELECTORS.mermaidDocEditor,
+ scrollport: `${FULL_PAGE_CM_HOST_SELECTORS.mermaidDocEditor} .cm-scroller`,
+ },
+ { prelude: CONFLICT_SCROLLPORT_SELECTOR, scrollport: CONFLICT_SCROLLPORT_SELECTOR },
+ {
+ prelude: `${CONFLICT_SCROLLPORT_SELECTOR} diffs-container`,
+ scrollport: CONFLICT_SCROLLPORT_SELECTOR,
},
];
@@ -45,13 +86,19 @@ function listSourceFiles(dir: string): string[] {
.filter(
(entry) =>
entry.isFile() &&
- /\.tsx?$/.test(entry.name) &&
- !/\.(test|test-helper|dom\.test)\.tsx?$/.test(entry.name),
+ /\.(tsx?|jsx?)$/.test(entry.name) &&
+ !/\.(test|test-helper)\.(tsx?|jsx?)$/.test(entry.name),
)
.map((entry) => join(entry.parentPath, entry.name))
.filter((file) => !relative(dir, file).split(sep).includes('locales'));
}
+function listStylesheetFiles(dir: string): string[] {
+ return readdirSync(dir, { recursive: true, withFileTypes: true })
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.css'))
+ .map((entry) => join(entry.parentPath, entry.name));
+}
+
function mountsFullPageCodeMirror(absPath: string): boolean {
return FULL_PAGE_CM_THEME.test(readFileSync(absPath, 'utf-8'));
}
@@ -78,6 +125,24 @@ function declarationBlockAt(css: string, offset: number): string {
return '';
}
+function owningSelector(block: CssBlock): string | null {
+ for (const prelude of [...block.ancestors, block.prelude].toReversed()) {
+ if (!prelude.startsWith('@')) return prelude;
+ }
+ return null;
+}
+
+function insetBearingSelectors(css: string): string[] {
+ const found = new Set<string>();
+ for (const block of collectBlocks(css)) {
+ if (!block.declarations.includes(INSET_VALUE)) continue;
+ const owner = owningSelector(block);
+ if (owner === null) continue;
+ for (const selector of splitSelectorList(owner)) found.add(selector);
+ }
+ return [...found].toSorted();
+}
+
function composerInsetOffset(css: string, prelude: string): number | null {
for (const offset of ruleOffsets(css, prelude)) {
if (declarationBlockAt(css, offset).includes(INSET_VALUE)) return offset;
@@ -88,6 +153,50 @@ function composerInsetOffset(css: string, prelude: string): number | null {
describe('full-page CodeMirror surfaces reserve the Ask AI composer height', () => {
const css = readGlobalsCssWithoutComments();
+ test('every registered surface is keyed by a host in the shared record', () => {
+ expect(
+ Object.keys(FULL_PAGE_CM_SURFACES).toSorted(),
+ 'this table is keyed by `FULL_PAGE_CM_HOST_SELECTORS` and indexes its host selector out ' +
+ 'rather than restating it as a sibling field, so a surface can no longer be paired with ' +
+ "another surface's selector and still satisfy every assertion here. A host in the record " +
+ 'with no entry here has nothing checking it reserves the composer height, and repeats the ' +
+ 'end-of-document burial this registry exists to stop',
+ ).toEqual(Object.keys(FULL_PAGE_CM_HOST_SELECTORS).toSorted());
+ });
+
+ test('every globals.css rule that reserves the composer inset names a scrollport', () => {
+ expect(
+ insetBearingSelectors(css),
+ 'a selector in globals.css reserves `--ask-composer-height` but is not accounted for here, ' +
+ 'or an accounted-for selector no longer reserves it. This equality and its sibling below ' +
+ 'are set-wise, one direction each: together they prove no inset rule is missing from the ' +
+ 'table and no enumerated scrollport is dead weight. Neither reads the two fields of one ' +
+ 'row together, so pairing a row with the scrollport that actually scrolls its prelude is ' +
+ 'on the author. Without this equality a new surface can take its inset and never reach ' +
+ '`documentScrollports`, which is the bug this module exists to stop, one level up. Add a ' +
+ '`COMPOSER_INSET_RULES` row naming the scrollport that scrolls this prelude, and add that ' +
+ 'scrollport to `DOCUMENT_SCROLLPORT_SELECTORS` if it is new',
+ ).toEqual([...new Set(COMPOSER_INSET_RULES.map((rule) => rule.prelude))].toSorted());
+ });
+
+ test('every scrollport the composer re-clamps compensates a real inset rule', () => {
+ expect(
+ [...new Set(COMPOSER_INSET_RULES.map((rule) => rule.scrollport))].toSorted(),
+ 'a member of `DOCUMENT_SCROLLPORT_SELECTORS` compensates no globals.css inset rule, so the ' +
+ 'composer re-clamps an element that reserves no room for it. That member is either dead ' +
+ 'weight reading as coverage its surface does not have, or the surface lost its inset rule',
+ ).toEqual([...DOCUMENT_SCROLLPORT_SELECTORS].toSorted());
+ });
+
+ test('the conflict surface, enumerated as a literal rather than through the record, reserves the composer height', () => {
+ expect(
+ composerInsetOffset(css, `${CONFLICT_SCROLLPORT_SELECTOR} diffs-container`),
+ `\`${CONFLICT_SCROLLPORT_SELECTOR}\` reaches \`documentScrollports\` as a bare literal, so ` +
+ 'nothing else ties it to the inset it exists to compensate. Renaming this prelude leaves ' +
+ 'the composer clamping a scrollport that reserves no room, and every other test green',
+ ).not.toBeNull();
+ });
+
test('the padding reset that every full-page CM surface has to undo is still there', () => {
const resetOffsets = ruleOffsets(css, RESET_PRELUDE);
expect(
@@ -106,7 +215,7 @@ describe('full-page CodeMirror surfaces reserve the Ask AI composer height', ()
).toBe(true);
});
- test.each(FULL_PAGE_CM_SURFACES)(
+ test.each(FULL_PAGE_CM_SURFACE_CASES)(
'$component reserves the composer height and wins the tie against the reset',
({ component, hostSelector, insetKind }) => {
const prelude = insetKind === 'content' ? `${hostSelector} .cm-content` : hostSelector;
@@ -127,7 +236,7 @@ describe('full-page CodeMirror surfaces reserve the Ask AI composer height', ()
},
);
- test.each(FULL_PAGE_CM_SURFACES)(
+ test.each(FULL_PAGE_CM_SURFACE_CASES)(
'$component reserves exactly one composer height',
({ hostSelector }) => {
const insetOffsets = [
@@ -145,7 +254,7 @@ describe('full-page CodeMirror surfaces reserve the Ask AI composer height', ()
test('no other component mounts a full-page CodeMirror without an entry here', () => {
const registered = new Set(
- FULL_PAGE_CM_SURFACES.map((surface) => join(SRC_ROOT, surface.component)),
+ Object.values(FULL_PAGE_CM_SURFACES).map((surface) => join(SRC_ROOT, surface.component)),
);
const unregistered = listSourceFiles(SRC_ROOT)
.filter((file) => !registered.has(file))
@@ -155,18 +264,100 @@ describe('full-page CodeMirror surfaces reserve the Ask AI composer height', ()
unregistered,
'these components match the full-page CodeMirror syntax detector (`EditorView.theme(...)` ' +
"with `height: '100%'`) but are not registered above, so nothing checks that they reserve " +
- 'the composer height. Add each to FULL_PAGE_CM_SURFACES with the host selector its ' +
- 'globals.css inset rule uses, or tighten the detector if the match is not a full-page surface',
+ 'the composer height. Add each to FULL_PAGE_CM_SURFACES under the FULL_PAGE_CM_HOST_SELECTORS ' +
+ 'key whose selector its globals.css inset rule uses, or tighten the detector if the match ' +
+ 'is not a full-page surface',
+ ).toEqual([]);
+ });
+
+ test('an inset nested in an at-rule inside a style rule is attributed to that rule', () => {
+ expect(
+ insetBearingSelectors(
+ `.new-surface { @media (min-width: 40rem) { padding-bottom: ${INSET_VALUE}, 0px); } }`,
+ ),
+ 'skipping every `@`-prefixed prelude rather than descending through it attributes this ' +
+ 'inset to nothing and returns an empty list, which reads exactly like a stylesheet that ' +
+ 'reserves nothing. A surface that takes its inset only under a media query would then ' +
+ 'never reach `documentScrollports` and nothing here would say so. The shape is reachable: ' +
+ 'globals.css already nests `@starting-style` inside a style rule, and Tailwind v4 flattens ' +
+ 'that nesting through Lightning CSS at build time',
+ ).toEqual(['.new-surface']);
+ });
+
+ test('an inset nested in a @supports probe inside a style rule is attributed to that rule', () => {
+ expect(
+ insetBearingSelectors(
+ `.probed-surface { @supports (height: 1lh) { padding-bottom: ${INSET_VALUE}, 0px); } }`,
+ ),
+ 'the @supports spelling of the nesting above has to resolve to the same owning selector, ' +
+ 'otherwise the fix covers one at-rule keyword rather than the class',
+ ).toEqual(['.probed-surface']);
+ });
+
+ test('a style rule nested inside an at-rule is still attributed to the style rule', () => {
+ expect(
+ insetBearingSelectors(
+ `@media (min-width: 40rem) { .outer-nested { padding-bottom: ${INSET_VALUE}, 0px); } }`,
+ ),
+ 'outer nesting was already handled and has to stay handled: the selector, not the media ' +
+ 'query wrapping it, is what the composer clamps',
+ ).toEqual(['.outer-nested']);
+ });
+
+ test('a declaration with no style rule anywhere above it is attributed to no selector', () => {
+ expect(
+ insetBearingSelectors(`@media (min-width: 40rem) { padding-bottom: ${INSET_VALUE}, 0px); }`),
+ 'an at-rule that carries the declaration directly has no selector to name, so it cannot ' +
+ 'produce a scrollport row. Reporting the at-rule prelude as a selector would put ' +
+ '`@media (min-width: 40rem)` into a table of things the composer re-clamps',
+ ).toEqual([]);
+ });
+
+ test('nothing outside globals.css reserves the composer inset where this guard cannot see it', () => {
+ const allowed = new Set(
+ INSET_VAR_ALLOWED_OUTSIDE_GLOBALS_CSS.map((rel) => join(SRC_ROOT, rel)),
+ );
+ const offenders = [
+ ...listSourceFiles(SRC_ROOT),
+ ...listStylesheetFiles(SRC_ROOT).filter((file) => file !== join(SRC_ROOT, 'globals.css')),
+ ]
+ .filter((file) => !allowed.has(file))
+ .filter((file) => readFileSync(file, 'utf-8').includes(INSET_VAR))
+ .map((file) => file.slice(SRC_ROOT.length + 1))
+ .toSorted();
+ expect(
+ offenders,
+ `these files name \`${INSET_VAR}\` outside globals.css, which is the one stylesheet every ` +
+ 'other assertion in this file reads. The idiomatic way to reserve the inset on a new ' +
+ 'surface here is a Tailwind arbitrary value in a `className` (`pb-[var(' +
+ `${INSET_VAR},0px)]\`), and this repo already carries about thirty arbitrary-value ` +
+ '`var()` classes, so the bypass is house style rather than hypothetical. Tailwind compiles ' +
+ 'those to CSS at build time and jsdom never applies the result, so no runtime assertion ' +
+ 'can reach them and a source scan is the only place this is checkable. Move the rule into ' +
+ 'globals.css and register it in `COMPOSER_INSET_RULES`, or allowlist the file above if it ' +
+ 'publishes the variable rather than consuming it',
+ ).toEqual([]);
+ });
+
+ test('each allowlisted publisher still names the inset variable', () => {
+ const stale = INSET_VAR_ALLOWED_OUTSIDE_GLOBALS_CSS.filter(
+ (rel) => !readFileSync(join(SRC_ROOT, rel), 'utf-8').includes(INSET_VAR),
+ );
+ expect(
+ stale,
+ `these files are allowlisted from the scan above but no longer mention \`${INSET_VAR}\`, so ` +
+ 'the allowlist is holding open an exemption nothing uses. A later file moved to one of ' +
+ 'these paths would inherit a blanket pass',
).toEqual([]);
});
test('the registry is not silently empty', () => {
- expect(FULL_PAGE_CM_SURFACES.length).toBeGreaterThan(0);
+ expect(Object.keys(FULL_PAGE_CM_SURFACES).length).toBeGreaterThan(0);
const found = listSourceFiles(SRC_ROOT).filter(mountsFullPageCodeMirror);
expect(
found.length,
'the full-page CodeMirror detector matched nothing at all, so the completeness test above ' +
'passes by finding nothing rather than by finding everything registered',
- ).toBe(FULL_PAGE_CM_SURFACES.length);
+ ).toBe(Object.keys(FULL_PAGE_CM_SURFACES).length);
});
});
diff --git a/packages/app/src/globals.css b/packages/app/src/globals.css
index 9484241e3..1815b0d8c 100644
--- a/packages/app/src/globals.css
+++ b/packages/app/src/globals.css
@@ -1121,11 +1121,19 @@
}
/* Ease the inset + composer entrance so collapsing/expanding glides instead of a
- hard jump cut. The per-frame scroll re-clamp in BottomComposer keeps the bottom
- pinned while the padding transition plays. `bottom` is included because the
- composer's anchor tracks `--conflict-footer-height`, which flips between 0 and
- the conflict footer's height when conflict mode mounts/unmounts. Reduced-motion
- users get the instant change. */
+ hard jump cut. Only the `.editor-doc-scroll` content inset is eased. The host-route
+ inset (`[data-mermaid-doc-editor]`) steps in one frame because it pads a border box
+ that also carries the non-scrolling diagram pane, so easing it would animate the
+ diagram's viewport rather than a text inset. The conflict surface's
+ `.conflict-view diffs-container` is a content inset of the same shape as the eased
+ rule, so easing it would be structurally sound. It is left unanimated because that
+ surface has no measured geometry coverage, and an easing change there cannot be
+ verified against the re-clamp.
+ The per-frame scroll re-clamp in BottomComposer keeps the bottom pinned either
+ way. `bottom` is
+ included because the composer's anchor tracks `--conflict-footer-height`, which
+ flips between 0 and the conflict footer's height when conflict mode
+ mounts/unmounts. Reduced-motion users get the instant change. */
@media (prefers-reduced-motion: no-preference) {
.editor-doc-scroll :is(.ProseMirror, .cm-content) {
transition: padding-bottom 240ms cubic-bezier(0.22, 1, 0.36, 1);
@@ -2761,10 +2769,16 @@ body[data-editor-tab-dragging] * {
The `padding: 0` reset above ties on specificity with the shared
`.editor-doc-scroll :is(.ProseMirror, .cm-content)` inset rule and, being
later, zeroes it, so those surfaces' last lines would sit under the composer
- while WYSIWYG clears. Both hosts scroll inside CodeMirror's own `.cm-scroller`
- (each sets `height: 100%` on the editor), so the room has to come from padding
- the CONTENT: padding the host would shrink the editor box, cutting the gutter
- and the scrollbar off above the composer instead of running them behind it.
+ while WYSIWYG clears. `[data-text-doc-editor]` scrolls inside CodeMirror's own
+ `.cm-scroller`; `.source-editor` sits in a content-sized ancestor chain, so its
+ `height: 100%` resolves to auto and the outer `.editor-doc-scroll` is what
+ scrolls. Either way the room has to come from padding the CONTENT, for a
+ different reason per host: padding the text-doc host would shrink its own scroll
+ box, cutting the gutter and the scrollbar off above the composer instead of
+ running them behind it, and padding the source host would reserve the height a
+ second time on top of this rule (the EITHER/OR below), while still ending its
+ gutter above the card (that host paints no scrollbar of its own, since it is
+ not the scroll parent).
`[data-mermaid-doc-editor]` takes the host route because the same wrapper also
hosts its non-scrolling diagram pane. Its source mode knowingly ends the
gutter and scrollbar above the composer, preserving one inset across that
diff --git a/packages/app/tests/stress/composer-growth-eof-reveal.e2e.ts b/packages/app/tests/stress/composer-growth-eof-reveal.e2e.ts
new file mode 100644
index 000000000..dad99b577
--- /dev/null
+++ b/packages/app/tests/stress/composer-growth-eof-reveal.e2e.ts
@@ -0,0 +1,407 @@
+import { randomUUID } from 'node:crypto';
+import { writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { Page } from '@playwright/test';
+import { expect, test, toggleMode } from './_helpers';
+
+const COMPOSER_CARD = '[data-testid="bottom-composer"] > div';
+const COMPOSER_INPUT = '.composer-prosemirror';
+const OUTER_SCROLLPORT = '[data-testid="editor-scroll-container"]';
+const WYSIWYG_BODY = '.editor-doc-scroll .ProseMirror:not(.composer-prosemirror)';
+const WYSIWYG_LINE = `${WYSIWYG_BODY} > *`;
+const SOURCE_SCROLLPORT = '.source-editor .cm-scroller';
+const SOURCE_LINE = '.source-editor .cm-content .cm-line';
+const TEXT_DOC_CONTENT = '[data-text-doc-editor] .cm-content';
+const TEXT_DOC_SCROLLPORT = '[data-text-doc-editor] .cm-scroller';
+const TEXT_DOC_LINE = `${TEXT_DOC_CONTENT} .cm-line`;
+const MERMAID_CONTENT = '[data-mermaid-doc-editor] .cm-content';
+const MERMAID_SCROLLPORT = '[data-mermaid-doc-editor] .cm-scroller';
+const MERMAID_LINE = `${MERMAID_CONTENT} .cm-line`;
+
+const LINE_COUNT = 300;
+
+const CASE_TIMEOUT_MS = 180_000;
+const FIRST_PAINT_TIMEOUT_MS = 30_000;
+const MODE_SWITCH_TIMEOUT_MS = 10_000;
+const POLL_TIMEOUT_MS = 20_000;
+
+const GROW_PROMPT =
+ 'Please refactor the trailing helpers in this file and explain the reasoning in detail so that ' +
+ 'the composer input wraps onto several visual lines and the floating card grows noticeably taller ' +
+ 'than the single-line resting height it started at before this prompt was typed into it.';
+
+const markdownBody = Array.from({ length: LINE_COUNT }, (_, index) => `Paragraph number ${index}.`)
+ .concat('Final paragraph, the one the caret sits on.')
+ .join('\n\n');
+
+function textDocBody(): string {
+ return `${Array.from({ length: LINE_COUNT }, (_, index) => `export const l${index} = ${index};`)
+ .concat('export const lastLineSentinel = true;')
+ .join('\n')}\n`;
+}
+
+function mermaidDocBody(): string {
+ return `${['graph TD']
+ .concat(Array.from({ length: LINE_COUNT }, (_, index) => ` n${index} --> n${index + 1}`))
+ .concat(' nLast[the last line the caret sits on]')
+ .join('\n')}\n`;
+}
+
+interface Surface {
+ readonly label: string;
+ readonly lineSelector: string;
+ readonly scrollportSelector: string;
+}
+
+interface Geometry {
+ readonly cardTop: number;
+ readonly lineBottom: number;
+ readonly composerHeight: number;
+ readonly scrollTop: number;
+ readonly scrollMax: number;
+}
+
+const clearanceOf = (geometry: Geometry): number => geometry.cardTop - geometry.lineBottom;
+
+function describeTransition(surface: Surface, before: Geometry, after: Geometry): string {
+ return [
+ `[${surface.label}] the last line of the document must keep painting above the Ask AI card`,
+ ` scrollport ${surface.scrollportSelector}`,
+ ` composer height ${before.composerHeight} -> ${after.composerHeight}`,
+ ` card top ${before.cardTop.toFixed(1)} -> ${after.cardTop.toFixed(1)} (moved ${(after.cardTop - before.cardTop).toFixed(1)})`,
+ ` line bottom ${before.lineBottom.toFixed(1)} -> ${after.lineBottom.toFixed(1)} (moved ${(after.lineBottom - before.lineBottom).toFixed(1)})`,
+ ` scroll ${before.scrollTop.toFixed(1)}/${before.scrollMax.toFixed(1)} -> ${after.scrollTop.toFixed(1)}/${after.scrollMax.toFixed(1)}`,
+ ` clearance ${clearanceOf(before).toFixed(1)} -> ${clearanceOf(after).toFixed(1)}`,
+ ` compensation ${(after.lineBottom - before.lineBottom - (after.cardTop - before.cardTop)).toFixed(1)} (0 = the scrollport tracked the growing card)`,
+ ].join('\n');
+}
+
+async function readComposerHeight(page: Page): Promise<number> {
+ return page.evaluate(() =>
+ Number.parseFloat(
+ getComputedStyle(document.documentElement).getPropertyValue('--ask-composer-height') || '0',
+ ),
+ );
+}
+
+async function readLineBottom(page: Page, lineSelector: string): Promise<number> {
+ return page.evaluate((selector) => {
+ const painted = [...document.querySelectorAll<HTMLElement>(selector)].filter(
+ (element) => element.closest('.ok-mode-hidden') === null,
+ );
+ const last = painted.at(-1);
+ if (!last) throw new Error(`no painted line matched ${selector}`);
+ return last.getBoundingClientRect().bottom;
+ }, lineSelector);
+}
+
+async function readGeometry(page: Page, surface: Surface): Promise<Geometry> {
+ return page.evaluate(
+ ([cardSelector, lineSelector, scrollportSelector]) => {
+ const card = document.querySelector(cardSelector);
+ if (!(card instanceof HTMLElement))
+ throw new Error('the Ask AI composer card is not painted');
+ const scrollport = document.querySelector(scrollportSelector);
+ if (!(scrollport instanceof HTMLElement)) {
+ throw new Error(`no painted scrollport matched ${scrollportSelector}`);
+ }
+ const painted = [...document.querySelectorAll<HTMLElement>(lineSelector)].filter(
+ (element) => element.closest('.ok-mode-hidden') === null,
+ );
+ const last = painted.at(-1);
+ if (!last) throw new Error(`no painted line matched ${lineSelector}`);
+ return {
+ cardTop: card.getBoundingClientRect().top,
+ lineBottom: last.getBoundingClientRect().bottom,
+ composerHeight: Number.parseFloat(
+ getComputedStyle(document.documentElement).getPropertyValue('--ask-composer-height') ||
+ '0',
+ ),
+ scrollTop: scrollport.scrollTop,
+ scrollMax: scrollport.scrollHeight - scrollport.clientHeight,
+ };
+ },
+ [COMPOSER_CARD, surface.lineSelector, surface.scrollportSelector] as const,
+ );
+}
+
+async function waitForComposerPublished(page: Page): Promise<void> {
+ await expect
+ .poll(() => readComposerHeight(page), {
+ message:
+ 'the composer never published --ask-composer-height, so every geometry assertion below ' +
+ 'would compare an unreserved layout against itself and pass vacuously',
+ timeout: POLL_TIMEOUT_MS,
+ })
+ .toBeGreaterThan(0);
+}
+
+async function waitForGeometrySettled(page: Page, surface: Surface): Promise<Geometry> {
+ let previous: Geometry | undefined;
+ await expect
+ .poll(
+ async () => {
+ const current = await readGeometry(page, surface);
+ const stable =
+ previous !== undefined &&
+ Math.abs(previous.cardTop - current.cardTop) < 0.5 &&
+ Math.abs(previous.lineBottom - current.lineBottom) < 0.5 &&
+ Math.abs(previous.scrollTop - current.scrollTop) < 0.5;
+ previous = current;
+ return stable;
+ },
+ {
+ message: `${surface.label}: the card, the last line and the scrollport never stopped moving`,
+ timeout: POLL_TIMEOUT_MS,
+ intervals: [150, 150, 200, 200, 300, 300, 500],
+ },
+ )
+ .toBe(true);
+ return readGeometry(page, surface);
+}
+
+async function pinScrollportToBottom(page: Page, surface: Surface): Promise<void> {
+ let previousMax = Number.NaN;
+ await expect
+ .poll(
+ async () => {
+ const { scrollTop, scrollMax } = await page.evaluate((selector) => {
+ const scrollport = document.querySelector(selector);
+ if (!(scrollport instanceof HTMLElement)) {
+ throw new Error(`no painted scrollport matched ${selector}`);
+ }
+ scrollport.scrollTop = scrollport.scrollHeight;
+ return {
+ scrollTop: scrollport.scrollTop,
+ scrollMax: scrollport.scrollHeight - scrollport.clientHeight,
+ };
+ }, surface.scrollportSelector);
+ const pinned = scrollMax > 0 && scrollMax - scrollTop < 1 && scrollMax === previousMax;
+ previousMax = scrollMax;
+ return pinned;
+ },
+ {
+ message:
+ `${surface.label}: ${surface.scrollportSelector} never came to rest at its own scroll ` +
+ 'end, so the document was never scrolled to the line this test is about',
+ timeout: POLL_TIMEOUT_MS,
+ intervals: [150, 150, 200, 200, 300, 300, 500],
+ },
+ )
+ .toBe(true);
+}
+
+async function placeCaretOnLastLine(page: Page, surface: Surface): Promise<void> {
+ await page
+ .locator(surface.lineSelector)
+ .filter({ hasNot: page.locator('.ok-mode-hidden') })
+ .last()
+ .click({ position: { x: 4, y: 4 } });
+}
+
+async function settleAtEndOfDocument(page: Page, surface: Surface): Promise<Geometry> {
+ await pinScrollportToBottom(page, surface);
+ await placeCaretOnLastLine(page, surface);
+ await pinScrollportToBottom(page, surface);
+ return waitForGeometrySettled(page, surface);
+}
+
+async function growComposer(page: Page, surface: Surface, before: Geometry): Promise<void> {
+ const minimumGrowth = clearanceOf(before);
+ await page.locator(COMPOSER_INPUT).first().click();
+ await page.keyboard.type(GROW_PROMPT, { delay: 1 });
+ await expect
+ .poll(() => readComposerHeight(page), {
+ message:
+ `${surface.label}: typing a multi-line prompt never grew the composer card past the ` +
+ `${minimumGrowth.toFixed(1)}px the last line already cleared it by, so an uncompensated ` +
+ 'scrollport would still clear the card and the assertion below would pass vacuously',
+ timeout: POLL_TIMEOUT_MS,
+ })
+ .toBeGreaterThan(before.composerHeight + minimumGrowth);
+}
+
+function assertLastLineStaysAboveCard(surface: Surface, before: Geometry, after: Geometry): void {
+ expect(
+ before.scrollMax - before.scrollTop,
+ `${surface.label}: precondition, ${surface.scrollportSelector} must be pinned at its end`,
+ ).toBeLessThan(2);
+ expect(
+ clearanceOf(before),
+ `${surface.label}: precondition, the last line must clear the card before the composer changes`,
+ ).toBeGreaterThan(0);
+ expect(
+ after.composerHeight - before.composerHeight,
+ `${surface.label}: precondition, the card has to grow by more than the ` +
+ `${clearanceOf(before).toFixed(1)}px it already cleared the last line by, or a scrollport ` +
+ 'that compensated for nothing would still clear the card and the assertion below would ' +
+ 'pass vacuously',
+ ).toBeGreaterThan(clearanceOf(before));
+ expect(clearanceOf(after), describeTransition(surface, before, after)).toBeGreaterThan(0);
+}
+
+test.describe('the Ask AI composer keeps the end-of-document line visible as it grows', () => {
+ test.setTimeout(CASE_TIMEOUT_MS);
+
+ test('markdown in WYSIWYG mode keeps its last block above the growing card', async ({
+ page,
+ api,
+ }) => {
+ const docName = `composer-eof-wysiwyg-${randomUUID().slice(0, 8)}`;
+ await api.seedDocs([{ name: `${docName}.md`, markdown: markdownBody }]);
+ const surface: Surface = {
+ label: 'markdown WYSIWYG',
+ lineSelector: WYSIWYG_LINE,
+ scrollportSelector: OUTER_SCROLLPORT,
+ };
+
+ await page.goto(`/#/${docName}`);
+ await expect(page.locator(WYSIWYG_BODY).first()).toBeVisible({
+ timeout: FIRST_PAINT_TIMEOUT_MS,
+ });
+ await waitForComposerPublished(page);
+
+ const before = await settleAtEndOfDocument(page, surface);
+ await growComposer(page, surface, before);
+ const after = await waitForGeometrySettled(page, surface);
+
+ assertLastLineStaysAboveCard(surface, before, after);
+ });
+
+ test('markdown in source mode keeps its last line above the growing card', async ({
+ page,
+ api,
+ }) => {
+ const docName = `composer-eof-source-${randomUUID().slice(0, 8)}`;
+ await api.seedDocs([{ name: `${docName}.md`, markdown: markdownBody }]);
+ const surface: Surface = {
+ label: 'markdown source mode',
+ lineSelector: SOURCE_LINE,
+ scrollportSelector: OUTER_SCROLLPORT,
+ };
+
+ await page.goto(`/#/${docName}`);
+ await expect(page.locator(WYSIWYG_BODY).first()).toBeVisible({
+ timeout: FIRST_PAINT_TIMEOUT_MS,
+ });
+ await toggleMode(page, 'source');
+ await expect(
+ page.locator(SOURCE_SCROLLPORT).first(),
+ 'the markdown doc never entered source mode after toggleMode, so the CodeMirror lines this ' +
+ 'case measures would be absent and settleAtEndOfDocument would throw',
+ ).toBeVisible({ timeout: MODE_SWITCH_TIMEOUT_MS });
+ await waitForComposerPublished(page);
+
+ const before = await settleAtEndOfDocument(page, surface);
+ await growComposer(page, surface, before);
+ const after = await waitForGeometrySettled(page, surface);
+
+ assertLastLineStaysAboveCard(surface, before, after);
+ });
+
+ test('an editable text doc keeps its last line above the growing card', async ({
+ page,
+ workerServer,
+ }) => {
+ const docName = `composer-eof-text-${randomUUID().slice(0, 8)}.ts`;
+ writeFileSync(join(workerServer.contentDir, docName), textDocBody(), 'utf-8');
+ const surface: Surface = {
+ label: 'editable text doc',
+ lineSelector: TEXT_DOC_LINE,
+ scrollportSelector: TEXT_DOC_SCROLLPORT,
+ };
+
+ await page.goto(`/#/${docName}`);
+ await expect(page.locator(TEXT_DOC_CONTENT).first()).toBeVisible({
+ timeout: FIRST_PAINT_TIMEOUT_MS,
+ });
+ await waitForComposerPublished(page);
+
+ const before = await settleAtEndOfDocument(page, surface);
+ await growComposer(page, surface, before);
+ const after = await waitForGeometrySettled(page, surface);
+
+ assertLastLineStaysAboveCard(surface, before, after);
+ });
+
+ test('a mermaid doc in source mode keeps its last line above the growing card', async ({
+ page,
+ workerServer,
+ }) => {
+ const docName = `composer-eof-mermaid-${randomUUID().slice(0, 8)}.mmd`;
+ writeFileSync(join(workerServer.contentDir, docName), mermaidDocBody(), 'utf-8');
+ const surface: Surface = {
+ label: 'mermaid doc source mode',
+ lineSelector: MERMAID_LINE,
+ scrollportSelector: MERMAID_SCROLLPORT,
+ };
+
+ await page.goto(`/#/${docName}`);
+ await expect(page.locator('[data-mermaid-doc-editor]').first()).toBeVisible({
+ timeout: FIRST_PAINT_TIMEOUT_MS,
+ });
+ await toggleMode(page, 'source');
+ await expect(
+ page.locator(MERMAID_CONTENT).first(),
+ 'the mermaid doc never mounted its source-mode CodeMirror content after toggleMode, so ' +
+ 'the scrollport this case pins would be absent and settleAtEndOfDocument would throw',
+ ).toBeVisible({ timeout: MODE_SWITCH_TIMEOUT_MS });
+ await waitForComposerPublished(page);
+
+ const before = await settleAtEndOfDocument(page, surface);
+ await growComposer(page, surface, before);
+ const after = await waitForGeometrySettled(page, surface);
+
+ assertLastLineStaysAboveCard(surface, before, after);
+ });
+
+ test('an editable text doc keeps its last line above the card when the composer reopens', async ({
+ page,
+ workerServer,
+ }) => {
+ const docName = `composer-eof-reopen-${randomUUID().slice(0, 8)}.ts`;
+ writeFileSync(join(workerServer.contentDir, docName), textDocBody(), 'utf-8');
+ const surface: Surface = {
+ label: 'editable text doc, composer reopened',
+ lineSelector: TEXT_DOC_LINE,
+ scrollportSelector: TEXT_DOC_SCROLLPORT,
+ };
+
+ await page.goto(`/#/${docName}`);
+ await expect(page.locator(TEXT_DOC_CONTENT).first()).toBeVisible({
+ timeout: FIRST_PAINT_TIMEOUT_MS,
+ });
+ await waitForComposerPublished(page);
+
+ await page.getByTestId('ask-ai-collapse').click();
+ await expect(page.getByTestId('ask-ai-reopen-badge')).toBeVisible();
+ await pinScrollportToBottom(page, surface);
+ await placeCaretOnLastLine(page, surface);
+ await pinScrollportToBottom(page, surface);
+
+ const dismissedLineBottom = await readLineBottom(page, surface.lineSelector);
+
+ await page.getByTestId('ask-ai-reopen-badge').click();
+ await waitForComposerPublished(page);
+ const after = await waitForGeometrySettled(page, surface);
+
+ expect(
+ dismissedLineBottom,
+ `${surface.label}: precondition, with the composer collapsed the last line has to sit below ` +
+ 'where the reopened card lands, or it would clear the card without the reveal having done ' +
+ 'anything',
+ ).toBeGreaterThan(after.cardTop);
+ expect(
+ clearanceOf(after),
+ [
+ `[${surface.label}] reopening the composer over a document pinned at its end must not bury the last line`,
+ ` scrollport ${surface.scrollportSelector}`,
+ ` composer height ${after.composerHeight}`,
+ ` card top ${after.cardTop.toFixed(1)}`,
+ ` line bottom ${dismissedLineBottom.toFixed(1)} -> ${after.lineBottom.toFixed(1)}`,
+ ` scroll ${after.scrollTop.toFixed(1)}/${after.scrollMax.toFixed(1)}`,
+ ` clearance ${clearanceOf(after).toFixed(1)}`,
+ ].join('\n'),
+ ).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/app/vitest.dom.config.ts b/packages/app/vitest.dom.config.ts
index 010b253c5..b38a89434 100644
--- a/packages/app/vitest.dom.config.ts
+++ b/packages/app/vitest.dom.config.ts
@@ -2,7 +2,8 @@ import { fileURLToPath } from 'node:url';
import { defineConfig, type ViteUserConfig } from 'vitest/config';
import { appVitestConfig } from './vitest.config';
-// Tier-3 DOM project: the `*.dom.test.tsx` React-runtime suite. A dedicated
+// Tier-3 DOM project: the `*.dom.test.ts?(x)` suite — `.tsx` mounts React,
+// `.ts` is the same jsdom tier for DOM-only tests. A dedicated
// vitest project with the jsdom environment and per-file isolation, replacing
// the invocation-scoped `bun test --isolate --preload ./tests/dom/jsdom-preload.ts`
// chain the retired scripts/run-test-dom.sh carried. Everything else (lingui
@@ -44,7 +45,7 @@ export const appDomVitestConfig = {
// `.tsx` mounts React; `.ts` is the same jsdom tier for DOM-only tests
// that never render a component (shadow-root helpers, for instance).
include: ['**/*.dom.test.ts?(x)'],
- // The base config excludes `**/*.dom.test.tsx` so the unit tier stays
+ // The base config excludes `**/*.dom.test.ts?(x)` so the unit tier stays
// no-DOM; this is the one project that runs them, so drop that single
// exclusion while keeping node_modules / .spec / .e2e out.
exclude: appVitestConfig.test.exclude.filter((pattern) => pattern !== '**/*.dom.test.ts?(x)'),