Skip to content

The agent that grows with you

perf(desktop): share thread-message position lookups across transcript rows

Austin Pickett449fae030aa6
diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
index 7f08e4f8360..19f560e1920 100644
--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
@@ -27,6 +27,7 @@ import { MESSAGE_PARTS_COMPONENTS } from '@/components/assistant-ui/thread/messa
import { ReactionPicker } from '@/components/assistant-ui/thread/message-reactions'
import { ResponseMessageIds } from '@/components/assistant-ui/thread/response-group'
import { ResponseLoadingIndicator, TurnActivityIndicator } from '@/components/assistant-ui/thread/status'
+import { threadMessageIndex } from '@/components/assistant-ui/thread/thread-message-index'
import { MessageTimelineTimestamp } from '@/components/assistant-ui/thread/timeline-timestamp'
import { useMessageReactions, useTapbackDoubleClick } from '@/components/assistant-ui/thread/use-message-reactions'
import { AGENT_MESSAGE_RE } from '@/components/assistant-ui/thread/user-message'
@@ -126,32 +127,26 @@ export const AssistantMessage: FC<AssistantMessageProps> = props => {
const interAgentSender = useAuiState(s => {
const messages = s.thread.messages
- for (let i = messages.length - 1; i >= 0; i--) {
- if (messages[i].id !== s.message.id) {
- continue
+ // Shared id->index map: a per-row scan for its own position was
+ // mounted-rows x transcript-length on every streamed chunk (#126486).
+ for (let j = threadMessageIndex(messages, s.message.id) - 1; j >= 0; j--) {
+ const prev = messages[j] as { content?: unknown; role?: string }
+
+ if (prev.role === 'assistant') {
+ return null
}
- for (let j = i - 1; j >= 0; j--) {
- const prev = messages[j] as { content?: unknown; role?: string }
+ if (prev.role === 'user') {
+ const match = AGENT_MESSAGE_RE.exec(messageContentText(prev.content as never).trim())
- if (prev.role === 'assistant') {
+ if (!match) {
return null
}
- if (prev.role === 'user') {
- const match = AGENT_MESSAGE_RE.exec(messageContentText(prev.content as never).trim())
-
- if (!match) {
- return null
- }
-
- const sender = (match[1] || match[3] || 'agent').trim()
+ const sender = (match[1] || match[3] || 'agent').trim()
- return dispatchedTo(messages.slice(0, j), [match[1], match[2], match[3]]) ? null : sender
- }
+ return dispatchedTo(messages.slice(0, j), [match[1], match[2], match[3]]) ? null : sender
}
-
- return null
}
return null
diff --git a/apps/desktop/src/components/assistant-ui/thread/stream-settled-renders.test.tsx b/apps/desktop/src/components/assistant-ui/thread/stream-settled-renders.test.tsx
new file mode 100644
index 00000000000..c6c51f0ffe9
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/thread/stream-settled-renders.test.tsx
@@ -0,0 +1,204 @@
+// Streaming into a long transcript must not re-render the settled history
+// (#126486, regression of #69120). A streamed delta replaces only the tail
+// ChatMessage; everything upstream of the thread keeps identity for settled
+// turns, so the only components allowed to render per chunk are the tail's.
+//
+// This drives the PRODUCTION transcript pipeline — ChatMessage[] ->
+// useRuntimeMessageRepository -> useIncrementalExternalStoreRuntime -> <Thread />
+// — and counts renders per message id at two levels: the message root
+// (`useMessageReactions`, called once per root render) and the text part
+// (`useMessagePartText`, read by every rendered text part).
+import type * as assistantUiModule from '@assistant-ui/react'
+import { AssistantRuntimeProvider, type ThreadMessage } from '@assistant-ui/react'
+import { act, cleanup, render } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { useRuntimeMessageRepository } from '@/app/chat/runtime-repository'
+import type * as messageReactionsModule from '@/components/assistant-ui/thread/use-message-reactions'
+import type { ChatMessage } from '@/lib/chat-messages'
+import { useIncrementalExternalStoreRuntime } from '@/lib/incremental-external-store-runtime'
+
+import { stubThreadEnvironment, stubThreadViewportSize } from '../test-utils'
+
+import { Thread } from '.'
+
+const rootRenders = new Map<string, number>()
+const textRenders = new Map<string, number>()
+
+const bump = (map: Map<string, number>, id: string) => map.set(id, (map.get(id) ?? 0) + 1)
+
+vi.mock('@/components/assistant-ui/thread/use-message-reactions', async importActual => {
+ const actual = await importActual<typeof messageReactionsModule>()
+
+ return {
+ ...actual,
+ // Called once per render by each message root (assistant and user).
+ useMessageReactions: (messageId: string, role: 'assistant' | 'user') => {
+ bump(rootRenders, messageId)
+
+ return actual.useMessageReactions(messageId, role)
+ }
+ }
+})
+
+vi.mock('@assistant-ui/react', async importActual => {
+ const actual = await importActual<typeof assistantUiModule>()
+
+ // Every text-part consumer (the part component and the markdown surface
+ // under it) reads its text through this hook, so a call is a text-part render.
+ function useMessagePartText() {
+ const id = actual.useAuiState(s => s.message.id)
+ bump(textRenders, id)
+
+ return actual.useMessagePartText()
+ }
+
+ return { ...actual, useMessagePartText }
+})
+
+stubThreadEnvironment()
+stubThreadViewportSize()
+
+beforeEach(() => {
+ rootRenders.clear()
+ textRenders.clear()
+})
+
+afterEach(() => {
+ cleanup()
+})
+
+const text = (id: string, role: ChatMessage['role'], body: string, pending = false): ChatMessage => ({
+ id,
+ role,
+ parts: [{ type: 'text', text: body }],
+ ...(pending ? { pending: true } : {})
+})
+
+function Harness({ messages, busy }: { busy: boolean; messages: ChatMessage[] }) {
+ const messageRepository = useRuntimeMessageRepository(messages)
+
+ const runtime = useIncrementalExternalStoreRuntime<ThreadMessage>({
+ messageRepository,
+ isRunning: busy,
+ onNew: async () => {}
+ })
+
+ return (
+ <AssistantRuntimeProvider runtime={runtime}>
+ <Thread />
+ </AssistantRuntimeProvider>
+ )
+}
+
+// PROBE_TURNS=400 turns this into the long-transcript measurement from #126486
+// (per-chunk wall time is printed); the default keeps the contract test cheap.
+const PROBE = process.env.PROBE_TURNS !== undefined
+const HISTORY_TURNS = Number(process.env.PROBE_TURNS ?? 3)
+const CHUNKS = 10
+
+function history(): ChatMessage[] {
+ const out: ChatMessage[] = []
+
+ for (let turn = 0; turn < HISTORY_TURNS; turn += 1) {
+ out.push(text(`u${turn}`, 'user', `question ${turn}`))
+ out.push({
+ id: `a${turn}`,
+ role: 'assistant',
+ parts: [
+ { type: 'reasoning', text: `thinking ${turn}` },
+ {
+ type: 'tool-call',
+ toolCallId: `call-${turn}`,
+ toolName: 'terminal',
+ args: { command: 'ls' },
+ argsText: '{"command":"ls"}',
+ result: 'ok'
+ },
+ { type: 'text', text: `settled answer ${turn}` }
+ ] as ChatMessage['parts']
+ })
+ // A tool-only follow-up turn: coalesced into its neighbour by the pipeline.
+ out.push({
+ id: `t${turn}`,
+ role: 'assistant',
+ parts: [
+ {
+ type: 'tool-call',
+ toolCallId: `call-${turn}-b`,
+ toolName: 'terminal',
+ args: { command: 'pwd' },
+ argsText: '{"command":"pwd"}',
+ result: '/'
+ }
+ ] as ChatMessage['parts']
+ })
+ }
+
+ return out
+}
+
+function sum(map: Map<string, number>, ids: readonly string[]) {
+ return ids.reduce((total, id) => total + (map.get(id) ?? 0), 0)
+}
+
+describe('streaming into a settled transcript', () => {
+ it('does not re-render settled messages per streamed chunk', async () => {
+ const settled = history()
+ const settledIds = settled.map(m => m.id)
+ const settledAssistantIds = settledIds.filter(id => id.startsWith('a'))
+ const prompt = text('u-live', 'user', 'live question')
+
+ let body = 'tok0'
+ const stream = () => [...settled, prompt, text('a-live', 'assistant', body, true)]
+
+ const { findByText, rerender } = render(<Harness busy messages={stream()} />)
+
+ await findByText('tok0')
+
+ // Let the render-budget backfill finish mounting older rows first, so the
+ // window below measures RE-renders of mounted rows, not first mounts.
+ for (let settle = 0, last = -1; settle < 50 && rootRenders.size !== last; settle += 1) {
+ last = rootRenders.size
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 50))
+ })
+ }
+
+ const mountedBefore = new Set(rootRenders.keys())
+
+ // Sanity: the counters see the settled rows at all.
+ expect(sum(textRenders, settledAssistantIds)).toBeGreaterThan(0)
+
+ const rootBefore = sum(rootRenders, settledIds)
+ const textBefore = sum(textRenders, settledIds)
+ const liveTextBefore = textRenders.get('a-live') ?? 0
+
+ const t0 = performance.now()
+
+ for (let chunk = 1; chunk <= CHUNKS; chunk += 1) {
+ body = `${body} tok${chunk}`
+ await act(async () => {
+ rerender(<Harness busy messages={stream()} />)
+ })
+ }
+
+ const elapsed = performance.now() - t0
+ await findByText(body)
+
+ if (PROBE) {
+ console.info(
+ `[probe] turns=${HISTORY_TURNS} ms/chunk=${(elapsed / CHUNKS).toFixed(2)} mountedBefore=${mountedBefore.size} mountedAfter=${rootRenders.size}`
+ )
+ }
+
+ const settledRootPerChunk = (sum(rootRenders, settledIds) - rootBefore) / CHUNKS
+ const settledTextPerChunk = (sum(textRenders, settledIds) - textBefore) / CHUNKS
+ const liveTextPerChunk = ((textRenders.get('a-live') ?? 0) - liveTextBefore) / CHUNKS
+
+ // The live tail must actually be streaming, or the zero below is vacuous.
+ expect(liveTextPerChunk).toBeGreaterThanOrEqual(1)
+ expect(settledRootPerChunk).toBe(0)
+ expect(settledTextPerChunk).toBe(0)
+ })
+})
diff --git a/apps/desktop/src/components/assistant-ui/thread/thread-message-index.test.ts b/apps/desktop/src/components/assistant-ui/thread/thread-message-index.test.ts
new file mode 100644
index 00000000000..7f87be544ad
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/thread/thread-message-index.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest'
+
+import { threadMessageIndex, threadUserOrdinal } from './thread-message-index'
+
+const rows = [
+ { id: 'u1', role: 'user' },
+ { id: 'a1', role: 'assistant' },
+ { id: 'u2', role: 'user' },
+ { id: 'a2', role: 'assistant' }
+]
+
+describe('thread message index', () => {
+ it('finds a row index and a user ordinal, or reports none', () => {
+ expect(threadMessageIndex(rows, 'a2')).toBe(3)
+ expect(threadMessageIndex(rows, 'missing')).toBe(-1)
+ expect(threadUserOrdinal(rows, 'u2')).toBe(1)
+ expect(threadUserOrdinal(rows, 'a1')).toBeNull()
+ })
+
+ it('is keyed by array identity, so a new transcript array is re-indexed', () => {
+ expect(threadMessageIndex(rows, 'a2')).toBe(3)
+
+ const next = [{ id: 'u0', role: 'user' }, ...rows]
+
+ expect(threadMessageIndex(next, 'a2')).toBe(4)
+ expect(threadUserOrdinal(next, 'u2')).toBe(2)
+ })
+})
diff --git a/apps/desktop/src/components/assistant-ui/thread/thread-message-index.ts b/apps/desktop/src/components/assistant-ui/thread/thread-message-index.ts
new file mode 100644
index 00000000000..8a341707d40
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/thread/thread-message-index.ts
@@ -0,0 +1,58 @@
+// Shared position lookups over `s.thread.messages`, built once per array.
+//
+// Every mounted message row re-runs its `useAuiState` selectors on each thread
+// notify — one per streamed chunk. A selector that scans the transcript to find
+// its own row therefore costs mounted-rows x transcript-length per chunk, which
+// is how streaming into a long chat got slower with every settled turn
+// (#126486). The runtime publishes one messages array per notify, so keying on
+// its identity lets every row in that notify share a single O(n) pass.
+
+type Row = { readonly id: string; readonly role: string }
+
+const indexCache = new WeakMap<readonly Row[], Map<string, number>>()
+const userOrdinalCache = new WeakMap<readonly Row[], Map<string, number>>()
+
+function memo(
+ cache: WeakMap<readonly Row[], Map<string, number>>,
+ messages: readonly Row[],
+ build: () => Map<string, number>
+) {
+ let map = cache.get(messages)
+
+ if (!map) {
+ map = build()
+ cache.set(messages, map)
+ }
+
+ return map
+}
+
+/** Index of the LAST row with `id`, or -1. */
+export function threadMessageIndex(messages: readonly Row[], id: string): number {
+ return (
+ memo(indexCache, messages, () => {
+ const map = new Map<string, number>()
+
+ messages.forEach((message, index) => map.set(message.id, index))
+
+ return map
+ }).get(id) ?? -1
+ )
+}
+
+/** Position of `id` among the user rows (first occurrence), or null. */
+export function threadUserOrdinal(messages: readonly Row[], id: string): null | number {
+ return (
+ memo(userOrdinalCache, messages, () => {
+ const map = new Map<string, number>()
+
+ for (const message of messages) {
+ if (message.role === 'user' && !map.has(message.id)) {
+ map.set(message.id, map.size)
+ }
+ }
+
+ return map
+ }).get(id) ?? null
+ )
+}
diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message.tsx
index 710b4a39456..231b1739e79 100644
--- a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/user-message.tsx
@@ -10,6 +10,7 @@ import {
} from '@/components/assistant-ui/thread/content'
import { ReactionBadge, ReactionPicker } from '@/components/assistant-ui/thread/message-reactions'
import { BackgroundResult } from '@/components/assistant-ui/thread/system-message'
+import { threadUserOrdinal } from '@/components/assistant-ui/thread/thread-message-index'
import { MessageTimelineTimestamp } from '@/components/assistant-ui/thread/timeline-timestamp'
import { type RestoreMessageTarget } from '@/components/assistant-ui/thread/types'
import { useMessageReactions } from '@/components/assistant-ui/thread/use-message-reactions'
@@ -263,23 +264,7 @@ export const UserMessage: FC<{
return null
})
- const runtimeUserOrdinal = useAuiState(s => {
- let ordinal = 0
-
- for (const message of s.thread.messages) {
- if (message.role !== 'user') {
- continue
- }
-
- if (message.id === s.message.id) {
- return ordinal
- }
-
- ordinal += 1
- }
-
- return null
- })
+ const runtimeUserOrdinal = useAuiState(s => threadUserOrdinal(s.thread.messages, s.message.id))
const attachmentRefs = useAuiState(s => {
const custom = (s.message.metadata?.custom ?? {}) as { attachmentRefs?: unknown }