From 7fbef083b5fb20ab95266dc331675f3ac63c9716 Mon Sep 17 00:00:00 2001 From: sorghum Date: Fri, 27 Nov 2026 06:30:25 +0000 Subject: [PATCH 1/3] fix: preserve transient virtual row measurements --- web/src/chat.ts | 7 +- web/src/components/Conversation.tsx | 12 ++- web/tests/chat-scroll.test.mjs | 94 ++++++++++++++++++++- web/tests/conversation-performance.test.mjs | 7 +- 4 files changed, 111 insertions(+), 9 deletions(-) diff --git a/web/src/chat.ts b/web/src/chat.ts index f17e0dab..5a355a3a 100644 --- a/web/src/chat.ts +++ b/web/src/chat.ts @@ -88,8 +88,8 @@ export function userMessageDock(messages: { id: string; role: string; text: stri * Legacy `onScroll()` decision: streamed content pushes the viewport up without * the user leaving, so an upward movement marks `away`; returning near the * bottom resumes follow. A clamp that lands exactly at the bottom is the - * browser adjusting to shrunk content, not the user scrolling up; once away, - * only downward movement back into that window resumes follow. + * browser adjusting to shrunk content, not the user scrolling up; when that + * clamp was not deliberate input, it can also resume follow. */ export function chatScrollState(element: { scrollHeight: number; scrollTop: number; clientHeight: number } | null, previousTop: number, away: boolean, deliberateUp = false, threshold = CHAT_SCROLL_THRESHOLD) { if (!element) return { away, showScrollButton: false }; @@ -105,7 +105,8 @@ export function chatScrollState(element: { scrollHeight: number; scrollTop: numb } /** Message updates follow the same state as scroll tracking: once a deliberate - * upward scroll marks the reader away, only returning near the bottom resumes follow. */ + * upward scroll marks the reader away, follow resumes after returning near the bottom + * or after a browser clamp lands exactly at the bottom. */ export function chatShouldFollowMessages(away: boolean) { return !away; } diff --git a/web/src/components/Conversation.tsx b/web/src/components/Conversation.tsx index 90b403ea..7b807024 100644 --- a/web/src/components/Conversation.tsx +++ b/web/src/components/Conversation.tsx @@ -121,6 +121,9 @@ export function Messages({ session, loading, remoteRunning = false, scrollRef, o // Parents key this list by session id, so these measurements live and die with // the session instance instead of being mutated during a render transition. const heights = useRef(new Map()); + // Commit-phase measurements do not publish a render by themselves, but they + // keep heights for rows that unmount before ResizeObserver reports them. + const mountedHeights = useRef(new Map()); const nodes = useRef(new Map()); const observer = useRef(null); const [revision, setRevision] = useState(0); @@ -183,6 +186,8 @@ export function Messages({ session, loading, remoteRunning = false, scrollRef, o } nodes.current.set(id, node); node.dataset.virtualMessageId = id; + const height = node.getBoundingClientRect().height; + if (height > 0) mountedHeights.current.set(id, height); observer.current?.observe(node); }, []); @@ -190,10 +195,13 @@ export function Messages({ session, loading, remoteRunning = false, scrollRef, o const ids = new Set(messages.map(message => String(message.id))); let changed = false; for (const key of [...heights.current.keys()]) if (!ids.has(key)) { heights.current.delete(key); changed = true; } + for (const key of [...mountedHeights.current.keys()]) if (!ids.has(key)) mountedHeights.current.delete(key); if (changed) setRevision(value => value + 1); }, [messages]); - const heightsList = useMemo(() => messages.map(message => heights.current.get(String(message.id)) || estimateMessageHeight(message)), [messages, revision]); - const view = useMemo(() => virtualMessageWindow(heightsList, viewport.top, viewport.height), [heightsList, viewport.top, viewport.height]); + // Viewport renders must pick up commit-phase measurements even when the + // observer did not get a chance to publish them first. + const heightsList = messages.map(message => heights.current.get(String(message.id)) || mountedHeights.current.get(String(message.id)) || estimateMessageHeight(message)); + const view = virtualMessageWindow(heightsList, viewport.top, viewport.height); useEffect(() => { if (offsetsRef) offsetsRef.current = view.offsets; }, [offsetsRef, view.offsets]); const render = (message: Message) => message.role === 'user' diff --git a/web/tests/chat-scroll.test.mjs b/web/tests/chat-scroll.test.mjs index 8364cb52..1090a5bd 100644 --- a/web/tests/chat-scroll.test.mjs +++ b/web/tests/chat-scroll.test.mjs @@ -67,6 +67,7 @@ const { default: BlockRenderer } = await import(await sourceUrl('components/Bloc })); const chatWindowUrl = await sourceUrl('chat-window.ts', { './chat': chatUrl }); +const { estimateMessageHeight, virtualMessageWindow } = await import(chatWindowUrl); // Conversation.tsx must tag every message so the dock can jump to it. const imagePreviews = []; globalThis.__loopraTestImagePreviews = imagePreviews; @@ -331,10 +332,13 @@ function patchVirtualLayout(container, positions) { node.getBoundingClientRect = () => ({ top: position.top, height: position.height, bottom: position.top + position.height, left: 0, right: 600, width: 600, x: 0, y: position.top, toJSON: () => ({}) }); } } -async function measureVirtualMessages() { +async function measureVirtualMessages(afterCallback) { const resize = ResizeObserverStub.instances.at(-1); const entries = [...resize.observed].map(target => ({ target })); - await act(async () => resize.callback(entries)); + const original = resize.callback; + if (afterCallback) resize.callback = callbackEntries => { original(callbackEntries); afterCallback(); }; + try { await act(async () => resize.callback(entries)); } + finally { resize.callback = original; } } test('sparse measured outliers do not inflate unmounted row estimates', async () => { @@ -405,6 +409,92 @@ test('virtual layout corrections preserve the overlapping anchor row', async () } finally { await view.close(); } }); +test('corrected virtual scrolling keeps the anchor visible after window movement', async () => { + const messages = longSession(); + const scroll = document.createElement('div'); + Object.defineProperties(scroll, { + scrollTop: { configurable: true, writable: true, value: 3200 }, + clientHeight: { configurable: true, value: 600 }, + }); + scroll.getBoundingClientRect = () => ({ top: 0, height: 600, bottom: 600, left: 0, right: 800, width: 800, x: 0, y: 0, toJSON: () => ({}) }); + const expandedHeights = new Map(); + const actualHeight = index => (index % 2 ? 440 : 120) + (expandedHeights.get(`m${index}`) || 0); + const measured = new Map(); + let layoutTop = 0; + const dispatchScroll = async () => { + layoutTop = scroll.scrollTop; + await act(async () => scroll.dispatchEvent(new dom.window.Event('scroll'))); + }; + const indexOf = id => Number(id.slice(1)); + const positionOf = id => { + const index = indexOf(id); + const heightsList = messages.map(message => measured.get(String(message.id)) || estimateMessageHeight(message)); + const viewWindow = virtualMessageWindow(heightsList, layoutTop, scroll.clientHeight); + if (index < viewWindow.start || index >= viewWindow.end) return null; + let position = viewWindow.topHeight; + for (let row = viewWindow.start; row < index; row++) position += actualHeight(row); + return position; + }; + const originalRect = dom.window.HTMLElement.prototype.getBoundingClientRect; + dom.window.HTMLElement.prototype.getBoundingClientRect = function () { + const id = this.dataset?.virtualMessageId; + if (!id) return originalRect.call(this); + const index = indexOf(id); + const position = positionOf(id); + const height = actualHeight(index); + const top = position === null ? 0 : position - scroll.scrollTop; + return { top, height, bottom: top + height, left: 0, right: 600, width: 600, x: 0, y: top, toJSON: () => ({}) }; + }; + const syncMeasured = container => { + for (const node of container.querySelectorAll('.virtual-message-item')) { + const id = node.dataset.virtualMessageId; + if (id) measured.set(id, actualHeight(indexOf(id))); + } + }; + const corrections = []; + const correct = delta => { + corrections.push(delta); + scroll.scrollTop += delta; + }; + const scrollRef = { current: scroll }; + let view; + try { + view = await renderMessages(messages, { scrollRef, onCorrectScroll: correct }); + layoutTop = scroll.scrollTop; + await measureVirtualMessages(() => syncMeasured(view.container)); + // Applying a correction in a browser queues a real scroll event. Flush those + // events until the corrected viewport and mounted window agree. + for (let round = 0; round < 5; round++) { + const before = corrections.length; + await dispatchScroll(); + if (corrections.length === before) break; + } + const anchor = [...view.container.querySelectorAll('.virtual-message-item')] + .map(node => ({ id: node.dataset.virtualMessageId, rect: node.getBoundingClientRect() })) + .find(row => row.rect.bottom > 0); + assert.ok(anchor, 'initial viewport has an anchor row'); + corrections.length = 0; + + const mounted = [...view.container.querySelectorAll('.virtual-message-item')]; + const expanded = mounted.map(node => node.dataset.virtualMessageId).filter(id => indexOf(id) < indexOf(anchor.id)).at(-1); + assert.ok(expanded, 'a mounted row above the anchor can grow'); + expandedHeights.set(expanded, 500); + await measureVirtualMessages(() => syncMeasured(view.container)); + assert.equal(corrections.length, 1, 'the measurement/window movement produces exactly one initial correction'); + syncMeasured(view.container); + await dispatchScroll(); + assert.equal(corrections.length, 1, 'the real scroll event after correction does not correct again'); + + const anchored = view.container.querySelector(`[data-virtual-message-id="${anchor.id}"]`); + assert.ok(anchored, 'the original anchor row is still mounted'); + const rect = anchored.getBoundingClientRect(); + assert.ok(rect.bottom > 0 && rect.top < scroll.clientHeight, `anchor row remains in the viewport, got top=${rect.top} bottom=${rect.bottom}`); + } finally { + dom.window.HTMLElement.prototype.getBoundingClientRect = originalRect; + if (view) await view.close(); + } +}); + test('unmounted row estimates follow message content instead of visible outliers', async () => { const messages = longSession(); messages[5] = { ...messages[5], text: Array.from({ length: 250 }, (_, line) => `FINAL FIX LINE ${line + 1}`).join('\n') }; diff --git a/web/tests/conversation-performance.test.mjs b/web/tests/conversation-performance.test.mjs index f4d4e471..62048881 100644 --- a/web/tests/conversation-performance.test.mjs +++ b/web/tests/conversation-performance.test.mjs @@ -47,13 +47,16 @@ const blockUrl = dataUrl(` } `); const { renders } = await import(blockUrl); +const chatUrl = dataUrl(transpile(await readFile(new URL('../src/chat.ts', import.meta.url), 'utf8'))); +const chatWindowOutput = transpile(await readFile(new URL('../src/chat-window.ts', import.meta.url), 'utf8')) + .replaceAll(`'./chat'`, JSON.stringify(chatUrl)).replaceAll(`"./chat"`, JSON.stringify(chatUrl)); const specifiers = { react: reactUrl, 'react-i18next': reactI18nextStubUrl, 'react/jsx-runtime': import.meta.resolve('react/jsx-runtime'), 'lucide-react': import.meta.resolve('lucide-react'), - '../chat': dataUrl(transpile(await readFile(new URL('../src/chat.ts', import.meta.url), 'utf8'))), - '../chat-window': dataUrl(transpile(await readFile(new URL('../src/chat-window.ts', import.meta.url), 'utf8'))), + '../chat': chatUrl, + '../chat-window': dataUrl(chatWindowOutput), '../file-stats': dataUrl(transpile(await readFile(new URL('../src/file-stats.ts', import.meta.url), 'utf8'))), '../web-sources': dataUrl(transpile(await readFile(new URL('../src/web-sources.ts', import.meta.url), 'utf8'))), '../lib': dataUrl('export const getSessionMessages = session => session.messages;'), From 5dbe1d923d8c6f8310d574876200d28ea74c18c5 Mon Sep 17 00:00:00 2001 From: sorghum Date: Fri, 27 Nov 2026 06:34:15 +0000 Subject: [PATCH 2/3] fix: cache virtual row height estimates --- web/src/chat-window.ts | 12 ++++++++++-- web/src/components/Conversation.tsx | 3 ++- web/tests/chat-window.test.mjs | 8 ++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/web/src/chat-window.ts b/web/src/chat-window.ts index ff40f97e..8fa615a4 100644 --- a/web/src/chat-window.ts +++ b/web/src/chat-window.ts @@ -30,9 +30,15 @@ function visualWidth(line: string) { return width; } +const estimateCache = new WeakMap(); + /** Content-aware estimate for an unmounted row. Explicit lines dominate very - * long answers; wide characters wrap sooner than ASCII text. */ + * long answers; wide characters wrap sooner than ASCII text. Session messages + * are immutable, so unchanged rows do not need their text scanned on every + * virtual-scroll frame. */ export function estimateMessageHeight(message: { role: 'user' | 'assistant'; text?: string; images?: unknown[] }) { + const cached = estimateCache.get(message); + if (cached !== undefined) return cached; const widthUnits = message.role === 'user' ? USER_WIDTH_UNITS : ASSISTANT_WIDTH_UNITS; let text = message.text || ''; let chrome = 0; @@ -46,7 +52,9 @@ export function estimateMessageHeight(message: { role: 'user' | 'assistant'; tex } const lines = text.split(/\r?\n/).reduce((total, line) => total + Math.max(1, Math.ceil(visualWidth(line) / widthUnits)), 0); const base = message.role === 'user' ? USER_BASE_HEIGHT : ASSISTANT_BASE_HEIGHT; - return base + lines * LINE_HEIGHT_ESTIMATE + chrome + (message.images?.length || 0) * 160; + const height = base + lines * LINE_HEIGHT_ESTIMATE + chrome + (message.images?.length || 0) * 160; + estimateCache.set(message, height); + return height; } export type VirtualMessageWindow = { start: number; end: number; topHeight: number; bottomHeight: number; offsets: number[] }; diff --git a/web/src/components/Conversation.tsx b/web/src/components/Conversation.tsx index 7b807024..5b470656 100644 --- a/web/src/components/Conversation.tsx +++ b/web/src/components/Conversation.tsx @@ -199,7 +199,8 @@ export function Messages({ session, loading, remoteRunning = false, scrollRef, o if (changed) setRevision(value => value + 1); }, [messages]); // Viewport renders must pick up commit-phase measurements even when the - // observer did not get a chance to publish them first. + // observer did not get a chance to publish them first. Estimate caching keeps + // this per-row pass cheap for long histories. const heightsList = messages.map(message => heights.current.get(String(message.id)) || mountedHeights.current.get(String(message.id)) || estimateMessageHeight(message)); const view = virtualMessageWindow(heightsList, viewport.top, viewport.height); useEffect(() => { if (offsetsRef) offsetsRef.current = view.offsets; }, [offsetsRef, view.offsets]); diff --git a/web/tests/chat-window.test.mjs b/web/tests/chat-window.test.mjs index 720b43bc..44c525a8 100644 --- a/web/tests/chat-window.test.mjs +++ b/web/tests/chat-window.test.mjs @@ -61,3 +61,11 @@ test('user attachment envelopes estimate as compact controls rather than documen assert.ok(withAttachment < 250, `attachment-backed user row stayed compact, got ${withAttachment}`); assert.equal(withAttachment - bare, 40, 'the only added estimate is the attachment control'); }); + +test('message height estimates are cached by immutable message object', () => { + let reads = 0; + const message = { role: 'assistant', get text() { reads += 1; return Array.from({ length: 100 }, (_, line) => `line ${line}`).join('\n'); } }; + const first = estimateMessageHeight(message); + assert.equal(estimateMessageHeight(message), first); + assert.equal(reads, 1, 'unchanged message objects are not rescanned'); +}); From 8347034adc1e7f30035b4e45e6c2a7f703456633 Mon Sep 17 00:00:00 2001 From: sorghum Date: Fri, 27 Nov 2026 06:42:23 +0000 Subject: [PATCH 3/3] fix: simplify virtual anchor regression coverage --- web/src/chat-window.ts | 12 +-- web/src/components/Conversation.tsx | 13 +-- web/tests/chat-scroll.test.mjs | 136 ++++++++-------------------- web/tests/chat-window.test.mjs | 8 -- 4 files changed, 42 insertions(+), 127 deletions(-) diff --git a/web/src/chat-window.ts b/web/src/chat-window.ts index 8fa615a4..ff40f97e 100644 --- a/web/src/chat-window.ts +++ b/web/src/chat-window.ts @@ -30,15 +30,9 @@ function visualWidth(line: string) { return width; } -const estimateCache = new WeakMap(); - /** Content-aware estimate for an unmounted row. Explicit lines dominate very - * long answers; wide characters wrap sooner than ASCII text. Session messages - * are immutable, so unchanged rows do not need their text scanned on every - * virtual-scroll frame. */ + * long answers; wide characters wrap sooner than ASCII text. */ export function estimateMessageHeight(message: { role: 'user' | 'assistant'; text?: string; images?: unknown[] }) { - const cached = estimateCache.get(message); - if (cached !== undefined) return cached; const widthUnits = message.role === 'user' ? USER_WIDTH_UNITS : ASSISTANT_WIDTH_UNITS; let text = message.text || ''; let chrome = 0; @@ -52,9 +46,7 @@ export function estimateMessageHeight(message: { role: 'user' | 'assistant'; tex } const lines = text.split(/\r?\n/).reduce((total, line) => total + Math.max(1, Math.ceil(visualWidth(line) / widthUnits)), 0); const base = message.role === 'user' ? USER_BASE_HEIGHT : ASSISTANT_BASE_HEIGHT; - const height = base + lines * LINE_HEIGHT_ESTIMATE + chrome + (message.images?.length || 0) * 160; - estimateCache.set(message, height); - return height; + return base + lines * LINE_HEIGHT_ESTIMATE + chrome + (message.images?.length || 0) * 160; } export type VirtualMessageWindow = { start: number; end: number; topHeight: number; bottomHeight: number; offsets: number[] }; diff --git a/web/src/components/Conversation.tsx b/web/src/components/Conversation.tsx index 5b470656..90b403ea 100644 --- a/web/src/components/Conversation.tsx +++ b/web/src/components/Conversation.tsx @@ -121,9 +121,6 @@ export function Messages({ session, loading, remoteRunning = false, scrollRef, o // Parents key this list by session id, so these measurements live and die with // the session instance instead of being mutated during a render transition. const heights = useRef(new Map()); - // Commit-phase measurements do not publish a render by themselves, but they - // keep heights for rows that unmount before ResizeObserver reports them. - const mountedHeights = useRef(new Map()); const nodes = useRef(new Map()); const observer = useRef(null); const [revision, setRevision] = useState(0); @@ -186,8 +183,6 @@ export function Messages({ session, loading, remoteRunning = false, scrollRef, o } nodes.current.set(id, node); node.dataset.virtualMessageId = id; - const height = node.getBoundingClientRect().height; - if (height > 0) mountedHeights.current.set(id, height); observer.current?.observe(node); }, []); @@ -195,14 +190,10 @@ export function Messages({ session, loading, remoteRunning = false, scrollRef, o const ids = new Set(messages.map(message => String(message.id))); let changed = false; for (const key of [...heights.current.keys()]) if (!ids.has(key)) { heights.current.delete(key); changed = true; } - for (const key of [...mountedHeights.current.keys()]) if (!ids.has(key)) mountedHeights.current.delete(key); if (changed) setRevision(value => value + 1); }, [messages]); - // Viewport renders must pick up commit-phase measurements even when the - // observer did not get a chance to publish them first. Estimate caching keeps - // this per-row pass cheap for long histories. - const heightsList = messages.map(message => heights.current.get(String(message.id)) || mountedHeights.current.get(String(message.id)) || estimateMessageHeight(message)); - const view = virtualMessageWindow(heightsList, viewport.top, viewport.height); + const heightsList = useMemo(() => messages.map(message => heights.current.get(String(message.id)) || estimateMessageHeight(message)), [messages, revision]); + const view = useMemo(() => virtualMessageWindow(heightsList, viewport.top, viewport.height), [heightsList, viewport.top, viewport.height]); useEffect(() => { if (offsetsRef) offsetsRef.current = view.offsets; }, [offsetsRef, view.offsets]); const render = (message: Message) => message.role === 'user' diff --git a/web/tests/chat-scroll.test.mjs b/web/tests/chat-scroll.test.mjs index 1090a5bd..451b37bd 100644 --- a/web/tests/chat-scroll.test.mjs +++ b/web/tests/chat-scroll.test.mjs @@ -67,7 +67,6 @@ const { default: BlockRenderer } = await import(await sourceUrl('components/Bloc })); const chatWindowUrl = await sourceUrl('chat-window.ts', { './chat': chatUrl }); -const { estimateMessageHeight, virtualMessageWindow } = await import(chatWindowUrl); // Conversation.tsx must tag every message so the dock can jump to it. const imagePreviews = []; globalThis.__loopraTestImagePreviews = imagePreviews; @@ -332,13 +331,10 @@ function patchVirtualLayout(container, positions) { node.getBoundingClientRect = () => ({ top: position.top, height: position.height, bottom: position.top + position.height, left: 0, right: 600, width: 600, x: 0, y: position.top, toJSON: () => ({}) }); } } -async function measureVirtualMessages(afterCallback) { +async function measureVirtualMessages() { const resize = ResizeObserverStub.instances.at(-1); const entries = [...resize.observed].map(target => ({ target })); - const original = resize.callback; - if (afterCallback) resize.callback = callbackEntries => { original(callbackEntries); afterCallback(); }; - try { await act(async () => resize.callback(entries)); } - finally { resize.callback = original; } + await act(async () => resize.callback(entries)); } test('sparse measured outliers do not inflate unmounted row estimates', async () => { @@ -378,13 +374,18 @@ test('sparse measured outliers do not inflate unmounted row estimates', async () test('virtual layout corrections preserve the overlapping anchor row', async () => { const scroll = document.createElement('div'); Object.defineProperties(scroll, { - scrollTop: { configurable: true, writable: true, value: 100 }, + scrollTop: { configurable: true, writable: true, value: 3200 }, clientHeight: { configurable: true, value: 600 }, }); scroll.getBoundingClientRect = () => ({ top: 0, height: 600, bottom: 600, left: 0, right: 800, width: 800, x: 0, y: 0, toJSON: () => ({}) }); const scrollRef = { current: scroll }; const corrections = []; - const view = await renderMessages(longSession(), { scrollRef, onCorrectScroll: delta => corrections.push(delta) }); + let applyCorrections = false; + const correct = delta => { + corrections.push(delta); + if (applyCorrections) scroll.scrollTop += delta; + }; + const view = await renderMessages(longSession(), { scrollRef, onCorrectScroll: correct }); try { const positions = new Map(); for (const node of view.container.querySelectorAll('.virtual-message-item')) { @@ -392,107 +393,46 @@ test('virtual layout corrections preserve the overlapping anchor row', async () const index = Number(id.slice(1)); positions.set(id, { top: index * 320, height: 320 }); } - patchVirtualLayout(view.container, positions); + const patchDynamicLayout = () => { + for (const node of view.container.querySelectorAll('.virtual-message-item')) { + const id = node.querySelector('[data-message-id]').dataset.messageId; + const position = positions.get(id) || { top: 0, height: 320 }; + node.getBoundingClientRect = () => { + const top = position.top - scroll.scrollTop; + return { top, height: position.height, bottom: top + position.height, left: 0, right: 600, width: 600, x: 0, y: top, toJSON: () => ({}) }; + }; + } + }; + patchDynamicLayout(); await measureVirtualMessages(); + const originalAnchor = [...view.container.querySelectorAll('.virtual-message-item')] + .map(node => ({ id: node.dataset.virtualMessageId, rect: node.getBoundingClientRect() })) + .find(row => row.rect.bottom > 0); + assert.ok(originalAnchor, 'the initial viewport has an anchor row'); corrections.length = 0; + applyCorrections = true; for (const [id, position] of positions) positions.set(id, { ...position, top: position.top + 500 }); - patchVirtualLayout(view.container, positions); + patchDynamicLayout(); const rows = [...view.container.querySelectorAll('.virtual-message-item')]; const last = rows.at(-1); - const rect = last.getBoundingClientRect(); - last.getBoundingClientRect = () => ({ ...rect, height: 321, bottom: rect.top + 321 }); + const lastId = last.dataset.virtualMessageId; + positions.set(lastId, { ...positions.get(lastId), height: 321 }); + patchDynamicLayout(); const resize = ResizeObserverStub.instances.at(-1); await act(async () => resize.callback([{ target: last }])); assert.deepEqual(corrections, [500]); - } finally { await view.close(); } -}); - -test('corrected virtual scrolling keeps the anchor visible after window movement', async () => { - const messages = longSession(); - const scroll = document.createElement('div'); - Object.defineProperties(scroll, { - scrollTop: { configurable: true, writable: true, value: 3200 }, - clientHeight: { configurable: true, value: 600 }, - }); - scroll.getBoundingClientRect = () => ({ top: 0, height: 600, bottom: 600, left: 0, right: 800, width: 800, x: 0, y: 0, toJSON: () => ({}) }); - const expandedHeights = new Map(); - const actualHeight = index => (index % 2 ? 440 : 120) + (expandedHeights.get(`m${index}`) || 0); - const measured = new Map(); - let layoutTop = 0; - const dispatchScroll = async () => { - layoutTop = scroll.scrollTop; + assert.equal(scroll.scrollTop, 3700, 'the correction is applied to the scroller'); + const anchorNode = view.container.querySelector(`[data-virtual-message-id="${originalAnchor.id}"]`); + assert.ok(anchorNode, 'the original anchor row is still mounted'); + const anchorRect = anchorNode.getBoundingClientRect(); + assert.equal(anchorRect.top, originalAnchor.rect.top, 'the original anchor returns to its viewport position'); + assert.ok(anchorRect.bottom > 0 && anchorRect.top < scroll.clientHeight, 'the original anchor remains visible after correction'); + const correctionCount = corrections.length; await act(async () => scroll.dispatchEvent(new dom.window.Event('scroll'))); - }; - const indexOf = id => Number(id.slice(1)); - const positionOf = id => { - const index = indexOf(id); - const heightsList = messages.map(message => measured.get(String(message.id)) || estimateMessageHeight(message)); - const viewWindow = virtualMessageWindow(heightsList, layoutTop, scroll.clientHeight); - if (index < viewWindow.start || index >= viewWindow.end) return null; - let position = viewWindow.topHeight; - for (let row = viewWindow.start; row < index; row++) position += actualHeight(row); - return position; - }; - const originalRect = dom.window.HTMLElement.prototype.getBoundingClientRect; - dom.window.HTMLElement.prototype.getBoundingClientRect = function () { - const id = this.dataset?.virtualMessageId; - if (!id) return originalRect.call(this); - const index = indexOf(id); - const position = positionOf(id); - const height = actualHeight(index); - const top = position === null ? 0 : position - scroll.scrollTop; - return { top, height, bottom: top + height, left: 0, right: 600, width: 600, x: 0, y: top, toJSON: () => ({}) }; - }; - const syncMeasured = container => { - for (const node of container.querySelectorAll('.virtual-message-item')) { - const id = node.dataset.virtualMessageId; - if (id) measured.set(id, actualHeight(indexOf(id))); - } - }; - const corrections = []; - const correct = delta => { - corrections.push(delta); - scroll.scrollTop += delta; - }; - const scrollRef = { current: scroll }; - let view; - try { - view = await renderMessages(messages, { scrollRef, onCorrectScroll: correct }); - layoutTop = scroll.scrollTop; - await measureVirtualMessages(() => syncMeasured(view.container)); - // Applying a correction in a browser queues a real scroll event. Flush those - // events until the corrected viewport and mounted window agree. - for (let round = 0; round < 5; round++) { - const before = corrections.length; - await dispatchScroll(); - if (corrections.length === before) break; - } - const anchor = [...view.container.querySelectorAll('.virtual-message-item')] - .map(node => ({ id: node.dataset.virtualMessageId, rect: node.getBoundingClientRect() })) - .find(row => row.rect.bottom > 0); - assert.ok(anchor, 'initial viewport has an anchor row'); - corrections.length = 0; - - const mounted = [...view.container.querySelectorAll('.virtual-message-item')]; - const expanded = mounted.map(node => node.dataset.virtualMessageId).filter(id => indexOf(id) < indexOf(anchor.id)).at(-1); - assert.ok(expanded, 'a mounted row above the anchor can grow'); - expandedHeights.set(expanded, 500); - await measureVirtualMessages(() => syncMeasured(view.container)); - assert.equal(corrections.length, 1, 'the measurement/window movement produces exactly one initial correction'); - syncMeasured(view.container); - await dispatchScroll(); - assert.equal(corrections.length, 1, 'the real scroll event after correction does not correct again'); - - const anchored = view.container.querySelector(`[data-virtual-message-id="${anchor.id}"]`); - assert.ok(anchored, 'the original anchor row is still mounted'); - const rect = anchored.getBoundingClientRect(); - assert.ok(rect.bottom > 0 && rect.top < scroll.clientHeight, `anchor row remains in the viewport, got top=${rect.top} bottom=${rect.bottom}`); - } finally { - dom.window.HTMLElement.prototype.getBoundingClientRect = originalRect; - if (view) await view.close(); - } + assert.equal(corrections.length, correctionCount, 'the resulting real scroll event does not trigger another correction'); + } finally { await view.close(); } }); test('unmounted row estimates follow message content instead of visible outliers', async () => { diff --git a/web/tests/chat-window.test.mjs b/web/tests/chat-window.test.mjs index 44c525a8..720b43bc 100644 --- a/web/tests/chat-window.test.mjs +++ b/web/tests/chat-window.test.mjs @@ -61,11 +61,3 @@ test('user attachment envelopes estimate as compact controls rather than documen assert.ok(withAttachment < 250, `attachment-backed user row stayed compact, got ${withAttachment}`); assert.equal(withAttachment - bare, 40, 'the only added estimate is the attachment control'); }); - -test('message height estimates are cached by immutable message object', () => { - let reads = 0; - const message = { role: 'assistant', get text() { reads += 1; return Array.from({ length: 100 }, (_, line) => `line ${line}`).join('\n'); } }; - const first = estimateMessageHeight(message); - assert.equal(estimateMessageHeight(message), first); - assert.equal(reads, 1, 'unchanged message objects are not rescanned'); -});