perf(desktop): long streaming agent sessions — steady window cut, stable rows, stepped backfill, pane-shared budget (#83446)
* test(desktop): stress long agent sessions in the multitab perf scenario --tools seeds every transcript with settled tool rounds and drives the live stream as a working agent turn (tool calls opened and completed between text chunks), and each tile reveal is timed to next paint (reveal_max_ms) so deep transcripts report their mount cost. * perf(desktop): hold the transcript window cut steady while streaming A fresh weight-walk per store flush slid the cut forward one message at a time, ~30x/s, and every slide re-indexed the whole windowed transcript — each row rendered a different message and the runtime repository took its O(window) rebuild path instead of the one-message update. advanceTranscriptWindow anchors the cut to a message id and re-cuts once per ~half page of new content instead of once per flush. * perf(desktop): stable rows, stepped backfill, pane-shared render budget Three thread-list fixes for long streaming sessions: memoize the visible- groups slice and each turn row so a budget-cut advance no longer re-renders every mounted turn per streamed token; raise the first-paint backfill in BACKFILL_STEP slices (one bounded commit per frame) instead of a single 20-to-600 transition whose commit landed as a 780ms freeze mid-stream; and share RENDER_BUDGET across mounted panes so a 4-way grid mounts a quarter page per pane instead of 4x the fibers.
This commit is contained in:
@@ -10,6 +10,9 @@
|
||||
// actually mid-turn (zone leaders first, so S=zones means "every visible
|
||||
// transcript streams, every hidden tab idles"); the rest sit settled.
|
||||
// --sessions N seeds a populated recents list (a lived-in sessions DB).
|
||||
// --turns N sets transcript depth per tile (long sessions), and --tools makes
|
||||
// every transcript an AGENT session: seeded turns carry settled tool rounds,
|
||||
// and the live stream opens/completes tool calls between text chunks.
|
||||
//
|
||||
// Drives the real pipeline synthetically (no backend, no credits): each tick
|
||||
// routes one delta per streaming session through `hook.update` — the same
|
||||
@@ -68,16 +71,27 @@ const COLLECT = `
|
||||
* (wiring cache + in-flight journal + publish + view sync). Driving
|
||||
* `hook.publish` alone under-models a stream: it skips the journal and the
|
||||
* cache, which is exactly where multi-session cost used to hide. */
|
||||
const setup = (tiles, seedTurns, streamSeed, zones, seedSessions, streaming, dead) => `
|
||||
const setup = (tiles, seedTurns, streamSeed, zones, seedSessions, streaming, dead, tools) => `
|
||||
(() => {
|
||||
const hook = window.__HERMES_SESSION_TILES__
|
||||
if (!hook) return 'no-hook'
|
||||
if (!hook.update) return 'no-update-hook'
|
||||
|
||||
const turn = (sid, i) => ([
|
||||
{ id: sid + '-u' + i, role: 'user', timestamp: Date.now(),
|
||||
parts: [{ type: 'text', text: 'Review question ' + i + ': does the diff in module ' + i + ' handle the error path?' }] },
|
||||
{ id: sid + '-a' + i, role: 'assistant', timestamp: Date.now(), pending: false,
|
||||
// A settled tool call the way the gateway stores one: streamed args (kept
|
||||
// as argsText too) and a result blob. Real agent transcripts are MOSTLY
|
||||
// these — a long session is hundreds of terminal/read_file/patch rounds.
|
||||
const toolPart = (sid, i, k) => {
|
||||
const args = { command: 'rg -n "handler" src/module-' + i + ' | head -40', background: false }
|
||||
return {
|
||||
type: 'tool-call', toolCallId: sid + '-t' + i + '-' + k, toolName: k % 2 ? 'read_file' : 'terminal',
|
||||
args, argsText: JSON.stringify(args),
|
||||
result: JSON.stringify({ success: true, output: Array.from({ length: 18 },
|
||||
(_, l) => 'src/module-' + i + '.ts:' + (l * 7 + 3) + ': const handler = wrap(ctx, retry)').join('\\n') })
|
||||
}
|
||||
}
|
||||
|
||||
const turn = (sid, i) => {
|
||||
const answer = { id: sid + '-a' + i, role: 'assistant', timestamp: Date.now(), pending: false,
|
||||
parts: [{ type: 'text', text: [
|
||||
'## Finding ' + i, '',
|
||||
'The handler swallows the rejection. Key points for hunk \\\`' + i + '\\\`:', '',
|
||||
@@ -90,7 +104,19 @@ const setup = (tiles, seedTurns, streamSeed, zones, seedSessions, streaming, dea
|
||||
'\\\`\\\`\\\`', '',
|
||||
'| path | covered |', '|---|---|', '| happy | yes |', '| error | no |', ''
|
||||
].join('\\n') }] }
|
||||
])
|
||||
const rows = [
|
||||
{ id: sid + '-u' + i, role: 'user', timestamp: Date.now(),
|
||||
parts: [{ type: 'text', text: 'Review question ' + i + ': does the diff in module ' + i + ' handle the error path?' }] }
|
||||
]
|
||||
// Agent work turn (--tools): two tool rounds before the answer, the
|
||||
// shape run_conversation actually produces.
|
||||
if (${tools}) {
|
||||
rows.push({ id: sid + '-w' + i, role: 'assistant', timestamp: Date.now(), pending: false,
|
||||
parts: [{ type: 'text', text: 'Checking module ' + i + '.' }, toolPart(sid, i, 0), toolPart(sid, i, 1)] })
|
||||
}
|
||||
rows.push(answer)
|
||||
return rows
|
||||
}
|
||||
|
||||
const state = (sid, rid, isStreaming) => {
|
||||
const messages = []
|
||||
@@ -185,8 +211,16 @@ const setup = (tiles, seedTurns, streamSeed, zones, seedSessions, streaming, dea
|
||||
const reveal = sid => `window.__HERMES_LAYOUT_TREE__.reveal(${JSON.stringify(`session-tile:${sid}`)})`
|
||||
|
||||
/** Page-side driver: grow every tile's streaming tail by `chunk` each
|
||||
* `intervalMs`, through the same write path the gateway flush uses. */
|
||||
const drive = (chunk, intervalMs, totalTokens) => `
|
||||
* `intervalMs`, through the same write path the gateway flush uses.
|
||||
*
|
||||
* With `tools`, the stream is a working AGENT turn, not a monologue: every
|
||||
* 12th tick opens a live tool call on the streaming message (args, no
|
||||
* result — the running spinner), every 12th+6 completes it with a result
|
||||
* blob, and text keeps flowing between rounds. That exercises the tool-part
|
||||
* update path (find + replace inside the parts array) and the ToolCall
|
||||
* renderer's pending→complete transitions, which text-only streaming never
|
||||
* touches. */
|
||||
const drive = (chunk, intervalMs, totalTokens, tools) => `
|
||||
(() => {
|
||||
const hook = window.__HERMES_SESSION_TILES__
|
||||
let pushed = 0
|
||||
@@ -196,9 +230,30 @@ const drive = (chunk, intervalMs, totalTokens) => `
|
||||
if (!prev.streamId) return prev
|
||||
const messages = prev.messages.map(m => {
|
||||
if (m.id !== prev.streamId) return m
|
||||
const head = m.parts.slice(0, -1)
|
||||
const last = m.parts[m.parts.length - 1]
|
||||
return { ...m, parts: [...head, { type: 'text', text: last.text + ${JSON.stringify(chunk)} }] }
|
||||
const parts = m.parts.slice()
|
||||
if (${tools} && pushed % 12 === 0) {
|
||||
const args = { command: 'npm test -- --run suite-' + pushed, background: false }
|
||||
parts.push({ type: 'tool-call', toolCallId: rid + '-live-' + pushed, toolName: 'terminal',
|
||||
args, argsText: JSON.stringify(args) })
|
||||
} else if (${tools} && pushed % 12 === 6) {
|
||||
for (let p = parts.length - 1; p >= 0; p--) {
|
||||
const part = parts[p]
|
||||
if (part.type === 'tool-call' && part.result === undefined) {
|
||||
parts[p] = { ...part, result: JSON.stringify({ success: true,
|
||||
output: 'suite-' + pushed + ': 214 passed, 0 failed\\n'.repeat(12) }) }
|
||||
break
|
||||
}
|
||||
}
|
||||
parts.push({ type: 'text', text: '' })
|
||||
} else {
|
||||
const last = parts[parts.length - 1]
|
||||
if (last && last.type === 'text') {
|
||||
parts[parts.length - 1] = { type: 'text', text: last.text + ${JSON.stringify(chunk)} }
|
||||
} else {
|
||||
parts.push({ type: 'text', text: ${JSON.stringify(chunk)} })
|
||||
}
|
||||
}
|
||||
return { ...m, parts }
|
||||
})
|
||||
return { ...prev, messages }
|
||||
})
|
||||
@@ -247,6 +302,9 @@ export default {
|
||||
const seedSessions = Number(opts.sessions ?? 0)
|
||||
const streaming = Math.min(Number(opts.streaming ?? tiles), tiles)
|
||||
const dead = Number(opts.dead ?? 0)
|
||||
// --tools: seeded turns carry settled tool rounds and the live stream
|
||||
// opens/completes tool calls between text — an agent working, not talking.
|
||||
const tools = Boolean(opts.tools)
|
||||
const tokens = Number(opts.tokens ?? 240)
|
||||
// Matches STREAM_DELTA_FLUSH_MS — one publish per session per real flush.
|
||||
const intervalMs = Number(opts.intervalMs ?? 33)
|
||||
@@ -261,15 +319,29 @@ export default {
|
||||
|
||||
await cdp.send('Runtime.enable')
|
||||
|
||||
const ok = await cdp.eval(setup(tiles, seedTurns, streamSeed, zones, seedSessions, streaming, dead))
|
||||
const ok = await cdp.eval(setup(tiles, seedTurns, streamSeed, zones, seedSessions, streaming, dead, tools))
|
||||
|
||||
if (ok !== 'ok') {
|
||||
throw new Error(`multitab setup failed (${ok}) — dev hooks missing? (needs a dev/probe renderer)`)
|
||||
}
|
||||
|
||||
// Mount every tab (keep-alive mounts on first activation), then settle.
|
||||
// Each reveal is timed to the next paint — with deep transcripts the
|
||||
// first mount is the "why does switching tabs hang" number.
|
||||
const revealMs = []
|
||||
|
||||
for (let n = 1; n <= tiles; n++) {
|
||||
await cdp.eval(reveal(`perf-tile-${n}`))
|
||||
const ms = Number(
|
||||
await cdp.eval(`
|
||||
new Promise(resolve => {
|
||||
const t0 = performance.now()
|
||||
${reveal(`perf-tile-${n}`)}
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve(performance.now() - t0)))
|
||||
})
|
||||
`)
|
||||
)
|
||||
|
||||
revealMs.push(ms)
|
||||
await sleep(350)
|
||||
}
|
||||
|
||||
@@ -286,7 +358,7 @@ export default {
|
||||
|
||||
await sleep(1000)
|
||||
await cdp.eval(RECORDERS)
|
||||
await cdp.eval(drive(chunk, intervalMs, tokens))
|
||||
await cdp.eval(drive(chunk, intervalMs, tokens, tools))
|
||||
await sleep(tokens * intervalMs + 1500)
|
||||
|
||||
const data = JSON.parse(await cdp.eval(COLLECT))
|
||||
@@ -331,7 +403,8 @@ export default {
|
||||
longtask_max_ms: Math.round((ltDurations.length ? Math.max(...ltDurations) : 0) * 10) / 10,
|
||||
frame_p95_ms: Math.round(percentile(frames, 0.95) * 10) / 10,
|
||||
frame_p99_ms: Math.round(percentile(frames, 0.99) * 10) / 10,
|
||||
slow_frames_33: frames.filter(f => f > 33).length
|
||||
slow_frames_33: frames.filter(f => f > 33).length,
|
||||
reveal_max_ms: Math.round(Math.max(...revealMs) * 10) / 10
|
||||
},
|
||||
detail: {
|
||||
tiles,
|
||||
@@ -339,10 +412,13 @@ export default {
|
||||
streaming,
|
||||
dead,
|
||||
sessions: seedSessions,
|
||||
tools,
|
||||
turns: seedTurns,
|
||||
code: Boolean(opts.code),
|
||||
windowS: Math.round(windowS * 10) / 10,
|
||||
avgFps: Math.round(avgFps * 10) / 10,
|
||||
worstSecondFps: Math.round(worstFps * 10) / 10,
|
||||
revealMs: revealMs.map(v => Math.round(v)),
|
||||
frameHistogram: frameHistogram(frames)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useStore } from '@nanostores/react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import type { ReadableAtom } from 'nanostores'
|
||||
import type * as React from 'react'
|
||||
import { memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useLocation } from 'react-router'
|
||||
|
||||
import type { SubmitTextOptions } from '@/app/session/hooks/use-prompt-actions/utils'
|
||||
@@ -64,7 +64,7 @@ import { ScrollToBottomButton } from './scroll-to-bottom-button'
|
||||
import { useSessionView } from './session-view'
|
||||
import { SessionActionsMenu } from './sidebar/session-actions-menu'
|
||||
import { threadLoadingState } from './thread-loading'
|
||||
import { selectTranscriptWindow } from './transcript-window'
|
||||
import { advanceTranscriptWindow, type TranscriptWindowState } from './transcript-window'
|
||||
|
||||
interface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {
|
||||
gateway: HermesGateway | null
|
||||
@@ -229,18 +229,25 @@ function ChatRuntimeBoundary({
|
||||
|
||||
const [windowPages, setWindowPages] = useState(1)
|
||||
const [windowSessionKey, setWindowSessionKey] = useState(runtimeId)
|
||||
// Sticky-cut continuity across flushes (advanceTranscriptWindow). A ref, not
|
||||
// state: it is derived from `messages` and must never trigger a render.
|
||||
const windowStateRef = useRef<null | TranscriptWindowState>(null)
|
||||
|
||||
// Reset the window on session swap during RENDER, so a large expand from the
|
||||
// previous chat can't leak into the next one's first paint (#55191).
|
||||
if (windowSessionKey !== runtimeId) {
|
||||
setWindowSessionKey(runtimeId)
|
||||
setWindowPages(1)
|
||||
windowStateRef.current = null
|
||||
}
|
||||
|
||||
const { messages: windowedMessages, windowed } = useMemo(
|
||||
() => selectTranscriptWindow(messages, windowPages),
|
||||
[messages, windowPages]
|
||||
)
|
||||
const { messages: windowedMessages, windowed } = useMemo(() => {
|
||||
const next = advanceTranscriptWindow(windowStateRef.current, messages, windowPages)
|
||||
|
||||
windowStateRef.current = next
|
||||
|
||||
return next.window
|
||||
}, [messages, windowPages])
|
||||
|
||||
const runtimeMessageRepository = useRuntimeMessageRepository(windowedMessages)
|
||||
|
||||
|
||||
@@ -4,10 +4,12 @@ import type { ChatMessage } from '@/lib/chat-messages'
|
||||
import { RENDER_WEIGHT_CHARS } from '@/lib/render-weight'
|
||||
|
||||
import {
|
||||
advanceTranscriptWindow,
|
||||
alignToBranchGroup,
|
||||
selectTranscriptWindow,
|
||||
TRANSCRIPT_WINDOW_BUDGET,
|
||||
TRANSCRIPT_WINDOW_MIN_MESSAGES
|
||||
TRANSCRIPT_WINDOW_MIN_MESSAGES,
|
||||
TRANSCRIPT_WINDOW_SLACK
|
||||
} from './transcript-window'
|
||||
|
||||
const message = (id: string, chars: number, branchGroupId?: string): ChatMessage => ({
|
||||
@@ -121,6 +123,97 @@ describe('selectTranscriptWindow', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('advanceTranscriptWindow', () => {
|
||||
const heavyChars = RENDER_WEIGHT_CHARS * 40
|
||||
|
||||
it('matches a fresh walk on first call', () => {
|
||||
const messages = transcript(400, heavyChars)
|
||||
|
||||
const state = advanceTranscriptWindow(null, messages)
|
||||
|
||||
expect(state.window).toEqual(selectTranscriptWindow(messages))
|
||||
expect(state.anchorId).toBe(state.window.messages[0].id)
|
||||
})
|
||||
|
||||
it('holds the cut while a streaming tail grows within slack', () => {
|
||||
const messages = transcript(400, heavyChars)
|
||||
const state = advanceTranscriptWindow(null, messages)
|
||||
|
||||
// Stream: the tail message grows, no new messages. A fresh weight-walk
|
||||
// would slide the cut forward; the sticky window must not.
|
||||
const grown = [...messages.slice(0, -1), message('m-399', heavyChars * 2)]
|
||||
const next = advanceTranscriptWindow(state, grown)
|
||||
|
||||
expect(next.anchorId).toBe(state.anchorId)
|
||||
expect(next.window.messages[0].id).toBe(state.window.messages[0].id)
|
||||
// Same message set from the anchor on — every existing row keeps its index.
|
||||
expect(next.window.messages.length).toBe(state.window.messages.length)
|
||||
})
|
||||
|
||||
it('re-cuts once the tail outgrows budget plus slack', () => {
|
||||
const messages = transcript(400, heavyChars)
|
||||
let state = advanceTranscriptWindow(null, messages)
|
||||
|
||||
// Keep appending. Each step either HOLDS the cut (identical anchor) or
|
||||
// RE-CUTS to exactly what a fresh walk would pick — never something in
|
||||
// between — and at least one re-cut must happen before the tail has grown
|
||||
// by a full slack's worth of weight.
|
||||
const appended = [...messages]
|
||||
let recuts = 0
|
||||
|
||||
for (let i = 0; i < TRANSCRIPT_WINDOW_SLACK + 1; i++) {
|
||||
appended.push(message(`a-new-${i}`, RENDER_WEIGHT_CHARS))
|
||||
const prev = state
|
||||
state = advanceTranscriptWindow(state, appended)
|
||||
|
||||
if (state.anchorId === prev.anchorId) {
|
||||
expect(state.window.messages[0].id).toBe(prev.window.messages[0].id)
|
||||
} else {
|
||||
recuts++
|
||||
expect(state.window).toEqual(selectTranscriptWindow(appended))
|
||||
}
|
||||
}
|
||||
|
||||
expect(recuts).toBeGreaterThanOrEqual(1)
|
||||
// Streaming causes a re-cut per ~half page of content, not one per flush.
|
||||
expect(recuts).toBeLessThan(5)
|
||||
})
|
||||
|
||||
it('falls back to a fresh walk when the anchor disappears', () => {
|
||||
const messages = transcript(400, heavyChars)
|
||||
const state = advanceTranscriptWindow(null, messages)
|
||||
|
||||
// Session swap / compression rewrite: disjoint ids.
|
||||
const swapped = transcript(300, heavyChars).map(m => ({ ...m, id: `other-${m.id}` }))
|
||||
const next = advanceTranscriptWindow(state, swapped)
|
||||
|
||||
expect(next.window).toEqual(selectTranscriptWindow(swapped))
|
||||
})
|
||||
|
||||
it('re-walks when pages change so Show earlier still grows the window', () => {
|
||||
const messages = transcript(400, heavyChars)
|
||||
const one = advanceTranscriptWindow(null, messages, 1)
|
||||
const two = advanceTranscriptWindow(one, messages, 2)
|
||||
|
||||
expect(two.window.messages.length).toBeGreaterThan(one.window.messages.length)
|
||||
})
|
||||
|
||||
it('stays pass-through (uncut) while the transcript fits the budget', () => {
|
||||
const messages = transcript(50, 100)
|
||||
const state = advanceTranscriptWindow(null, messages)
|
||||
|
||||
expect(state.anchorId).toBeNull()
|
||||
expect(state.window.messages).toBe(messages)
|
||||
|
||||
const grown = [...messages, message('m-next', 100)]
|
||||
const next = advanceTranscriptWindow(state, grown)
|
||||
|
||||
// Still uncut: identity of the full array is preserved for the runtime.
|
||||
expect(next.window.messages).toBe(grown)
|
||||
expect(next.window.windowed).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('alignToBranchGroup', () => {
|
||||
const messages = [message('u-1', 10), message('a-1', 10, 'g'), message('a-2', 10, 'g'), message('u-2', 10)]
|
||||
|
||||
|
||||
@@ -106,3 +106,67 @@ export function selectTranscriptWindow(messages: readonly ChatMessage[], pages =
|
||||
|
||||
return { messages: messages.slice(start), windowed: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* How far past the budget a window may grow before the cut moves again.
|
||||
* Half a page: each re-cut trims about this much, so streaming causes one
|
||||
* re-cut per ~half page of new content instead of one per flush.
|
||||
*/
|
||||
export const TRANSCRIPT_WINDOW_SLACK = TRANSCRIPT_WINDOW_BUDGET / 2
|
||||
|
||||
export interface TranscriptWindowState {
|
||||
/** Id of the window's first message; null while the transcript is uncut. */
|
||||
anchorId: null | string
|
||||
pages: number
|
||||
window: TranscriptWindow
|
||||
}
|
||||
|
||||
/**
|
||||
* `selectTranscriptWindow` with a STICKY cut.
|
||||
*
|
||||
* A fresh weight-walk per store flush moves the cut forward as the streaming
|
||||
* tail grows — one message at a time, ~30x/s. Every slide re-indexes the whole
|
||||
* windowed transcript: each row of the thread now renders a DIFFERENT message
|
||||
* (full markdown re-parse + re-highlight per row) and the runtime repository
|
||||
* takes its O(window) rebuild path instead of the one-message update. That —
|
||||
* not the transcript's size — was the long-session collapse: below the budget
|
||||
* the window is pass-through and streaming is O(1); the flush the transcript
|
||||
* outgrew it, every token cost a whole-window re-render.
|
||||
*
|
||||
* So the cut is anchored to a message id and holds while the tail stays within
|
||||
* budget + slack. Streaming then costs a re-cut once per ~half page of content.
|
||||
* The anchor vanishing (session swap, compression rewrite) or a pages change
|
||||
* ("Show earlier") falls through to a fresh walk.
|
||||
*/
|
||||
export function advanceTranscriptWindow(
|
||||
prev: null | TranscriptWindowState,
|
||||
messages: readonly ChatMessage[],
|
||||
pages = 1
|
||||
): TranscriptWindowState {
|
||||
const budget = TRANSCRIPT_WINDOW_BUDGET * Math.max(1, Math.floor(pages))
|
||||
|
||||
if (prev && prev.pages === pages && messages.length > 0) {
|
||||
const start = prev.anchorId === null ? 0 : messages.findIndex(message => message.id === prev.anchorId)
|
||||
|
||||
if (start !== -1) {
|
||||
let weight = 0
|
||||
|
||||
for (let i = messages.length - 1; i >= start; i--) {
|
||||
weight += messageStoreWeight(messages[i].parts)
|
||||
}
|
||||
|
||||
if (weight <= budget + TRANSCRIPT_WINDOW_SLACK) {
|
||||
const window: TranscriptWindow =
|
||||
start === 0
|
||||
? { messages: messages as ChatMessage[], windowed: prev.anchorId !== null }
|
||||
: { messages: messages.slice(start), windowed: true }
|
||||
|
||||
return { anchorId: prev.anchorId, pages, window }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const window = selectTranscriptWindow(messages, pages)
|
||||
|
||||
return { anchorId: window.windowed ? window.messages[0].id : null, pages, window }
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { ThreadPrimitive, useAuiEvent, useAuiState } from '@assistant-ui/react'
|
||||
import { useStore } from '@nanostores/react'
|
||||
import { atom } from 'nanostores'
|
||||
import {
|
||||
type ComponentProps,
|
||||
type CSSProperties,
|
||||
@@ -62,6 +64,19 @@ export type MessageGroup = { id: string; weight: number } & (
|
||||
// (TRANSCRIPT_WINDOW_BUDGET), so this cannot admit more than one window's
|
||||
// content.
|
||||
const RENDER_BUDGET = 600
|
||||
// Every mounted transcript list registers here (see the mount effect). The
|
||||
// budget above is sized for ONE full-height pane; a grid split shows several
|
||||
// panes at once, each a fraction of the screen — yet each was still mounting
|
||||
// the full budget. Four visible panes meant 4x the mounted message fibers,
|
||||
// and every streaming flush pays selector re-runs and React commit traversal
|
||||
// over ALL of them — measured as the 4-zone collapse in the long-session
|
||||
// matrix (worst-second 8fps while 1-2 zones held 50+). Sharing the budget
|
||||
// keeps "screens of scrollback" constant instead of "turns per pane": a pane
|
||||
// a quarter the height gets a quarter the page, floored at a quarter budget
|
||||
// (MIN_VISIBLE_GROUPS still floors the turn count regardless of weight).
|
||||
// Panes that already backfilled keep their mounted content when the count
|
||||
// changes — the share only caps where NEW backfills stop.
|
||||
const $mountedTranscriptPanes = atom(0)
|
||||
// Never offer "Show earlier" over fewer turns than this, however heavy they
|
||||
// are. A weight-only cut on a session of enormous turns put the button two
|
||||
// turns from the bottom, where it reads as broken rather than as paging — the
|
||||
@@ -81,6 +96,10 @@ const MIN_VISIBLE_GROUPS = 8
|
||||
// interruptibly, so the only thing a smaller budget changes is how much work
|
||||
// blocks the click-to-paint path.
|
||||
const FIRST_PAINT_BUDGET = 20
|
||||
// Units the backfill adds per committed step (see the backfill effect). ~8-15
|
||||
// ordinary turns or 1-2 tool-heavy ones per frame — big enough to fill a page
|
||||
// in ~10 frames, small enough that no single commit approaches a frame budget.
|
||||
const BACKFILL_STEP = 60
|
||||
|
||||
// Browsers may quantize a requested scrollTop to a nearby device-pixel
|
||||
// boundary. use-stick-to-bottom otherwise compares the lower actual value to
|
||||
@@ -230,6 +249,61 @@ export function liveTailStart(
|
||||
return Math.min(floor, Math.max(ceiling, start))
|
||||
}
|
||||
|
||||
interface TurnRowProps {
|
||||
components: ThreadMessageComponents
|
||||
group: MessageGroup
|
||||
resetKey: string
|
||||
virtualized: boolean
|
||||
}
|
||||
|
||||
// One turn (or standalone message) of the transcript. memo() is the point:
|
||||
// the rows array below is REBUILT whenever the DOM budget's cut advances
|
||||
// (hiddenCount changes its slice), and without per-row bail-out that rebuild
|
||||
// re-rendered every mounted turn — markdown, code cards, tool blocks — in one
|
||||
// synchronous frame, a 100-800ms stall once a second on a streaming long
|
||||
// session. With memo, a rebuild re-renders only rows whose props changed:
|
||||
// the dropped head row unmounts, the virtualization boundary rows flip their
|
||||
// flag, and everything else bails on identical group/resetKey identity.
|
||||
//
|
||||
// content-visibility:auto (virtualized rows) — off-screen turns skip style
|
||||
// recalc, layout, and paint. On a long transcript this is what keeps
|
||||
// UNRELATED UI fast: any dialog/popover mount (Radix Presence reads
|
||||
// getComputedStyle) forces a whole-document style recalc, measured
|
||||
// ~650-730ms per open on a 1300-message session and ~100-200ms with this
|
||||
// on. contain-intrinsic-size keeps a placeholder height for never-rendered
|
||||
// turns (auto: remembered real size once rendered), so scrollbar/anchoring
|
||||
// stay stable. Sticky human bubbles are unaffected — their turn is rendered
|
||||
// whenever any part of it intersects the viewport.
|
||||
//
|
||||
// The live tail (newest turns) is exempt: virtualizing a turn whose final
|
||||
// size hasn't been remembered yet snaps it to a stale height when it scrolls
|
||||
// off, drifting stick-to-bottom up over old turns. See liveTailStart.
|
||||
const TurnRow = memo(function TurnRow({ components, group, resetKey, virtualized }: TurnRowProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex min-w-0 flex-col gap-(--conversation-turn-gap) pb-(--conversation-turn-gap)',
|
||||
virtualized && '[contain-intrinsic-size:auto_37.5rem] [content-visibility:auto]'
|
||||
)}
|
||||
>
|
||||
<MessageRenderBoundary resetKey={resetKey}>
|
||||
{group.kind === 'turn' ? (
|
||||
<div
|
||||
className="composer-human-ai-pair-container relative flex min-w-0 flex-col gap-(--conversation-turn-gap)"
|
||||
data-slot="aui_turn-pair"
|
||||
>
|
||||
{group.indices.map(index => (
|
||||
<ThreadPrimitive.MessageByIndex components={components} index={index} key={index} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<ThreadPrimitive.MessageByIndex components={components} index={group.index} />
|
||||
)}
|
||||
</MessageRenderBoundary>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
|
||||
clampToComposer,
|
||||
components,
|
||||
@@ -273,6 +347,16 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
|
||||
|
||||
const { olderAvailable, expandWindow } = useTranscriptWindow()
|
||||
|
||||
useEffect(() => {
|
||||
$mountedTranscriptPanes.set($mountedTranscriptPanes.get() + 1)
|
||||
|
||||
return () => $mountedTranscriptPanes.set($mountedTranscriptPanes.get() - 1)
|
||||
}, [])
|
||||
|
||||
const mountedPanes = useStore($mountedTranscriptPanes)
|
||||
// This pane's share of the render budget — see $mountedTranscriptPanes.
|
||||
const paneBudget = Math.max(Math.ceil(RENDER_BUDGET / Math.max(1, mountedPanes)), RENDER_BUDGET / 4)
|
||||
|
||||
const [renderBudget, setRenderBudget] = useState(FIRST_PAINT_BUDGET)
|
||||
|
||||
// Cut the budget during RENDER, not in the post-commit layout effect. An
|
||||
@@ -330,9 +414,17 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
|
||||
// synchronous commit that freezes input right after the switch. Route
|
||||
// changes stay urgent (main.tsx disables router transitions); it's exactly
|
||||
// this backfill that belongs at background priority. "Show earlier" pages
|
||||
// (budget > RENDER_BUDGET) never re-enter here.
|
||||
// (budget > paneBudget) never re-enter here.
|
||||
//
|
||||
// In BOUNDED STEPS, not one jump to the full budget. A transition render is
|
||||
// interruptible but its COMMIT is not, and one 20→600 step commits every
|
||||
// backfilled turn at once — measured as a 780ms uninterruptible frame when
|
||||
// the session was revealed while other tiles streamed (the flushes kept
|
||||
// interrupting the transition, which finally landed whole, seconds later,
|
||||
// mid-stream). Each step commits at most BACKFILL_STEP units (~40-80ms);
|
||||
// the effect re-arms off the committed budget, so steps pace one per frame.
|
||||
useEffect(() => {
|
||||
if (renderBudget >= RENDER_BUDGET) {
|
||||
if (renderBudget >= paneBudget) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -348,11 +440,11 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
|
||||
// Functional max, not a plain set: an urgent "Show earlier" click can
|
||||
// land between scheduling and committing this transition, and a plain
|
||||
// set would rebase over it and shrink the budget back down.
|
||||
startTransition(() => setRenderBudget(budget => Math.max(budget, RENDER_BUDGET)))
|
||||
startTransition(() => setRenderBudget(budget => Math.max(budget, Math.min(budget + BACKFILL_STEP, paneBudget))))
|
||||
})
|
||||
|
||||
return () => cancelAnimationFrame(rafId)
|
||||
}, [anchorBeforePrepend, renderBudget])
|
||||
}, [anchorBeforePrepend, paneBudget, renderBudget])
|
||||
|
||||
// Weights (part count + visible character cost) fold into the BUDGET only.
|
||||
// Group identity stays structural, so a streaming append re-runs this cheap
|
||||
@@ -376,10 +468,16 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
|
||||
const hiddenCount = firstVisibleGroupIndex(
|
||||
weightedGroups,
|
||||
renderBudget,
|
||||
renderBudget >= RENDER_BUDGET ? MIN_VISIBLE_GROUPS : 0
|
||||
renderBudget >= paneBudget ? MIN_VISIBLE_GROUPS : 0
|
||||
)
|
||||
|
||||
const visibleGroups = hiddenCount > 0 ? groups.slice(hiddenCount) : groups
|
||||
// Memoized for IDENTITY, not to save the slice: `rows` below keys off this
|
||||
// array, and an inline slice handed it a fresh array every render — so the
|
||||
// moment a transcript outgrew the render budget (hiddenCount > 0), every
|
||||
// streamed token rebuilt every visible row's JSX and re-rendered the whole
|
||||
// mounted transcript. Under the budget the raw `groups` identity made the
|
||||
// memo hold; heavy sessions lost it exactly when they could least afford to.
|
||||
const visibleGroups = useMemo(() => (hiddenCount > 0 ? groups.slice(hiddenCount) : groups), [groups, hiddenCount])
|
||||
|
||||
// Where the always-rendered live tail begins. Derived from the WEIGHTED
|
||||
// groups (render cost, not turns) so the tail is a viewport's worth of content —
|
||||
@@ -537,13 +635,13 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
|
||||
anchorBeforePrepend()
|
||||
|
||||
if (action === 'dom') {
|
||||
setRenderBudget(budget => budget + RENDER_BUDGET)
|
||||
setRenderBudget(budget => budget + paneBudget)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
expandWindow()
|
||||
}, [anchorBeforePrepend, expandWindow, hiddenCount, olderAvailable])
|
||||
}, [anchorBeforePrepend, expandWindow, hiddenCount, olderAvailable, paneBudget])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = scrollRef.current
|
||||
@@ -566,43 +664,13 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
|
||||
const rows = useMemo(
|
||||
() =>
|
||||
visibleGroups.map((group, indexInVisible) => (
|
||||
// content-visibility:auto — off-screen turns skip style recalc,
|
||||
// layout, and paint. On a long transcript this is what keeps
|
||||
// UNRELATED UI fast: any dialog/popover mount (Radix Presence
|
||||
// reads getComputedStyle) forces a whole-document style recalc,
|
||||
// measured ~650-730ms per open on a 1300-message session and
|
||||
// ~100-200ms with this on. contain-intrinsic-size keeps a
|
||||
// placeholder height for never-rendered turns (auto: remembered
|
||||
// real size once rendered), so scrollbar/anchoring stay stable.
|
||||
// Sticky human bubbles are unaffected — their turn is rendered
|
||||
// whenever any part of it intersects the viewport.
|
||||
//
|
||||
// The live tail (newest turns) is exempt: virtualizing a turn
|
||||
// whose final size hasn't been remembered yet snaps it to a stale
|
||||
// height when it scrolls off, drifting stick-to-bottom up over old
|
||||
// turns. See liveTailStart.
|
||||
<div
|
||||
className={cn(
|
||||
'flex min-w-0 flex-col gap-(--conversation-turn-gap) pb-(--conversation-turn-gap)',
|
||||
indexInVisible < tailStart && '[contain-intrinsic-size:auto_37.5rem] [content-visibility:auto]'
|
||||
)}
|
||||
<TurnRow
|
||||
components={components}
|
||||
group={group}
|
||||
key={group.id}
|
||||
>
|
||||
<MessageRenderBoundary resetKey={structuralSignature}>
|
||||
{group.kind === 'turn' ? (
|
||||
<div
|
||||
className="composer-human-ai-pair-container relative flex min-w-0 flex-col gap-(--conversation-turn-gap)"
|
||||
data-slot="aui_turn-pair"
|
||||
>
|
||||
{group.indices.map(index => (
|
||||
<ThreadPrimitive.MessageByIndex components={components} index={index} key={index} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<ThreadPrimitive.MessageByIndex components={components} index={group.index} />
|
||||
)}
|
||||
</MessageRenderBoundary>
|
||||
</div>
|
||||
resetKey={structuralSignature}
|
||||
virtualized={indexInVisible < tailStart}
|
||||
/>
|
||||
)),
|
||||
[visibleGroups, components, structuralSignature, tailStart]
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user