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.

fix(agents): measure tall history ahead of WebKit scroll gestures (#9179)

Wolf Mermelsteinb848de56f04c
diff --git a/apps/web/src/features/channel/Channel/ThreadList.tsx b/apps/web/src/features/channel/Channel/ThreadList.tsx
index 0936ee9eaf..a621163bea 100644
--- a/apps/web/src/features/channel/Channel/ThreadList.tsx
+++ b/apps/web/src/features/channel/Channel/ThreadList.tsx
@@ -112,6 +112,9 @@ type ThreadListProps = {
const NEAR_TOP_THRESHOLD = 800;
const HISTORY_BUFFER_VIEWPORTS = 3;
const WEBKIT_HISTORY_BUFFER_VIEWPORTS = 6;
+// How far above the reading position WebKit keeps rows measured: about as far
+// as one long momentum fling travels.
+const WEBKIT_MEASURED_HISTORY_VIEWPORTS = 12;
const EXPLICIT_SCROLL_DOWN_TRIGGER_DISTANCE = 64;
const clamp = (value: number, min: number, max: number) =>
@@ -237,6 +240,49 @@ export function ThreadList(props: ThreadListProps) {
},
});
+ // Assigned once the virtualizer exists; its first range is computed inside
+ // the constructor, before the binding below is initialized.
+ let measured: { instance: typeof virtualizer } | undefined;
+ // The core reuses extracted indexes while the visible range holds still,
+ // so a pass that stopped at its unmeasured-row cap would not resume once
+ // those rows are measured. Measurements past such a pass start the next.
+ const [historyPass, setHistoryPass] = createSignal(0);
+ let resumeHistoryAfter: number | undefined;
+
+ // A WebKit gesture cannot move the native top boundary, so rows above that
+ // are taller than their estimate grow only the visual adjustment, and a
+ // fling stops at scrollTop 0 with history still above it. Keep the rows a
+ // fling can reach mounted and measured before it starts, a few unmeasured
+ // rows per pass, so the native extent above them is the real one.
+ function withMeasuredHistory(range: Range): number[] {
+ const indexes = defaultRangeExtractor(range);
+ const instance = measured?.instance;
+ const first = indexes[0];
+ const visibleStart = instance?.measurementsCache[range.startIndex]?.start;
+ if (
+ !scrollCompensation ||
+ !instance ||
+ first === undefined ||
+ visibleStart === undefined
+ )
+ return indexes;
+ const buffer = viewportSize() * WEBKIT_MEASURED_HISTORY_VIEWPORTS;
+ const added: number[] = [];
+ let unmeasured = 0;
+ let top = instance.measurementsCache[first]?.start ?? visibleStart;
+ for (let index = first - 1; index >= 0; index--) {
+ const item = instance.measurementsCache[index];
+ if (!item || visibleStart - top >= buffer || unmeasured >= OVERSCAN)
+ break;
+ added.unshift(index);
+ top = item.start;
+ if (!instance.itemSizeCache.has(item.key)) unmeasured += 1;
+ }
+ resumeHistoryAfter =
+ unmeasured >= OVERSCAN ? instance.itemSizeCache.size : undefined;
+ return added.length === 0 ? indexes : [...added, ...indexes];
+ }
+
const virtualizer = createVirtualizer<HTMLDivElement, HTMLDivElement>({
// Do not consume initialOffset against an empty query result. Enabling
// with the first page lets TanStack render the latest rows immediately.
@@ -305,12 +351,13 @@ export function ThreadList(props: ThreadListProps) {
)
: 0,
get rangeExtractor() {
+ historyPass();
const index =
props.targetId === undefined
? -1
: props.keys().indexOf(props.targetId);
return (range: Range) => {
- const indexes = defaultRangeExtractor(range);
+ const indexes = withMeasuredHistory(range);
if (index < 0 || index >= range.count || indexes.includes(index))
return indexes;
return [...indexes, index].sort((a, b) => a - b);
@@ -385,9 +432,20 @@ export function ThreadList(props: ThreadListProps) {
instance.scrollToEnd();
}
}),
- onChange: scheduleScrollState,
+ onChange: (instance) => {
+ scheduleScrollState();
+ if (
+ resumeHistoryAfter !== undefined &&
+ instance.itemSizeCache.size > resumeHistoryAfter
+ ) {
+ resumeHistoryAfter = undefined;
+ queueMicrotask(() => setHistoryPass((pass) => pass + 1));
+ }
+ },
});
+ measured = { instance: virtualizer };
+
function writeScroll(...[offset, options, instance]: Parameters<ScrollToFn>) {
// WebKit ends native momentum on scrollTo writes. Keep TanStack's logical
// offset, but counter-shift the rows until wheel/touch scrolling settles.
diff --git a/apps/web/src/features/channel/Channel/tests/thread-list-pagination.test.tsx b/apps/web/src/features/channel/Channel/tests/thread-list-pagination.test.tsx
index 2be6652af4..f10c57ff2b 100644
--- a/apps/web/src/features/channel/Channel/tests/thread-list-pagination.test.tsx
+++ b/apps/web/src/features/channel/Channel/tests/thread-list-pagination.test.tsx
@@ -189,6 +189,50 @@ describe('history loading ahead of scrolling', () => {
expect(f.paginate).toHaveBeenCalledTimes(3);
});
+ it.each([true, false])(
+ 'measures rows taller than the estimate ahead of a gesture (safari=%s)',
+ async (safari) => {
+ platform.safari = safari;
+ // Browsers report an observed element once, which is how rows mounted
+ // during a scroll get measured.
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(readonly callback: ResizeObserverCallback) {}
+ observe(target: Element) {
+ queueMicrotask(() =>
+ this.callback(
+ [{ target } as ResizeObserverEntry],
+ this as unknown as ResizeObserver
+ )
+ );
+ }
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ // Rows three times the estimate, as long agent transcripts are: a
+ // fling over unmeasured rows hits the native top while history remains.
+ const keys = Array.from({ length: 40 }, (_, index) => String(index));
+ for (const key of keys) rowHeights.set(key, 300);
+ const { container } = render(() => (
+ <ThreadList keys={() => keys}>{({ id }) => <div>{id}</div>}</ThreadList>
+ ));
+ const mounted = () =>
+ [...container.querySelectorAll('[data-index]')].map((row) =>
+ Number(row.getAttribute('data-index'))
+ );
+ // Rows 38-39 fill the viewport. Safari measures twelve viewports
+ // (4800px, rows 22-37) above them, more than one pass of six unmeasured
+ // rows; others mount only the default overscan of six (rows 32-37).
+ await waitFor(() => expect(mounted()).toContain(32));
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ if (safari) expect(Math.min(...mounted())).toBeLessThanOrEqual(22);
+ else expect(Math.min(...mounted())).toBe(32);
+ expect(Math.max(...mounted())).toBe(39);
+ }
+ );
+
it('ends native scrolling at the latest message while a gesture shifts the rows', async () => {
const f = setup();
await waitFor(() => expect(f.paginate).toHaveBeenCalledOnce());
diff --git a/apps/web/src/features/channel/docs/sticky-scrolling.md b/apps/web/src/features/channel/docs/sticky-scrolling.md
index 33bfecc81a..af2d172230 100644
--- a/apps/web/src/features/channel/docs/sticky-scrolling.md
+++ b/apps/web/src/features/channel/docs/sticky-scrolling.md
@@ -74,6 +74,12 @@ The sizer's height excludes the adjustment during this period, so its end moves
the shifted rows: native scrolling stops at the latest message instead of continuing
into blank space below it (or stopping short of it), and the distance to the bottom
compares native positions.
+Because a gesture never moves the native top boundary, rows above that are taller than
+their 96px estimate would only grow the adjustment, and a long fling stops at
+`scrollTop` 0 with history still above it. On WebKit the range extractor
+therefore keeps rows up to twelve viewports above the reading position mounted
+and measured before a gesture reaches them, adding at most six unmeasured rows
+per range pass.
Scroll boundaries follow the same rule: momentum bounces there, and a finger can hold
the list against an edge. Explicit message, reply, latest, and pinned viewport/inset
navigation flush the adjustment before computing targets.
diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.md
index a02bfe37ce..f8ca4c43df 100644
--- a/docs/agent-guide/ai-chat.md
+++ b/docs/agent-guide/ai-chat.md
@@ -1889,7 +1889,9 @@ at the latest message, including when history arrives after the empty view. Shor
transcripts start with 16px of top padding, with the user prompt followed by the
agent response; streaming output grows downward into the available space. Only
the visible rows and an overscan buffer are mounted: scroll to older turns before
-searching their DOM text.
+searching their DOM text. On iPhone and Safari the buffer above extends twelve
+viewports, so a long fling up a transcript of tall replies keeps its momentum
+instead of stopping at a false top.
Search links add `agent_message_turn=<zero-based turn>&agent_message_author=user|agent`.
They wait for history to load, then scroll to and highlight the matching folded