The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): warm session switch pegs renderer main thread (#95595)
Finn763e245e40f731c
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsxindex 14651b7f727..1b95bc769a2 100644--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@ -78,7 +78,7 @@ import {mergeOlderTranscriptPage,transcriptBackfillAvailable} from './transcript-backfill'-import { advanceTranscriptWindow, type TranscriptWindowState } from './transcript-window'+import { advanceSessionTranscriptWindow, type SessionWindowMemo } from './transcript-window'interface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {gateway: HermesGateway | null@@ -247,22 +247,37 @@ 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)+ // Per-session sticky-cut continuity (advanceSessionTranscriptWindow). A ref,+ // not state: it is derived from `messages` and must never trigger a render.+ // Keyed by runtime id so a warm switch back to a session whose transcript+ // is unchanged reuses the previous windowed slice BY REFERENCE — no window+ // re-index, no runtime-repository rebuild, no per-row re-parse/re-highlight+ // (#95595). Bounded internally (oldest session evicted).+ const windowStateRef = useRef(new Map<string, SessionWindowMemo>())+ // The memo below intentionally skips `runtimeId` in its deps (a switch+ // always changes the messages array too, which re-runs it), so the current+ // value must come from a ref rather than the stale render closure.+ const runtimeIdRef = useRef(runtimeId)+ runtimeIdRef.current = runtimeId// 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).+ // previous chat can't leak into the next one's first paint (#55191). The+ // per-session map above keeps each session's own cut; only the page count+ // resets on a switch.if (windowSessionKey !== runtimeId) {setWindowSessionKey(runtimeId)setWindowPages(1)- windowStateRef.current = null}const { messages: windowedMessages, windowed } = useMemo(() => {- const next = advanceTranscriptWindow(windowStateRef.current, messages, windowPages)-- windowStateRef.current = next+ const next = advanceSessionTranscriptWindow(+ windowStateRef.current,+ // Draft state has no runtime id yet; a single shared slot is fine there+ // (mirrors the old single-slot behaviour for the no-runtime case).+ runtimeIdRef.current ?? '',+ messages,+ windowPages+ )return next.window}, [messages, windowPages])@@ -296,7 +311,7 @@ function ChatRuntimeBoundary({// something older to show. Fire-and-forget: the prepend lands through the// session-state write path and re-renders this boundary.if (- !windowStateRef.current?.window.windowed &&+ !windowStateRef.current.get(runtimeIdRef.current ?? '')?.state.window.windowed &&runtimeId &&storedId &&transcriptBackfillAvailable(storedId, tailProfile)diff --git a/apps/desktop/src/app/chat/right-rail/preview-file.tsx b/apps/desktop/src/app/chat/right-rail/preview-file.tsxindex f3723f19d74..6c43c0cea43 100644--- a/apps/desktop/src/app/chat/right-rail/preview-file.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-file.tsx@@ -348,17 +348,7 @@ function MarkdownCode({ className, children, ...props }: ComponentProps<'code'>)const code = String(children).replace(/\n$/, '')const highlighted = (- <ShikiHighlighter- addDefaultStyles={false}- as="div"- defaultColor="light-dark()"- delay={80}- language={language}- showLanguage={false}- theme={SHIKI_THEME}- >- {code}- </ShikiHighlighter>+ <ShikiHighlighter code={code} language={language} theme={SHIKI_THEME} />)// ```mermaid / ```svg fences route to the shared lazy renderers (same@@ -661,17 +651,7 @@ export function SourceView({ filePath, language, text }: { filePath?: string; la})}</div><div className="preview-source-code min-w-0 [&_pre]:m-0" data-selectable-text="true">- <ShikiHighlighter- addDefaultStyles={false}- as="div"- defaultColor="light-dark()"- delay={80}- language={language || 'text'}- showLanguage={false}- theme={SHIKI_THEME}- >- {chunk.text}- </ShikiHighlighter>+ <ShikiHighlighter code={chunk.text} language={language || 'text'} theme={SHIKI_THEME} /></div></Fragment>))}diff --git a/apps/desktop/src/app/chat/transcript-window.test.ts b/apps/desktop/src/app/chat/transcript-window.test.tsindex 600056e0b7a..963b914a795 100644--- a/apps/desktop/src/app/chat/transcript-window.test.ts+++ b/apps/desktop/src/app/chat/transcript-window.test.ts@@ -4,8 +4,10 @@ import type { ChatMessage } from '@/lib/chat-messages'import { RENDER_WEIGHT_CHARS } from '@/lib/render-weight'import {+ advanceSessionTranscriptWindow,advanceTranscriptWindow,alignToBranchGroup,+ MAX_SESSION_WINDOWS,selectTranscriptWindow,TRANSCRIPT_WINDOW_BUDGET,TRANSCRIPT_WINDOW_MIN_MESSAGES,@@ -214,6 +216,87 @@ describe('advanceTranscriptWindow', () => {})})+describe('advanceSessionTranscriptWindow', () => {+ const heavyChars = RENDER_WEIGHT_CHARS * 40++ it('matches a fresh walk on first visit', () => {+ const memos = new Map()+ const messages = transcript(400, heavyChars)++ const state = advanceSessionTranscriptWindow(memos, 'session-a', messages)++ expect(state.window).toEqual(selectTranscriptWindow(messages))+ expect(state.anchorId).toBe(state.window.messages[0].id)+ })++ it('returns the SAME windowed slice by reference on a warm re-visit with an unchanged transcript', () => {+ const memos = new Map()+ const sessionA = transcript(400, heavyChars)+ const sessionB = transcript(300, heavyChars).map(m => ({ ...m, id: `b-${m.id}` }))++ // Visit B, then A, then B again — the exact warm-switch shape of #95595.+ const firstB = advanceSessionTranscriptWindow(memos, 'session-b', sessionB)+ advanceSessionTranscriptWindow(memos, 'session-a', sessionA)+ const secondB = advanceSessionTranscriptWindow(memos, 'session-b', sessionB)++ expect(secondB.window.windowed).toBe(true)+ // THE perf guard: same transcript array => same windowed slice reference,+ // so the runtime repository and every row keep their identity.+ expect(secondB.window.messages).toBe(firstB.window.messages)+ expect(secondB.anchorId).toBe(firstB.anchorId)+ })++ it('holds the sticky cut when a re-visited session grew while away', () => {+ const memos = new Map()+ const messages = transcript(400, heavyChars)+ const state = advanceSessionTranscriptWindow(memos, 'session-a', messages)++ // While away, the session streamed a few light turns (within slack).+ const grown = [...messages, ...transcript(10, 100)]+ const next = advanceSessionTranscriptWindow(memos, 'session-a', grown)++ // Sticky cut survived the switch-away: same anchor, no fresh re-walk.+ expect(next.anchorId).toBe(state.anchorId)+ expect(next.window.messages[0].id).toBe(state.window.messages[0].id)+ // The anchored slice now simply includes the 10 new light turns.+ expect(next.window.messages.length).toBe(state.window.messages.length + 10)+ })++ it('falls back to a fresh walk when the anchor vanished while away', () => {+ const memos = new Map()+ const messages = transcript(400, heavyChars)+ advanceSessionTranscriptWindow(memos, 'session-a', messages)++ // Compression rewrite: disjoint ids while the user was elsewhere.+ const rewritten = transcript(300, heavyChars).map(m => ({ ...m, id: `compressed-${m.id}` }))+ const next = advanceSessionTranscriptWindow(memos, 'session-a', rewritten)++ expect(next.window).toEqual(selectTranscriptWindow(rewritten))+ })++ it('re-walks when pages change on re-entry', () => {+ const memos = new Map()+ const messages = transcript(400, heavyChars)++ const one = advanceSessionTranscriptWindow(memos, 'session-a', messages, 1)+ const two = advanceSessionTranscriptWindow(memos, 'session-a', messages, 2)++ expect(two.window.messages.length).toBeGreaterThan(one.window.messages.length)+ })++ it('keeps sessions independent and evicts the oldest memo past the cap', () => {+ const memos = new Map()++ for (let i = 0; i < MAX_SESSION_WINDOWS + 5; i++) {+ advanceSessionTranscriptWindow(memos, `session-${i}`, transcript(400, heavyChars))+ }++ expect(memos.size).toBeLessThanOrEqual(MAX_SESSION_WINDOWS)+ expect(memos.has('session-0')).toBe(false)+ expect(memos.has(`session-${MAX_SESSION_WINDOWS + 4}`)).toBe(true)+ })+})+describe('alignToBranchGroup', () => {const messages = [message('u-1', 10), message('a-1', 10, 'g'), message('a-2', 10, 'g'), message('u-2', 10)]diff --git a/apps/desktop/src/app/chat/transcript-window.ts b/apps/desktop/src/app/chat/transcript-window.tsindex b63e6d316cd..64373316461 100644--- a/apps/desktop/src/app/chat/transcript-window.ts+++ b/apps/desktop/src/app/chat/transcript-window.ts@@ -170,3 +170,65 @@ export function advanceTranscriptWindow(return { anchorId: window.windowed ? window.messages[0].id : null, pages, window }}++/** How many sessions keep a sticky window before the oldest is evicted. */+export const MAX_SESSION_WINDOWS = 12++/**+ * A window state plus the exact message array it was computed from.+ * The array identity is load-bearing: when a session is re-entered with the+ * IDENTICAL transcript (the warm-switch path of #95595), the stored window —+ * including the exact `window.messages` slice reference — is reused as-is.+ * The reference reuse is what stops `useRuntimeMessageRepository` from+ * rebuilding (and every row from re-rendering) on a warm switch.+ */+export interface SessionWindowMemo {+ messages: readonly ChatMessage[]+ state: TranscriptWindowState+}++/**+ * `advanceTranscriptWindow` with a STICKY cut that survives session switches.+ *+ * The previous single-slot state was nulled on every switch, so a warm+ * re-entry always re-ran the weight walk and rebuilt the windowed slice —+ * which re-indexed the whole windowed transcript (markdown re-parse ++ * re-highlight per row) even though nothing had changed. This keeps one memo+ * per session:+ *+ * - Re-entering a session with the same transcript array returns the cached+ * windowed slice BY REFERENCE — the runtime repository and every message+ * row stay mounted, so the switch is O(1).+ * - Re-entering with a changed transcript keeps the sticky cut (anchor still+ * present, tail within budget + slack) instead of re-walking from scratch.+ * - The anchor vanishing (compression rewrite) or a pages change falls+ * through to `advanceTranscriptWindow`'s existing fresh-walk behaviour.+ *+ * The map is bounded (oldest session evicted) so an unbounded session list+ * cannot grow it without limit.+ */+export function advanceSessionTranscriptWindow(+ memos: Map<string, SessionWindowMemo>,+ sessionKey: string,+ messages: readonly ChatMessage[],+ pages = 1+): TranscriptWindowState {+ const memo = memos.get(sessionKey)++ // Warm re-visit with the identical transcript and page count: reuse the+ // cached state wholesale, preserving the windowed slice reference.+ if (memo && memo.messages === messages && memo.state.pages === pages) {+ return memo.state+ }++ const state = advanceTranscriptWindow(memo?.state ?? null, messages, pages)++ memos.set(sessionKey, { messages, state })++ if (memos.size > MAX_SESSION_WINDOWS) {+ const oldest = memos.keys().next().value as string+ memos.delete(oldest)+ }++ return state+}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex 4790f027656..cec1ebf5212 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -157,6 +157,7 @@ import {isSessionGoneError,overlayConcurrentMessageChanges,patchSessionWorkspace,+ preserveEquivalentTranscript,preserveLocalPendingTurnMessages,reconcileResumeMessages,removeRepresentedLocalLiveProjection,@@ -1372,26 +1373,37 @@ export function useSessionActions({const activatedState = updateSessionState(cachedRuntimeId,- state => ({- ...state,- messages: visibleActivatedMessages,- transcriptProvenance:- acceptedPersistedDisplayTranscript || hasValidProvenance- ? (expectedProvenance ?? undefined)- : undefined,- ...(pendingClarifyProjection- ? {- awaitingResponse: false,- sawAssistantPayload: true,- streamId: pendingClarifyProjection.streamId- }- : {}),- ...(clearedClarifyProjection- ? {- streamId: state.busy ? (clearedClarifyProjection.streamId ?? state.streamId) : null- }- : {})- }),+ state => {+ // #95595: the reconcilers above always produce fresh+ // message objects, so an unconditional publish replaces the+ // warm-cached array with new-object equivalents and every+ // visible row re-normalizes + remounts (markdown re-parse ++ // shiki re-highlight per row, seconds of main-thread work).+ // Keep the existing array when the content is unchanged —+ // same guard the cold-resume path uses below.+ const messages = preserveEquivalentTranscript(state.messages, visibleActivatedMessages)++ return {+ ...state,+ messages,+ transcriptProvenance:+ acceptedPersistedDisplayTranscript || hasValidProvenance+ ? (expectedProvenance ?? undefined)+ : undefined,+ ...(pendingClarifyProjection+ ? {+ awaitingResponse: false,+ sawAssistantPayload: true,+ streamId: pendingClarifyProjection.streamId+ }+ : {}),+ ...(clearedClarifyProjection+ ? {+ streamId: state.busy ? (clearedClarifyProjection.streamId ?? state.streamId) : null+ }+ : {})+ }+ },storedSessionId)diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.tsindex d5f76b14233..19bff08385d 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts@@ -26,6 +26,7 @@ import {goneSessionVerdict,isSessionGoneError,overlayConcurrentMessageChanges,+ preserveEquivalentTranscript,preserveLocalPendingTurnMessages,reconcileResumeMessages,removeRepresentedLocalLiveProjection,@@ -1717,3 +1718,43 @@ describe('overlayConcurrentMessageChanges', () => {])})})++describe('preserveEquivalentTranscript', () => {+ it('keeps the current array BY REFERENCE when the replacement is content-equivalent', () => {+ // The exact warm-resume shape of #95595: fresh objects, identical content.+ const current = [msg('u-1', 'user', 'hello'), msg('a-1', 'assistant', 'const x = 1')]+ const freshObjects = current.map(message => ({ ...message, parts: [...message.parts] }))++ const preserved = preserveEquivalentTranscript(current, freshObjects)++ expect(preserved).toBe(current)+ expect(preserved[0]).toBe(current[0])+ })++ it('keeps the current array when the arrays are the same reference', () => {+ const current = [msg('u-1', 'user', 'hello')]++ expect(preserveEquivalentTranscript(current, current)).toBe(current)+ })++ it('accepts the replacement when anything changed', () => {+ const current = [msg('u-1', 'user', 'hello')]+ const next = [msg('u-1', 'user', 'hello'), msg('a-1', 'assistant', 'new turn')]++ expect(preserveEquivalentTranscript(current, next)).toBe(next)+ })++ it('rejects the replacement when a message diverges in content', () => {+ const current = [msg('u-1', 'user', 'hello')]+ const next = [msg('u-1', 'user', 'hello world')]++ expect(preserveEquivalentTranscript(current, next)).toBe(next)+ })++ it('rejects the replacement when metadata a row renders diverges', () => {+ const current = [msg('u-1', 'user', 'hello')]+ const next = [msg('u-1', 'user', 'hello', { pending: true })]++ expect(preserveEquivalentTranscript(current, next)).toBe(next)+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex 113539132be..875b059ed23 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts@@ -298,6 +298,23 @@ export function chatMessageArraysEquivalent(a: ChatMessage[], b: ChatMessage[]):return a.length === b.length && a.every((message, index) => chatMessagesEquivalent(message, b[index]))}+/**+ * Keep the CURRENT array when the replacement is content-equivalent.+ *+ * The resume reconcilers create fresh `ChatMessage` objects via+ * `toChatMessages` even when nothing changed. Publishing those unconditionally+ * replaces the `$messages`/session-slice array with a new reference of fresh+ * objects — and because `useRuntimeMessageRepository` keys its normalization+ * cache (and React keys its rows) by object identity, every message in the+ * window re-normalizes and remounts: full markdown re-parse + shiki+ * re-highlight per row, on the main thread, per warm session switch (#95595).+ * Returning `current` when the content is equivalent keeps array AND object+ * identity, so the warm switch is O(1) paint.+ */+export function preserveEquivalentTranscript(current: ChatMessage[], next: ChatMessage[]): ChatMessage[] {+ return chatMessageArraysEquivalent(current, next) ? current : next+}+export function reconcileResumeMessages(nextMessages: ChatMessage[], previousMessages: ChatMessage[]): ChatMessage[] {if (!previousMessages.length) {return nextMessagesdiff --git a/apps/desktop/src/components/assistant-ui/thread/index.test.tsx b/apps/desktop/src/components/assistant-ui/thread/index.test.tsxnew file mode 100644index 00000000000..4bf2c822327--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/thread/index.test.tsx@@ -0,0 +1,82 @@+import { render } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'++/**+ * Issue #95595 proposed-fix #3: the `messageComponents` map handed to+ * ThreadMessageList must keep its REFERENCE IDENTITY across a session switch.+ * If it re-minted, React would unmount/remount every visible message — async+ * re-rendered parts (shiki code blocks) collapse and re-expand, and the whole+ * thread visibly jumps on every tab switch.+ *+ * The memo deps are deliberately only the boolean "definedness" gates (the+ * callbacks themselves reach the composer through a ref), so a plain switch+ * — sessionId changing, callbacks unchanged — must not change the map.+ */+let lastComponents: unknown++vi.mock('@/components/assistant-ui/thread/list', () => ({+ ThreadMessageList: (props: { components: unknown }) => {+ lastComponents = props.components++ return null+ }+}))++vi.mock('@/components/assistant-ui/thread/timeline', () => ({+ ThreadTimeline: () => null+}))++vi.mock('@/components/assistant-ui/thread/status', () => ({+ BackgroundResumeNotice: () => null,+ CenteredThreadSpinner: () => null+}))++vi.mock('@/i18n', () => ({+ useI18n: () => ({+ t: {+ assistant: {+ thread: {+ restoreBody: 'restore body',+ restoreConfirm: 'Restore',+ restoreTitle: 'Restore this turn?'+ }+ },+ common: {+ cancel: 'Cancel',+ confirm: 'Confirm',+ done: 'Done',+ loading: 'Loading'+ }+ }+ })+}))++import { Thread } from './index'++describe('Thread messageComponents identity across session switches', () => {+ it('does not re-mint messageComponents when only the session changes', () => {+ const { rerender } = render(<Thread sessionId="session-a" />)+ const first = lastComponents++ expect(first).toBeDefined()++ rerender(<Thread sessionId="session-b" />)++ // THE guard: a switch must keep the component map reference, so the+ // incoming transcript reconciles instead of remounting.+ expect(lastComponents).toBe(first)++ rerender(<Thread sessionId="session-c" />)++ expect(lastComponents).toBe(first)+ })++ it('keeps the map stable across a plain parent re-render', () => {+ const { rerender } = render(<Thread sessionId="session-a" />)+ const first = lastComponents++ rerender(<Thread sessionId="session-a" />)++ expect(lastComponents).toBe(first)+ })+})diff --git a/apps/desktop/src/components/chat/shiki-block.test.tsx b/apps/desktop/src/components/chat/shiki-block.test.tsxnew file mode 100644index 00000000000..26273a73e7f--- /dev/null+++ b/apps/desktop/src/components/chat/shiki-block.test.tsx@@ -0,0 +1,122 @@+import { cleanup, render, screen } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++/**+ * Perf regression guard for #95595: switching to a warm session remounts the+ * incoming transcript, and every mounted code block used to re-tokenize from+ * scratch on the main thread. The content-keyed cache must make a remount of+ * an unchanged block a cache hit — ZERO highlighter calls.+ *+ * shiki itself is mocked (jsdom cannot run the oniguruma wasm engine); the+ * mock counts `codeToHtml` invocations, which is the cost we are guarding.+ */+const { codeToHtml } = vi.hoisted(() => ({+ codeToHtml: vi.fn((code: string) => {+ const escaped = String(code).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')++ return `<pre class="shiki"><code>${escaped}</code></pre>`+ })+}))++vi.mock('shiki', () => ({+ bundledLanguages: { typescript: 'typescript-loader', text: 'text-loader' },+ getSingletonHighlighter: vi.fn(async () => ({+ codeToHtml: (code: string) => codeToHtml(code),+ getLoadedLanguages: () => ['text', 'typescript'],+ loadLanguage: vi.fn(async () => undefined)+ }))+}))++vi.mock('shiki/engine/oniguruma', () => ({+ createOnigurumaEngine: vi.fn(() => ({}) as never)+}))++import CachedShikiBlock from '@/components/chat/shiki-block'+import { highlightCache } from '@/components/chat/shiki-highlight-cache'++const TS_BLOCK = { language: 'typescript', code: 'const answer: number = 42\n' }++async function waitForHighlighted(): Promise<void> {+ await screen.findByTestId('shiki-container', undefined, { timeout: 2_000 })+}++beforeEach(() => {+ codeToHtml.mockClear()+ highlightCache.clear()+})++afterEach(() => {+ cleanup()+})++describe('CachedShikiBlock (warm-switch perf guard)', () => {+ it('highlights on first mount and reuses the cached HTML on remount', async () => {+ const { unmount } = render(<CachedShikiBlock {...TS_BLOCK} />)+ await waitForHighlighted()++ expect(codeToHtml).toHaveBeenCalledTimes(1)+ expect(screen.getByTestId('shiki-container').innerHTML).toContain('const answer')++ // Warm session switch: the row unmounts and the SAME block mounts again.+ unmount()+ render(<CachedShikiBlock {...TS_BLOCK} />)+ await waitForHighlighted()++ // The guard: remounting an unchanged block must NOT re-tokenize.+ expect(codeToHtml).toHaveBeenCalledTimes(1)+ })++ it('re-highlights a block whose code changed (cache miss)', async () => {+ const { unmount } = render(<CachedShikiBlock {...TS_BLOCK} />)+ await waitForHighlighted()++ unmount()+ render(<CachedShikiBlock code="const other = true\n" language="typescript" />)+ await waitForHighlighted()++ expect(codeToHtml).toHaveBeenCalledTimes(2)+ })++ it('keeps blocks independent: N blocks highlight N times across two mounts', async () => {+ const { unmount } = render(+ <>+ <CachedShikiBlock {...TS_BLOCK} />+ <CachedShikiBlock code="function two(): void {}\n" language="typescript" />+ </>+ )++ await screen.findAllByTestId('shiki-container', undefined, { timeout: 2_000 })++ expect(codeToHtml).toHaveBeenCalledTimes(2)++ unmount()+ render(+ <>+ <CachedShikiBlock {...TS_BLOCK} />+ <CachedShikiBlock code="function two(): void {}\n" language="typescript" />+ </>+ )+ await screen.findAllByTestId('shiki-container', undefined, { timeout: 2_000 })++ // Two mounts of the same two blocks: exactly two tokenizations total.+ expect(codeToHtml).toHaveBeenCalledTimes(2)+ })++ it('does not cache a failed highlight, so a retry can succeed', async () => {+ codeToHtml.mockRejectedValueOnce(new Error('boom'))++ const { unmount } = render(<CachedShikiBlock {...TS_BLOCK} />)+ await waitForHighlighted()++ // The failure degrades to escaped plain text (and is NOT cached).+ expect(screen.getByTestId('shiki-container').innerHTML).toContain('const answer')+ expect(codeToHtml).toHaveBeenCalledTimes(1)++ unmount()+ render(<CachedShikiBlock {...TS_BLOCK} />)+ await waitForHighlighted()++ // Second mount tries the highlighter again instead of serving stale HTML.+ expect(codeToHtml).toHaveBeenCalledTimes(2)+ })+})diff --git a/apps/desktop/src/components/chat/shiki-block.tsx b/apps/desktop/src/components/chat/shiki-block.tsxindex 4279d218356..aea72875e7c 100644--- a/apps/desktop/src/components/chat/shiki-block.tsx+++ b/apps/desktop/src/components/chat/shiki-block.tsx@@ -1,15 +1,185 @@'use client'/**- * The ONLY static importer of `react-shiki` (and through it the multi-MB- * shiki language/theme bundle). Every consumer reaches this module through+ * The ONLY static importer of shiki (and through it the multi-MB shiki+ * language/theme/wasm bundle). Every consumer reaches this module through* `React.lazy(() => import('./shiki-block'))` — see `LazyShiki` in* shiki-highlighter.tsx — so the shiki chunk stays entirely off the* cold-start path and loads on the first highlighted code block instead.** Do NOT import this module statically from anything the entry graph* reaches, or the chunk moves back into boot.+ *+ * Unlike the previous pass-through of `react-shiki`'s component, this module+ * is cache-aware: highlighted output is stored in a module-level LRU cache+ * keyed by (theme scope, language, code), so a REMOUNT of an unchanged code+ * block (the warm-session-switch path of #95595) paints the cached HTML+ * synchronously and never re-tokenizes. Only cache misses run shiki, and+ * misses are debounced so a streaming block settles before the heavy work+ * starts.+ */+import { useEffect, useMemo, useState } from 'react'+import { bundledLanguages, getSingletonHighlighter } from 'shiki'+import type { BundledLanguage, BundledTheme, Highlighter } from 'shiki'+import { createOnigurumaEngine } from 'shiki/engine/oniguruma'++import {+ SHIKI_HIGHLIGHT_SCOPE,+ SHIKI_THEME+} from '@/components/chat/shiki-config'+import { highlightCache, highlightCacheKey } from '@/components/chat/shiki-highlight-cache'++/** Same debounce react-shiki's `delay` used to throttle highlight work with. */+const HIGHLIGHT_DELAY_MS = 120++// Stable identity for "no color replacements" so the memo/effect deps below+// never churn on renders that don't pass the prop.+const NO_COLOR_REPLACEMENTS: Record<string, Record<string, string>> = {}++export interface CachedShikiBlockProps {+ language: string+ code: string+ /** Theme override; defaults to the shared SHIKI_THEME. */+ theme?: { dark: string; light: string }+ /** Color replacements; defaults to none (the chat passes its own). */+ colorReplacements?: Record<string, Record<string, string>>+}++function isLoadableLanguage(language: string): boolean {+ return language === 'text' || language in bundledLanguages+}++/**+ * Cache scope for one theme configuration. Part of the cache key: a block+ * highlighted under a different theme is a different render.+ */+function highlightScope(+ theme: { dark: string; light: string },+ colorReplacements: Record<string, Record<string, string>>+): string {+ return `${SHIKI_HIGHLIGHT_SCOPE}:${theme.dark}:${theme.light}:${JSON.stringify(colorReplacements)}`+}++let highlighterPromise: Promise<Highlighter> | null = null+let loadedThemes = new Set<string>([SHIKI_THEME.dark, SHIKI_THEME.light])++/**+ * Lazily-created shiki singleton, mirroring react-shiki's full bundle: only+ * the languages actually seen are loaded into it (the singleton is created+ * with the first block's language, later ones are `loadLanguage`d on demand;+ * override themes are `loadTheme`d the same way). Unknown languages are left+ * unloaded and fall through to shiki's plain-text handling, as before.*/-import ShikiHighlighter from 'react-shiki'+async function highlightToHtml(+ language: string,+ code: string,+ theme: { dark: string; light: string },+ colorReplacements: Record<string, Record<string, string>>+): Promise<string> {+ if (!highlighterPromise) {+ highlighterPromise = getSingletonHighlighter({+ // Only bundled languages are ever passed here (isLoadableLanguage+ // guards both call sites), so the cast is safe.+ langs: isLoadableLanguage(language) ? [language as BundledLanguage] : [],+ themes: [SHIKI_THEME.dark, SHIKI_THEME.light],+ engine: createOnigurumaEngine(import('shiki/wasm'))+ })+ }++ const highlighter = await highlighterPromise++ if (isLoadableLanguage(language) && !highlighter.getLoadedLanguages().includes(language)) {+ await highlighter.loadLanguage(language as BundledLanguage)+ }++ const missingThemes = [theme.dark, theme.light].filter(name => !loadedThemes.has(name))++ if (missingThemes.length > 0) {+ await highlighter.loadTheme(...(missingThemes as BundledTheme[]))+ missingThemes.forEach(name => loadedThemes.add(name))+ }++ return highlighter.codeToHtml(code, {+ lang: language,+ themes: { dark: theme.dark, light: theme.light },+ defaultColor: 'light-dark()',+ colorReplacements+ })+}++function escapeHtml(text: string): string {+ return text+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+}++/** Never let a highlight failure blank a block — degrade to escaped plain text. */+function plainTextHtml(code: string): string {+ return `<pre class="shiki" style="background-color:transparent;margin:0"><code>${escapeHtml(code)}</code></pre>`+}++export default function CachedShikiBlock({+ language,+ code,+ theme,+ colorReplacements+}: CachedShikiBlockProps) {+ const themeConfig = theme ?? SHIKI_THEME+ const replacements = colorReplacements ?? NO_COLOR_REPLACEMENTS++ const cacheKey = useMemo(+ () => highlightCacheKey(highlightScope(themeConfig, replacements), language, code),+ [language, code, replacements, themeConfig]+ )++ const [html, setHtml] = useState<string | null>(() => highlightCache.get(cacheKey) ?? null)++ useEffect(() => {+ let cancelled = false++ // Cache hit — no highlighter work at all. This is the warm-switch path:+ // the previous visit already rendered this block, so paint it again.+ const cached = highlightCache.get(cacheKey)++ if (cached !== undefined) {+ setHtml(cached)++ return+ }++ const timer = window.setTimeout(() => {+ highlightToHtml(language, code, themeConfig, replacements)+ .then(result => {+ if (cancelled) {+ return+ }++ highlightCache.set(cacheKey, result)+ setHtml(result)+ })+ .catch(error => {+ if (cancelled) {+ return+ }++ console.error('shiki highlight failed; rendering plain code', error)+ setHtml(plainTextHtml(code))+ })+ }, HIGHLIGHT_DELAY_MS)++ return () => {+ cancelled = true+ window.clearTimeout(timer)+ }+ }, [cacheKey, code, language, replacements, themeConfig])++ if (html === null) {+ // Nothing to paint yet (miss, debounce pending). Matches react-shiki's+ // own empty render while the highlight is in flight.+ return null+ }-export default ShikiHighlighter+ return <div className="rs-root not-prose" dangerouslySetInnerHTML={{ __html: html }} data-testid="shiki-container" />+}diff --git a/apps/desktop/src/components/chat/shiki-config.ts b/apps/desktop/src/components/chat/shiki-config.tsnew file mode 100644index 00000000000..4ba81aaf069--- /dev/null+++ b/apps/desktop/src/components/chat/shiki-config.ts@@ -0,0 +1,33 @@+// Shiki theme/color constants shared by the chat code-block renderer+// (shiki-highlighter.tsx) and the lazy shiki chunk (shiki-block.tsx). Kept in+// their own dependency-free module so the lazy chunk can import them without+// pulling the main chat module (or react-shiki) into the shiki bundle.++// `github-dark-dimmed` is GitHub's lower-contrast dark palette — the vivid+// `github-dark-default` tokens read harsh at our small code size. Shared by the+// inline diff renderer too (see diff-lines.tsx) so code + diffs match.+export const SHIKI_THEME = { dark: 'github-dark-dimmed', light: 'github-light-default' } as const++/**+ * `github-light-default` colors comments `#6e7781` (~4.2:1 against the code+ * card background) — borderline unreadable at our 11px code size, and worst of+ * all for shell snippets where a single `#` turns the rest of the line into one+ * long comment span. Remap light-mode comments to GitHub's darker muted gray+ * (`#57606a`, ~6.4:1). Dark mode (`#8b949e`, ~6.1:1) already reads fine, so we+ * leave it untouched. Keyed per theme name so the bump only applies in light.+ */+export const SHIKI_COLOR_REPLACEMENTS: Record<string, Record<string, string>> = {+ 'github-light-default': { '#6e7781': '#57606a' }+}++/**+ * Cache-key scope for the content-addressed highlight cache. Bumping this+ * invalidates every cached highlight at once — bump it whenever the rendering+ * options (themes, color replacements) change, because keys are NOT allowed to+ * silently produce a different DOM than the one they were computed with.+ */+export const SHIKI_HIGHLIGHT_SCOPE = `hermes-shiki-v1:${JSON.stringify({+ dark: SHIKI_THEME.dark,+ light: SHIKI_THEME.light,+ colorReplacements: SHIKI_COLOR_REPLACEMENTS+})}`diff --git a/apps/desktop/src/components/chat/shiki-highlight-cache.test.ts b/apps/desktop/src/components/chat/shiki-highlight-cache.test.tsnew file mode 100644index 00000000000..77dde0d9412--- /dev/null+++ b/apps/desktop/src/components/chat/shiki-highlight-cache.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from 'vitest'++import {+ HIGHLIGHT_CACHE_MAX_CHARS,+ HIGHLIGHT_CACHE_MAX_ENTRIES,+ HighlightCache,+ highlightCacheKey+} from '@/components/chat/shiki-highlight-cache'++describe('highlightCacheKey', () => {+ it('separates scope, language and code so distinct blocks never collide', () => {+ const a = highlightCacheKey('scope-1', 'ts', 'const x = 1')+ const b = highlightCacheKey('scope-1', 'ts', 'const x = 2')++ expect(a).not.toBe(b)+ expect(highlightCacheKey('scope-1', 'js', 'const x = 1')).not.toBe(a)+ expect(highlightCacheKey('scope-2', 'ts', 'const x = 1')).not.toBe(a)+ })+})++describe('HighlightCache', () => {+ it('round-trips an entry and refreshes recency on get', () => {+ const cache = new HighlightCache(3, 1000)++ cache.set('a', 'A')+ cache.set('b', 'B')+ cache.set('c', 'C')+ // Touch the oldest entry so it becomes the newest.+ expect(cache.get('a')).toBe('A')+ cache.set('d', 'D')++ // 'b' is now the least recently used and must be evicted first.+ expect(cache.has('b')).toBe(false)+ expect(cache.get('a')).toBe('A')+ expect(cache.get('c')).toBe('C')+ expect(cache.get('d')).toBe('D')+ })++ it('evicts oldest-first past the entry cap', () => {+ const cache = new HighlightCache(2, 1_000_000)++ cache.set('a', 'A')+ cache.set('b', 'B')+ cache.set('c', 'C')++ expect(cache.size).toBe(2)+ expect(cache.has('a')).toBe(false)+ expect(cache.has('b')).toBe(true)+ expect(cache.has('c')).toBe(true)+ })++ it('evicts oldest-first past the total-char cap', () => {+ const cache = new HighlightCache(HIGHLIGHT_CACHE_MAX_ENTRIES, 10)++ cache.set('a', '12345')+ cache.set('b', '123456')++ expect(cache.size).toBe(1)+ expect(cache.has('a')).toBe(false)+ expect(cache.has('b')).toBe(true)+ expect(cache.totalChars).toBeLessThanOrEqual(10)+ })++ it('replaces an existing key in place without double-counting chars', () => {+ const cache = new HighlightCache(2, 100)++ cache.set('a', '12345')+ cache.set('a', '1234567890')++ expect(cache.size).toBe(1)+ expect(cache.totalChars).toBe(10)+ })++ it('stays within both caps for a large burst of unique blocks', () => {+ const cache = new HighlightCache(HIGHLIGHT_CACHE_MAX_ENTRIES, HIGHLIGHT_CACHE_MAX_CHARS)++ for (let i = 0; i < 2_000; i++) {+ cache.set(`block-${i}`, `html-${i}`.repeat(100))+ }++ expect(cache.size).toBeLessThanOrEqual(HIGHLIGHT_CACHE_MAX_ENTRIES)+ expect(cache.totalChars).toBeLessThanOrEqual(HIGHLIGHT_CACHE_MAX_CHARS)+ })++ it('clear drops everything', () => {+ const cache = new HighlightCache()++ cache.set('a', 'A')+ cache.clear()++ expect(cache.size).toBe(0)+ expect(cache.totalChars).toBe(0)+ expect(cache.get('a')).toBeUndefined()+ })+})diff --git a/apps/desktop/src/components/chat/shiki-highlight-cache.ts b/apps/desktop/src/components/chat/shiki-highlight-cache.tsnew file mode 100644index 00000000000..3b0b7fe93bb--- /dev/null+++ b/apps/desktop/src/components/chat/shiki-highlight-cache.ts@@ -0,0 +1,90 @@+// ── Content-addressed syntax-highlight cache (#95595) ────────────────────────+// Switching to a warm session remounts the incoming transcript, and every+// mounted code block used to be re-tokenized from scratch by shiki — N blocks+// × full tokenization on the renderer main thread, on every switch, even+// though the code had not changed. The fix is a module-level LRU cache keyed+// by (scope, language, code) holding the final highlighted HTML, so a remount+// of an unchanged block paints the cached markup synchronously and never+// touches the highlighter.+//+// Bounds: shiki's tokenized HTML is ~5-10x the source size, so an unbounded+// cache would leak renderer memory over a long session list. Cap both the+// entry count and the total cached characters; evict oldest-first.+//+// This module is intentionally dependency-free (no React, no shiki) so the+// cache logic can be unit-tested in isolation.++export const HIGHLIGHT_CACHE_MAX_ENTRIES = 512+export const HIGHLIGHT_CACHE_MAX_CHARS = 6 * 1024 * 1024++/** Unique key for one highlighted block: scope + language + exact code. */+export function highlightCacheKey(scope: string, language: string, code: string): string {+ return `${scope}\u0000${language}\u0000${code}`+}++/**+ * Bounded LRU map of highlight cache keys to rendered HTML. `get` refreshes+ * recency (Map insertion order is used as the LRU clock); `set` evicts the+ * oldest entries until both caps hold.+ */+export class HighlightCache {+ private readonly entries = new Map<string, string>()+ private chars = 0++ constructor(+ private readonly maxEntries: number = HIGHLIGHT_CACHE_MAX_ENTRIES,+ private readonly maxChars: number = HIGHLIGHT_CACHE_MAX_CHARS+ ) {}++ get size(): number {+ return this.entries.size+ }++ get totalChars(): number {+ return this.chars+ }++ has(key: string): boolean {+ return this.entries.has(key)+ }++ get(key: string): string | undefined {+ const value = this.entries.get(key)++ if (value !== undefined) {+ // Refresh recency: re-inserting moves the entry to the newest position.+ this.entries.delete(key)+ this.entries.set(key, value)+ }++ return value+ }++ set(key: string, html: string): void {+ if (this.entries.has(key)) {+ this.chars -= this.entries.get(key)!.length+ this.entries.delete(key)+ }++ this.entries.set(key, html)+ this.chars += html.length+ this.evict()+ }++ clear(): void {+ this.entries.clear()+ this.chars = 0+ }++ private evict(): void {+ while ((this.entries.size > this.maxEntries || this.chars > this.maxChars) && this.entries.size > 0) {+ const oldestKey = this.entries.keys().next().value as string+ const oldest = this.entries.get(oldestKey)!+ this.entries.delete(oldestKey)+ this.chars -= oldest.length+ }+ }+}++/** The renderer-wide highlight cache. Lives for the lifetime of the module. */+export const highlightCache = new HighlightCache()diff --git a/apps/desktop/src/components/chat/shiki-highlighter.tsx b/apps/desktop/src/components/chat/shiki-highlighter.tsxindex 6823bba7cfd..dcb27bd9a1c 100644--- a/apps/desktop/src/components/chat/shiki-highlighter.tsx+++ b/apps/desktop/src/components/chat/shiki-highlighter.tsx@@ -1,15 +1,20 @@'use client'import type { SyntaxHighlighterProps } from '@assistant-ui/react-streamdown'-import { type ComponentProps, type FC, lazy, Suspense, useMemo } from 'react'-import type ShikiHighlighter from 'react-shiki'+import { type FC, lazy, Suspense, useMemo } from 'react'import { CodeCard, CodeCardBody } from '@/components/chat/code-card'import { ExpandableBlock } from '@/components/chat/expandable-block'+// Theme constants live in shiki-config (dependency-free) so the lazy shiki+// chunk can import them without pulling this module into the shiki bundle.+import { SHIKI_COLOR_REPLACEMENTS } from '@/components/chat/shiki-config'import { CopyButton } from '@/components/ui/copy-button'import { useI18n } from '@/i18n'import { isLikelyProseCodeBlock } from '@/lib/markdown-code'+import type { CachedShikiBlockProps } from './shiki-block'+export { SHIKI_COLOR_REPLACEMENTS, SHIKI_THEME } from '@/components/chat/shiki-config'+/*** Streamdown's code adapter renders header + body as inline siblings, so we* own the wrapping `<CodeCard>` here and neutralize the upstream@@ -17,46 +22,34 @@ import { isLikelyProseCodeBlock } from '@/lib/markdown-code'* background-only — no header row, no language label — so a fence reads as a* tinted slab of the reply; copy is a hover-reveal control in the corner.*- * `react-shiki` full bundle so all `bundledLanguages` work; theme switches- * follow the document `color-scheme` via `defaultColor="light-dark()"`.+ * The heavy lifting lives in the lazy `shiki-block` chunk (full bundle so all+ * `bundledLanguages` work; theme switches follow the document `color-scheme`+ * via `defaultColor="light-dark()"`), and its output is cached by content so+ * warm-session switches never re-tokenize unchanged blocks (#95595).*/interface HermesSyntaxHighlighterProps extends SyntaxHighlighterProps {defer?: boolean}-// `github-dark-dimmed` is GitHub's lower-contrast dark palette — the vivid-// `github-dark-default` tokens read harsh at our small code size. Shared by the-// inline diff renderer too (see diff-lines.tsx) so code + diffs match.-export const SHIKI_THEME = { dark: 'github-dark-dimmed', light: 'github-light-default' } as const--/**- * `github-light-default` colors comments `#6e7781` (~4.2:1 against the code- * card background) — borderline unreadable at our 11px code size, and worst of- * all for shell snippets where a single `#` turns the rest of the line into one- * long comment span. Remap light-mode comments to GitHub's darker muted gray- * (`#57606a`, ~6.4:1). Dark mode (`#8b949e`, ~6.1:1) already reads fine, so we- * leave it untouched. Keyed per theme name so the bump only applies in light.- */-const SHIKI_COLOR_REPLACEMENTS: Record<string, Record<string, string>> = {- 'github-light-default': { '#6e7781': '#57606a' }-}-const MAX_HIGHLIGHT_CHARS = 150_000const MAX_HIGHLIGHT_LINES = 3_000const CHUNK_LINES = 200const EST_LINE_PX = 16-// react-shiki (and through it the multi-MB shiki grammar/theme bundle) is the+// shiki (and through it the multi-MB grammar/theme/wasm bundle) is the// heaviest dependency in the renderer. `shiki-block.tsx` is its only static// importer, so this lazy() is the single seam that keeps shiki out of the// entry chunk — it loads on the first highlighted code block, not at boot.+// The lazy module is cache-aware (#95595): unchanged blocks paint from a+// content-keyed cache instead of re-tokenizing on every mount.const ShikiBlock = lazy(() => import('./shiki-block'))-/** Drop-in ShikiHighlighter that suspends on first use and renders the code- * as plain preformatted text until the shiki chunk arrives. */-export const LazyShiki: FC<ComponentProps<typeof ShikiHighlighter>> = props => (- <Suspense fallback={<PlainCode code={String(props.children ?? '')} />}>- <ShikiBlock {...props} />+/** Suspends on first use and renders the code as plain preformatted text+ * until the shiki chunk arrives. Highlighted output is cached by+ * (theme, language, code), so revisits never re-tokenize (#95595). */+export const LazyShiki: FC<CachedShikiBlockProps> = ({ language, code, theme, colorReplacements }) => (+ <Suspense fallback={<PlainCode code={code} />}>+ <ShikiBlock code={code} colorReplacements={colorReplacements} language={language} theme={theme} /></Suspense>)@@ -160,18 +153,7 @@ export const SyntaxHighlighter: FC<HermesSyntaxHighlighterProps> = ({{plain ? (<PlainCode code={trimmed} />) : (- <LazyShiki- addDefaultStyles={false}- as="div"- colorReplacements={SHIKI_COLOR_REPLACEMENTS}- defaultColor="light-dark()"- delay={120}- language={language || 'text'}- showLanguage={false}- theme={SHIKI_THEME}- >- {trimmed}- </LazyShiki>+ <LazyShiki code={trimmed} colorReplacements={SHIKI_COLOR_REPLACEMENTS} language={language || 'text'} />)}</Pre></ExpandableBlock>