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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(ui): level-trigger the chat older-page loader (#1554)
Call White34bc889bd910
diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.jsonindex 803b3abe4..58fff0f83 100644--- a/ui/eslint-baseline.json+++ b/ui/eslint-baseline.json@@ -101,7 +101,6 @@},"src/components/workbench/ChatPage.tsx": {"@typescript-eslint/no-explicit-any": 1,- "react-hooks/preserve-manual-memoization": 2,"react-hooks/set-state-in-effect": 3},"src/components/workbench/FileTree.tsx": {diff --git a/ui/src/components/workbench/ChatOlderPaging.test.tsx b/ui/src/components/workbench/ChatOlderPaging.test.tsxnew file mode 100644index 000000000..625add156--- /dev/null+++ b/ui/src/components/workbench/ChatOlderPaging.test.tsx@@ -0,0 +1,434 @@+/** @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() }),+}));++vi.mock('../../context/InstanceAuthorizationContext', () => ({+ useInstanceAuthorization: () => ({+ 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,+}));++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;++ 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 };++// 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);+};++// 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>(() => {});++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(),+ 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(),+ needsLatestReload: false,+ onReloadLatest: vi.fn().mockResolvedValue(true),+ jumpTarget: over.jumpTarget ?? null,+ onJumpHandled: vi.fn(),+ highlightedId: null,+ messageFontSize: 14,+ onQuickReply: vi.fn(),+ provisionRequestsByMessage: new Map(),+ onVaultRequestResolved: vi.fn(),+ onQuoteSelection: vi.fn(),+ onAskInNewSession: vi.fn(),+ readOnly: false,+ followingTailRef: createRef<boolean>() as React.MutableRefObject<boolean>,+ };+ 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 };+};++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);+ nextFrameId = 1;+ frames.clear();+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {+ const id = nextFrameId++;+ frames.set(id, cb);+ return id;+ });+ vi.stubGlobal('cancelAnimationFrame', (id: number) => {+ frames.delete(id);+ });+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ });++ afterEach(() => {+ cleanup();+ 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));+ 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));+ 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));+ 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 });++ await act(async () => FakeIntersectionObserver.move(true));+ 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));+ expect(onLoadOlder).toHaveBeenCalledTimes(1);++ // 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));+ expect(onLoadOlder).toHaveBeenCalledTimes(1);+ });++ it('does not page while the reader is following the live tail', async () => {+ 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 }));+ expect(onLoadOlder).not.toHaveBeenCalled();+ });++ // 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('pages once the reader stops following the tail, with no new intersection', async () => {+ const onLoadOlder = vi.fn().mockReturnValue(neverLands());+ renderTranscript({ onLoadOlder, following: true });++ await act(async () => FakeIntersectionObserver.move(true));+ expect(onLoadOlder).not.toHaveBeenCalled();++ // 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));+ expect(onLoadOlder).toHaveBeenCalledTimes(1);+ });++ 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' });++ // 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));+ 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 }));+ 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 });++ await act(async () => FakeIntersectionObserver.move(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));++ // 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('offers an explicit retry instead of re-asking after a failed page', 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);+ 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());+ expect(onLoadOlder).toHaveBeenCalledTimes(2);+ });++ 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);++ // 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));+ expect(onLoadOlder).toHaveBeenCalledTimes(2);+ });+});diff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsxindex 4f0cc04eb..b68bea4ec 100644--- a/ui/src/components/workbench/ChatPage.hydration.test.tsx+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx@@ -166,14 +166,19 @@ describe('ChatPage transcript hydration', () => {let bootstrap: Deferred<never>;beforeEach(() => {- vi.stubGlobal(- 'ResizeObserver',- class {- observe() {}- unobserve() {}- disconnect() {}- },- );+ // The transcript drives its scroll anchor and its older-page trigger from+ // these two; jsdom implements neither, and nothing here depends on what they+ // would report.+ for (const name of ['ResizeObserver', 'IntersectionObserver']) {+ vi.stubGlobal(+ name,+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ }sessionRow = deferred();bootstrap = deferred();mocks.events = null;diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 84f7a3738..a80dda1bd 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -135,7 +135,6 @@ import {type TurnActivityGroupWire,} from '../../lib/agentActivity';import { errorMessage } from '@/lib/errorMessage';-import { useLatestRef } from '@/lib/useLatestRef';import { sessionAgentDisplayName } from './sessionAgentName';// While a turn is in flight, reconcile the working/Stop state against the@@ -178,6 +177,12 @@ 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.+const OLDER_TRIGGER_BAND_PX = 120;+// 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// row's hint so the shortcut is discoverable instead of folklore.@@ -3373,7 +3378,10 @@ interface TranscriptProps {footer?: React.ReactNode;}-const Transcript: React.FC<TranscriptProps> = ({+// Exported for tests (like ChatHeaderBar / MessageRow / ThinkingBubble below):+// the older-page trigger is a property of this subtree, and driving it through+// the whole ChatPage would prove it only for one wiring of the props.+export const Transcript: React.FC<TranscriptProps> = ({messages,session,agentDisplayName,@@ -3461,10 +3469,11 @@ const Transcript: React.FC<TranscriptProps> = ({// 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, not state, so the- // scroll handler + ResizeObserver read it without stale closures or extra renders.- // Owned by ChatPage (see followingTailRef) so its retained-window trim can read- // the same follow state; every pinnedRef.current access below drives it.+ // 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.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@@ -3479,30 +3488,64 @@ const Transcript: React.FC<TranscriptProps> = ({// own and is fresh in the commit that changes either side of the comparison.const [historyOverflows, setHistoryOverflows] = useState(false);// Surfaces a failed older-page fetch. Without it the spinner simply vanishes,- // which is indistinguishable from reaching the start of history — and since a- // failure adds no content, a reader parked at the top gets no further scroll- // event, so the silent retry the re-arm allows would never actually be reached.+ // which is indistinguishable from reaching the start of history — and a failure+ // 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);+ const setFollowingTail = useCallback(+ (next: boolean) => {+ pinnedRef.current = next;+ setFollowingTailState(next);+ },+ [pinnedRef],+ );const loadOlderRef = useRef(onLoadOlder);const reloadLatestRef = useRef(onReloadLatest);- // Load ONE older page per scroll gesture, not a cascade. The top threshold can- // stay satisfied across many scroll events — momentum/inertial scrolling (iOS- // touch AND macOS trackpad in Chrome) keeps firing while the post-load anchor- // restore + overshoot ride through the trigger zone — which fired older-page- // loads back-to-back all the way to the first message. So disarm on trigger and- // re-arm only once scrolling has SETTLED (a continuous fling keeps resetting the- // timer; a new deliberate scroll after the pause re-arms). Settle-based re-arm- // also recovers a failed load (it re-arms regardless of outcome).- const canLoadOlderRef = useRef(true);- const settleTimerRef = useRef<number | null>(null);- // Mirror loadingOlder so the settle timer (which closes over a stale value)- // can avoid re-arming while a page load is still in flight.- const loadingOlderPropRef = useLatestRef(loadingOlder);- // A failed load adds no content → no anchor restore → the viewport stays at the- // top, where the position gate below would never re-arm. Mark it so the settle- // re-arms regardless of position and a later scroll can retry. Re-arming at- // settle (not immediately) avoids a retry storm within the same fling.- const loadFailedRef = useRef(false);+ // 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;@@ -3588,10 +3631,10 @@ const Transcript: React.FC<TranscriptProps> = ({const el = scrollRef.current;if (!el) return;el.scrollTop = el.scrollHeight;- pinnedRef.current = true;+ setFollowingTail(true);anchorRef.current = null;setShowJump(false);- }, []);+ }, [setFollowingTail]);// Jump-to-latest handler behind the down-arrow button. A search result that// was not already loaded installs a centered historical window; its loaded@@ -3607,44 +3650,96 @@ const Transcript: React.FC<TranscriptProps> = ({});}, [needsLatestReload, scrollToBottom]);- // Re-arm the older-page loader once scrolling has settled (~150ms idle) AND the- // viewport is at rest out of the trigger band (scrollTop > 300, i.e. down in- // loaded content) — or a load just failed (no content/restore was added, so the- // position gate can never re-arm and we must recover anyway). Evaluating at rest- // is what stops a single fling from "crossing" the threshold; the in-flight guard- // keeps it disarmed until the load resolves. Called from the scroll handler AND- // from a failed load (a slow failure parked at the top emits no further scroll,- // so it has to schedule its own re-arm here).- const scheduleReArm = useCallback(() => {- if (settleTimerRef.current !== null) clearTimeout(settleTimerRef.current);- settleTimerRef.current = window.setTimeout(() => {- const node = scrollRef.current;- if (node && !loadingOlderPropRef.current && (node.scrollTop > 300 || loadFailedRef.current)) {- canLoadOlderRef.current = true;- loadFailedRef.current = false;- }- }, 150);- }, []);-- // The one path that starts an older-page load, so the scroll trigger and the+ // The one path that starts an older-page load, so the sentinel trigger and the// retry affordance cannot drift apart on how a failure is recorded.const runLoadOlder = useCallback(() => {- canLoadOlderRef.current = false;- loadFailedRef.current = false;+ setLoadInFlight(true);setOlderLoadFailed(false);void Promise.resolve(loadOlderRef.current()).then((ok) => {- if (ok === false) {- // Fetch failed: no content/restore, viewport parked at top. A slow failure- // already missed the in-flight-skipped settle and won't get another scroll,- // so schedule the re-arm here too (it ignores position when loadFailedRef)- // and offer an explicit retry, since a reader who stays put emits no scroll- // for that re-armed loader to fire on.- loadFailedRef.current = true;- setOlderLoadFailed(true);- scheduleReArm();- }+ 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);});- }, [scheduleReArm]);+ }, []);++ // 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.+ 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;+ 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]);const handleScroll = () => {const el = scrollRef.current;@@ -3654,19 +3749,15 @@ const Transcript: React.FC<TranscriptProps> = ({// historical search window cannot be considered pinned to live tail until// the explicit latest reload succeeds.const pinned = distance < 80 && !needsLatestReload;- pinnedRef.current = pinned;+ setFollowingTail(pinned);setShowJump(distance > 240 || needsLatestReload);// Only track an anchor while reading history; following needs none (the bottom// is free to grow). Re-capturing here keeps it current as the user scrolls.if (pinned) anchorRef.current = null;else captureAnchor();- // One older page per scroll gesture: re-arm only on settle, at rest, out of the- // top zone (see scheduleReArm) — a continuous fling keeps resetting it, so the- // anchor-restore scroll + momentum can't cascade more pages.- scheduleReArm();- if (hasOlder && !loadingOlder && canLoadOlderRef.current && el.scrollTop < 120) {- runLoadOlder();- }+ // 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.};// Open each session pinned to the latest message (instant, no animation) —@@ -3674,19 +3765,17 @@ const Transcript: React.FC<TranscriptProps> = ({useEffect(() => {if (lastSessionRef.current === session.id) return;lastSessionRef.current = session.id;- pinnedRef.current = true;+ setFollowingTail(true);anchorRef.current = null;setShowJump(false);// Paging state belongs to the session that was open, not to the transcript:// the component stays mounted across a switch, so a load that failed in the// previous session would otherwise greet the next one with a retry line for- // a page it never asked for, and a disarmed loader would wait for a settle.- canLoadOlderRef.current = true;- loadFailedRef.current = false;+ // a page it never asked for, and hold its loader off with it.setOlderLoadFailed(false);const id = requestAnimationFrame(() => scrollToBottom());return () => cancelAnimationFrame(id);- }, [session.id, scrollToBottom]);+ }, [session.id, scrollToBottom, setFollowingTail]);// Deep-link jump (P5): once ChatPage has put the target message into// ``messages`` (either it was already loaded or the around-window was fetched@@ -3714,9 +3803,11 @@ const Transcript: React.FC<TranscriptProps> = ({}let raf2 = 0;suppressAnchorRef.current = true;- pinnedRef.current = false;anchorRef.current = null;const raf1 = requestAnimationFrame(() => {+ // Unpin with the scroll that actually leaves the tail, not a frame ahead+ // of it: until this runs the transcript has not moved anywhere.+ setFollowingTail(false);const row = el.querySelector(`[data-message-id="${CSS.escape(jumpTarget)}"]`);if (row) {row.scrollIntoView({ block: 'center' });@@ -3736,7 +3827,15 @@ const Transcript: React.FC<TranscriptProps> = ({if (raf2) cancelAnimationFrame(raf2);suppressAnchorRef.current = false;};- }, [jumpTarget, messages, needsLatestReload, captureAnchor, onJumpHandled, scrollToBottom]);+ }, [+ jumpTarget,+ messages,+ needsLatestReload,+ captureAnchor,+ onJumpHandled,+ scrollToBottom,+ 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"@@ -3826,6 +3925,11 @@ const Transcript: React.FC<TranscriptProps> = ({/>)}<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={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, sodiff --git a/ui/src/lib/transcriptScrollAnchor.ts b/ui/src/lib/transcriptScrollAnchor.tsindex e33dbe083..40c7e87da 100644--- a/ui/src/lib/transcriptScrollAnchor.ts+++ b/ui/src/lib/transcriptScrollAnchor.ts@@ -13,9 +13,13 @@// viewport keeps the raw top-of-window ``scrollTop`` and the reader is dropped on// the oldest row of the page that just arrived. The transient members of that// 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 — and it was that-// near-zero ``scrollTop`` which then failed the loader's re-arm gate, leaving-// paging dead until the reader scrolled back down and up again.+// 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.//// 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