Skip to content

The agent that grows with you

fix(desktop): a long chat keeps following its bottom when a turn settles

Teknium14084e9f9911
diff --git a/apps/desktop/e2e/core/tail-resync-merge.spec.ts b/apps/desktop/e2e/core/tail-resync-merge.spec.ts
index b788d06e65b..88531099923 100644
--- a/apps/desktop/e2e/core/tail-resync-merge.spec.ts
+++ b/apps/desktop/e2e/core/tail-resync-merge.spec.ts
@@ -55,6 +55,9 @@ const SEED_ROUNDS = 10
const SEED_TURNS = 6
const CHECKED_TURNS = 3
const OBSERVE_MS = 13_000
+// The app's own line between a reader at the bottom and one in history
+// (RUN_START_SNAP_THRESHOLD_PX in thread/list.tsx).
+const OFF_BOTTOM_PX = 64
const SHOTS = process.env.HERMES_E2E_SHOT_DIR
@@ -102,17 +105,27 @@ async function withApp(
}
}
-/** How often each marker shows in the visible thread, and whether they read in order. */
+/**
+ * How often each marker shows in the visible thread, whether they read in
+ * order, and whether the thread still follows its bottom. innerText skips the
+ * off-screen turns content-visibility leaves unrendered, so the marker count is
+ * only meaningful while the view sits at the newest turn: nothing here scrolls,
+ * and a view that stopped following is the symptom itself (a settled turn's
+ * row-height jump read as a scroll-up), reported as such.
+ */
async function turnShape(
page: Page,
markers: string[]
-): Promise<{ counts: number[]; doubled: string[]; ordered: boolean }> {
- const text = await page.evaluate(() => {
+): Promise<{ counts: number[]; doubled: string[]; offBottom: number; ordered: boolean }> {
+ const { offBottom, text } = await page.evaluate(() => {
const el = ([...document.querySelectorAll('[data-slot="aui_thread-viewport"]')] as HTMLElement[]).find(
node => node.getClientRects().length > 0
)
- return el ? el.innerText.replace(/\s+/g, ' ') : ''
+ return {
+ offBottom: el ? Math.round(el.scrollHeight - el.clientHeight - el.scrollTop) : -1,
+ text: el ? el.innerText.replace(/\s+/g, ' ') : ''
+ }
})
const counts = markers.map(marker => text.split(marker).length - 1)
@@ -126,6 +139,7 @@ async function turnShape(
return {
counts,
doubled: [...seen].filter(([, count]) => count > 1).map(([marker, count]) => `${marker}x${count}`),
+ offBottom,
ordered: positions.every((at, i) => at >= 0 && (i === 0 || at > positions[i - 1]))
}
}
@@ -155,6 +169,7 @@ async function observeTurn(page: Page, markers: string[], label: string): Promis
const deadline = Date.now() + OBSERVE_MS
let shot = false
let nextReturn = 0
+ let previousOffBottom = 0
while (Date.now() < deadline) {
if (Date.now() >= nextReturn) {
@@ -164,9 +179,14 @@ async function observeTurn(page: Page, markers: string[], label: string): Promis
const shape = await turnShape(page, markers)
- if (shape.counts.some(count => count !== 1) || !shape.ordered || shape.doubled.length) {
+ // Off the bottom on two samples in a row: a follow that lags one frame
+ // behind a resize is not a view that stopped following.
+ const lostBottom = shape.offBottom > OFF_BOTTOM_PX && previousOffBottom > OFF_BOTTOM_PX
+ previousOffBottom = shape.offBottom
+
+ if (shape.counts.some(count => count !== 1) || !shape.ordered || shape.doubled.length || lostBottom) {
bad.push(
- `${markers.map((m, i) => `${m}x${shape.counts[i]}`).join(' ')} ordered=${shape.ordered} doubled=${shape.doubled.join(',')}`
+ `${markers.map((m, i) => `${m}x${shape.counts[i]}`).join(' ')} ordered=${shape.ordered} doubled=${shape.doubled.join(',')} offBottom=${shape.offBottom}px`
)
if (SHOTS && !shot) {
diff --git a/apps/desktop/src/components/assistant-ui/thread/list-row-identity.test.tsx b/apps/desktop/src/components/assistant-ui/thread/list-row-identity.test.tsx
new file mode 100644
index 00000000000..a954d7f1cd0
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/thread/list-row-identity.test.tsx
@@ -0,0 +1,98 @@
+import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'
+import { act, render } from '@testing-library/react'
+import { describe, expect, it } from 'vitest'
+
+import { stubThreadEnvironment, stubThreadViewportSize } from '../test-utils'
+
+import { TranscriptWindowProvider } from './transcript-window'
+
+import { Thread } from '.'
+
+stubThreadEnvironment()
+stubThreadViewportSize()
+
+const createdAt = new Date('2026-08-01T00:00:00.000Z')
+
+/**
+ * The same stored turns as a newest-page read returns them: renderer ids carry
+ * the row's position in that page (`<ts>-<index>-<role>`), the durable row id
+ * rides metadata.custom.rowId.
+ */
+function storedTurns(pageOffset: number, turns = 4): ThreadMessage[] {
+ return Array.from({ length: turns }, (_, turn) => {
+ const userRow = 100 + turn * 2
+
+ return [
+ {
+ id: `1793025691.78-${turn * 2 + pageOffset}-user`,
+ role: 'user',
+ content: [{ type: 'text', text: `prompt ${turn}` }],
+ attachments: [],
+ createdAt,
+ metadata: { custom: { rowId: userRow } }
+ } as ThreadMessage,
+ {
+ id: `1793025691.78-${turn * 2 + 1 + pageOffset}-assistant`,
+ role: 'assistant',
+ content: [{ type: 'text', text: `reply ${turn}` }],
+ status: { type: 'complete', reason: 'stop' },
+ createdAt,
+ metadata: {
+ unstable_state: null,
+ unstable_annotations: [],
+ unstable_data: [],
+ steps: [],
+ custom: { rowId: userRow + 1 }
+ }
+ } as ThreadMessage
+ ]
+ }).flat()
+}
+
+function Harness({ messages }: { messages: ThreadMessage[] }) {
+ const runtime = useExternalStoreRuntime<ThreadMessage>({ isRunning: false, messages, onNew: async () => {} })
+
+ return (
+ <AssistantRuntimeProvider runtime={runtime}>
+ <TranscriptWindowProvider value={{ olderAvailable: false, expandWindow: () => {} }}>
+ <Thread sessionId="s1" sessionKey="s1" />
+ </TranscriptWindowProvider>
+ </AssistantRuntimeProvider>
+ )
+}
+
+const turnRows = (container: HTMLElement) => [
+ ...container.querySelectorAll<HTMLElement>('[data-slot="aui_message-group"]')
+]
+
+describe('transcript row identity', () => {
+ it('keeps every stored turn mounted when a slid newest page re-reads it under new renderer ids', async () => {
+ // A remounted row is a new element with no remembered size: off screen it
+ // drops to the contain-intrinsic-size placeholder, the transcript height
+ // jumps, and the clamp reads as a scroll-up that stops the follow.
+ const { container, rerender } = render(<Harness messages={storedTurns(0)} />)
+
+ await act(async () => {
+ await new Promise<void>(resolve => window.setTimeout(resolve, 0))
+ })
+
+ const before = turnRows(container)
+ expect(before).toHaveLength(4)
+
+ rerender(<Harness messages={storedTurns(12)} />)
+
+ await act(async () => {
+ await new Promise<void>(resolve => window.setTimeout(resolve, 0))
+ })
+
+ const after = turnRows(container)
+ expect(after).toHaveLength(4)
+ expect(after.map((row, index) => row === before[index])).toEqual([true, true, true, true])
+ expect(after.map(row => row.textContent?.match(/prompt \d/)?.[0])).toEqual([
+ 'prompt 0',
+ 'prompt 1',
+ 'prompt 2',
+ 'prompt 3'
+ ])
+ })
+})
diff --git a/apps/desktop/src/components/assistant-ui/thread/list.tsx b/apps/desktop/src/components/assistant-ui/thread/list.tsx
index 19f97056788..31fe6b5a9cf 100644
--- a/apps/desktop/src/components/assistant-ui/thread/list.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/list.tsx
@@ -411,6 +411,39 @@ export function liveTailStart(
return Math.min(floor, Math.max(ceiling, start))
}
+/**
+ * React identity of the row a message opens. A stored row's renderer id is
+ * built from its position in the page it was read from, so every newest-page
+ * re-read that slides the window hands every row in it a new id. Keyed by
+ * that id, each settled turn remounted the whole page: a remounted row is a
+ * new element with no remembered size, so an off-screen one drops to the
+ * contain-intrinsic-size placeholder, the transcript height jumps, and the
+ * scrollTop clamp reads as a scroll-up to use-stick-to-bottom (the view stops
+ * following). The durable row id is the same row in every page.
+ */
+export function transcriptRowKey(message: { id: string; metadata?: { custom?: Record<string, unknown> } }): string {
+ const rowId = message.metadata?.custom?.rowId
+
+ return typeof rowId === 'number' ? `row:${rowId}` : message.id
+}
+
+/**
+ * Per-message React keys, indexed like thread.messages. Two rendered messages
+ * can carry one durable row (hydration splits a stored row it renders in
+ * parts); the later copy keeps its own renderer id as its key.
+ */
+export function turnRowKeys(rowKeySignature: string, structuralSignature: string): string[] {
+ const seen = new Set<string>()
+ const ids = structuralSignature.split('\n').map(row => row.split(':')[1])
+
+ return rowKeySignature.split('\n').map((key, index) => {
+ const unique = seen.has(key) ? (ids[index] ?? key) : key
+ seen.add(unique)
+
+ return unique
+ })
+}
+
interface TurnRowProps {
components: ThreadMessageComponents
group: MessageGroup
@@ -434,8 +467,13 @@ interface TurnRowProps {
// ~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.
+// stay stable. It sits on EVERY row, not only virtualized ones: the browser
+// records a remembered size only while the declaration is present, so a row
+// that gained it together with content-visibility (leaving the live tail
+// off screen) dropped to the 37.5rem placeholder, and the height change
+// clamped scrollTop into a scroll-up that stopped the follow. 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
@@ -444,8 +482,8 @@ const TurnRow = memo(function TurnRow({ components, group, resetKey, virtualized
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]'
+ 'flex min-w-0 flex-col gap-(--conversation-turn-gap) pb-(--conversation-turn-gap) [contain-intrinsic-size:auto_37.5rem]',
+ virtualized && '[content-visibility:auto]'
)}
data-slot="aui_message-group"
>
@@ -496,6 +534,7 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
// part-appends can't churn group identity (that would defeat the rows memo
// below on every tick). Weights are folded in separately for the budget.
const groups = useMemo(() => buildGroups(structuralSignature), [structuralSignature])
+ const rowKeySignature = useAuiState(s => s.thread.messages.map(transcriptRowKey).join('\n'))
const renderEmpty = groups.length === 0 && Boolean(emptyPlaceholder)
// use-stick-to-bottom owns scrollTop (single writer): follow while locked,
@@ -1545,19 +1584,19 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({
// changed (measured live: 865 wasted Block renders in one drag, walked to
// "MessageRenderBoundary (children only)" by explain()). With it, React
// bails out on element identity and a scroll flip re-renders nothing below.
- const rows = useMemo(
- () =>
- visibleGroups.map((group, indexInVisible) => (
- <TurnRow
- components={components}
- group={group}
- key={group.id}
- resetKey={structuralSignature}
- virtualized={indexInVisible < tailStart}
- />
- )),
- [visibleGroups, components, structuralSignature, tailStart]
- )
+ const rows = useMemo(() => {
+ const rowKeys = turnRowKeys(rowKeySignature, structuralSignature)
+
+ return visibleGroups.map((group, indexInVisible) => (
+ <TurnRow
+ components={components}
+ group={group}
+ key={rowKeys[group.kind === 'turn' ? group.indices[0] : group.index] ?? group.id}
+ resetKey={structuralSignature}
+ virtualized={indexInVisible < tailStart}
+ />
+ ))
+ }, [visibleGroups, components, rowKeySignature, structuralSignature, tailStart])
useMessagesBelow({ contentRef, scrollRef, isAtBottom, paneVisible, rows, sessionKey, sessionId: scrollSessionId })
useStickyPromptClip({ contentRef, scrollRef, paneVisible, rows })