Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

refactor(agent): use TanStack transcript virtualization (#6246)

Wolf Mermelstein887156242991
diff --git a/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md b/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md
index 0c9c79758a..ce56d8b7a4 100644
--- a/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md
+++ b/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md
@@ -4,6 +4,12 @@ How `block-channel` / `features/channel` is wired, as a template for giving `blo
real state (live updates, send path, scroll, input). All paths relative to `apps/web/src`
unless absolute. Line numbers are as of commit `254b60f339`.
+These are historical design notes, not a current implementation inventory.
+Section 5 and the scroll recommendation below were refreshed against `17a1dc1848`.
+The agent now has a live reconciled feed, wired composer, and shared TanStack
+ThreadList; the remaining proposed factories/API names below describe the earlier
+design exploration and must be checked against current code before reuse.
+
---
## 1. Block entry & composition
@@ -195,30 +201,28 @@ and each `*InTargetCaches` helper applies the change to all three cache families
## 5. Scroll & list (summary)
-- **Virtualization**: `virtua/solid` (`Virtualizer` in `Channel/ThreadList.tsx:712`), not a
- hand-rolled list. `itemSize={96}` estimate, `bufferSize={500}`, `shift` prop flips during
- top-pagination so existing items keep their offsets, `keepMounted` pins the target thread's
- row during nested navigation, `cache={snapshot.virtualCache}` restores measured sizes.
-- **ThreadList contract**: renders from `keys: Accessor<string[]>` + row render prop; emits
- `onNavigationReady(ThreadListNavigation)` (scrollTo/scrollToId/scrollToBottom/scrollToElementInItem/markUserIntent, :38–61)
- and `onScrollStateChange(ThreadListScrollState)` ({didInitialScroll, isNearBottom, distanceFromTop/Bottom,...}, :63–70).
-- **Initial scroll** is a small state machine: preposition to bottom before measurement
- (:538), retry via `onScrollEnd` (:553), RAF fallbacks for "nothing moved". Everything else
- (target scrolls, pagination) is gated on `didInitialScroll`.
-- **pinToBottom** (:328): after scroll-to-bottom, re-pin every frame for 1s + ResizeObserver,
- aborted by wheel-up/touch-drag — absorbs late-settling content (images, growing agent output).
- **This is the piece a streaming agent transcript wants most.**
-- **Pagination triggers**: `onScrollNearTop/Bottom` fire only with `scrollIntent.isUserInteracting()`
- (:662) so virtualizer-resize scrolls can't fetch pages.
-- **Sticky scroll**: `createStickyScrollEffect` (§3) — follow only if appended-at-bottom && near true bottom.
-- **Scroll snapshots**: `onScrollSnapshotChange` emits `{scrollOffset, virtualCache, isNearBottom}`
- on every scroll; Channel keeps the latest in a signal; entry-state captor persists it; on
- restore, `isNearBottom` snapshots collapse to "scroll to bottom" (ThreadList.tsx:520–529).
-- **Target navigation**: adapter resolves id → Channel `goToMessage` → controller sets
- `loadAroundMessageId` (new query window) + pending scroll ids → effect scrolls when key
- present → row calls `positionTarget`/`onTargetMessageScrolled` to finish → 1s flash then clear.
-- `ScrollToBottomOverlay` reads `threadListScrollState`; `handleScrollToBottom` (Channel.tsx:545)
- resets the query to the default bottom window if `hasPreviousPage` (mid-history slice).
+- **Virtualization**: `@tanstack/solid-virtual` in `Channel/ThreadList.tsx`, with
+ `anchorTo: 'end'`, a 96px estimate, six-row overscan, and measured variable heights.
+ Solid `Key` owns rows by message ID rather than virtual-range index.
+- **Contract**: `keys: Accessor<string[]>`, a row render prop, `onReady(navigation)`
+ (scrollToLatest/scrollToMessage/scrollToElement), and `onScroll(state, snapshot)`.
+ `initialPosition` supports latest, element, and restore; `targetId` keeps a
+ navigation target mounted. `onReady` can return cleanup.
+- **Initial layout**: `createScrollLifecycle` waits for a nonempty measured list;
+ the initial offset seeds the latest range even when data arrives asynchronously.
+- **Following**: core end anchoring handles measured streaming growth and
+ `followOnAppend` follows new keys only near the end (50px). No one-second agent
+ settle loop or independent growth observer is needed.
+- **Mobile**: numeric `insets` participate in measurements and navigation; viewport
+ and floating-inset changes preserve the pin only when previously near the end.
+ Short lists bottom-align within these insets.
+- **Snapshots**: `{scrollOffset, measurements, isNearBottom}`; channel persists them,
+ but the agent transcript currently opens at latest rather than restoring history.
+- **Chrome**: `CustomScrollbar` and `ScrollToBottomOverlay`; the overlay requires
+ explicit downward scrolling while more than one viewport from the bottom.
+- **Agent reuse**: `component/Transcript.tsx` renders this same ThreadList with
+ session/turn/author keys, shared message width, and `ReplyToSelection`. Do not
+ reintroduce the former Virtua implementation or duplicate the list machinery.
---
@@ -290,12 +294,9 @@ messages in a `Scroll` (component/Block.tsx), `AgentInput` with an unwired `onSe
`optimisticInsertChannelMessage` + `adoptAgentSessionPlaceholder`. The channel's prompt-echo
problem (`hide-duplicate-prompts.ts`, flagged as a stopgap in Channel.tsx:241–250) is the
cautionary tale: decide the dedup key (client nonce in the frame?) up front.
-5. **Scroll**: at minimum `createStickyScrollEffect`'s exact rule (follow only when appended
- at bottom && near bottom) + a `pinToBottom`-style settle loop, since agent output grows
- after append. If transcripts get long, adopt `ThreadList` itself — it's channel-flavored but
- its props are generic (`keys`, render prop, navigation/scroll-state callbacks); virtua is
- the right tool for a multi-thousand-row session. Persist `{scrollOffset, virtualCache, isNearBottom}`
- in the entry-state captor like the adapter does.
+5. **Scroll (implemented)**: reuse `ThreadList` directly, as described in section 5.
+ If history restoration is later added, use its `measurements` snapshot contract,
+ not the retired Virtua cache or a second pinning loop.
6. **Entry-state captor** (`splitPanel.handle.registerEntryStateCaptor`) for scroll position +
composer-adjacent state so split history restore doesn't reset the view.
7. **Input**: reuse `ChannelInput` (not `TaskModeChannelInput`) or keep `AgentInput` but adopt
diff --git a/apps/web/src/features/block-agent/component/Transcript.test.tsx b/apps/web/src/features/block-agent/component/Transcript.test.tsx
new file mode 100644
index 0000000000..09f3cf741f
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/Transcript.test.tsx
@@ -0,0 +1,381 @@
+import type { FoldedMessage } from '@service-agent-fold/generated/types';
+import { cleanup, render } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { createStore, reconcile } from 'solid-js/store';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { Transcript } from './Transcript';
+
+const session = vi.hoisted(() => ({
+ messages: () => [] as FoldedMessage[],
+ quoteSelection: vi.fn(),
+ touch: false,
+ top: () => 40,
+ bottom: (): number => 80,
+}));
+vi.mock('../context/AgentSessionContext', () => ({
+ useAgentSession: () => session,
+}));
+vi.mock('@components/app/split-layout/layoutUtils', () => ({
+ useSplitPanel: () => ({ contentOffsetTop: session.top }),
+}));
+vi.mock('@components/app/mobile/float-regions/float-region-state', () => ({
+ FloatRegions: { hostHeight: () => session.bottom() },
+}));
+vi.mock('@core/mobile/isTouchDevice', () => ({
+ isTouchDevice: () => session.touch,
+}));
+vi.mock('@ui', () => ({ cn: (...classes: string[]) => classes.join(' ') }));
+vi.mock('./AgentMessage', () => ({
+ Message: (props: { message: FoldedMessage }) => (
+ <span data-message={`${props.message.turn}:${props.message.author.kind}`}>
+ {JSON.stringify(props.message.parts)}
+ </span>
+ ),
+}));
+vi.mock('./ReplyToSelection', () => ({
+ ReplyToSelection: (props: {
+ container?: HTMLElement;
+ onReply: (text: string) => void;
+ }) => (
+ <button
+ data-selection-connected={!!props.container}
+ onClick={() => props.onReply('selected text')}
+ >
+ Reply to selection
+ </button>
+ ),
+}));
+
+const message = (turn: number, text = 'hello'): FoldedMessage =>
+ ({
+ agentSessionId: 'session',
+ turn,
+ author: { kind: 'agent' },
+ parts: [{ kind: 'text', text }],
+ stop: null,
+ }) as FoldedMessage;
+
+// Keep the real ThreadList/Solid adapter/core. Only browser geometry and the
+// expensive message renderer are substituted; jsdom has no layout engine.
+let viewport = 400;
+let rowHeight = 96;
+const originalScrollTo = HTMLElement.prototype.scrollTo;
+const observers = new Set<{
+ callback: ResizeObserverCallback;
+ elements: Set<Element>;
+}>();
+const resize = () => {
+ for (const observer of observers) {
+ observer.callback(
+ [...observer.elements].map((target) => ({
+ target,
+ contentBoxSize: [],
+ devicePixelContentBoxSize: [],
+ borderBoxSize: [
+ { inlineSize: 800, blockSize: (target as HTMLElement).offsetHeight },
+ ],
+ contentRect: target.getBoundingClientRect(),
+ })),
+ {} as ResizeObserver
+ );
+ }
+};
+const settle = async () => {
+ await new Promise((resolve) => setTimeout(resolve, 40));
+};
+
+beforeEach(() => {
+ viewport = 400;
+ rowHeight = 96;
+ session.touch = false;
+ session.bottom = () => 80;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ elements = new Set<Element>();
+ constructor(public callback: ResizeObserverCallback) {
+ observers.add(this);
+ }
+ observe(element: Element) {
+ observers.add(this);
+ this.elements.add(element);
+ }
+ unobserve(element: Element) {
+ this.elements.delete(element);
+ }
+ disconnect() {
+ this.elements.clear();
+ observers.delete(this);
+ }
+ }
+ );
+ vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ return this.hasAttribute('data-index') ? rowHeight : viewport;
+ }
+ );
+ vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(800);
+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(
+ () => viewport
+ );
+ vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ return Math.max(
+ viewport,
+ Number.parseFloat(
+ (this.firstElementChild as HTMLElement)?.style.height
+ ) || 0
+ );
+ }
+ );
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(
+ function (this: HTMLElement) {
+ return {
+ width: 800,
+ height: this.offsetHeight,
+ top: 0,
+ left: 0,
+ bottom: this.offsetHeight,
+ right: 800,
+ x: 0,
+ y: 0,
+ toJSON() {},
+ };
+ }
+ );
+ HTMLElement.prototype.scrollTo = function (
+ options: ScrollToOptions | number = {}
+ ) {
+ const top = typeof options === 'number' ? options : (options.top ?? 0);
+ this.scrollTop = Math.max(
+ 0,
+ Math.min(top, this.scrollHeight - this.clientHeight)
+ );
+ this.dispatchEvent(new Event('scroll'));
+ };
+});
+afterEach(() => {
+ cleanup();
+ observers.clear();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ HTMLElement.prototype.scrollTo = originalScrollTo;
+ window.getSelection()?.removeAllRanges();
+});
+
+function mount(initial: FoldedMessage[]) {
+ const [messages, setMessages] = createSignal(initial);
+ session.messages = messages;
+ const view = render(() => <Transcript />);
+ const scroller = view.container.querySelector<HTMLDivElement>(
+ '[data-channel-scroll]'
+ )!;
+ return { ...view, scroller, setMessages };
+}
+
+describe('Transcript with the shared TanStack ThreadList', () => {
+ it('reveals the overlay on downward thumb drag and refreshes the unpinned thumb range', async () => {
+ const view = mount(Array.from({ length: 50 }, (_, i) => message(i)));
+ await settle();
+ view.scroller.scrollTo({ top: 500 });
+ await settle();
+ const gutter = view.scroller.nextElementSibling as HTMLElement;
+ const thumb = gutter.firstElementChild as HTMLElement;
+ let captured = false;
+ gutter.setPointerCapture = () => {
+ captured = true;
+ };
+ gutter.hasPointerCapture = () => captured;
+ gutter.releasePointerCapture = () => {
+ captured = false;
+ };
+ const pointer = (type: string, clientY: number) =>
+ gutter.dispatchEvent(
+ Object.assign(new Event(type, { bubbles: true }), {
+ button: 0,
+ pointerId: 1,
+ pointerType: 'mouse',
+ clientY,
+ })
+ );
+ const thumbTop = Number.parseFloat(
+ thumb.style.transform.slice('translateY('.length)
+ );
+ pointer('pointerdown', thumbTop + 2);
+ pointer('pointermove', thumbTop + 22);
+ // jsdom does not dispatch scroll events for direct scrollTop assignments.
+ view.scroller.dispatchEvent(new Event('scroll'));
+ pointer('pointerup', thumbTop + 22);
+ await settle();
+ expect(view.getByText('Scroll to bottom')).toBeTruthy();
+
+ const offset = view.scroller.scrollTop;
+ const oldHeight = Number.parseFloat(thumb.style.height);
+ const sizer = view.scroller.firstElementChild!;
+ expect(
+ [...observers].some((observer) => observer.elements.has(sizer))
+ ).toBe(true);
+ // Change only the sizer style, without row mutations or a scroll event.
+ (sizer as HTMLElement).style.height =
+ `${view.scroller.scrollHeight + 2000}px`;
+ resize();
+ await settle();
+ expect(view.scroller.scrollTop).toBe(offset);
+ expect(Number.parseFloat(thumb.style.height)).toBeLessThan(oldHeight);
+ });
+
+ it('loads asynchronous history at latest with only a bounded range mounted', async () => {
+ const view = mount([]);
+ await settle();
+ view.setMessages(Array.from({ length: 200 }, (_, i) => message(i)));
+ await settle();
+ expect(
+ view.container.querySelector('[data-message="199:agent"]')
+ ).not.toBeNull();
+ expect(
+ view.container.querySelectorAll('[data-message]').length
+ ).toBeLessThan(30);
+ expect(view.scroller.scrollTop).toBe(view.scroller.scrollHeight - viewport);
+ });
+
+ it('bottom-aligns a short transcript inside mobile insets and preserves selection wiring', async () => {
+ session.touch = true;
+ const view = mount([message(0)]);
+ await settle();
+ const row = view.container.querySelector<HTMLElement>('[data-index="0"]')!;
+ expect(row.style.transform).toBe('translateY(224px)');
+ expect(view.scroller.scrollTop).toBe(0);
+ const reply = view.getByText('Reply to selection');
+ expect(reply.getAttribute('data-selection-connected')).toBe('true');
+ reply.click();
+ expect(session.quoteSelection).toHaveBeenCalledWith('selected text');
+ });
+
+ it('uses the channel header inset without a fixed-pixel decorative gap', async () => {
+ session.touch = true;
+ rowHeight = 500;
+ const view = mount([message(0)]);
+ await settle();
+ resize();
+ await settle();
+ const row = view.container.querySelector<HTMLElement>('[data-index="0"]')!;
+ expect(row.style.transform).toBe('translateY(40px)');
+ expect(view.scroller.scrollHeight).toBe(40 + 500 + 80);
+ });
+
+ it('keeps a mounted row and its selection when its message object is replaced', async () => {
+ const view = mount([message(0)]);
+ await settle();
+ const row = view.container.querySelector('[data-index]');
+ const text = view.container.querySelector('[data-message]')!;
+ const range = document.createRange();
+ range.selectNode(text);
+ window.getSelection()!.addRange(range);
+ view.setMessages([message(0, 'streamed text'), message(1)]);
+ await settle();
+ expect(view.container.querySelector('[data-index]')).toBe(row);
+ expect(view.container.querySelector('[data-message]')).toBe(text);
+ expect(text.textContent).toContain('streamed text');
+ expect(window.getSelection()!.containsNode(text, true)).toBe(true);
+ view.setMessages([]);
+ await settle();
+ expect(view.container.querySelector('[data-message]')).toBeNull();
+ });
+
+ it('renders in-place reconciled parts updates without remounting the message', async () => {
+ const [messages, setMessages] = createStore([message(0, 'first token')]);
+ session.messages = () => messages;
+ const view = render(() => <Transcript />);
+ await settle();
+ const originalMessage = messages[0];
+ const originalParts = messages[0].parts;
+ const originalPart = messages[0].parts[0];
+ const row = view.container.querySelector('[data-index]');
+ const text = view.container.querySelector('[data-message]');
+
+ // The feed reconciles at an existing array index, not by replacing its
+ // accessor or message object. Nested store reads must remain subscribed.
+ setMessages(0, reconcile(message(0, 'first token and more')));
+ await settle();
+ expect(messages[0]).toBe(originalMessage);
+ expect(messages[0].parts).toBe(originalParts);
+ expect(messages[0].parts[0]).toBe(originalPart);
+ expect(view.container.querySelector('[data-index]')).toBe(row);
+ expect(view.container.querySelector('[data-message]')).toBe(text);
+ expect(text?.textContent).toContain('first token and more');
+
+ const next = message(0, 'finished text');
+ next.parts.push({ kind: 'text', text: 'a newly streamed part' });
+ setMessages(0, reconcile(next));
+ await settle();
+ expect(view.container.querySelector('[data-index]')).toBe(row);
+ expect(view.container.querySelector('[data-message]')).toBe(text);
+ expect(text?.textContent).toContain('finished text');
+ expect(text?.textContent).toContain('a newly streamed part');
+ });
+
+ it('follows appends and measured streaming growth only while pinned', async () => {
+ const view = mount(Array.from({ length: 30 }, (_, i) => message(i)));
+ await settle();
+ view.setMessages((list) => [...list, message(30)]);
+ await settle();
+ rowHeight = 140;
+ resize();
+ await settle();
+ expect(view.scroller.scrollTop).toBe(view.scroller.scrollHeight - viewport);
+
+ view.scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: -600 }));
+ view.scroller.scrollTo({ top: 500 });
+ await settle();
+ const offset = view.scroller.scrollTop;
+ view.setMessages((list) => [...list, message(31)]);
+ await settle();
+ expect(view.scroller.scrollTop).toBe(offset);
+ expect(view.scroller.scrollTop).toBeLessThan(
+ view.scroller.scrollHeight - viewport - 50
+ );
+ });
+
+ it('keeps the end pin through keyboard squish and floating composer inset changes', async () => {
+ session.touch = true;
+ const [bottom, setBottom] = createSignal(80);
+ session.bottom = bottom;
+ const view = mount(Array.from({ length: 30 }, (_, i) => message(i)));
+ await settle();
+ viewport = 250;
+ resize();
+ await settle();
+ expect(view.scroller.scrollTop).toBe(view.scroller.scrollHeight - viewport);
+ setBottom(160);
+ await settle();
+ expect(view.scroller.scrollTop).toBe(view.scroller.scrollHeight - viewport);
+ view.scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: -600 }));
+ view.scroller.scrollTo({ top: 500 });
+ await settle();
+ const offset = view.scroller.scrollTop;
+ setBottom(200);
+ viewport = 400;
+ resize();
+ await settle();
+ expect(view.scroller.scrollTop).toBe(offset);
+ });
+
+ it('reveals the shared overlay on downward intent and resumes following on click', async () => {
+ const view = mount(Array.from({ length: 50 }, (_, i) => message(i)));
+ await settle();
+ view.scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: -600 }));
+ view.scroller.scrollTo({ top: 500 });
+ await settle();
+ expect(view.queryByText('Scroll to bottom')).toBeNull();
+ view.scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: 100 }));
+ view.scroller.scrollTo({ top: 600 });
+ await settle();
+ view.getByText('Scroll to bottom').click();
+ await settle();
+ expect(view.scroller.scrollTop).toBe(view.scroller.scrollHeight - viewport);
+ expect(view.queryByText('Scroll to bottom')).toBeNull();
+ view.setMessages((list) => [...list, message(50)]);
+ await settle();
+ expect(view.scroller.scrollTop).toBe(view.scroller.scrollHeight - viewport);
+ });
+});
diff --git a/apps/web/src/features/block-agent/component/Transcript.tsx b/apps/web/src/features/block-agent/component/Transcript.tsx
index 11cd539ed7..ef3c55e577 100644
--- a/apps/web/src/features/block-agent/component/Transcript.tsx
+++ b/apps/web/src/features/block-agent/component/Transcript.tsx
@@ -1,218 +1,73 @@
-/**
- * The message chain: a virtualized transcript that loads pinned to the
- * bottom and follows appends while the reader is near it.
- *
- * The scroll recipe is the channel's `ThreadList` distilled (see
- * CHANNEL_BLOCK_NOTES.md §5): virtua for virtualization, an immediate
- * bottom preposition on mount (virtua overshoots with an unmeasured
- * viewport and the browser clamps — first paint lands at the bottom), then
- * a settle loop that keeps re-pinning while late content (Pierre diffs,
- * markdown) grows the list, aborting on a real scroll-up gesture. opencode
- * solves the same problem by patching @tanstack/virtual-core with
- * `anchorTo: "end"`/`followOnAppend` — virtua plus this loop is the
- * unpatched equivalent.
- *
- * Chrome shared with the channel: the `@ui` `Scroll` thumb (hidden native
- * scrollbar, drag-seekable gutter) and the channel's `ScrollToBottomOverlay`,
- * fed by the same scroll-state shape `ThreadList` emits.
- */
-
+/** Agent messages on the channel's end-anchored TanStack scroll surface. */
import { ScrollToBottomOverlay } from '@channel/Channel/ScrollToBottomOverlay';
-import type { ThreadListScrollState } from '@channel/Channel/ThreadList';
-import { createMobileKeyboardScrollPin } from '@core/component/AI/component/message/create-mobile-keyboard-scroll-pin';
-import { Scroll } from '@ui';
-import { createSignal, onCleanup } from 'solid-js';
-import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
+import {
+ ThreadList,
+ type ThreadListNavigation,
+ type ThreadListScrollState,
+} from '@channel/Channel/ThreadList';
+import { FloatRegions } from '@components/app/mobile/float-regions/float-region-state';
+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { createMemo, createSignal, Show } from 'solid-js';
import { useAgentSession } from '../context/AgentSessionContext';
import { Message } from './AgentMessage';
import { ReplyToSelection } from './ReplyToSelection';
-/** The channel's `NEAR_BOTTOM_THRESHOLD`: within this, the view follows. */
-const NEAR_BOTTOM_PX = 50;
-/** How long the bottom pin keeps correcting after a scroll-to-bottom. */
-const SETTLE_MS = 1000;
-/** The channel's `BASE_ITEM_SIZE` estimate. */
-const ITEM_SIZE = 96;
-
export function Transcript() {
const { messages, quoteSelection } = useAgentSession();
-
- let scrollRef: HTMLDivElement | undefined;
- let handle: VirtualizerHandle | undefined;
- let cancelPin: (() => void) | undefined;
- let growthObserver: ResizeObserver | undefined;
- let viewportObserver: ResizeObserver | undefined;
+ const splitPanel = useSplitPanel();
const [transcriptEl, setTranscriptEl] = createSignal<HTMLDivElement>();
- const [contentEl, setContentEl] = createSignal<HTMLDivElement>();
-
- onCleanup(() => {
- cancelPin?.();
- growthObserver?.disconnect();
- viewportObserver?.disconnect();
- });
- // Whether the view should chase the bottom as content grows. True until
- // the reader scrolls away; recomputed on every scroll.
- let follow = true;
- let didInitialScroll = false;
- let lastScrollTop = 0;
-
- // The scroller's inner height, so short transcripts can bottom-align:
- // the flex spacer needs the content wrapper to be at least viewport-tall.
- const [viewportHeight, setViewportHeight] = createSignal(0);
const [scrollState, setScrollState] = createSignal<ThreadListScrollState>();
-
- const distanceFromBottom = () => {
- const el = scrollRef;
- if (!el) return 0;
- return el.scrollHeight - el.scrollTop - el.clientHeight;
- };
-
- const emitScrollState = () => {
- const el = scrollRef;
- if (!el) return;
- const distance = distanceFromBottom();
- setScrollState({
- didInitialScroll,
- isNearBottom: distance <= NEAR_BOTTOM_PX,
- isScrollingDown: el.scrollTop >= lastScrollTop,
- distanceFromTop: el.scrollTop,
- distanceFromBottom: distance,
- viewportSize: el.clientHeight,
- });
- lastScrollTop = el.scrollTop;
- };
-
- /**
- * Scroll to the newest message, then keep re-pinning to the true bottom for
- * a short window so late-settling content can't leave the last message cut
- * off. Aborts on a wheel-up or touch drag (a tap is not a scroll) — the
- * channel's `pinToBottom`, without its target machinery.
- */
- const pinToBottom = () => {
- cancelPin?.();
- const el = scrollRef;
- if (!el || !handle) return;
- follow = true;
- handle.scrollToIndex(messages().length - 1, { align: 'end' });
-
- let rafId = 0;
- const start = performance.now();
-
- const stop = () => {
- if (rafId) cancelAnimationFrame(rafId);
- el.removeEventListener('wheel', onWheel);
- el.removeEventListener('pointerdown', onPointerDown);
- if (cancelPin === stop) cancelPin = undefined;
- didInitialScroll = true;
- emitScrollState();
- };
- function onWheel(event: WheelEvent) {
- if (event.deltaY < 0) stop();
- }
- function onPointerDown(event: PointerEvent) {
- if (event.pointerType === 'touch') stop();
- }
- el.addEventListener('wheel', onWheel, { passive: true });
- el.addEventListener('pointerdown', onPointerDown, { passive: true });
- cancelPin = stop;
-
- const tick = () => {
- if (distanceFromBottom() > 1) el.scrollTop = el.scrollHeight;
- if (performance.now() - start >= SETTLE_MS) {
- stop();
- return;
- }
- rafId = requestAnimationFrame(tick);
- };
- rafId = requestAnimationFrame(tick);
- };
-
- // Follow growth beyond the pin window: whenever the virtualized content
- // resizes (a new turn, a streaming message getting longer) and the reader
- // hasn't scrolled away, snap back to the bottom. This is the sticky-scroll
- // rule — follow only near the bottom — applied to content growth, which is
- // how agent output arrives.
- const observeGrowth = (el: HTMLDivElement) => {
- growthObserver = new ResizeObserver(() => {
- if (follow && distanceFromBottom() > 1) {
- const scroller = scrollRef;
- if (scroller) scroller.scrollTop = scroller.scrollHeight;
- }
- });
- growthObserver.observe(el);
- };
-
- const attachScroller = (el: HTMLDivElement) => {
- scrollRef = el;
- // `Scroll` owns the element's onScroll; listen alongside it.
- el.addEventListener(
- 'scroll',
- () => {
- follow = distanceFromBottom() <= NEAR_BOTTOM_PX;
- emitScrollState();
- },
- { passive: true }
- );
- viewportObserver = new ResizeObserver(() => {
- setViewportHeight(el.clientHeight);
- emitScrollState();
- });
- viewportObserver.observe(el);
- };
-
- // Full-frame mobile: keep pinned to the bottom across virtual-keyboard
- // show/hide when the reader was already at the bottom — same recipe as
- // the AI chat, now that the composer lives in the accessory float.
- createMobileKeyboardScrollPin({
- scrollEl: () => scrollRef,
- wrapperEl: contentEl,
- scrollToBottom: () => pinToBottom(),
- });
+ let navigation: ThreadListNavigation | undefined;
+
+ // Object identity and array positions can change as the live fold reconciles.
+ const messageById = createMemo(
+ () =>
+ new Map(
+ messages().map((message) => [
+ `${message.agentSessionId}:${message.turn}:${message.author.kind}`,
+ message,
+ ])
+ )
+ );
+ const keys = createMemo(() => [...messageById().keys()]);
+ // Insets belong in virtual measurements, not CSS padding outside the sizer.
+ // ThreadList preserves the end pin across keyboard/viewport and inset resizes.
+ const insets = () =>
+ isTouchDevice()
+ ? {
+ start: splitPanel?.contentOffsetTop() ?? 0,
+ end: FloatRegions.hostHeight(),
+ }
+ : { start: 0, end: 0 };
return (
<div class="relative flex-1 min-h-0" ref={setTranscriptEl}>
- <Scroll scrollRef={attachScroller}>
- <div
- ref={setContentEl}
- class="flex flex-col [overflow-anchor:none] touch:pt-[calc(var(--mobile-content-inset-top,0)+0.5rem)] touch:pb-(--mobile-content-inset-bottom)"
- style={{ 'min-height': `${viewportHeight()}px` }}
- >
- {/* Bottom-align short transcripts, chat-style. */}
- <div aria-hidden style={{ 'flex-grow': 1 }} />
- <div ref={observeGrowth}>
- <Virtualizer
- ref={(virtualizer) => {
- if (!virtualizer) return;
- handle = virtualizer;
- // Issue the bottom target immediately, before virtua has a
- // measured viewport — overshoot clamps to the current
- // maximum, so the first painted frame is already at the
- // bottom.
- if (messages().length > 0) pinToBottom();
- }}
- scrollRef={scrollRef}
- data={messages()}
- itemSize={ITEM_SIZE}
- onScrollEnd={() => {
- // The feed fills asynchronously; if rows arrived after mount
- // and we're meant to be following, correct the landing.
- if (follow && distanceFromBottom() > NEAR_BOTTOM_PX) {
- pinToBottom();
- }
- }}
- >
- {(message) => (
- <div class="macro-message-width mx-auto px-4 pb-4 min-w-0">
- <Message message={message} />
- </div>
- )}
- </Virtualizer>
- </div>
- </div>
- </Scroll>
+ <ThreadList
+ keys={keys}
+ initialPosition={{ type: 'latest' }}
+ insets={insets()}
+ onReady={(handle) => {
+ navigation = handle;
+ return () => {
+ navigation = undefined;
+ };
+ }}
+ onScroll={(state) => setScrollState(state)}
+ >
+ {({ id }) => (
+ <Show when={messageById().get(id)}>
+ {(message) => (
+ <div class="macro-message-width mx-auto px-4 pb-4 min-w-0">
+ <Message message={message()} />
+ </div>
+ )}
+ </Show>
+ )}
+ </ThreadList>
<ScrollToBottomOverlay
scrollState={scrollState}
- onScrollToBottom={pinToBottom}
+ onScrollToBottom={() => navigation?.scrollToLatest()}
class="touch:top-[calc(var(--mobile-content-inset-top,0)+1rem)]"
/>
<ReplyToSelection container={transcriptEl()} onReply={quoteSelection} />
diff --git a/apps/web/src/features/channel/Channel/ThreadList.tsx b/apps/web/src/features/channel/Channel/ThreadList.tsx
index e63d7d27ef..c9afbed29d 100644
--- a/apps/web/src/features/channel/Channel/ThreadList.tsx
+++ b/apps/web/src/features/channel/Channel/ThreadList.tsx
@@ -504,7 +504,13 @@ export function ThreadList(props: ThreadListProps) {
</Key>
</div>
</div>
- <CustomScrollbar scrollContainer={scrollEl} />
+ <CustomScrollbar
+ scrollContainer={scrollEl}
+ watchContent
+ onScrollIntent={(delta) =>
+ scrollIntent.markUserIntent(delta > 0 ? 'down' : 'up')
+ }
+ />
</>
);
}
diff --git a/apps/web/src/lib/core/component/CustomScrollbar.tsx b/apps/web/src/lib/core/component/CustomScrollbar.tsx
index 1ce51d428e..b2055e1438 100644
--- a/apps/web/src/lib/core/component/CustomScrollbar.tsx
+++ b/apps/web/src/lib/core/component/CustomScrollbar.tsx
@@ -12,14 +12,16 @@ interface CustomScrollbarProps {
enabled?: boolean;
reverse?: boolean;
horizontal?: boolean;
+ /** Called before a pointer-driven scroll, with the signed offset change. */
+ onScrollIntent?: (delta: number) => void;
/**
* Reveal the bar when the pointer moves within this many px of the
* scrollbar edge, instead of only when hovering the gutter itself.
*/
revealZone?: number;
/**
- * Re-measure when content mounts/unmounts inside the container. Needed
- * when content loads in after mount without resizing the container.
+ * Re-measure when content mounts/unmounts or direct content wrappers resize.
+ * Includes virtual sizer growth without a viewport resize or scroll event.
*/
watchContent?: boolean;
/**
@@ -150,7 +152,14 @@ function InnerCustomScrollbar(props: CustomScrollbarProps) {
let mutationObserver: MutationObserver | undefined;
if (props.watchContent) {
- mutationObserver = new MutationObserver(updateScrollMetrics);
+ const observeContent = () => {
+ resizeObserver.disconnect();
+ resizeObserver.observe(container);
+ for (const child of container.children) resizeObserver.observe(child);
+ updateScrollMetrics();
+ };
+ observeContent();
+ mutationObserver = new MutationObserver(observeContent);
mutationObserver.observe(container, { childList: true, subtree: true });
}
@@ -180,6 +189,9 @@ function InnerCustomScrollbar(props: CustomScrollbarProps) {
const clamped = Math.max(0, Math.min(mt, localPos - THUMB_INSET));
let newPos = (clamped / mt) * max;
if (props.reverse && !horiz()) newPos = newPos - max;
+ const delta =
+ newPos - (horiz() ? container.scrollLeft : container.scrollTop);
+ if (delta !== 0) props.onScrollIntent?.(delta);
if (horiz()) {
container.scrollLeft = newPos;
} else {
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 7246c2bfa6..494bb4b8ef 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -59,13 +59,39 @@ stays tappable and clear of the home indicator. The box is full width; the text
sits on top and a footer row holds the model name (left, e.g. `Auto ⌄`) and
**Send** (right). Tapping the model name opens a bottom sheet listing every
model with a check on the current one — pick a row to switch. On desktop the
-transcript and composer are half the pane wide so expanding **Context** only
+transcript and composer use the shared channel message width so expanding **Context** only
grows vertically; your messages are right-aligned bubbles and the model pill
sits above the box. Tap the session title
to open the title menu (caret), then **Rename** — that opens the same style of
rename dialog automations use. Do not expect a tap on the name itself to start
an inline edit.
+### Transcript navigation
+
+Agent sessions reuse the channel's TanStack `ThreadList`. Opening a session lands
+at the latest message, including when history arrives after the empty view. Short
+transcripts sit at the bottom, above the composer. Only the visible rows and an
+overscan buffer are mounted: scroll to older turns before searching their DOM text.
+
+- New messages and growing streamed replies follow while within 50px of the end.
+ Scroll up to read history without being pulled back by subsequent output.
+- Far above the end, scroll downward to reveal **Scroll to bottom**. Clicking it
+ returns to latest and resumes following. The right-edge custom scrollbar is also
+ drag-seekable, like channels.
+- Select mounted transcript text to use **Reply to selection**. Streaming updates
+ retain message-row identity; scrolling a row outside the virtual window can
+ unmount it, so finish selecting/quoting before navigating far away.
+- On mobile, messages scroll behind the floating header and composer. Their insets
+ are included in list measurements. Keyboard show/hide and composer/queue height
+ changes keep latest visible only if the reader was already pinned.
+
+Regression check: open a long session, let a reply stream while at latest, then
+scroll several screens up and confirm output does not pull you down. Scroll down
+to reveal the overlay and return to latest. Repeat with a short session and on a
+physical phone while opening/dismissing the keyboard, both at latest and in history.
+
+### Sending and queueing
+
- Sending is never blocked by a running turn. A prompt sent mid-turn is queued
**server-side** and dispatches automatically when the current turn ends, one per turn.
The queue holds at most 50 entries; past that a send is refused with an error rather