Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(chat): preserve reader position while paging history (#1893)

Call Whiteb3f031790dee
diff --git a/ui/e2e/chat-paging/README.md b/ui/e2e/chat-paging/README.md
new file mode 100644
index 000000000..3451e4211
--- /dev/null
+++ b/ui/e2e/chat-paging/README.md
@@ -0,0 +1,23 @@
+# Chat Paging Browser Regression
+
+From `ui/`, install the existing Playwright Chromium browser with
+`npx playwright install chromium`, then run `npm run test:chat-paging`.
+
+The command typechecks the fixture and tests, starts a dedicated Vite server on
+loopback port 5198, and runs desktop and mobile Chromium in isolated browser
+contexts. The real `Transcript` component receives in-memory messages and page
+responses. No Avibe backend, credentials, or persistent application state is
+used. This suite is separate from the live Model Hub suite.
+
+The tests verify one page per upward request, stable reader position across
+the 300-message retention cap, fast responses with unchanged content height,
+empty pages followed by wheel or touch input, keyboard focus and repeat handling,
+continuous gestures, nested scrolling, and explicit failure recovery.
+Screenshots and failed traces are written under `e2e/.artifacts/chat-paging/`.
+
+For interactive inspection on a regular Vite dev server, open
+`/e2e/chat-paging/fixture.html`. Query parameters select the initial retained
+count (`count=300`), response delay (`delay=0`), or an empty/failed first page
+(`empty=1` / `fail=1`). `empty=10` returns ten empty pages; `nested=1&count=1`
+includes a scrollable activity fixture. These fixtures are not included in
+production builds.
diff --git a/ui/e2e/chat-paging/fixture.html b/ui/e2e/chat-paging/fixture.html
new file mode 100644
index 000000000..23619937a
--- /dev/null
+++ b/ui/e2e/chat-paging/fixture.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Chat Paging Regression</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="./fixture.tsx"></script>
+ </body>
+</html>
diff --git a/ui/e2e/chat-paging/fixture.tsx b/ui/e2e/chat-paging/fixture.tsx
new file mode 100644
index 000000000..b4e68efc8
--- /dev/null
+++ b/ui/e2e/chat-paging/fixture.tsx
@@ -0,0 +1,112 @@
+import { useRef, useState } from 'react';
+import { createRoot } from 'react-dom/client';
+import { MemoryRouter } from 'react-router-dom';
+
+import { Transcript } from '../../src/components/workbench/ChatPage';
+import { ApiProvider, type WorkbenchMessage, type WorkbenchSession } from '../../src/context/ApiContext';
+import { ToastContext } from '../../src/context/ToastContext';
+import { WindowManagerContext, type WindowManagerValue } from '../../src/context/WindowManagerContext';
+import '../../src/i18n';
+import '../../src/index.css';
+
+const noop = () => {};
+const session = { id: 'paging-fixture', title: 'History', metadata: {} } as WorkbenchSession;
+const history: WorkbenchMessage[] = Array.from({ length: 600 }, (_, index) => ({
+ id: `message-${index + 1}`,
+ scope_id: null,
+ session_id: session.id,
+ platform: 'avibe',
+ author: index % 2 ? 'agent' : 'user',
+ type: index % 2 ? 'result' : 'user',
+ source: index % 2 ? 'agent' : 'user',
+ author_id: null,
+ author_name: null,
+ native_message_id: null,
+ parent_native_message_id: null,
+ text: `Message ${index + 1}\nFirst line of history.\nSecond line of history.`,
+ content: {},
+ metadata: {},
+ created_at: new Date(Date.UTC(2026, 8, 1, 0, 0, index)).toISOString(),
+ updated_at: new Date(Date.UTC(2026, 8, 1, 0, 0, index)).toISOString(),
+ delivered_at: null,
+ read_at: null,
+}));
+const params = new URLSearchParams(window.location.search);
+const initialCount = Number(params.get('count') ?? 50);
+const delay = Number(params.get('delay') ?? 100);
+
+export function Fixture() {
+ const [messages, setMessages] = useState(history.slice(-initialCount));
+ const [before, setBefore] = useState(history.length - initialCount);
+ const [loading, setLoading] = useState(false);
+ const [loads, setLoads] = useState(0);
+ const [needsLatestReload, setNeedsLatestReload] = useState(false);
+ const followingTailRef = useRef(true);
+
+ const loadOlder = async () => {
+ setLoading(true);
+ setLoads((count) => count + 1);
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ if (params.has('fail') && loads === 0) {
+ setLoading(false);
+ return false;
+ }
+ const start = Math.max(0, before - 50);
+ if (loads >= Number(params.get('empty') ?? 0)) {
+ setMessages((current) => [...history.slice(start, before), ...current].slice(0, 300));
+ if (messages.length + before - start > 300) setNeedsLatestReload(true);
+ }
+ setBefore(start);
+ setLoading(false);
+ return true;
+ };
+
+ return (
+ <div className="flex h-dvh flex-col bg-background text-foreground" data-testid="chat-paging-fixture" data-loads={loads}>
+ <Transcript
+ messages={messages}
+ session={session}
+ agentDisplayName="Agent"
+ working={false}
+ hasOlder={before > 0}
+ loadingOlder={loading}
+ onLoadOlder={loadOlder}
+ needsLatestReload={needsLatestReload}
+ onReloadLatest={async () => {
+ setMessages(history.slice(-50));
+ setBefore(history.length - 50);
+ setNeedsLatestReload(false);
+ return true;
+ }}
+ jumpTarget={null}
+ onJumpHandled={noop}
+ highlightedId={null}
+ messageFontSize={14}
+ onQuickReply={noop}
+ provisionRequestsByMessage={new Map()}
+ onVaultRequestResolved={noop}
+ onQuoteSelection={noop}
+ onAskInNewSession={noop}
+ readOnly
+ followingTailRef={followingTailRef}
+ footer={params.has('nested') ? (
+ <div data-testid="nested-scroller" tabIndex={0} className="h-40 overflow-y-auto">
+ {Array.from({ length: 30 }, (_, index) => <p key={index}>Activity line {index + 1}</p>)}
+ </div>
+ ) : undefined}
+ />
+ </div>
+ );
+}
+
+createRoot(document.getElementById('root')!).render(
+ <MemoryRouter>
+ <ToastContext.Provider value={{ showToast: noop }}>
+ <ApiProvider>
+ <WindowManagerContext.Provider value={{ focusedId: null, focusCanvas: noop } as WindowManagerValue}>
+ <Fixture />
+ </WindowManagerContext.Provider>
+ </ApiProvider>
+ </ToastContext.Provider>
+ </MemoryRouter>,
+);
diff --git a/ui/e2e/chat-paging/paging.spec.ts b/ui/e2e/chat-paging/paging.spec.ts
new file mode 100644
index 000000000..24fa6af02
--- /dev/null
+++ b/ui/e2e/chat-paging/paging.spec.ts
@@ -0,0 +1,156 @@
+import { expect, test, type Page } from '@playwright/test';
+import { copy } from '../support/copy';
+
+const fixture = (page: Page) => page.getByTestId('chat-paging-fixture');
+const scroller = (page: Page) => page.getByTestId('chat-transcript');
+const loads = async (page: Page) => Number(await fixture(page).getAttribute('data-loads'));
+const open = async (page: Page, query = '') => {
+ // No API request from this fixture may reach a running Avibe service.
+ await page.route('**/api/**', (route) => route.fulfill({ status: 503, json: { error: 'No backend in this fixture' } }));
+ await page.goto(`/e2e/chat-paging/fixture.html${query}`);
+ await expect(scroller(page)).toBeVisible();
+ if (new URLSearchParams(query).get('count') !== '1') {
+ await expect.poll(() => scroller(page).evaluate((el) => el.scrollTop)).toBeGreaterThan(120);
+ }
+};
+
+test('each upward visit loads one page and preserves the reader through the retained-window cap', async ({ page }, testInfo) => {
+ await open(page);
+ for (let index = 0; index < 8; index += 1) {
+ const anchorId = await page.locator('[data-message-id]').first().getAttribute('data-message-id');
+ const anchor = page.locator(`[data-message-id="${anchorId}"]`);
+ await scroller(page).evaluate((el) => { el.scrollTop = 0; });
+ const top = await anchor.evaluate((el) => el.getBoundingClientRect().top);
+ await expect(fixture(page)).toHaveAttribute('data-loads', String(index + 1));
+ await expect(page.getByRole('status', { name: copy('chat.loadingOlder') })).toHaveCount(0);
+ await expect.poll(() => scroller(page).evaluate((el) => el.scrollTop)).toBeGreaterThan(120);
+ expect(Math.abs(await anchor.evaluate((el) => el.getBoundingClientRect().top) - top)).toBeLessThan(1);
+ await expect(page.locator('[data-message-id]')).toHaveCount(Math.min(100 + index * 50, 300));
+ // Observe an idle interval: finishing, resizing and queued scroll events
+ // must not produce another request without a new upward input.
+ await page.waitForTimeout(150);
+ expect(await loads(page)).toBe(index + 1);
+ }
+ await page.screenshot({ path: testInfo.outputPath('reader.png'), scale: 'css' });
+});
+
+test('restores a capped window even when the page lands before the next resize observation', async ({ page }) => {
+ await open(page, '?count=300&delay=0');
+ const height = await scroller(page).evaluate((el) => el.scrollHeight);
+ for (let index = 0; index < 3; index += 1) {
+ await scroller(page).evaluate((el) => { el.scrollTop = 0; });
+ await expect(fixture(page)).toHaveAttribute('data-loads', String(index + 1));
+ await expect.poll(() => scroller(page).evaluate((el) => el.scrollTop)).toBeGreaterThan(120);
+ expect(await scroller(page).evaluate((el) => el.scrollHeight)).toBe(height);
+ await page.waitForTimeout(150);
+ expect(await loads(page)).toBe(index + 1);
+ }
+});
+
+test('waits after an empty page and accepts another upward gesture at the hard top', async ({ page, isMobile }) => {
+ await open(page, '?empty=1');
+ await scroller(page).evaluate((el) => { el.scrollTop = 0; });
+ await expect(fixture(page)).toHaveAttribute('data-loads', '1');
+ await expect(page.getByRole('status', { name: copy('chat.loadingOlder') })).toHaveCount(0);
+ await page.waitForTimeout(200);
+ expect(await loads(page)).toBe(1);
+ expect(await scroller(page).evaluate((el) => el.scrollTop)).toBe(0);
+ if (isMobile) {
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: 180, y: 200 }] });
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: 180, y: 300 }] });
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
+ await cdp.detach();
+ } else {
+ await scroller(page).hover();
+ await page.mouse.wheel(0, -150);
+ }
+ await expect(fixture(page)).toHaveAttribute('data-loads', '2');
+ await expect(page.locator('[data-message-id]')).toHaveCount(100);
+});
+
+test('offers an explicit retry for a failed page and then restores the reader', async ({ page }) => {
+ await open(page, '?fail=1');
+ await scroller(page).evaluate((el) => { el.scrollTop = 0; });
+ const retry = page.getByRole('button', { name: copy('chat.olderLoadFailed') });
+ await expect(retry).toBeVisible();
+ await page.waitForTimeout(200);
+ expect(await loads(page)).toBe(1);
+ await retry.click();
+ await expect(page.locator('[data-message-id]')).toHaveCount(100);
+ expect(await loads(page)).toBe(2);
+ await expect.poll(() => scroller(page).evaluate((el) => el.scrollTop)).toBeGreaterThan(120);
+});
+
+test('consumes one continuous gesture even when every response is empty and immediate', async ({ page, isMobile }) => {
+ await open(page, '?count=1&empty=10&delay=0');
+ if (isMobile) {
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: 180, y: 200 }] });
+ for (const y of [250, 300, 350]) {
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: 180, y }] });
+ await page.waitForTimeout(70);
+ expect(await loads(page)).toBe(1);
+ }
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
+ await page.waitForTimeout(250);
+ expect(await loads(page)).toBe(1);
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: 180, y: 200 }] });
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: 180, y: 250 }] });
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
+ await cdp.detach();
+ } else {
+ await scroller(page).hover();
+ for (const delta of [-150, -100, -50]) {
+ await page.mouse.wheel(0, delta);
+ await page.waitForTimeout(70);
+ expect(await loads(page)).toBe(1);
+ }
+ await page.waitForTimeout(250);
+ await page.mouse.wheel(0, -100);
+ }
+ await expect(fixture(page)).toHaveAttribute('data-loads', '2');
+});
+
+test('reaches the transcript with Tab and pages once per key press', async ({ page }) => {
+ await open(page, '?count=1&empty=10&delay=0');
+ await page.keyboard.press('Tab');
+ await expect(scroller(page)).toBeFocused();
+ await page.keyboard.down('PageUp');
+ await expect(fixture(page)).toHaveAttribute('data-loads', '1');
+ await page.keyboard.down('PageUp');
+ await page.waitForTimeout(100);
+ expect(await loads(page)).toBe(1);
+ await page.keyboard.up('PageUp');
+ await page.keyboard.press('PageUp');
+ await expect(fixture(page)).toHaveAttribute('data-loads', '2');
+});
+
+test('scrolls nested content without paging the surrounding transcript', async ({ page, isMobile }) => {
+ await open(page, '?count=1&nested=1&empty=10&delay=0');
+ const nested = page.getByTestId('nested-scroller');
+ await nested.evaluate((el) => { el.scrollTop = 150; });
+ expect(await scroller(page).evaluate((el) => el.scrollTop)).toBe(0);
+ if (isMobile) {
+ const bounds = (await nested.boundingBox())!;
+ const x = bounds.x + bounds.width / 2;
+ const y = bounds.y + 30;
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] });
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: y + 45 }] });
+ await expect.poll(() => nested.evaluate((el) => el.scrollTop)).toBeLessThan(150);
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
+ await cdp.detach();
+ } else {
+ await nested.hover();
+ await page.mouse.wheel(0, -50);
+ await expect.poll(() => nested.evaluate((el) => el.scrollTop)).toBeLessThan(150);
+ }
+ await page.waitForTimeout(200);
+ expect(await loads(page)).toBe(0);
+ await nested.focus();
+ await nested.evaluate((el) => { el.scrollTop = 300; });
+ await page.keyboard.press('PageUp');
+ await expect.poll(() => nested.evaluate((el) => el.scrollTop)).toBeLessThan(300);
+ expect(await loads(page)).toBe(0);
+});
diff --git a/ui/e2e/chat-paging/tsconfig.json b/ui/e2e/chat-paging/tsconfig.json
new file mode 100644
index 000000000..121b6be7f
--- /dev/null
+++ b/ui/e2e/chat-paging/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "extends": "../../tsconfig.app.json",
+ "compilerOptions": {
+ "types": ["vite/client", "node"]
+ },
+ "include": ["*.ts", "*.tsx", "../../playwright.chat-paging.config.ts", "../../agentation.d.ts"],
+ "exclude": []
+}
diff --git a/ui/package.json b/ui/package.json
index 3f1920b8a..8361a6fdf 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -19,6 +19,7 @@
"test:crypto": "vitest run src/lib/vaultCrypto.test.ts",
"e2e": "playwright test",
"e2e:headed": "playwright test --headed",
+ "test:chat-paging": "tsc -p e2e/chat-paging/tsconfig.json --noEmit && playwright test --config playwright.chat-paging.config.ts",
"validate:catalog": "node scripts/validate-scenario-catalog.mjs",
"validate:theme": "node scripts/validate-theme.mjs"
},
diff --git a/ui/playwright.chat-paging.config.ts b/ui/playwright.chat-paging.config.ts
new file mode 100644
index 000000000..353c70664
--- /dev/null
+++ b/ui/playwright.chat-paging.config.ts
@@ -0,0 +1,20 @@
+import { defineConfig, devices } from '@playwright/test';
+
+// This suite renders the real Transcript with an in-memory pagination owner.
+// It has no Avibe backend, credentials, or persistent application state.
+export default defineConfig({
+ testDir: './e2e/chat-paging',
+ outputDir: './e2e/.artifacts/chat-paging',
+ workers: 1,
+ retries: 0,
+ use: { baseURL: 'http://127.0.0.1:5198', locale: 'en-US', trace: 'retain-on-failure' },
+ webServer: {
+ command: 'npm run dev -- --host 127.0.0.1 --port 5198 --strictPort',
+ env: { VIBE_UI_BACKEND: 'http://127.0.0.1:9' },
+ url: 'http://127.0.0.1:5198/e2e/chat-paging/fixture.html',
+ },
+ projects: [
+ { name: 'desktop', use: { ...devices['Desktop Chrome'] } },
+ { name: 'mobile', use: { ...devices['iPhone 13'], browserName: 'chromium' } },
+ ],
+});
diff --git a/ui/playwright.config.ts b/ui/playwright.config.ts
index 767ee2796..822ef2a67 100644
--- a/ui/playwright.config.ts
+++ b/ui/playwright.config.ts
@@ -16,6 +16,7 @@ import { BASE_URL } from './e2e/support/env';
export default defineConfig({
testDir: './e2e',
+ testIgnore: '**/chat-paging/**',
outputDir: './e2e/.artifacts/test-results',
// Every spec mutates shared instance state (sources, agent modes, the
// runtime switch). Parallel workers would race on it, so the suite is serial
diff --git a/ui/src/components/workbench/ChatOlderPaging.test.tsx b/ui/src/components/workbench/ChatOlderPaging.test.tsx
index 625add156..eb32bfdb1 100644
--- a/ui/src/components/workbench/ChatOlderPaging.test.tsx
+++ b/ui/src/components/workbench/ChatOlderPaging.test.tsx
@@ -1,219 +1,77 @@
/** @vitest-environment jsdom */
-// The transcript's older-page loader must be LEVEL-triggered: for as long as the
-// reader is inside the trigger band at the top of the loaded window and older
-// history remains, pages keep arriving. The invariant is deliberately stated
-// without reference to scroll events, because the reader most likely to want
-// another page — already parked at the very top — cannot produce one: an upward
-// gesture at scrollTop 0 moves nothing, so no scroll event is emitted at all.
-//
-// The IntersectionObserver stub below models the one browser guarantee the fix
-// rests on: ``observe()`` reports the CURRENT intersection state, rather than
-// waiting for the next crossing. So each test declares where the reader is as a
-// standing fact and lets the component ask as often as it likes.
-
import { act, cleanup, fireEvent, render } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter } from 'react-router-dom';
-import { createRef } from 'react';
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
-vi.mock('../../context/ApiContext', () => ({
- useApi: () => ({}),
-}));
-
-vi.mock('../../context/ToastContext', () => ({
- useToast: () => ({ showToast: vi.fn() }),
-}));
+import { createRef, type ComponentProps } from 'react';
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('../../context/ApiContext', () => ({ useApi: () => ({}) }));
+vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));
vi.mock('../../context/InstanceAuthorizationContext', () => ({
useInstanceAuthorization: () => ({
- capabilities: {
- can_chat: true,
- can_manage_instance: false,
- can_use_show_pages: false,
- can_use_vault_secrets: false,
- },
+ capabilities: { can_chat: true, can_manage_instance: false, can_use_show_pages: false, can_use_vault_secrets: false },
}),
}));
-
vi.mock('../../context/WindowManagerContext', () => ({
useWindowManager: () => ({ focusedId: null, focusCanvas: vi.fn() }),
}));
-
-vi.mock('../../lib/useIsDesktop', () => ({
- isDesktopViewport: () => false,
- useIsDesktop: () => false,
-}));
-
-// Importing ChatPage pulls in the composer's lexical stack, which touches
-// browser APIs jsdom lacks at module scope. The transcript never renders it.
-vi.mock('./Composer', () => ({
- Composer: () => null,
-}));
+vi.mock('../../lib/useIsDesktop', () => ({ isDesktopViewport: () => false, useIsDesktop: () => false }));
+// The transcript does not render the composer's browser-only Lexical stack.
+vi.mock('./Composer', () => ({ Composer: () => null }));
import { Transcript } from './ChatPage';
-import type { WorkbenchSession } from '../../context/ApiContext';
-
-// One live IntersectionObserver stub shared by the render under test. ``atTop``
-// is the world: where the reader is sitting. Every observe() answers with it,
-// which is what a real observer does for a freshly observed target.
-class FakeIntersectionObserver {
- static live: FakeIntersectionObserver[] = [];
- static atTop = false;
-
- private callback: IntersectionObserverCallback;
- private observed = new Set<Element>();
- private pending = new Set<Element>();
- private readonly root: Element | null;
+import type { WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
+
+type Props = ComponentProps<typeof Transcript>;
+const messages = (first: number, count: number): WorkbenchMessage[] =>
+ Array.from({ length: count }, (_, index) => ({
+ id: `msg-${first + index}`,
+ session_id: 'session-1',
+ platform: 'avibe',
+ author: 'user',
+ type: 'user',
+ text: `Message ${first + index}`,
+ content: {},
+ metadata: {},
+ created_at: new Date(Date.UTC(2026, 8, 1, 0, 0, first + index)).toISOString(),
+ }) as WorkbenchMessage);
- constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) {
- this.callback = callback;
- this.root = (options?.root as Element | null) ?? null;
- FakeIntersectionObserver.live.push(this);
- }
-
- // The element the transcript scrolls. The observer is rooted at it, so a test
- // reaches it through the observer rather than by matching a class name.
- static scroller(): HTMLElement {
- const root = FakeIntersectionObserver.live[0]?.root;
- if (!(root instanceof HTMLElement)) {
- throw new Error('the older-page observer was not rooted at the scroll container');
- }
- return root;
- }
-
- observe(target: Element) {
- this.observed.add(target);
- this.deliver(target);
- }
-
- unobserve(target: Element) {
- this.observed.delete(target);
- }
-
- disconnect() {
- this.observed.clear();
- FakeIntersectionObserver.live = FakeIntersectionObserver.live.filter((io) => io !== this);
- }
-
- // Simulate the reader's position changing under a live observer.
- static move(atTop: boolean) {
- FakeIntersectionObserver.atTop = atTop;
- for (const io of [...FakeIntersectionObserver.live]) {
- for (const target of io.deliverable()) io.deliver(target);
- }
- }
-
- private deliverable() {
- return [...this.observed];
- }
-
- // A real observer never calls back from inside ``observe()``: the delivery is
- // queued, and the intersection it reports is computed when the queue runs, not
- // when it was queued. That gap is a whole frame in which the reader can move,
- // so the fake keeps it — a component that only behaves correctly when its own
- // re-observe answers instantly is not correct.
- private deliver(target: Element) {
- // One notification per target per frame, however many times the browser was
- // asked. A real observer batches its entries into a single callback, so a
- // component never sees two answers with no render in between.
- if (this.pending.has(target)) return;
- this.pending.add(target);
- queueMicrotask(() => {
- this.pending.delete(target);
- if (!this.observed.has(target)) return;
- const entry = { target, isIntersecting: FakeIntersectionObserver.atTop };
- this.callback([entry as IntersectionObserverEntry], this as never);
- });
- }
-}
-
-const session = (): WorkbenchSession =>
- ({
- id: 'session-1',
- title: 'Session',
- agent_name: null,
- archived_at: null,
- }) as unknown as WorkbenchSession;
-
-// A transcript taller than its viewport, scrolled up to the top of the loaded
-// window: the reader is in history, which is what paging exists for.
-const READING_HISTORY = { scrollTop: 0, scrollHeight: 10_000, clientHeight: 800 };
-// A transcript SHORT enough to fit its viewport. There is nothing to scroll, so
-// the reader is still following the live tail even though the top of the loaded
-// window — and the sentinel with it — is permanently in view.
-const FITS_VIEWPORT = { scrollTop: 0, scrollHeight: 800, clientHeight: 800 };
+const pendingPage = () => {
+ let land!: (ok: boolean) => void;
+ const promise = new Promise<boolean>((resolve) => { land = resolve; });
+ return { promise, land };
+};
-// Frame callbacks are queued rather than run inline, because the deep-link jump
-// spreads across two frames and its suppression window — open in the first,
-// released in the second — is a state the trigger has to be tested against.
let nextFrameId = 1;
const frames = new Map<number, FrameRequestCallback>();
const flushFrames = () => {
const queued = [...frames.values()];
frames.clear();
- for (const cb of queued) cb(0);
+ queued.forEach((callback) => callback(0));
};
-// jsdom has no layout, so where the reader sits is stated as geometry and
-// announced with the scroll event a browser would emit. This is the production
-// path: the transcript derives "following the live tail" from exactly these
-// three numbers, and nothing else tells it where the reader is.
-const placeReader = (
- el: HTMLElement,
- geometry: { scrollTop: number; scrollHeight: number; clientHeight: number },
-) => {
- for (const [prop, value] of Object.entries(geometry)) {
- Object.defineProperty(el, prop, { value, writable: true, configurable: true });
- }
- fireEvent.scroll(el);
-};
-
-// A page the test lands by hand. Landing is not a detail these tests can leave
-// to a resolved mock: a page that lands re-asks the level question, so a world
-// that never moves would be asked for pages forever. Production moves it — the
-// prepended rows and the anchor restore push the sentinel back out of the band.
-const pendingPage = () => {
- let land: (ok: boolean) => void = () => {};
- const promise = new Promise<boolean>((resolve) => {
- land = resolve;
- });
- return { promise, land: (ok: boolean) => land(ok) };
-};
-
-// A request that goes out and never comes back — for tests that assert what was
-// asked for rather than what happened next.
-const neverLands = () => new Promise<boolean>(() => {});
+class TestResizeObserver {
+ static live = new Set<TestResizeObserver>();
+ constructor(private callback: ResizeObserverCallback) { TestResizeObserver.live.add(this); }
+ observe() {}
+ unobserve() {}
+ disconnect() { TestResizeObserver.live.delete(this); }
+ static resize() { for (const observer of TestResizeObserver.live) observer.callback([], observer as unknown as ResizeObserver); }
+}
-const renderTranscript = (over: {
- hasOlder?: boolean;
- loadingOlder?: boolean;
- onLoadOlder?: () => void | Promise<boolean>;
- // A deep-link target. With no rows rendered the jump finds nothing to centre,
- // which is fine: what matters here is the suppression window it opens.
- jumpTarget?: string;
- // Whether the reader is following the live tail. Defaults to "scrolled up in
- // history", the state every paging assertion below is about.
- following?: boolean;
-}) => {
- const props = {
- messages: [],
- session: session(),
+const renderTranscript = (over: Partial<Props> = {}) => {
+ const props: Props = {
+ messages: messages(301, 50),
+ session: { id: 'session-1', title: 'Session', agent_name: null, archived_at: null } as WorkbenchSession,
agentDisplayName: null,
- // No rows, but ``working`` keeps the transcript out of its empty state, so the
- // scroll container (and the sentinel inside it) mounts. The trigger does not
- // depend on row content.
- working: true,
- hasOlder: over.hasOlder ?? true,
- loadingOlder: over.loadingOlder ?? false,
- onLoadOlder: over.onLoadOlder ?? vi.fn(),
+ working: false,
+ hasOlder: true,
+ loadingOlder: false,
+ onLoadOlder: vi.fn().mockResolvedValue(true),
needsLatestReload: false,
onReloadLatest: vi.fn().mockResolvedValue(true),
- jumpTarget: over.jumpTarget ?? null,
+ jumpTarget: null,
onJumpHandled: vi.fn(),
highlightedId: null,
messageFontSize: 14,
@@ -224,211 +82,343 @@ const renderTranscript = (over: {
onAskInNewSession: vi.fn(),
readOnly: false,
followingTailRef: createRef<boolean>() as React.MutableRefObject<boolean>,
+ ...over,
};
- const view = render(
- <MemoryRouter>
- <Transcript {...props} />
- </MemoryRouter>,
- );
- // The mount effect jumps to the bottom inside a frame callback and pins the
- // transcript there. Let that land first, so this placement is what the
- // component ends up believing rather than something it overwrites later.
- act(() => flushFrames());
- placeReader(FakeIntersectionObserver.scroller(), over.following ? FITS_VIEWPORT : READING_HISTORY);
-
- const rerender = (next: Partial<typeof props>) =>
- view.rerender(
- <MemoryRouter>
- <Transcript {...props} {...next} />
- </MemoryRouter>,
- );
- return { ...view, rerender, props };
+ const view = render(<MemoryRouter><Transcript {...props} /></MemoryRouter>);
+ const scroller = view.getByTestId('chat-transcript');
+ const geometry = { extraAbove: 0 };
+ let scrollTop = 0;
+ const loadingSlotHeight = () => scroller.querySelector('[role="status"], button')?.classList.contains('h-8') ? 44 : 0;
+ Object.defineProperties(scroller, {
+ clientHeight: { configurable: true, get: () => 800 },
+ scrollHeight: { configurable: true, get: () => scroller.querySelectorAll('[data-message-id]').length * 112 + 40 + loadingSlotHeight() + geometry.extraAbove },
+ scrollTop: {
+ configurable: true,
+ get: () => scrollTop,
+ set: (value: number) => { scrollTop = Math.max(0, Math.min(value, scroller.scrollHeight - scroller.clientHeight)); },
+ },
+ });
+ scroller.getBoundingClientRect = () => ({ top: 10, bottom: 810, height: 800 }) as DOMRect;
+ // jsdom has no layout. Derive every row's position from the committed DOM,
+ // including prepended rows and the transient loading slot + column gap.
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
+ if (this.dataset.messageId === undefined) return { top: 0, bottom: 0, height: 0 } as DOMRect;
+ const rows = Array.from(scroller.querySelectorAll('[data-message-id]'));
+ const index = rows.indexOf(this);
+ const top = 30 + index * 112 + loadingSlotHeight() + (index > 0 ? geometry.extraAbove : 0) - scrollTop;
+ return { top, bottom: top + 100, height: 100 } as DOMRect;
+ });
+ act(flushFrames);
+ const rerender = (next: Partial<Props>) => {
+ Object.assign(props, next);
+ view.rerender(<MemoryRouter><Transcript {...props} /></MemoryRouter>);
+ };
+ const scrollTo = (top: number) => {
+ fireEvent.pointerDown(scroller, { pointerType: 'mouse' });
+ scroller.scrollTop = top;
+ fireEvent.scroll(scroller);
+ };
+ return { ...view, scroller, geometry, props, rerender, scrollTo };
};
describe('transcript older-page loading', () => {
beforeEach(() => {
- // jsdom ships no CSS namespace object; the deep-link jump escapes its target
- // id before looking the row up.
vi.stubGlobal('CSS', { escape: (value: string) => value });
- FakeIntersectionObserver.live = [];
- FakeIntersectionObserver.atTop = false;
- vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
+ TestResizeObserver.live.clear();
+ vi.stubGlobal('ResizeObserver', TestResizeObserver);
+ vi.stubGlobal('IntersectionObserver', class { observe() {} disconnect() {} unobserve() {} });
nextFrameId = 1;
frames.clear();
- vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
const id = nextFrameId++;
- frames.set(id, cb);
+ frames.set(id, callback);
return id;
});
- vi.stubGlobal('cancelAnimationFrame', (id: number) => {
- frames.delete(id);
- });
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- observe() {}
- unobserve() {}
- disconnect() {}
- },
- );
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id));
});
-
afterEach(() => {
cleanup();
+ vi.restoreAllMocks();
vi.unstubAllGlobals();
});
- it('keeps loading pages while the reader stays at the top, with no scroll event', async () => {
- const first = pendingPage();
- const onLoadOlder = vi.fn().mockReturnValueOnce(first.promise).mockReturnValue(neverLands());
- renderTranscript({ onLoadOlder });
-
- // The reader scrolls up into the trigger band.
- await act(async () => FakeIntersectionObserver.move(true));
+ it('requires fresh upward input for each page, even when a page adds no visible rows', async () => {
+ const now = vi.spyOn(performance, 'now').mockReturnValue(0);
+ const page = pendingPage();
+ const onLoadOlder = vi.fn().mockReturnValueOnce(page.promise).mockResolvedValue(true);
+ const { scroller, scrollTo, rerender } = renderTranscript({ onLoadOlder });
+ scrollTo(0);
expect(onLoadOlder).toHaveBeenCalledTimes(1);
-
- // The page is in flight and the reader is still in the band: asking again
- // would put a second request on the wire for the page already coming.
- await act(async () => FakeIntersectionObserver.move(true));
+ rerender({ loadingOlder: true });
+ fireEvent.wheel(scroller, { deltaY: -100 });
+ fireEvent.scroll(scroller);
expect(onLoadOlder).toHaveBeenCalledTimes(1);
- // It lands, and the reader never moved — still at the top of the loaded
- // window, still more history behind it. This is the case the old
- // scroll-armed latch deadlocked on, and the whole point of the fix.
- await act(async () => first.land(true));
+ await act(async () => { rerender({ loadingOlder: false }); page.land(true); });
+ act(TestResizeObserver.resize);
+ fireEvent.scroll(scroller);
+ expect(scroller.scrollTop).toBe(0);
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ now.mockReturnValue(300);
+ await act(async () => fireEvent.wheel(scroller, { deltaY: -100 }));
expect(onLoadOlder).toHaveBeenCalledTimes(2);
});
- it('stops once the reader leaves the band or history runs out', async () => {
- const first = pendingPage();
- const onLoadOlder = vi.fn().mockReturnValue(first.promise);
- const { rerender } = renderTranscript({ onLoadOlder });
+ it.each([50, 300])('preserves the reader through a prepend with %i retained rows and no resize notification', async (count) => {
+ const page = pendingPage();
+ const onLoadOlder = vi.fn().mockReturnValueOnce(page.promise).mockReturnValue(new Promise(() => {}));
+ const { scroller, scrollTo, rerender, geometry } = renderTranscript({ messages: messages(301, count), onLoadOlder });
+ scrollTo(0);
+ const anchor = scroller.querySelector('[data-message-id="msg-301"]')!;
+ const before = anchor.getBoundingClientRect().top;
+ const height = scroller.scrollHeight;
+ rerender({ loadingOlder: true });
+ expect(anchor.getBoundingClientRect().top).toBe(before);
+ expect(scroller.scrollTop).toBe(44);
- await act(async () => FakeIntersectionObserver.move(true));
+ await act(async () => {
+ rerender({ messages: messages(251, Math.min(count + 50, 300)), loadingOlder: false });
+ page.land(true);
+ });
+ expect(anchor.getBoundingClientRect().top).toBe(before);
+ expect(scroller.scrollTop).toBe(50 * 112);
+ if (count === 300) expect(scroller.scrollHeight).toBe(height);
+ // A queued scroll from mounting/removing the spinner sees the restored DOM.
+ fireEvent.scroll(scroller);
+ rerender({ agentDisplayName: 'Renamed agent' });
expect(onLoadOlder).toHaveBeenCalledTimes(1);
- // The prepended page pushes the sentinel out of the band (the anchor restore
- // does this for real) — the reader is no longer asking for anything.
- await act(async () => FakeIntersectionObserver.move(false));
- await act(async () => first.land(true));
+ geometry.extraAbove = 180;
+ act(TestResizeObserver.resize);
+ fireEvent.scroll(scroller);
+ expect(anchor.getBoundingClientRect().top).toBe(before);
expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ scrollTo(0);
+ expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ });
- // Back at the top, but the server says that was the last page.
- await act(async () => rerender({ hasOlder: false }));
- await act(async () => FakeIntersectionObserver.move(true));
+ it('allows another upward scroll inside the trigger band without a down-and-up detour', async () => {
+ const onLoadOlder = vi.fn().mockResolvedValue(true);
+ const { scrollTo } = renderTranscript({ onLoadOlder });
+ await act(async () => scrollTo(110));
expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ await act(async () => scrollTo(100));
+ expect(onLoadOlder).toHaveBeenCalledTimes(2);
});
- it('does not page while the reader is following the live tail', async () => {
+ const upwardInputs = {
+ wheel: (el: HTMLElement) => fireEvent.wheel(el, { deltaY: -100 }),
+ touch: (el: HTMLElement) => {
+ fireEvent.touchStart(el, { touches: [{ clientY: 100 }] });
+ fireEvent.touchMove(el, { touches: [{ clientY: 140 }] });
+ fireEvent.touchEnd(el);
+ },
+ keyboard: (el: HTMLElement) => fireEvent.keyDown(el, { key: 'PageUp' }),
+ };
+ it.each(Object.entries(upwardInputs))('accepts %s input at the hard top without a scroll event', async (_name, upward) => {
const onLoadOlder = vi.fn().mockResolvedValue(true);
- const { rerender } = renderTranscript({ onLoadOlder, following: true });
-
- // A transcript short enough to fit its viewport leaves the sentinel in the
- // band with the reader still parked on the latest message. Sentinel in view
- // is only a REQUEST for older history if the reader went looking for it —
- // otherwise opening or resizing such a chat would walk backwards through
- // history nobody asked to see.
- await act(async () => FakeIntersectionObserver.move(true));
- await act(async () => rerender({ loadingOlder: true }));
- await act(async () => rerender({ loadingOlder: false }));
+ const { scroller, rerender, props } = renderTranscript({ messages: messages(1, 1), onLoadOlder });
+ act(TestResizeObserver.resize);
+ rerender({ agentDisplayName: 'Renamed agent' });
+ expect(scroller.scrollTop).toBe(0);
expect(onLoadOlder).not.toHaveBeenCalled();
+ await act(async () => upward(scroller));
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ expect(props.followingTailRef.current).toBe(false);
});
- // The three tests below are one property seen from three sides: EVERY input to
- // the trigger re-asks the level question when it changes, not just the one the
- // browser watches. A guard that quietly goes false while nothing re-evaluates
- // is the same deadlock as a latch that never re-arms — it just needs a
- // different reader to walk into it.
+ it('consumes one touch drag across settled empty pages and momentum scrolls', async () => {
+ const onLoadOlder = vi.fn().mockResolvedValue(true);
+ const { scroller } = renderTranscript({ messages: messages(1, 1), onLoadOlder });
+ fireEvent.touchStart(scroller, { touches: [{ clientY: 100 }] });
+ for (const clientY of [140, 180, 220]) {
+ await act(async () => fireEvent.touchMove(scroller, { touches: [{ clientY }] }));
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ }
+ fireEvent.touchEnd(scroller);
+ fireEvent.scroll(scroller);
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ await act(async () => upwardInputs.touch(scroller));
+ expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ });
- it('pages once the reader stops following the tail, with no new intersection', async () => {
- const onLoadOlder = vi.fn().mockReturnValue(neverLands());
- renderTranscript({ onLoadOlder, following: true });
+ it('keeps a wheel burst consumed through momentum and rearms after an idle gap', async () => {
+ const now = vi.spyOn(performance, 'now').mockReturnValue(0);
+ const onLoadOlder = vi.fn().mockResolvedValue(true);
+ const { scroller } = renderTranscript({ messages: messages(1, 1), onLoadOlder });
+ for (const timestamp of [0, 50, 150, 250]) {
+ now.mockReturnValue(timestamp);
+ await act(async () => upwardInputs.wheel(scroller));
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ }
+ now.mockReturnValue(550);
+ await act(async () => upwardInputs.wheel(scroller));
+ expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ });
- await act(async () => FakeIntersectionObserver.move(true));
- expect(onLoadOlder).not.toHaveBeenCalled();
+ it('shares gesture consumption with scroll events inside the trigger band', async () => {
+ const onLoadOlder = vi.fn().mockResolvedValue(true);
+ const { scroller, scrollTo } = renderTranscript({ onLoadOlder });
+ scrollTo(200);
+ fireEvent.touchStart(scroller, { touches: [{ clientY: 100 }] });
+ for (const top of [110, 90]) {
+ await act(async () => {
+ scroller.scrollTop = top;
+ fireEvent.scroll(scroller);
+ });
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ }
+ fireEvent.touchEnd(scroller);
+ await act(async () => {
+ scroller.scrollTop = 70;
+ fireEvent.scroll(scroller);
+ });
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ await act(async () => upwardInputs.touch(scroller));
+ expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ });
- // A transcript only slightly taller than its viewport keeps the sentinel
- // inside the band at every scroll position, so scrolling up emits no new
- // intersection for the observer to report — the reader's own scroll is the
- // only evidence that they left the live tail.
- await act(async () => placeReader(FakeIntersectionObserver.scroller(), READING_HISTORY));
+ it('consumes input begun while a page is pending until the next gesture', async () => {
+ const first = pendingPage();
+ const onLoadOlder = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true);
+ const { scroller, scrollTo } = renderTranscript({ onLoadOlder });
+ scrollTo(0);
+ fireEvent.touchStart(scroller, { touches: [{ clientY: 100 }] });
+ fireEvent.touchMove(scroller, { touches: [{ clientY: 140 }] });
+ await act(async () => first.land(true));
+ await act(async () => fireEvent.touchMove(scroller, { touches: [{ clientY: 180 }] }));
expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ fireEvent.touchEnd(scroller);
+ await act(async () => upwardInputs.touch(scroller));
+ expect(onLoadOlder).toHaveBeenCalledTimes(2);
});
- it('pages once a deep-link jump releases its hold on the scroll position', async () => {
- const onLoadOlder = vi.fn().mockReturnValue(neverLands());
- const { rerender } = renderTranscript({ onLoadOlder, jumpTarget: 'msg-42' });
+ it('is keyboard focusable and requires a fresh key press after an empty page', async () => {
+ const onLoadOlder = vi.fn().mockResolvedValue(true);
+ const { scroller } = renderTranscript({ messages: messages(1, 1), onLoadOlder });
+ expect(scroller.tabIndex).toBe(0);
+ scroller.focus();
+ expect(document.activeElement).toBe(scroller);
+ await act(async () => upwardInputs.keyboard(scroller));
+ await act(async () => fireEvent.keyDown(scroller, { key: 'PageUp', repeat: true }));
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ await act(async () => upwardInputs.keyboard(scroller));
+ expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ });
- // A jump owns scrollTop until it settles, so the trigger stands down. A
- // target near the head of the loaded window lands INSIDE the band, which
- // makes this the reader's whole view of history rather than a moment in
- // passing.
- await act(async () => FakeIntersectionObserver.move(true));
+ it.each(Object.entries(upwardInputs))('lets a nested scroller own %s input until it can chain upward', async (_name, upward) => {
+ const onLoadOlder = vi.fn().mockResolvedValue(true);
+ const { scroller } = renderTranscript({ messages: messages(1, 1), onLoadOlder });
+ const panel = document.createElement('div');
+ panel.style.overflowY = 'auto';
+ Object.defineProperties(panel, { clientHeight: { value: 100 }, scrollHeight: { value: 500 } });
+ panel.scrollTop = 120;
+ const target = document.createElement('span');
+ panel.append(target);
+ scroller.append(panel);
+ await act(async () => upward(target));
expect(onLoadOlder).not.toHaveBeenCalled();
-
- // The jump acks itself once it has landed and the parent answers by clearing
- // the target — which is the whole of releasing the hold, and changes no
- // geometry. So unless the release itself re-asks, the reader is left parked
- // in the band with paging dead and no gesture available to revive it.
- await act(async () => flushFrames());
- await act(async () => rerender({ jumpTarget: null }));
+ panel.scrollTop = 0;
+ panel.style.overscrollBehaviorY = 'contain';
+ await act(async () => upward(target));
+ expect(onLoadOlder).not.toHaveBeenCalled();
+ panel.style.overscrollBehaviorY = 'auto';
+ await act(async () => upward(target));
expect(onLoadOlder).toHaveBeenCalledTimes(1);
});
- it('records no failure against a reader who has already left the band', async () => {
- const first = pendingPage();
- const onLoadOlder = vi.fn().mockReturnValueOnce(first.promise).mockReturnValue(neverLands());
- renderTranscript({ onLoadOlder });
+ it('does not interpret downward, pinch, or editing input as a request for history', () => {
+ const onLoadOlder = vi.fn();
+ const { scroller } = renderTranscript({ messages: messages(1, 1), onLoadOlder });
+ fireEvent.wheel(scroller, { deltaY: 100 });
+ fireEvent.keyDown(scroller, { key: 'PageDown' });
+ fireEvent.touchStart(scroller, { touches: [{ clientY: 100 }] });
+ fireEvent.touchMove(scroller, { touches: [{ clientY: 80 }] });
+ fireEvent.touchMove(scroller, { touches: [{ clientY: 140 }, { clientY: 160 }] });
+ const input = document.createElement('input');
+ scroller.append(input);
+ fireEvent.keyDown(input, { key: 'Home' });
+ expect(onLoadOlder).not.toHaveBeenCalled();
+ });
- await act(async () => FakeIntersectionObserver.move(true));
+ it('serializes multiple upward inputs until the active request settles', async () => {
+ const first = pendingPage();
+ const onLoadOlder = vi.fn().mockReturnValue(first.promise);
+ const { scroller, scrollTo } = renderTranscript({ onLoadOlder });
+ scrollTo(0);
+ for (const upward of Object.values(upwardInputs)) upward(scroller);
+ scrollTo(500);
+ scrollTo(0);
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ await act(async () => first.land(true));
expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ });
- // The reader gives up on a slow request and scrolls away; it fails only
- // afterwards. Recording that failure holds the trigger off for someone who
- // never saw it, and the exit that clears the record has already gone by.
- await act(async () => FakeIntersectionObserver.move(false));
+ it('stops when history is exhausted', async () => {
+ const onLoadOlder = vi.fn().mockResolvedValue(true);
+ const { scroller, scrollTo, rerender } = renderTranscript({ onLoadOlder });
+ await act(async () => scrollTo(0));
+ rerender({ hasOlder: false });
+ for (const upward of Object.values(upwardInputs)) upward(scroller);
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ });
- // They come back in the same frame the failure lands in. Recording it does
- // re-observe, which would normally notice they are gone and drop the record
- // — but that answer arrives at the end of the frame, by which time they are
- // back at the top and it reports so. Nothing clears the latch after that.
- await act(async () => {
- first.land(false);
- FakeIntersectionObserver.move(true);
- });
- expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ it('keeps a deep-link jump stable until the reader asks for more history', async () => {
+ const now = vi.spyOn(performance, 'now').mockReturnValue(0);
+ const onLoadOlder = vi.fn().mockResolvedValue(true);
+ const { scroller, scrollTo, rerender } = renderTranscript({ onLoadOlder, jumpTarget: 'missing-target' });
+ scrollTo(0);
+ fireEvent.wheel(scroller, { deltaY: -100 });
+ expect(onLoadOlder).not.toHaveBeenCalled();
+ act(flushFrames);
+ rerender({ jumpTarget: null });
+ expect(onLoadOlder).not.toHaveBeenCalled();
+ now.mockReturnValue(300);
+ await act(async () => fireEvent.wheel(scroller, { deltaY: -100 }));
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
});
- it('offers an explicit retry instead of re-asking after a failed page', async () => {
+ it('surfaces failures and offers one explicit retry without an automatic retry loop', async () => {
const onLoadOlder = vi.fn().mockResolvedValue(false);
- const { getByText } = renderTranscript({ onLoadOlder });
-
- // The failed page settles like a successful one, so it reaches the post-load
- // re-evaluation. But a failure adds no content: the reader is still in the
- // band, and re-asking would spin against a server that is still failing.
- await act(async () => FakeIntersectionObserver.move(true));
- expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ const { getByText, scroller, scrollTo } = renderTranscript({ onLoadOlder });
+ await act(async () => scrollTo(0));
expect(getByText('chat.olderLoadFailed')).toBeTruthy();
-
- // Clicking the retry line is the way forward for a reader who stays put. It
- // clears the failure, which re-asks — and the re-ask must not put a second
- // request on the wire beside the one the click just started.
- await act(async () => getByText('chat.olderLoadFailed').click());
+ act(TestResizeObserver.resize);
+ fireEvent.wheel(scroller, { deltaY: -100 });
+ expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ await act(async () => fireEvent.click(getByText('chat.olderLoadFailed')));
expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ scrollTo(500);
+ await act(async () => scrollTo(0));
+ expect(onLoadOlder).toHaveBeenCalledTimes(3);
});
- it('retries once when the reader leaves the band and comes back', async () => {
- const onLoadOlder = vi.fn().mockResolvedValue(false);
- renderTranscript({ onLoadOlder });
-
- await act(async () => FakeIntersectionObserver.move(true));
- expect(onLoadOlder).toHaveBeenCalledTimes(1);
+ it('does not hold a failure against a reader who left before it arrived', async () => {
+ const first = pendingPage();
+ const onLoadOlder = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true);
+ const { scrollTo, queryByText } = renderTranscript({ onLoadOlder });
+ scrollTo(0);
+ scrollTo(500);
+ await act(async () => first.land(false));
+ expect(queryByText('chat.olderLoadFailed')).toBeNull();
+ await act(async () => scrollTo(0));
+ expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ });
- // Moving away and back is a fresh ask, not the same doomed one repeated —
- // otherwise one failure would leave the retry line as the only way to page
- // for the rest of the session.
- await act(async () => FakeIntersectionObserver.move(false));
- await act(async () => FakeIntersectionObserver.move(true));
+ it('keeps an old session request from settling a new session request', async () => {
+ const previous = pendingPage();
+ const current = pendingPage();
+ const onLoadOlder = vi.fn().mockReturnValueOnce(previous.promise).mockReturnValue(current.promise);
+ const { scroller, scrollTo, rerender, props, queryByText } = renderTranscript({ onLoadOlder });
+ scrollTo(0);
+ rerender({ session: { ...props.session, id: 'session-2' }, messages: messages(401, 50) });
+ act(flushFrames);
+ scrollTo(0);
+ expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ await act(async () => previous.land(false));
+ expect(queryByText('chat.olderLoadFailed')).toBeNull();
+ fireEvent.wheel(scroller, { deltaY: -100 });
expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ await act(async () => current.land(true));
});
});
diff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsx
index e4372e8e5..4ec232c9f 100644
--- a/ui/src/components/workbench/ChatPage.hydration.test.tsx
+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx
@@ -704,15 +704,6 @@ describe('ChatPage transcript hydration', () => {
async ({ arrival, view }) => {
// No browser layout in jsdom; reader placement is driven explicitly below.
vi.stubGlobal('requestAnimationFrame', () => 0);
- let scrollRoot: HTMLElement | null = null;
- vi.stubGlobal('IntersectionObserver', class {
- constructor(_callback: IntersectionObserverCallback, options?: IntersectionObserverInit) {
- if (options?.root instanceof HTMLElement) scrollRoot = options.root;
- }
- observe() {}
- unobserve() {}
- disconnect() {}
- });
const previous: TurnActivityGroupWire = {
id: 'previous-phase', anchor_message_id: null, anchor_position: 'after',
open: true, status: 'interrupted', steps: 1, duration_ms: null,
@@ -784,7 +775,7 @@ describe('ChatPage transcript hydration', () => {
} else if (view === 'capped tail') {
// Enter through the real scroll handler; the boundary itself will detach
// the capped transcript rather than append an unseen tail message.
- if (!scrollRoot) throw new Error('transcript scroll root not observed');
+ const scrollRoot = screen.getByTestId('chat-transcript');
Object.defineProperties(scrollRoot, {
scrollHeight: { value: 10_000, configurable: true },
clientHeight: { value: 800, configurable: true },
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index d21f1c7de..2ecebd589 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -1,4 +1,4 @@
-import { Fragment, forwardRef, memo, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
+import { Fragment, forwardRef, memo, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Activity, ArrowLeft, ArrowRight, ArrowUpRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Image as ImageIcon, Info, Loader2, MapPin, MessageSquare, MessageSquareQuote, Pencil, Terminal, Undo2, UploadCloud, X } from 'lucide-react';
@@ -191,11 +191,10 @@ const emptyRuntimeState = (): SessionRuntimeState => ({
// below the viewport.
const MAX_RETAINED_MESSAGES = 300;
-// How close to the top of the loaded window counts as "the reader is asking for
-// older history". Handed to the older-page IntersectionObserver as a root margin,
-// so the browser evaluates it continuously as a BAND the reader can sit inside —
-// not as a threshold some event has to be caught crossing.
+// Upward input can request history inside this band.
const OLDER_TRIGGER_BAND_PX = 120;
+// Wheel events have no gesture-end event; an idle gap ends a momentum burst.
+const PAGING_WHEEL_IDLE_MS = 200;
// Display label for the archive chord (⇧⌘D / Ctrl+Shift+D). Resolved once at
// module load — the platform can't change mid-session — and shown as the archive
@@ -3616,6 +3615,18 @@ const TitleField = forwardRef<TitleFieldHandle, TitleFieldProps>(({ title, onCom
});
TitleField.displayName = 'TitleField';
+function transcriptOwnsUpwardInput(target: EventTarget, root: HTMLElement): boolean {
+ if (!(target instanceof Element) || !root.contains(target)) return false;
+ for (let node: Element | null = target; node && node !== root; node = node.parentElement) {
+ if (node.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"]')) return false;
+ const style = getComputedStyle(node);
+ if (/^(auto|scroll)$/.test(style.overflowY) && node.scrollHeight > node.clientHeight) {
+ if (node.scrollTop > 0 || /^(contain|none)$/.test(style.overscrollBehaviorY)) return false;
+ }
+ }
+ return true;
+}
+
interface TranscriptProps {
messages: WorkbenchMessage[];
session: WorkbenchSession;
@@ -3765,12 +3776,8 @@ export const Transcript: React.FC<TranscriptProps> = ({
// immediately yank it back to the row it had remembered. A ref (not state) so
// the scroll handler + observer read it synchronously with no re-render.
const suppressAnchorRef = useRef(false);
- // ``true`` while the viewport is FOLLOWING the bottom (at/near it) — drives the
- // auto-follow of new content and hides the jump button. A ref so the scroll
- // handler + ResizeObserver read it mid-layout without stale closures, and owned
- // by ChatPage (see followingTailRef) so its retained-window trim reads the same
- // follow state. It is the shadow of ``followingTail`` below and is written ONLY
- // by that state's setter — see the note there for why.
+ // Shared with ChatPage so retained-window trimming and scroll restoration
+ // agree synchronously on whether the reader is following the live tail.
const pinnedRef = followingTailRef;
// While the user has scrolled UP to read history (not pinned), remember the
// topmost row still in view and how far its top sits below the viewport top, so
@@ -3789,60 +3796,23 @@ export const Transcript: React.FC<TranscriptProps> = ({
// adds no content, so nothing moves and the trigger below has no change to react
// to. The explicit retry is the affordance for a reader who stays put.
const [olderLoadFailed, setOlderLoadFailed] = useState(false);
- // The older-page trigger below is a question about the PRESENT, and every one
- // of its inputs has to be able to re-ask it. The sentinel's intersection does
- // so by itself, and so does anything the component renders from — props and
- // state re-create the observer through the effect's dependency list. A ref
- // does not: it changes silently, so a guard that goes false behind a ref is a
- // deadlock exactly like a latch that never re-arms, which is the defect this
- // change exists to remove, one layer down.
- //
- // So the only ref the trigger reads is the intersection itself, which arrives
- // with its own re-ask. Where the scroll handler and the ResizeObserver also
- // need to read a guard synchronously mid-layout, the ref is kept as a shadow
- // of the state and written ONLY through the setter beside it; where a prop
- // already says the same thing, the prop is read directly rather than mirrored.
- // What matters is that the trigger reads reactive values, so
- // react-hooks/exhaustive-deps fails the build on an input left out of the
- // dependency list — completeness enforced rather than remembered.
-
- // Whether an older page WE started is still outstanding. ``loadingOlder``
- // reports the same thing but lags: it only arrives after ChatPage has
- // re-rendered, and until it does the trigger would happily start a second
- // request for the page already on the wire. Owning it here closes that window,
- // and settling is also the honest moment to re-ask — a page has landed, so the
- // level condition has a new answer.
- const [loadInFlight, setLoadInFlight] = useState(false);
- const [followingTail, setFollowingTailState] = useState(true);
+ // Input can arrive again before the parent's loading prop commits.
+ const loadInFlightRef = useRef(false);
+ const lastScrollTopRef = useRef(0);
+ const touchYRef = useRef<number | null>(null);
+ const pagingGestureRef = useRef<{
+ kind: 'pointer' | 'wheel' | 'touch' | 'keyboard';
+ consumed: boolean;
+ at: number;
+ } | null>(null);
const setFollowingTail = useCallback(
(next: boolean) => {
pinnedRef.current = next;
- setFollowingTailState(next);
},
[pinnedRef],
);
const loadOlderRef = useRef(onLoadOlder);
const reloadLatestRef = useRef(onReloadLatest);
- // Older pages are triggered by whether a zero-height sentinel at the head of the
- // transcript is within OLDER_TRIGGER_BAND_PX of the viewport top — a question
- // about the PRESENT, which the browser re-answers on every geometry change.
- //
- // What this replaces: a latch that disarmed on trigger and re-armed only from a
- // scroll event that had settled for 150ms with ``scrollTop > 300``. Both halves
- // describe a FUTURE event, and the reader most likely to want another page —
- // parked at the very top — can produce neither: an upward gesture at scrollTop 0
- // moves nothing, so the browser emits no scroll event at all. One fling that
- // rode past the post-load anchor restore back to the top therefore left paging
- // dead — no spinner, no request, older messages still on the server — until the
- // reader happened to scroll >300px back down and up again.
- //
- // Cascade prevention (the reason that latch existed) no longer needs a position
- // threshold: a successful page prepends content and the anchor restore pushes
- // the sentinel out of the band, so the condition goes false on its own. If it is
- // still true afterwards, the reader really is still at the top of the loaded
- // window, and loading again is the correct answer rather than a cascade.
- const topSentinelRef = useRef<HTMLDivElement | null>(null);
- const atTopRef = useRef(false);
useEffect(() => {
loadOlderRef.current = onLoadOlder;
@@ -3928,6 +3898,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
const el = scrollRef.current;
if (!el) return;
el.scrollTop = el.scrollHeight;
+ lastScrollTopRef.current = Math.max(0, el.scrollTop);
setFollowingTail(true);
anchorRef.current = null;
setShowJump(false);
@@ -3947,100 +3918,43 @@ export const Transcript: React.FC<TranscriptProps> = ({
});
}, [needsLatestReload, scrollToBottom]);
- // The one path that starts an older-page load, so the sentinel trigger and the
+ // The one path that starts an older-page load, so upward input and the
// retry affordance cannot drift apart on how a failure is recorded.
const runLoadOlder = useCallback(() => {
- setLoadInFlight(true);
+ if (!hasOlder || loadingOlder || loadInFlightRef.current || jumpTarget) return;
+ const requestingSession = session.id;
+ loadInFlightRef.current = true;
+ if (pagingGestureRef.current) pagingGestureRef.current.consumed = true;
+ setFollowingTail(false);
+ captureAnchor();
setOlderLoadFailed(false);
void Promise.resolve(loadOlderRef.current()).then((ok) => {
- setLoadInFlight(false);
- // A failed page adds no content, so the sentinel stays exactly where it
- // was and every later re-evaluation would see the same "reader wants more"
- // answer and re-ask — a retry storm against a server that is still
- // failing. Recording the failure both holds the automatic trigger off and
- // offers the retry line, which is the way forward for a reader who stays
- // put.
- //
- // Only if they DID stay put. A reader who left the band while the request
- // was in flight never saw this failure, and latching it behind their back
- // would refuse the automatic retry they are owed on returning — the exit
- // that would have cleared it happened before there was anything to clear.
- if (ok === false && atTopRef.current) setOlderLoadFailed(true);
+ if (lastSessionRef.current !== requestingSession) return;
+ loadInFlightRef.current = false;
+ const el = scrollRef.current;
+ if (ok === false && el && el.scrollTop <= OLDER_TRIGGER_BAND_PX) setOlderLoadFailed(true);
});
- }, []);
+ }, [captureAnchor, hasOlder, jumpTarget, loadingOlder, session.id, setFollowingTail]);
- // Start an older page when the sentinel is in the band and there is more to
- // load. Reads props directly — the effect below re-creates the observer when
- // they change — so it can never act on a stale snapshot.
+ // Only upward input asks for another page. Settling a request or changing
+ // layout is not a new request, even if the viewport remains near the top.
const maybeLoadOlder = useCallback(() => {
- if (!atTopRef.current || !hasOlder || loadingOlder || loadInFlight || olderLoadFailed) return;
- // Sentinel in view is only a REQUEST for older history if the reader went
- // looking for it. A transcript that fits its viewport — tall display, zoomed
- // out, enlarged window — puts the sentinel in the band while the reader is
- // still following the live tail, and paging there would walk backwards
- // through history nobody asked to see, on open and on every resize.
- if (followingTail) return;
- // A pending deep-link jump owns scrollTop, and the anchor restore is
- // suppressed along with it. Prepending under the jump would have nothing
- // holding the reader's row in place. A jump that lands near the head of the
- // loaded window arrives IN the band, so this is a real state to leave rather
- // than a momentary one — and ``jumpTarget`` IS that state: the effect below
- // acks the jump at the same moment it lifts suppression, which clears the
- // prop and re-asks. Reading it directly is why there is no mirror to keep in
- // step, and it holds from the moment the jump is requested rather than from
- // the frame the effect happens to run in.
- if (jumpTarget) return;
+ const el = scrollRef.current;
+ if (!el || el.scrollTop > OLDER_TRIGGER_BAND_PX || olderLoadFailed || suppressAnchorRef.current) return;
+ const gesture = pagingGestureRef.current;
+ if (gesture?.consumed) return;
+ // A gesture made during an outstanding request is consumed too, rather
+ // than becoming a queued request when the page settles mid-gesture.
+ if (gesture) gesture.consumed = true;
runLoadOlder();
- }, [
- followingTail,
- hasOlder,
- jumpTarget,
- loadInFlight,
- loadingOlder,
- olderLoadFailed,
- runLoadOlder,
- ]);
-
- // Older-page trigger. The observer answers "is the reader within
- // OLDER_TRIGGER_BAND_PX of the top of the loaded window?" and re-answers on
- // every geometry change the browser already tracks. Every OTHER input — more
- // history to fetch, a page already in flight, following the tail, a jump
- // holding scrollTop, a failure already recorded — is not geometry, so it
- // arrives as a dep of ``maybeLoadOlder``: re-creating the observer re-observes
- // the sentinel, and ``observe()`` always reports the CURRENT state instead of
- // waiting for the next crossing. That is what makes the loader level-triggered
- // in ALL of its inputs rather than only in the one the browser watches.
- // In particular a settled page re-evaluates the settled geometry (React has
- // committed the prepended rows and the ResizeObserver has restored the anchor
- // by the time this passive effect runs), so a reader who is still at the top
- // gets the next page without having to produce a scroll event they may be
- // unable to produce at all. That edge is ``loadInFlight``, which we own, not
- // the ``loadingOlder`` prop, which only mirrors it.
- // ``empty`` is in the deps for the same reason as the ResizeObserver below: the
- // scroll container mounts when the empty state goes away.
- useEffect(() => {
- const root = scrollRef.current;
- const sentinel = topSentinelRef.current;
- if (!root || !sentinel) return;
- const io = new IntersectionObserver(
- (entries) => {
- const atTop = entries[entries.length - 1]?.isIntersecting ?? false;
- atTopRef.current = atTop;
- // Leaving the band is the reader telling us they moved on. Drop the
- // failure latch so returning to the top retries once, instead of leaving
- // the retry line as the only way forward for the rest of the session.
- if (!atTop) setOlderLoadFailed(false);
- maybeLoadOlder();
- },
- { root, rootMargin: `${OLDER_TRIGGER_BAND_PX}px 0px 0px 0px` },
- );
- io.observe(sentinel);
- return () => io.disconnect();
- }, [maybeLoadOlder, empty]);
+ }, [olderLoadFailed, runLoadOlder]);
const handleScroll = () => {
const el = scrollRef.current;
if (!el) return;
+ const top = Math.max(0, el.scrollTop);
+ const movingUp = top < lastScrollTopRef.current;
+ lastScrollTopRef.current = top;
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
// Small tolerance keeps us "following" through sub-pixel rounding; a
// historical search window cannot be considered pinned to live tail until
@@ -4052,9 +3966,8 @@ export const Transcript: React.FC<TranscriptProps> = ({
// is free to grow). Re-capturing here keeps it current as the user scrolls.
if (pinned) anchorRef.current = null;
else captureAnchor();
- // Older-page loading is deliberately NOT triggered here: scroll events are the
- // one thing a reader already at the top cannot produce. See the sentinel
- // observer above.
+ if (top > OLDER_TRIGGER_BAND_PX) setOlderLoadFailed(false);
+ if (movingUp) maybeLoadOlder();
};
// Open each session pinned to the latest message (instant, no animation) —
@@ -4070,6 +3983,9 @@ export const Transcript: React.FC<TranscriptProps> = ({
// previous session would otherwise greet the next one with a retry line for
// a page it never asked for, and hold its loader off with it.
setOlderLoadFailed(false);
+ loadInFlightRef.current = false;
+ touchYRef.current = null;
+ pagingGestureRef.current = null;
const id = requestAnimationFrame(() => scrollToBottom());
return () => cancelAnimationFrame(id);
}, [session.id, scrollToBottom, setFollowingTail]);
@@ -4108,6 +4024,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
const row = el.querySelector(`[data-message-id="${CSS.escape(jumpTarget)}"]`);
if (row) {
row.scrollIntoView({ block: 'center' });
+ lastScrollTopRef.current = Math.max(0, el.scrollTop);
setShowJump(true); // not at the bottom anymore — offer the way back down
}
// Re-capture the anchor at the jumped-to position on the NEXT frame (after
@@ -4134,22 +4051,29 @@ export const Transcript: React.FC<TranscriptProps> = ({
setFollowingTail,
]);
- // The one place scroll position reacts to content size changes — two modes,
- // never conflated. (Conflating them WAS the bug: any resize while "at bottom"
- // forced scrollTop=scrollHeight, and the snap's own scroll event re-armed the
- // "at bottom" flag, so a history image loading as the user scrolled up kept
- // yanking them back to the latest message.)
- // • following → stay pinned to the exact bottom as content grows (new message,
- // thinking bubble, the latest message's own image finishing to load).
- // • reading history → restore the saved anchor so the row under the reader's
- // eyes stays fixed wherever the growth happened: an image above expands and
- // the anchor moves down with it (scrollTop tracks it), while growth below the
- // anchor leaves it alone.
- // ``[overflow-anchor:none]`` on the container hands anchoring entirely to us, so
- // behavior is identical on every browser instead of fighting Chrome/Firefox's
- // native anchoring; ResizeObserver delivers before paint, so the restore is
- // flicker-free. ``empty`` is in the deps so the observer (re)attaches when the
- // scroll container mounts after the empty state.
+ const restoreScrollPosition = useCallback(() => {
+ const el = scrollRef.current;
+ if (!el || suppressAnchorRef.current || jumpTarget) return;
+ if (pinnedRef.current) {
+ el.scrollTop = el.scrollHeight;
+ } else {
+ const anchor = anchorRef.current;
+ if (!anchor || !anchor.el.isConnected) return;
+ const currentTop = anchor.el.getBoundingClientRect().top - el.getBoundingClientRect().top;
+ const delta = currentTop - anchor.top;
+ if (Math.abs(delta) >= 0.5) el.scrollTop += delta;
+ }
+ // A programmatic adjustment must not look like upward input when its
+ // queued scroll event is delivered.
+ lastScrollTopRef.current = Math.max(0, el.scrollTop);
+ }, [jumpTarget, pinnedRef]);
+
+ // Prepending and trimming can leave the total height unchanged. Restore after
+ // every DOM commit, before paint or a queued scroll can capture a different
+ // row. This also covers the loading slot being inserted or removed.
+ useLayoutEffect(restoreScrollPosition);
+
+ // Images and viewport changes can resize outside a React commit.
useEffect(() => {
const el = scrollRef.current;
const content = contentRef.current;
@@ -4160,27 +4084,14 @@ export const Transcript: React.FC<TranscriptProps> = ({
// has expanded, an on-screen keyboard, or a resized window. Recomputed ahead
// of the anchor branches below so no early return can leave it stale.
setHistoryOverflows(el.scrollHeight > el.clientHeight + 1);
- // A programmatic jump owns scrollTop right now — neither pin-to-bottom nor
- // anchor-restore should move it, or it would fight the jump.
- if (suppressAnchorRef.current) return;
- if (pinnedRef.current) {
- el.scrollTop = el.scrollHeight;
- return;
- }
- const anchor = anchorRef.current;
- if (!anchor || !anchor.el.isConnected) return;
- const currentTop = anchor.el.getBoundingClientRect().top - el.getBoundingClientRect().top;
- const delta = currentTop - anchor.top;
- // Sub-pixel rect noise would otherwise write scrollTop on every fire; only
- // correct a real (≥0.5px) drift so reading history stays perfectly still.
- if (Math.abs(delta) >= 0.5) el.scrollTop += delta;
+ restoreScrollPosition();
});
ro.observe(content);
// The viewport shrinking under the reader is a resize too: pin-to-bottom has to
// re-pin and the anchor has to hold, exactly as when the content itself grew.
ro.observe(el);
return () => ro.disconnect();
- }, [empty]);
+ }, [empty, restoreScrollPosition]);
if (empty) {
// Even with no transcript-visible messages, a session can have pending vault requests —
@@ -4221,12 +4132,53 @@ export const Transcript: React.FC<TranscriptProps> = ({
onAskInNew={selectionActions.askInNew ? onAskInNewSession : undefined}
/>
)}
- <div ref={scrollRef} onScroll={handleScroll} className="min-h-0 flex-1 overflow-y-auto px-4 py-5 [overflow-anchor:none] md:px-8">
- {/* Marker for the very top of the loaded window: whether it is in view IS
- the "load older" condition (see the observer above). Outside
- ``contentRef`` so it joins neither the column's gap spacing nor the
- children pickScrollAnchor searches. */}
- <div ref={topSentinelRef} aria-hidden className="h-px" />
+ <div
+ ref={scrollRef}
+ data-testid="chat-transcript"
+ tabIndex={0}
+ onScroll={handleScroll}
+ onPointerDown={() => {
+ pagingGestureRef.current = { kind: 'pointer', consumed: false, at: 0 };
+ }}
+ onWheel={(event) => {
+ if (event.defaultPrevented || event.ctrlKey) return;
+ const at = performance.now();
+ const gesture = pagingGestureRef.current;
+ if (gesture?.kind !== 'wheel' || at - gesture.at > PAGING_WHEEL_IDLE_MS) {
+ pagingGestureRef.current = { kind: 'wheel', consumed: false, at };
+ } else {
+ gesture.at = at;
+ }
+ if (event.deltaY < 0 && Math.abs(event.deltaY) > Math.abs(event.deltaX)
+ && transcriptOwnsUpwardInput(event.target, event.currentTarget)) maybeLoadOlder();
+ }}
+ onTouchStart={(event) => {
+ touchYRef.current = event.touches.length === 1 ? event.touches[0].clientY : null;
+ pagingGestureRef.current = { kind: 'touch', consumed: event.touches.length !== 1, at: 0 };
+ }}
+ onTouchMove={(event) => {
+ const y = event.touches.length === 1 ? event.touches[0].clientY : null;
+ const previousY = touchYRef.current;
+ touchYRef.current = y;
+ if (y === null && pagingGestureRef.current) pagingGestureRef.current.consumed = true;
+ if (!event.defaultPrevented && y !== null && previousY !== null && y > previousY
+ && transcriptOwnsUpwardInput(event.target, event.currentTarget)) {
+ maybeLoadOlder();
+ }
+ }}
+ // Keep the consumed gesture through momentum scrolls after release.
+ // Only the next pointer, touch, wheel burst or key press re-arms it.
+ onTouchEnd={() => { touchYRef.current = null; }}
+ onTouchCancel={() => { touchYRef.current = null; }}
+ onKeyDown={(event) => {
+ if (!event.repeat) pagingGestureRef.current = { kind: 'keyboard', consumed: false, at: 0 };
+ if (event.defaultPrevented || !transcriptOwnsUpwardInput(event.target, event.currentTarget)) return;
+ if (event.key === 'ArrowUp' || event.key === 'PageUp' || event.key === 'Home' || (event.key === ' ' && event.shiftKey)) {
+ maybeLoadOlder();
+ }
+ }}
+ className="min-h-0 flex-1 overflow-y-auto px-4 py-5 [overflow-anchor:none] md:px-8"
+ >
<div ref={contentRef} className="mx-auto flex w-full max-w-[1080px] flex-col gap-3">
{forkSourceBanner}
{/* One slot at the head of the history for every way paging can end, so
diff --git a/ui/src/lib/transcriptScrollAnchor.ts b/ui/src/lib/transcriptScrollAnchor.ts
index 40c7e87da..65d344ea4 100644
--- a/ui/src/lib/transcriptScrollAnchor.ts
+++ b/ui/src/lib/transcriptScrollAnchor.ts
@@ -15,11 +15,9 @@
// group are worse still — the spinner is unmounted by the very commit that adds
// the page, so the restore is skipped for a disconnected node.
//
-// The restore is also what ENDS a page load: the older-page trigger asks whether
-// a sentinel at the head of the transcript is still near the viewport top, and
-// pushing the reader's row back down is what carries that sentinel out of range.
-// An anchor that restores nothing leaves the reader pinned at the top of the
-// loaded window, asking for page after page.
+// Restore after the message DOM commits, even when trimming the retained window
+// cancels out the prepended height. A ResizeObserver alone cannot detect that
+// change. Only the reader's next upward input asks for another page.
//
// So the rule below is structural rather than a list of elements to avoid: the
// search starts at the first message row and never looks above it. Chrome added