The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(desktop): bound messages-below scroll measurements
Xipong7df7b2776f51
diff --git a/apps/desktop/e2e/messages-below-position.spec.ts b/apps/desktop/e2e/messages-below-position.spec.tsnew file mode 100644index 00000000000..44d9043c220--- /dev/null+++ b/apps/desktop/e2e/messages-below-position.spec.ts@@ -0,0 +1,161 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import * as path from 'node:path'++import { build } from 'esbuild'++import { resolveElectronBinary } from './electron-binary'+import { _electron, expect, test } from './test'++test('messages-below reads stay bounded with real content-visibility groups', async ({}, testInfo) => {+ const temporary = mkdtempSync(path.join(tmpdir(), 'hermes-messages-below-'))+ const main = path.join(temporary, 'main.cjs')+ writeFileSync(+ main,+ `const { app, BrowserWindow } = require('electron');+app.setPath('userData', ${JSON.stringify(path.join(temporary, 'user-data'))});+app.whenReady().then(() => {+ const window = new BrowserWindow({ width: 1000, height: 800,+ webPreferences: { sandbox: true, contextIsolation: true, backgroundThrottling: false } });+ window.loadURL('about:blank');+});`+ )++ const bundle = await build({+ entryPoints: [path.resolve('src/components/assistant-ui/thread/use-messages-below.ts')],+ bundle: true,+ format: 'iife',+ globalName: 'MessagesBelow',+ write: false+ })+ const app = await _electron.launch({+ executablePath: resolveElectronBinary([path.resolve('.'), path.resolve('../..')]),+ args: ['--no-sandbox', main]+ })++ try {+ const page = await app.firstWindow()+ await page.setContent('<div id="viewport" style="height:600px;overflow:auto"><div id="content"></div></div>')+ await page.addScriptTag({ content: bundle.outputFiles[0].text })+ const results = await page.evaluate(async () => {+ const count = 512+ const viewport = document.getElementById('viewport')!+ const content = document.getElementById('content')!+ const starts: number[] = []+ let top = 0++ for (let index = 0; index < count; index++) {+ starts.push(top)+ const height = 160 + (index % 3) * 40+ const group = document.createElement('div')+ group.dataset.slot = 'aui_message-group'+ group.style.cssText = `height:${height}px;content-visibility:auto;contain-intrinsic-size:auto ${height}px`+ group.innerHTML =+ '<div data-slot="aui_user-message-root">prompt</div><div data-slot="aui_assistant-message-root">answer</div>'+ content.append(group)+ top += height+ }++ const api = (window as unknown as {+ MessagesBelow: {+ createMessagesBelowReader: (+ viewport: HTMLElement,+ content: HTMLElement+ ) => { read: () => { count: number; settled: boolean } }+ }+ }).MessagesBelow+ const reader = api.createMessagesBelowReader(viewport, content)+ const original = Element.prototype.getBoundingClientRect+ let outer = 0+ let inner = 0+ Element.prototype.getBoundingClientRect = function () {+ if (this.getAttribute('data-slot') === 'aui_message-group') {+ outer+++ } else if (this.matches('[data-slot="aui_user-message-root"], [data-slot="aui_assistant-message-root"]')) {+ inner+++ }++ return original.call(this)+ }++ const measurements: Array<{+ target: number+ indexed: number+ reference: number+ outer: number+ inner: number+ referenceOuter: number+ referenceInner: number+ }> = []++ try {+ // Prime structural membership before measuring the scroll-time path.+ reader.read()++ for (const target of [0, 300, 30, 500, 200]) {+ viewport.scrollTop = starts[target] + 80+ await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())))+ outer = inner = 0+ const indexed = reader.read().count+ const measured = { target, indexed, reference: 0, outer, inner, referenceOuter: 0, referenceInner: 0 }+ measured.outer = outer+ measured.inner = inner+ outer = inner = 0+ const bottom = viewport.getBoundingClientRect().bottom+ let reference = 0++ for (const group of content.querySelectorAll<HTMLElement>('[data-slot="aui_message-group"]')) {+ const groupRect = group.getBoundingClientRect()++ if (groupRect.bottom <= bottom + 1) {+ continue+ }++ const messages = group.querySelectorAll<HTMLElement>(+ '[data-slot="aui_user-message-root"], [data-slot="aui_assistant-message-root"]'+ )++ if (groupRect.top >= bottom) {+ reference += messages.length+ continue+ }++ for (const message of messages) {+ const messageRect = message.getBoundingClientRect()++ if (messageRect.height > 0 && messageRect.bottom > bottom + 1) {+ reference+++ }+ }+ }++ measured.reference = reference+ measured.referenceOuter = outer+ measured.referenceInner = inner+ measurements.push(measured)+ }+ } finally {+ Element.prototype.getBoundingClientRect = original+ }++ return measurements+ })++ console.log('Messages-below geometry measurements:', JSON.stringify(results))++ for (const row of results) {+ expect(row.indexed).toBe(row.reference)+ expect(row.outer).toBeLessThanOrEqual(Math.ceil(Math.log2(512)) + 2)+ expect(row.inner).toBeLessThanOrEqual(2)+ expect(row.referenceOuter).toBe(512)+ }++ await testInfo.attach('messages-below-measurements.json', {+ body: JSON.stringify(results, null, 2),+ contentType: 'application/json'+ })+ } finally {+ await app.close()+ rmSync(temporary, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/src/components/assistant-ui/thread/use-messages-below-perf.test.ts b/apps/desktop/src/components/assistant-ui/thread/use-messages-below-perf.test.tsnew file mode 100644index 00000000000..ca003c3c92e--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/thread/use-messages-below-perf.test.ts@@ -0,0 +1,52 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import { countMessagesBelow } from './use-messages-below'++const rect = (top: number, bottom: number): DOMRect =>+ ({ top, bottom, height: bottom - top, width: 800 } as DOMRect)++afterEach(() => {+ window.document.body.innerHTML = ''+ vi.restoreAllMocks()+})++describe('messages-below scroll cost', () => {+ it('does not measure every mounted group to count messages below the fold', () => {+ const count = 512+ const viewport = window.document.createElement('div')+ const content = window.document.createElement('div')+ viewport.append(content)+ window.document.body.append(viewport)+ const scrollTop = 300 * 100 + 50+ vi.spyOn(viewport, 'getBoundingClientRect').mockReturnValue(rect(0, 600))+ let groupReads = 0++ for (let index = 0; index < count; index++) {+ const group = window.document.createElement('div')+ group.dataset.slot = 'aui_message-group'+ content.append(group)+ vi.spyOn(group, 'getBoundingClientRect').mockImplementation(() => {+ groupReads++++ return rect(index * 100 - scrollTop, index * 100 + 100 - scrollTop)+ })++ for (const slot of ['aui_user-message-root', 'aui_assistant-message-root']) {+ const message = window.document.createElement('div')+ message.dataset.slot = slot+ group.append(message)+ vi.spyOn(message, 'getBoundingClientRect').mockReturnValue(+ slot === 'aui_user-message-root'+ ? rect(index * 100 - scrollTop, index * 100 + 40 - scrollTop)+ : rect(index * 100 + 40 - scrollTop, index * 100 + 100 - scrollTop)+ )+ }+ }++ expect(countMessagesBelow(viewport, content)).toEqual({+ count: 1 + (count - 307) * 2,+ settled: true+ })+ expect(groupReads).toBeLessThanOrEqual(Math.ceil(Math.log2(count)) + 2)+ })+})diff --git a/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsx b/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsxindex a71ea136efe..5eb076ec546 100644--- a/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsx@@ -3,10 +3,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { $threadMessagesBelowBySession, resetThreadScroll } from '@/store/thread-scroll'-import { countMessagesBelow, useMessagesBelow } from './use-messages-below'+import { countMessagesBelow, createMessagesBelowReader, useMessagesBelow } from './use-messages-below'function rect(top: number, bottom: number): DOMRect {- return { top, bottom, height: bottom - top } as DOMRect+ return { top, bottom, height: bottom - top, width: 800 } as DOMRect}function transcript() {@@ -69,10 +69,79 @@ describe('messages below the viewport', () => {expect(countMessagesBelow(viewport, content).count).toBe(0)})+ it('finds the fold with logarithmic group reads and reuses membership across scroll frames', () => {+ const count = 512+ const viewport = window.document.createElement('div')+ const content = window.document.createElement('div')+ viewport.append(content)+ let scrollTop = 0+ vi.spyOn(viewport, 'getBoundingClientRect').mockImplementation(() => rect(0, 600))+ const reads = { groups: 0, messages: 0 }+ const queries = vi.spyOn(content, 'querySelectorAll')++ for (let index = 0; index < count; index++) {+ const group = window.document.createElement('div')+ group.dataset.slot = 'aui_message-group'+ content.append(group)+ vi.spyOn(group, 'getBoundingClientRect').mockImplementation(() => {+ reads.groups++++ return rect(index * 100 - scrollTop, index * 100 + 100 - scrollTop)+ })++ for (const [slot, start, end] of [+ ['aui_user-message-root', 0, 40],+ ['aui_assistant-message-root', 40, 100]+ ] as const) {+ const message = window.document.createElement('div')+ message.dataset.slot = slot+ group.append(message)+ vi.spyOn(message, 'getBoundingClientRect').mockImplementation(() => {+ reads.messages++++ return rect(index * 100 + start - scrollTop, index * 100 + end - scrollTop)+ })+ }+ }++ const reader = createMessagesBelowReader(viewport, content)++ for (const index of [300, 20, 500, 200]) {+ scrollTop = index * 100 + 50+ reads.groups = reads.messages = 0+ const result = reader.read()+ const straddling = index + 6+ const expected = 1 + (count - straddling - 1) * 2+ expect(result).toEqual({ count: expected, settled: true })+ expect(reads.groups).toBeLessThanOrEqual(Math.ceil(Math.log2(count)) + 2)+ expect(reads.messages).toBe(2)+ }++ expect(queries.mock.calls.filter(([selector]) => selector === '[data-slot="aui_message-group"]').length).toBe(1)+ })++ it('invalidates cached membership only when counted message structure changes', () => {+ const { viewport, content } = transcript()+ const reader = createMessagesBelowReader(viewport, content)+ expect(reader.read().count).toBe(1)++ const paragraph = window.document.createElement('p')+ expect(+ reader.invalidate([{ type: 'childList', addedNodes: [paragraph], removedNodes: [] } as unknown as MutationRecord])+ ).toBe(false)++ const extra = window.document.createElement('div')+ extra.dataset.slot = 'aui_system-message-root'+ expect(+ reader.invalidate([{ type: 'childList', addedNodes: [extra], removedNodes: [] } as unknown as MutationRecord])+ ).toBe(true)+ })+it('remeasures scroll and resize, ignores hidden panes, and clears at the bottom', () => {const { viewport, content, assistantRect } = transcript()let frame: FrameRequestCallback | undefinedlet resize: ResizeObserverCallback | undefined+ let mutate: MutationCallback | undefinedvi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {frame = callback@@ -92,6 +161,17 @@ describe('messages below the viewport', () => {disconnect() {}})+ vi.stubGlobal(+ 'MutationObserver',+ class {+ constructor(callback: MutationCallback) {+ mutate = callback+ }++ observe() {}+ disconnect() {}+ }+ )const flush = () =>act(() => {@@ -114,6 +194,10 @@ describe('messages below the viewport', () => {flush()expect($threadMessagesBelowBySession.get()['runtime-a'] ?? 0).toBe(1)+ // Non-message subtree mutations do not schedule another geometry read.+ mutate?.([{ type: 'childList', addedNodes: [window.document.createElement('span')], removedNodes: [] } as unknown as MutationRecord], {} as MutationObserver)+ expect(frame).toBeUndefined()+// Another visible pane reaching bottom must not erase this reader's count.const sibling = renderHook(() => useMessagesBelow({ ...options, sessionId: 'runtime-b', isAtBottom: true }))expect($threadMessagesBelowBySession.get()['runtime-a']).toBe(1)@@ -174,6 +258,13 @@ describe('messages below the viewport', () => {disconnect() {}})+ vi.stubGlobal(+ 'MutationObserver',+ class {+ observe() {}+ disconnect() {}+ }+ )const flush = () =>act(() => {diff --git a/apps/desktop/src/components/assistant-ui/thread/use-messages-below.ts b/apps/desktop/src/components/assistant-ui/thread/use-messages-below.tsindex 2e2e1b2017c..92f765f08a1 100644--- a/apps/desktop/src/components/assistant-ui/thread/use-messages-below.ts+++ b/apps/desktop/src/components/assistant-ui/thread/use-messages-below.ts@@ -2,9 +2,13 @@ import { type ReactNode, type RefObject, useEffect } from 'react'import { publishThreadMessagesBelow } from '@/store/thread-scroll'+const GROUP_ROOT = '[data-slot="aui_message-group"]'+const MESSAGE_ROOTS ='[data-slot="aui_user-message-root"], [data-slot="aui_assistant-message-root"], [data-slot="aui_system-message-root"]'+const COUNTED_STRUCTURE = `${GROUP_ROOT}, ${MESSAGE_ROOTS}`+interface MessagesBelowOptions {contentRef: RefObject<HTMLElement | null>scrollRef: RefObject<HTMLElement | null>@@ -15,45 +19,144 @@ interface MessagesBelowOptions {sessionId: string | null}+interface GroupSummary {+ element: HTMLElement+ messageCount: number+ messagesAfter: number+}++const containsCountedStructure = (node: Node): boolean =>+ node instanceof Element && (node.matches(COUNTED_STRUCTURE) || node.querySelector(COUNTED_STRUCTURE) !== null)+/**- * Only measure inside the viewport's turn; leave skipped off-screen content- * asleep. `settled` is false when the turn straddling the fold has no layout- * boxes yet: content-visibility relevancy updates a frame after a programmatic- * scroll (a rail jump), and until then its messages measure as empty rects —- * counting them as "above the fold" undercounts by that turn.+ * Cache membership/counts only. Geometry stays live so images, expanded tools+ * and content-visibility can change heights without invalidating an offset+ * table. The transcript's outer message groups are in normal-flow DOM order,+ * so their bottoms are monotonic and the fold can be found with binary search.*/-export function countMessagesBelow(viewport: HTMLElement, content: HTMLElement): { count: number; settled: boolean } {- const bottom = viewport.getBoundingClientRect().bottom- let count = 0- let settled = true+export function createMessagesBelowReader(viewport: HTMLElement, content: HTMLElement) {+ let groups: GroupSummary[] | null = null++ const snapshot = (): GroupSummary[] => {+ if (groups) {+ return groups+ }- for (const group of content.querySelectorAll<HTMLElement>('[data-slot="aui_message-group"]')) {- const rect = group.getBoundingClientRect()+ const elements = [...content.querySelectorAll<HTMLElement>(GROUP_ROOT)]+ let messagesAfter = 0+ const reversed: GroupSummary[] = []- if (rect.bottom <= bottom + 1) {- continue+ for (let index = elements.length - 1; index >= 0; index--) {+ const element = elements[index]+ const messageCount = element.querySelectorAll(MESSAGE_ROOTS).length+ reversed.push({ element, messageCount, messagesAfter })+ messagesAfter += messageCount}- const messages = group.querySelectorAll<HTMLElement>(MESSAGE_ROOTS)+ groups = reversed.reverse()- if (rect.top >= bottom) {- count += messages.length+ return groups+ }- continue- }+ return {+ invalidate(records: readonly MutationRecord[]): boolean {+ const changed = records.some(record => {+ if (record.type === 'attributes') {+ const oldSlot = record.oldValue++ return (+ (record.target instanceof Element && record.target.matches(COUNTED_STRUCTURE)) ||+ oldSlot === 'aui_message-group' ||+ oldSlot === 'aui_user-message-root' ||+ oldSlot === 'aui_assistant-message-root' ||+ oldSlot === 'aui_system-message-root'+ )+ }++ return [...record.addedNodes, ...record.removedNodes].some(containsCountedStructure)+ })++ if (changed) {+ groups = null+ }++ return changed+ },++ read(): { count: number; settled: boolean } {+ const bottom = viewport.getBoundingClientRect().bottom+ const current = snapshot()+ const measured = new Map<number, DOMRect>()++ const rectAt = (index: number) => {+ const cached = measured.get(index)++ if (cached) {+ return cached+ }++ const rect = current[index].element.getBoundingClientRect()+ measured.set(index, rect)++ return rect+ }++ let before = 0+ let after = current.length- for (const message of messages) {- const messageRect = message.getBoundingClientRect()+ while (before < after) {+ const middle = Math.floor((before + after) / 2)- if (messageRect.height === 0 && messageRect.width === 0) {- settled = false- } else if (messageRect.height > 0 && messageRect.bottom > bottom + 1) {- count+++ if (rectAt(middle).bottom <= bottom + 1) {+ before = middle + 1+ } else {+ after = middle+ }}++ if (before >= current.length) {+ return { count: 0, settled: true }+ }++ let count = 0+ let settled = true++ // Normal-flow transcript groups do not overlap, so this loop normally+ // measures exactly one straddler plus the next group's outer box. Keep+ // walking if a test/transition temporarily overlaps groups; cost is+ // O(log n + k) where k is the number intersecting the fold.+ for (let index = before; index < current.length; index++) {+ const group = current[index]+ const rect = rectAt(index)++ if (rect.top >= bottom) {+ count += group.messageCount + group.messagesAfter++ break+ }++ for (const message of group.element.querySelectorAll<HTMLElement>(MESSAGE_ROOTS)) {+ const messageRect = message.getBoundingClientRect()++ if (messageRect.height === 0 && messageRect.width === 0) {+ settled = false+ } else if (messageRect.height > 0 && messageRect.bottom > bottom + 1) {+ count+++ }+ }+ }++ return { count, settled }}}+}- return { count, settled }+/**+ * Stateless helper retained for focused callers/tests. The hook below keeps one+ * reader for the mounted viewport so repeated scroll frames reuse membership.+ */+export function countMessagesBelow(viewport: HTMLElement, content: HTMLElement): { count: number; settled: boolean } {+ return createMessagesBelowReader(viewport, content).read()}export function useMessagesBelow({@@ -85,10 +188,11 @@ export function useMessagesBelow({let frame = 0let retried = false+ const reader = createMessagesBelowReader(viewport, content)const measure = () => {frame = 0- const { count, settled } = countMessagesBelow(viewport, content)+ const { count, settled } = reader.read()// One extra frame lets the skipped turn gain boxes; then publish what is// there so an empty turn can never stall the count.@@ -111,14 +215,29 @@ export function useMessagesBelow({schedule()viewport.addEventListener('scroll', schedule, { passive: true })- const observer = new ResizeObserver(schedule)- observer.observe(viewport)- observer.observe(content)+ const resize = new ResizeObserver(schedule)+ resize.observe(viewport)+ resize.observe(content)++ const mutations = new MutationObserver(records => {+ if (reader.invalidate(records)) {+ schedule()+ }+ })++ mutations.observe(content, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ['data-slot'],+ attributeOldValue: true+ })return () => {cancelAnimationFrame(frame)viewport.removeEventListener('scroll', schedule)- observer.disconnect()+ resize.disconnect()+ mutations.disconnect()}}, [contentRef, scrollRef, isAtBottom, paneVisible, rows, sessionKey, sessionId])}