From 6e4e15c5fc0d3431042b9600e9a5da1c48aa5f77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=92=89=E8=90=81?= Date: Mon, 24 Aug 2026 18:21:08 +0800 Subject: [PATCH 1/5] fix(web-shell): reduce streaming thought render jank --- ...eb-shell-collapsed-thinking-performance.md | 43 +++++ packages/web-shell/client/App.test.tsx | 1 + packages/web-shell/client/App.tsx | 158 +++++++++++++----- .../components/messages/ToolGroup.test.tsx | 25 ++- .../client/components/messages/ToolGroup.tsx | 156 +++++++++-------- .../messages/tools/ToolChrome.module.css | 5 - ...useAnimationFrameTranscriptBlocks.test.tsx | 33 +++- .../useAnimationFrameTranscriptBlocks.ts | 47 +++++- .../client/hooks/useMessages.test.ts | 117 +++++++++---- .../web-shell/client/hooks/useMessages.ts | 31 +++- 10 files changed, 445 insertions(+), 171 deletions(-) create mode 100644 docs/design/web-shell-collapsed-thinking-performance.md diff --git a/docs/design/web-shell-collapsed-thinking-performance.md b/docs/design/web-shell-collapsed-thinking-performance.md new file mode 100644 index 00000000000..e78b51a4264 --- /dev/null +++ b/docs/design/web-shell-collapsed-thinking-performance.md @@ -0,0 +1,43 @@ +# Web Shell collapsed thinking performance + +## Problem + +Pure assistant and thought tail appends wake the top-level `App`, even though +only the transcript row needs the new text. Compact activity summaries also +keep their complete tool and thought subtree mounted while collapsed, so hidden +rows continue reconciling streamed thought props. + +## Design + +The top-level app consumes a structural transcript snapshot. A store change +summary proves when an update is only an append to the active assistant or +thought block; those app-level notifications are ignored. Stores without a +change summary retain the existing behavior. + +The message list separately consumes the live throttled snapshot and applies +the existing streaming-tail projector against the app's latest structural +messages. This updates only the visible tail without starting a second +background-agent reconciliation loop. Structural changes still flow through +the app and replace the baseline immediately. Insight protocol markers use a +full projection while retaining the unchanged message prefix. + +Compact tool summaries mount their detail subtree only while expanded. The +summary button remains live while collapsed; expanding reconstructs the current +tool and thought rows from props. Collapse is immediate so the hidden subtree +stops work without waiting for an exit animation. + +## Compatibility + +Tool, permission, terminal, reset, history, and session changes remain +structural. Transcript callbacks continue receiving live snapshots from the +message-list boundary. Collapsing a compact group no longer preserves local +expanded state inside its hidden detail rows. + +## Verification + +- Prove structural snapshots ignore pure tail appends and resume on the next + structural change. +- Prove a collapsed compact group has no detail subtree and restores current + details when expanded. +- Run the deterministic folded-thought performance scenario and targeted unit + tests. diff --git a/packages/web-shell/client/App.test.tsx b/packages/web-shell/client/App.test.tsx index e7b59201470..6378bd7d5d0 100644 --- a/packages/web-shell/client/App.test.tsx +++ b/packages/web-shell/client/App.test.tsx @@ -586,6 +586,7 @@ vi.mock('@qwen-code/sdk/daemon', () => { }); vi.mock('./hooks/useMessages', () => ({ + projectStreamingTailMessages: () => undefined, useMessages: () => testState.messages, useMessagesFromBlocks: () => testState.messages, })); diff --git a/packages/web-shell/client/App.tsx b/packages/web-shell/client/App.tsx index d2091847344..ebc96bdc211 100644 --- a/packages/web-shell/client/App.tsx +++ b/packages/web-shell/client/App.tsx @@ -1,6 +1,8 @@ import './styles/globals.css'; import { createContext, + forwardRef, + memo, useCallback, useEffect, useLayoutEffect, @@ -8,6 +10,7 @@ import { useRef, useState, type CSSProperties, + type ComponentPropsWithoutRef, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode, @@ -42,6 +45,7 @@ import type { DaemonInputAnnotation, DaemonSessionAgentTaskStatus, DaemonSkillToggleMutation, + DaemonTranscriptBlockChangeSummary, DaemonTranscriptBlock, DaemonSessionMonitorTaskStatus, DaemonSessionShellTaskStatus, @@ -212,7 +216,10 @@ import { mergeCommands } from './hooks/daemonSessionMappers'; import { useAnimationFrameTranscriptSnapshot } from './hooks/useAnimationFrameTranscriptBlocks'; import { useBackgroundTasks } from './hooks/useBackgroundTasks'; import { isSessionDisconnectedError } from './utils/sessionErrors'; -import { useMessagesFromBlocks } from './hooks/useMessages'; +import { + projectStreamingTailMessages, + useMessagesFromBlocks, +} from './hooks/useMessages'; import { useSessionArtifacts } from './hooks/useSessionArtifacts'; import { useShallowMemo, useStableArray } from './hooks/useShallowMemo'; import { @@ -837,6 +844,97 @@ interface LocalAnchoredMessage { message: Message; } +function buildDisplayMessages( + messages: Message[], + recapMessage: LocalAnchoredMessage | null, +): Message[] { + if (!recapMessage) return filterModelSwitchMessages(messages); + const result = [...messages]; + const anchorIndex = recapMessage.anchorAfterId + ? result.findIndex((message) => message.id === recapMessage.anchorAfterId) + : -1; + result.splice( + anchorIndex >= 0 + ? anchorIndex + 1 + : Math.min(recapMessage.anchorIndex, result.length), + 0, + recapMessage.message, + ); + return filterModelSwitchMessages(result); +} + +type LiveMessageListProps = Omit< + ComponentPropsWithoutRef, + 'messages' | 'transcriptBlockCount' +> & { + baselineBlocks: readonly DaemonTranscriptBlock[]; + baselineSummary?: DaemonTranscriptBlockChangeSummary; + baselineMessages: Message[]; + recapMessage: LocalAnchoredMessage | null; + messagesRef: { current: Message[] }; + onTranscriptChange?: (blocks: readonly DaemonTranscriptBlock[]) => void; + t: ReturnType; +}; + +const LiveMessageList = memo( + forwardRef(function LiveMessageList( + { + baselineBlocks, + baselineSummary, + baselineMessages, + recapMessage, + messagesRef, + onTranscriptChange, + t, + ...props + }, + ref, + ) { + const live = useAnimationFrameTranscriptSnapshot(); + const messages = useMemo( + () => + projectStreamingTailMessages( + { + blocks: baselineBlocks, + messages: baselineMessages, + t, + blockChangeSummary: baselineSummary, + }, + live.blocks, + t, + live.blockChangeSummary, + ) ?? baselineMessages, + [ + baselineBlocks, + baselineMessages, + baselineSummary, + live.blockChangeSummary, + live.blocks, + t, + ], + ); + const displayMessages = useMemo( + () => buildDisplayMessages(messages, recapMessage), + [messages, recapMessage], + ); + useLayoutEffect(() => { + messagesRef.current = messages; + }, [messages, messagesRef]); + useEffect(() => { + onTranscriptChange?.(live.blocks); + }, [live.blocks, onTranscriptChange]); + + return ( + + ); + }), +); + interface ModelSwitchSummary { authType: string; modelId: string; @@ -2189,7 +2287,9 @@ export function App({ const CustomComposerHeader = renderComposerHeader; const CustomComposerFooter = renderComposerFooter; const store = useTranscriptStore(); - const { blocks, blockChangeSummary } = useAnimationFrameTranscriptSnapshot(); + const { blocks, blockChangeSummary } = useAnimationFrameTranscriptSnapshot({ + structuralOnly: true, + }); const connection = useConnection(); const logicalSessionKey = getLogicalSessionKey( connection.sessionId, @@ -2617,7 +2717,9 @@ export function App({ const messages = useMessagesFromBlocks(t, blocks, blockChangeSummary); const messagesRef = useRef(messages); - messagesRef.current = messages; + useLayoutEffect(() => { + messagesRef.current = messages; + }, [messages]); const [failedPrompt, setFailedPrompt] = useState(null); const failedPromptRef = useRef(failedPrompt); const [failedPromptRetry, setFailedPromptRetry] = @@ -2689,31 +2791,10 @@ export function App({ const lastNotifiedSessionIdRef = useRef(undefined); const lastNotifiedWorkspaceIdRef = useRef(undefined); const lastNotifiedWorkspaceCwdRef = useRef(undefined); - const displayMessages = useMemo(() => { - const localMessages = [recapMessage].filter( - (message): message is LocalAnchoredMessage => message !== null, - ); - if (localMessages.length === 0) { - return filterModelSwitchMessages(messages); - } - - const result = [...messages]; - for (const localMessage of localMessages.sort( - (a, b) => a.anchorIndex - b.anchorIndex, - )) { - const anchorIndex = localMessage.anchorAfterId - ? result.findIndex( - (message) => message.id === localMessage.anchorAfterId, - ) - : -1; - const index = - anchorIndex >= 0 - ? anchorIndex + 1 - : Math.min(localMessage.anchorIndex, result.length); - result.splice(index, 0, localMessage.message); - } - return filterModelSwitchMessages(result); - }, [messages, recapMessage]); + const displayMessages = useMemo( + () => buildDisplayMessages(messages, recapMessage), + [messages, recapMessage], + ); useEffect(() => { const failed = failedPromptRef.current; if (!failed) return; @@ -6820,8 +6901,9 @@ export function App({ if (sessionWriteBlocked) return; if (!requireActiveSessionForLocalCommand()) return; const messageId = `local-recap-${nextRecapMessageIdRef.current++}`; - const anchorIndex = messages.length; - const anchorAfterId = messages.at(-1)?.id; + const currentMessages = messagesRef.current; + const anchorIndex = currentMessages.length; + const anchorAfterId = currentMessages.at(-1)?.id; const sessionId = connection.sessionId; const workspaceCwd = connection.workspaceCwd; setRecapMessage({ @@ -6871,7 +6953,6 @@ export function App({ }, [ connection.sessionId, connection.workspaceCwd, - messages, requireActiveSessionForLocalCommand, sessionWriteBlocked, sessionActions, @@ -7830,10 +7911,6 @@ export function App({ onConnectionChange?.(connection.status); }, [connection.status, onConnectionChange]); - useEffect(() => { - onTranscriptChange?.(blocks); - }, [blocks, onTranscriptChange]); - useEffect(() => { if (connection.error) { const error = new Error(connection.error); @@ -12794,9 +12871,15 @@ export function App({ .join(' '); const messageListContent = ( - { args: { file_path: 'README.md' }, }), ]); + act(() => container.querySelector('button')?.click()); expect(container.textContent).toContain('Shell'); expect(container.textContent).toContain('查询用户工作空间列表'); @@ -998,6 +999,7 @@ describe('tool row rendering', () => { }, }), ]); + act(() => container.querySelector('button')?.click()); const titleRow = container.querySelector('[class*="expandedCardTitleRow"]'); expect(titleRow).not.toBeNull(); @@ -1012,6 +1014,7 @@ describe('tool row rendering', () => { content: [{ type: 'content', content: { text: 'Permission denied' } }], }), ]); + act(() => container.querySelector('button')?.click()); const titleRow = container.querySelector('[class*="expandedCardTitleRow"]'); expect(titleRow).not.toBeNull(); @@ -1022,6 +1025,7 @@ describe('tool row rendering', () => { const container = renderToolGroup([ makeTool({ toolName: 'glob', status: 'failed' }), ]); + act(() => container.querySelector('button')?.click()); const titleRow = container.querySelector('[class*="expandedCardTitleRow"]'); expect(titleRow).not.toBeNull(); @@ -1805,19 +1809,19 @@ describe('thinking rows in the compact summary', () => { true, ); const outerSummary = container.querySelector('button')!; - const parallelSummary = Array.from( - container.querySelectorAll('button'), - ).find((button) => button.textContent?.includes('Parallel agents'))!; expect(outerSummary.textContent).toContain('Ran 2 agents'); expect( container.querySelector('[data-testid="compact-parallel-agents"]'), - ).not.toBeNull(); + ).toBeNull(); expect(outerSummary.getAttribute('aria-expanded')).toBe('false'); - expect(parallelSummary.getAttribute('aria-expanded')).toBe('false'); act(() => outerSummary.click()); + const parallelSummary = Array.from( + container.querySelectorAll('button'), + ).find((button) => button.textContent?.includes('Parallel agents'))!; expect(outerSummary.getAttribute('aria-expanded')).toBe('true'); + expect(parallelSummary.getAttribute('aria-expanded')).toBe('false'); expect(parallelSummary.textContent).toContain('2/2 done'); act(() => parallelSummary.click()); @@ -1841,6 +1845,15 @@ describe('thinking rows in the compact summary', () => { expect(container.querySelector('button')?.textContent).toContain( 'Thinking', ); + expect( + container.querySelector('[class*="chatSummaryThoughtHeader"]'), + ).toBeNull(); + + act(() => container.querySelector('button')?.click()); + + expect( + container.querySelector('[class*="chatSummaryThoughtHeader"]'), + ).not.toBeNull(); }); it('renders a completed thought line that expands its content on click', () => { @@ -2032,8 +2045,8 @@ describe('thinking rows in the compact summary', () => { ], ); + act(() => container.querySelector('button')?.click()); act(() => { - container.querySelector('button')?.click(); for (const header of container.querySelectorAll( '[data-testid="compact-thinking-summary"]', )) { diff --git a/packages/web-shell/client/components/messages/ToolGroup.tsx b/packages/web-shell/client/components/messages/ToolGroup.tsx index e65de21baab..86408dea790 100644 --- a/packages/web-shell/client/components/messages/ToolGroup.tsx +++ b/packages/web-shell/client/components/messages/ToolGroup.tsx @@ -1811,89 +1811,85 @@ export const ToolGroup = memo(function ToolGroup({ aria-hidden="true" /> -
-
-
- {tools.map((tool) => { - if (groupedAgentCallIds.has(tool.callId)) return null; - const parallelAgents = parallelAgentsByFirstCallId.get( - tool.callId, - ); - return ( - - {thoughts - ?.filter( - (thought) => thought.beforeToolCallId === tool.callId, - ) - .map((thought, index) => ( - - ))} - {parallelAgents ? ( - <> -
- +
+
+ {tools.map((tool) => { + if (groupedAgentCallIds.has(tool.callId)) return null; + const parallelAgents = parallelAgentsByFirstCallId.get( + tool.callId, + ); + return ( + + {thoughts + ?.filter( + (thought) => thought.beforeToolCallId === tool.callId, + ) + .map((thought, index) => ( + -
- {parallelAgents - .slice(1) - .flatMap((agent) => - thoughts - ?.filter( - (thought) => - thought.beforeToolCallId === agent.callId, - ) - .map((thought, index) => ( - - )), - )} - - ) : ( - - )} - - ); - })} - {thoughts - ?.filter((thought) => thought.beforeToolCallId === undefined) - .map((thought, index) => ( - - ))} + ))} + {parallelAgents ? ( + <> +
+ +
+ {parallelAgents + .slice(1) + .flatMap((agent) => + thoughts + ?.filter( + (thought) => + thought.beforeToolCallId === agent.callId, + ) + .map((thought, index) => ( + + )), + )} + + ) : ( + + )} + + ); + })} + {thoughts + ?.filter((thought) => thought.beforeToolCallId === undefined) + .map((thought, index) => ( + + ))} +
-
+ )}
); } diff --git a/packages/web-shell/client/components/messages/tools/ToolChrome.module.css b/packages/web-shell/client/components/messages/tools/ToolChrome.module.css index 9757c0799d6..f8c5c528237 100644 --- a/packages/web-shell/client/components/messages/tools/ToolChrome.module.css +++ b/packages/web-shell/client/components/messages/tools/ToolChrome.module.css @@ -398,11 +398,6 @@ grid-template-rows: 1fr; min-height: 0; overflow: hidden; - transition: grid-template-rows 180ms ease; -} - -.chatSummaryContentCollapsed { - grid-template-rows: 0fr; } .chatSummaryContentInner { diff --git a/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx b/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx index d38aa62a7a5..eb62b0ea522 100644 --- a/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx +++ b/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx @@ -93,8 +93,8 @@ let renderLog: Array<{ revision?: number; }> = []; -function Harness() { - const snapshot = useAnimationFrameTranscriptSnapshot(); +function Harness({ structuralOnly = false }: { structuralOnly?: boolean }) { + const snapshot = useAnimationFrameTranscriptSnapshot({ structuralOnly }); latestBlocks = snapshot.blocks; latestSummary = snapshot.blockChangeSummary; renderCount += 1; @@ -123,6 +123,35 @@ afterEach(() => { }); describe('useAnimationFrameTranscriptSnapshot', () => { + it('keeps structural consumers asleep for pure tail appends', () => { + let pendingFrame: FrameRequestCallback | null = null; + vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { + pendingFrame = callback; + return 1; + }); + vi.spyOn(performance, 'now').mockReturnValue(1_000); + const first = { id: 'thought', text: 'a' } as DaemonTranscriptBlock; + testStore.update([first]); + container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); + act(() => root!.render()); + const initialRenderCount = renderCount; + + act(() => testStore.appendTail([{ ...first, text: 'ab' }], 'thought')); + + expect(pendingFrame).toBeNull(); + expect(renderCount).toBe(initialRenderCount); + expect(latestBlocks).toEqual([first]); + + const tool = { id: 'tool', kind: 'tool' } as DaemonTranscriptBlock; + act(() => testStore.update([{ ...first, text: 'ab' }, tool])); + act(() => pendingFrame?.(1_000)); + + expect(renderCount).toBeGreaterThan(initialRenderCount); + expect(latestBlocks).toEqual([{ ...first, text: 'ab' }, tool]); + }); + it('keeps coalesced tail blocks paired with their change summary', () => { let pendingFrame: FrameRequestCallback | null = null; vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { diff --git a/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.ts b/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.ts index fb6d55cc79d..cf7c8e0496f 100644 --- a/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.ts +++ b/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.ts @@ -36,7 +36,26 @@ interface AnimationFrameTranscriptSnapshot { blockChangeSummary?: DaemonTranscriptBlockChangeSummary; } -export function useAnimationFrameTranscriptSnapshot(): AnimationFrameTranscriptSnapshot { +interface AnimationFrameTranscriptSnapshotOptions { + structuralOnly?: boolean; +} + +function isSameTranscriptStructure( + previous: DaemonTranscriptBlockChangeSummary | undefined, + next: DaemonTranscriptBlockChangeSummary | undefined, +): boolean { + return ( + previous !== undefined && + next !== undefined && + previous.source === next.source && + previous.tailAppendBarrierRevision === next.tailAppendBarrierRevision + ); +} + +export function useAnimationFrameTranscriptSnapshot( + options: AnimationFrameTranscriptSnapshotOptions = {}, +): AnimationFrameTranscriptSnapshot { + const structuralOnly = options.structuralOnly === true; const store = useTranscriptStore(); const { sessionId } = useConnection(); const subscribe = useCallback( @@ -64,7 +83,14 @@ export function useAnimationFrameTranscriptSnapshot(): AnimationFrameTranscriptS } }; document.addEventListener('beforeinput', recordInput, true); + let previousSummary = store.getBlockChangeSummary?.(); const unsubscribe = store.subscribe(() => { + const nextSummary = store.getBlockChangeSummary?.(); + const tailOnly = + structuralOnly && + isSameTranscriptStructure(previousSummary, nextSummary); + previousSummary = nextSummary; + if (tailOnly) return; if (frame !== null) return; pendingSinceTs = performance.now(); frame = window.requestAnimationFrame(dispatchWhenDue); @@ -77,7 +103,7 @@ export function useAnimationFrameTranscriptSnapshot(): AnimationFrameTranscriptS } }; }, - [store], + [store, structuralOnly], ); const getSnapshot = useMemo(() => { let cached: @@ -90,12 +116,15 @@ export function useAnimationFrameTranscriptSnapshot(): AnimationFrameTranscriptS return () => { const state = store.getSnapshot(); const blockChangeSummary = store.getBlockChangeSummary?.(); - if ( - !cached || - cached.blocks !== state.blocks || - cached.blockIndexById !== state.blockIndexById || - cached.blockChangeSummary !== blockChangeSummary - ) { + const changed = structuralOnly + ? !isSameTranscriptStructure( + cached?.blockChangeSummary, + blockChangeSummary, + ) || cached?.blockIndexById !== state.blockIndexById + : cached?.blocks !== state.blocks || + cached?.blockIndexById !== state.blockIndexById || + cached?.blockChangeSummary !== blockChangeSummary; + if (!cached || changed) { cached = { blocks: state.blocks, blockIndexById: state.blockIndexById, @@ -104,7 +133,7 @@ export function useAnimationFrameTranscriptSnapshot(): AnimationFrameTranscriptS } return cached; }; - }, [store]); + }, [store, structuralOnly]); const live = useSyncExternalStore(subscribe, getSnapshot, getSnapshot); // Defer transcript re-renders so urgent updates — composer keystrokes, // button presses — are never queued behind a streaming frame. The deferred diff --git a/packages/web-shell/client/hooks/useMessages.test.ts b/packages/web-shell/client/hooks/useMessages.test.ts index cb167107a95..497aea7a870 100644 --- a/packages/web-shell/client/hooks/useMessages.test.ts +++ b/packages/web-shell/client/hooks/useMessages.test.ts @@ -350,7 +350,7 @@ describe('transcriptBlocksToLocalizedMessages', () => { ).toBeUndefined(); }); - it('falls back when an insight marker spans the appended-text boundary', async () => { + it('projects an insight marker that spans the appended-text boundary', async () => { const container = document.createElement('div'); const root = createRoot(container); const t = (key: string) => key; @@ -361,6 +361,7 @@ describe('transcriptBlocksToLocalizedMessages', () => { text: 'prefix "insi', streaming: true, }); + let latest: Message[] = []; function Consumer({ blocks, summary, @@ -368,7 +369,7 @@ describe('transcriptBlocksToLocalizedMessages', () => { blocks: DaemonTranscriptBlock[]; summary: DaemonTranscriptBlockChangeSummary; }) { - useMessagesFromBlocks(t, blocks, summary); + latest = useMessagesFromBlocks(t, blocks, summary); return null; } @@ -400,11 +401,15 @@ describe('transcriptBlocksToLocalizedMessages', () => { ); expect(adapterSpies.project).toHaveBeenCalledOnce(); + expect(latest).toMatchObject([ + { role: 'thinking', content: 'prefix "insight_progress":{}' }, + ]); await act(async () => root.unmount()); }); - it('falls back when a later append completes an insight message', () => { + it('projects a later append that completes an insight message', () => { const t = (key: string) => key; + const user = baseBlock({ id: 'user', kind: 'user', text: 'hello' }); const assistant = baseBlock({ id: 'assistant', kind: 'assistant', @@ -415,41 +420,97 @@ describe('transcriptBlocksToLocalizedMessages', () => { ...assistant, text: `${assistant.text}}`, }; - const messages = transcriptBlocksToLocalizedMessages([assistant], t); + const messages = transcriptBlocksToLocalizedMessages([user, assistant], t); const source = {}; - expect( - projectStreamingTailMessages( - { - blocks: [assistant], - messages, - t, - blockChangeSummary: { - source, - revision: 1, - tailAppendBarrierRevision: 1, - }, - }, - [completedAssistant], + const projected = projectStreamingTailMessages( + { + blocks: [user, assistant], + messages, t, - { + blockChangeSummary: { source, - revision: 2, + revision: 1, tailAppendBarrierRevision: 1, - tailBlockId: assistant.id, }, - ), - ).toBeUndefined(); + }, + [user, completedAssistant], + t, + { + source, + revision: 2, + tailAppendBarrierRevision: 1, + tailBlockId: assistant.id, + }, + ); + + expect(projected?.[0]).toBe(messages[0]); + expect(projected).toMatchObject([ + { role: 'user' }, + { role: 'insight_progress' }, + ]); expect( projectStreamingTailMessages( - { blocks: [assistant], messages, t }, - [completedAssistant], + { blocks: [user, assistant], messages, t }, + [user, completedAssistant], t, ), - ).toBeUndefined(); - expect( - transcriptBlocksToLocalizedMessages([completedAssistant], t), - ).toMatchObject([{ role: 'insight_progress' }]); + ).toMatchObject([{ role: 'user' }, { role: 'insight_progress' }]); + + const partialReady = { + ...completedAssistant, + text: `${completedAssistant.text}\n{"insight_ready":{"path":"/tmp/report.md"`, + }; + const partialReadyMessages = projectStreamingTailMessages( + { + blocks: [user, completedAssistant], + messages: projected!, + t, + blockChangeSummary: { + source, + revision: 2, + tailAppendBarrierRevision: 1, + }, + }, + [user, partialReady], + t, + { + source, + revision: 3, + tailAppendBarrierRevision: 1, + tailBlockId: assistant.id, + }, + ); + const completedReady = { + ...partialReady, + text: `${partialReady.text}}}`, + }; + const readyMessages = projectStreamingTailMessages( + { + blocks: [user, partialReady], + messages: partialReadyMessages!, + t, + blockChangeSummary: { + source, + revision: 3, + tailAppendBarrierRevision: 1, + }, + }, + [user, completedReady], + t, + { + source, + revision: 4, + tailAppendBarrierRevision: 1, + tailBlockId: assistant.id, + }, + ); + + expect(readyMessages?.[0]).toBe(messages[0]); + expect(readyMessages).toMatchObject([ + { role: 'user' }, + { role: 'insight_ready', path: '/tmp/report.md' }, + ]); }); it.each([undefined, ''])( diff --git a/packages/web-shell/client/hooks/useMessages.ts b/packages/web-shell/client/hooks/useMessages.ts index 3283512a12a..277f6856015 100644 --- a/packages/web-shell/client/hooks/useMessages.ts +++ b/packages/web-shell/client/hooks/useMessages.ts @@ -36,7 +36,7 @@ const BACKGROUND_AGENT_RECONCILIATION_MAX_ATTEMPTS = 8; // registration. Require repeated misses before treating the agent as gone. const MISSING_BACKGROUND_AGENT_GRACE_MISSES = 2; // Insight JSON can split one growing text block into multiple projected -// messages, so prefix identity reuse is unsafe once its marker appears. +// messages, so the tail needs a full projection once its marker appears. const INSIGHT_CONTENT_MARKER = '"insight_'; interface MessageProjection { @@ -201,8 +201,33 @@ export function projectStreamingTailMessages( typeof before.text !== 'string' || typeof after.text !== 'string' || after.text.length < before.text.length || - (!summaryProvesTailAppend && !after.text.startsWith(before.text)) || - after.text.includes(INSIGHT_CONTENT_MARKER) || + (!summaryProvesTailAppend && !after.text.startsWith(before.text)) + ) { + return undefined; + } + + if (after.text.includes(INSIGHT_CONTENT_MARKER)) { + const messages = transcriptBlocksToLocalizedMessages(blocks, t); + const tailPrefix = `${before.id}-`; + const firstTailMessageIndex = previous.messages.findIndex( + (message) => + message.id === before.id || message.id.startsWith(tailPrefix), + ); + const stablePrefixLength = + firstTailMessageIndex >= 0 ? firstTailMessageIndex : 0; + for (let i = 0; i < stablePrefixLength; i += 1) { + if ( + messages[i]?.id !== previous.messages[i]?.id || + messages[i]?.role !== previous.messages[i]?.role + ) { + break; + } + messages[i] = previous.messages[i]; + } + return messages; + } + + if ( (previousTail.role !== 'assistant' && previousTail.role !== 'thinking') || previousTail.isStreaming !== true || (after.kind === 'assistant') !== (previousTail.role === 'assistant') From ee3e076963c4a9243af952068c64dd63edcba97e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=92=89=E8=90=81?= Date: Mon, 24 Aug 2026 19:00:46 +0800 Subject: [PATCH 2/5] test(web-shell): expand historical question result --- .../client/components/WebShellTranscript.dom.test.tsx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/web-shell/client/components/WebShellTranscript.dom.test.tsx b/packages/web-shell/client/components/WebShellTranscript.dom.test.tsx index cb80bb3fe5e..53ac8a63364 100644 --- a/packages/web-shell/client/components/WebShellTranscript.dom.test.tsx +++ b/packages/web-shell/client/components/WebShellTranscript.dom.test.tsx @@ -342,6 +342,12 @@ describe('WebShellTranscript DOM integration', () => { , ); + const summary = container.querySelector('button')!; + expect(summary.textContent).toContain('Asked 1 question'); + expect(summary.getAttribute('aria-expanded')).toBe('false'); + + act(() => summary.click()); + expect(container.textContent).toContain('Ask user 1 question'); expect(container.textContent).toContain('User answer: Staging'); expect(container.querySelector('button[type="submit"]')).toBeNull(); From a1d2ea3e844e0affba9ebb45b35b99b5531cd042 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=92=89=E8=90=81?= Date: Mon, 24 Aug 2026 21:06:46 +0800 Subject: [PATCH 3/5] fix(web-shell): address streaming review findings --- ...eb-shell-collapsed-thinking-performance.md | 8 +- packages/web-shell/client/App.test.tsx | 37 ++++++- packages/web-shell/client/App.tsx | 3 - .../components/messages/ToolGroup.test.tsx | 66 +++++++++--- .../client/components/messages/ToolGroup.tsx | 7 +- ...useAnimationFrameTranscriptBlocks.test.tsx | 20 +++- .../useAnimationFrameTranscriptBlocks.ts | 6 +- .../client/hooks/useMessages.test.ts | 101 ++++++++++++++++++ .../web-shell/client/hooks/useMessages.ts | 7 +- 9 files changed, 221 insertions(+), 34 deletions(-) diff --git a/docs/design/web-shell-collapsed-thinking-performance.md b/docs/design/web-shell-collapsed-thinking-performance.md index e78b51a4264..b772df52684 100644 --- a/docs/design/web-shell-collapsed-thinking-performance.md +++ b/docs/design/web-shell-collapsed-thinking-performance.md @@ -21,10 +21,10 @@ background-agent reconciliation loop. Structural changes still flow through the app and replace the baseline immediately. Insight protocol markers use a full projection while retaining the unchanged message prefix. -Compact tool summaries mount their detail subtree only while expanded. The -summary button remains live while collapsed; expanding reconstructs the current -tool and thought rows from props. Collapse is immediate so the hidden subtree -stops work without waiting for an exit animation. +Compact tool summaries mount their detail subtree only while expanded, except +for MCP Apps whose iframe state must survive a collapse. The summary button +remains live while collapsed; expanding reconstructs the current tool and +thought rows from props. Collapse and expansion are immediate and unanimated. ## Compatibility diff --git a/packages/web-shell/client/App.test.tsx b/packages/web-shell/client/App.test.tsx index 6378bd7d5d0..63552c9441a 100644 --- a/packages/web-shell/client/App.test.tsx +++ b/packages/web-shell/client/App.test.tsx @@ -372,7 +372,9 @@ const { streamingState: 'idle' as StreamingState, sessionHasActivePrompt: false, blocks: [] as unknown[], + liveBlocks: undefined as unknown[] | undefined, messages: [] as unknown[], + streamingTailMessages: undefined as unknown[] | undefined, queuedPromptHoldHistory: [] as boolean[], queuedPromptStreamingState: 'idle', queuedPromptSessionHasActivePrompt: false, @@ -401,6 +403,7 @@ const { isResponding?: boolean; transcriptReloadPaused?: boolean; activeTurnStartedAt?: number; + transcriptBlockCount?: number; terminalBackgroundShellTaskIds?: ReadonlySet; } | null, latestBtwMessageProps: null as { @@ -586,13 +589,15 @@ vi.mock('@qwen-code/sdk/daemon', () => { }); vi.mock('./hooks/useMessages', () => ({ - projectStreamingTailMessages: () => undefined, + projectStreamingTailMessages: () => testState.streamingTailMessages, useMessages: () => testState.messages, useMessagesFromBlocks: () => testState.messages, })); vi.mock('./hooks/useAnimationFrameTranscriptBlocks', () => ({ - useAnimationFrameTranscriptSnapshot: () => ({ blocks: testState.blocks }), + useAnimationFrameTranscriptSnapshot: () => ({ + blocks: testState.liveBlocks ?? testState.blocks, + }), })); vi.mock('./hooks/useBackgroundTasks', () => ({ @@ -5019,7 +5024,9 @@ beforeEach(() => { testState.streamingState = 'idle'; testState.sessionHasActivePrompt = false; testState.blocks = []; + testState.liveBlocks = undefined; testState.messages = []; + testState.streamingTailMessages = undefined; testState.queuedPromptHoldHistory = []; testState.queuedPromptStreamingState = 'idle'; testState.queuedPromptSessionHasActivePrompt = false; @@ -5211,6 +5218,32 @@ afterEach(() => { vi.unstubAllGlobals(); }); +describe('App live transcript boundary', () => { + it('renders and copies the projected live tail over the structural baseline', async () => { + const writeText = vi + .spyOn(navigator.clipboard, 'writeText') + .mockResolvedValue(); + testState.prompt = '/copy'; + testState.blocks = [{ id: 'assistant', text: 'a' }]; + testState.liveBlocks = [{ id: 'assistant', text: 'ab' }]; + testState.messages = [{ id: 'assistant', role: 'assistant', content: 'a' }]; + testState.streamingTailMessages = [ + { id: 'assistant', role: 'assistant', content: 'ab' }, + ]; + + renderApp(); + await flush(); + + expect(testState.latestMessageListProps?.messages).toMatchObject([ + { id: 'assistant', role: 'assistant', content: 'ab' }, + ]); + expect(testState.latestMessageListProps?.transcriptBlockCount).toBe(1); + + await clickSubmit(document.body); + await vi.waitFor(() => expect(writeText).toHaveBeenCalledWith('ab')); + }); +}); + describe('App compact mode', () => { async function toggleCompactMode() { await act(async () => { diff --git a/packages/web-shell/client/App.tsx b/packages/web-shell/client/App.tsx index ebc96bdc211..0b7bc50f951 100644 --- a/packages/web-shell/client/App.tsx +++ b/packages/web-shell/client/App.tsx @@ -2717,9 +2717,6 @@ export function App({ const messages = useMessagesFromBlocks(t, blocks, blockChangeSummary); const messagesRef = useRef(messages); - useLayoutEffect(() => { - messagesRef.current = messages; - }, [messages]); const [failedPrompt, setFailedPrompt] = useState(null); const failedPromptRef = useRef(failedPrompt); const [failedPromptRetry, setFailedPromptRetry] = diff --git a/packages/web-shell/client/components/messages/ToolGroup.test.tsx b/packages/web-shell/client/components/messages/ToolGroup.test.tsx index 731bfd160ee..f3ea38b2021 100644 --- a/packages/web-shell/client/components/messages/ToolGroup.test.tsx +++ b/packages/web-shell/client/components/messages/ToolGroup.test.tsx @@ -10,6 +10,7 @@ import { WebShellCustomizationProvider } from '../../customization'; import { TranscriptRenderModeProvider } from '../../transcriptRenderMode'; import { SubagentDetailsProvider } from '../../subagentDetailsContext'; import { MonitorDetailsProvider } from '../../monitorDetailsContext'; +import { McpAppHostContext } from '../../mcpAppHostContext'; vi.mock('../../App', async () => { const { createContext } = await import('react'); @@ -92,12 +93,13 @@ function renderToolGroup( onOpenMonitor?: (tool: ACPToolCall) => Promise, language: 'en' | 'zh-CN' = 'en', generateContent?: SessionContentGenerator, + mcpAppHostUrl?: string, ): HTMLElement { const container = document.createElement('div'); document.body.appendChild(container); const root = createRoot(container); act(() => { - const group = ( + const toolGroup = ( ); + const group = mcpAppHostUrl ? ( + + {toolGroup} + + ) : ( + toolGroup + ); root.render( @@ -483,25 +492,49 @@ describe('tool group summary logic', () => { }); it('opens a completed MCP App result in the session transcript', () => { - const container = renderToolGroup([ - makeTool({ - toolName: 'mcp__demo__show_dashboard', - rawOutput: { - type: 'mcp_app', - serverName: 'demo', - resourceUri: 'ui://demo/dashboard', - html: '
Dashboard
', - toolResult: { content: [] }, - toolArguments: {}, - fallbackText: 'Dashboard ready', - }, - }), - ]); + const container = renderToolGroup( + [ + makeTool({ + toolName: 'mcp__demo__show_dashboard', + rawOutput: { + type: 'mcp_app', + serverName: 'demo', + resourceUri: 'ui://demo/dashboard', + html: '
Dashboard
', + toolResult: { content: [] }, + toolArguments: {}, + fallbackText: 'Dashboard ready', + }, + }), + ], + {}, + undefined, + false, + undefined, + undefined, + 'en', + undefined, + 'http://localhost:5173', + ); expect( container.querySelector('button')?.getAttribute('aria-expanded'), ).toBe('true'); - expect(container.textContent).toContain('Dashboard ready'); + + const content = container.querySelector( + '[class*="chatSummaryContentClip"]', + ); + const iframe = container.querySelector('iframe'); + expect(iframe).not.toBeNull(); + iframe!.dataset['testState'] = 'preserved'; + act(() => container.querySelector('button')?.click()); + expect(content).toBe( + container.querySelector('[class*="chatSummaryContentClip"]'), + ); + expect((content as HTMLElement | null)?.style.display).toBe('none'); + act(() => container.querySelector('button')?.click()); + expect(container.querySelector('iframe')).toBe(iframe); + expect(iframe?.dataset['testState']).toBe('preserved'); }); it('keeps an MCP App open when multiple tools share a summary', () => { @@ -829,7 +862,6 @@ describe('tool row rendering', () => { const content = container.querySelector( '[class*="chatSummaryContentClip"]', ); - expect(content?.className).not.toContain('chatSummaryContentCollapsed'); expect(content?.textContent).toContain('custom 5s'); act(() => { diff --git a/packages/web-shell/client/components/messages/ToolGroup.tsx b/packages/web-shell/client/components/messages/ToolGroup.tsx index 86408dea790..fd29f13d985 100644 --- a/packages/web-shell/client/components/messages/ToolGroup.tsx +++ b/packages/web-shell/client/components/messages/ToolGroup.tsx @@ -1811,8 +1811,11 @@ export const ToolGroup = memo(function ToolGroup({ aria-hidden="true" /> - {chatExpanded && ( -
+ {(chatExpanded || hasMcpApp) && ( +
{tools.map((tool) => { diff --git a/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx b/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx index eb62b0ea522..8928dea1ccd 100644 --- a/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx +++ b/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx @@ -20,10 +20,12 @@ const testStore = vi.hoisted(() => { revision: 0, tailAppendBarrierRevision: 0, }; + let blockChangeSummaryEnabled = true; const listeners = new Set<() => void>(); return { getSnapshot: () => ({ blocks, blockIndexById }), - getBlockChangeSummary: () => blockChangeSummary, + getBlockChangeSummary: () => + blockChangeSummaryEnabled ? blockChangeSummary : undefined, subscribe: (listener: () => void) => { listeners.add(listener); return () => listeners.delete(listener); @@ -60,6 +62,9 @@ const testStore = vi.hoisted(() => { }; listeners.forEach((listener) => listener()); }, + disableBlockChangeSummary() { + blockChangeSummaryEnabled = false; + }, reset() { blocks = []; blockIndexById = {}; @@ -68,6 +73,7 @@ const testStore = vi.hoisted(() => { revision: 0, tailAppendBarrierRevision: 0, }; + blockChangeSummaryEnabled = true; listeners.clear(); }, }; @@ -123,6 +129,18 @@ afterEach(() => { }); describe('useAnimationFrameTranscriptSnapshot', () => { + it('caches structural snapshots when the store has no change summary', () => { + testStore.disableBlockChangeSummary(); + container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); + + act(() => root!.render()); + + expect(renderCount).toBe(1); + expect(latestBlocks).toEqual([]); + }); + it('keeps structural consumers asleep for pure tail appends', () => { let pendingFrame: FrameRequestCallback | null = null; vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { diff --git a/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.ts b/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.ts index cf7c8e0496f..7763abef1f8 100644 --- a/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.ts +++ b/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.ts @@ -116,7 +116,11 @@ export function useAnimationFrameTranscriptSnapshot( return () => { const state = store.getSnapshot(); const blockChangeSummary = store.getBlockChangeSummary?.(); - const changed = structuralOnly + const canCompareStructure = + structuralOnly && + cached?.blockChangeSummary !== undefined && + blockChangeSummary !== undefined; + const changed = canCompareStructure ? !isSameTranscriptStructure( cached?.blockChangeSummary, blockChangeSummary, diff --git a/packages/web-shell/client/hooks/useMessages.test.ts b/packages/web-shell/client/hooks/useMessages.test.ts index 497aea7a870..a520b49ab8c 100644 --- a/packages/web-shell/client/hooks/useMessages.test.ts +++ b/packages/web-shell/client/hooks/useMessages.test.ts @@ -513,6 +513,35 @@ describe('transcriptBlocksToLocalizedMessages', () => { ]); }); + it('falls back when an insight tail has no matching projected message', () => { + const t = (key: string) => key; + const thought = baseBlock({ + id: 'merged-thought', + kind: 'thought', + text: 'prefix "insi', + streaming: true, + }); + + expect( + projectStreamingTailMessages( + { + blocks: [thought], + messages: [ + { + id: 'earlier-assistant', + role: 'thinking', + content: thought.text, + isStreaming: true, + }, + ], + t, + }, + [{ ...thought, text: 'prefix "insight_progress":{}' }], + t, + ), + ).toBeUndefined(); + }); + it.each([undefined, ''])( 'falls back safely when a streaming block has empty text (%j)', async (text) => { @@ -707,6 +736,78 @@ describe('background agent task reconciliation', () => { await act(async () => root.unmount()); }); + it('keeps agent reconciliation when an insight tail has no projected message', async () => { + const container = document.createElement('div'); + const root = createRoot(container); + const t = (key: string) => key; + const source = {}; + const agent = backgroundAgentBlock('agent-call'); + const tail = baseBlock({ + id: 'empty-thought', + kind: 'thought', + text: '', + streaming: true, + }); + let latest: Message[] = []; + hookState.connection.status = 'connected'; + hookState.resolveSubagentSession.mockReset(); + hookState.resolveSubagentSession.mockResolvedValue( + backgroundAgentResolution('completed'), + ); + function Consumer({ + blocks, + summary, + }: { + blocks: DaemonTranscriptBlock[]; + summary: DaemonTranscriptBlockChangeSummary; + }) { + latest = useMessagesFromBlocks(t, blocks, summary); + return null; + } + + await act(async () => + root.render( + createElement(Consumer, { + blocks: [agent, tail], + summary: { + source, + revision: 1, + tailAppendBarrierRevision: 1, + }, + }), + ), + ); + await vi.waitFor(() => + expect(latest[0]).toMatchObject({ + role: 'tool_group', + tools: [{ status: 'completed' }], + }), + ); + + await act(async () => + root.render( + createElement(Consumer, { + blocks: [ + agent, + { ...tail, text: 'prefix "insight_progress":{}', updatedAt: 2 }, + ], + summary: { + source, + revision: 2, + tailAppendBarrierRevision: 1, + tailBlockId: tail.id, + }, + }), + ), + ); + + expect(latest[0]).toMatchObject({ + role: 'tool_group', + tools: [{ status: 'completed' }], + }); + await act(async () => root.unmount()); + }); + it('uses terminal agent notifications as a reconciliation trigger without requiring toolUseId', () => { expect( getBackgroundAgentNotificationKey([ diff --git a/packages/web-shell/client/hooks/useMessages.ts b/packages/web-shell/client/hooks/useMessages.ts index 277f6856015..592f391378b 100644 --- a/packages/web-shell/client/hooks/useMessages.ts +++ b/packages/web-shell/client/hooks/useMessages.ts @@ -207,15 +207,14 @@ export function projectStreamingTailMessages( } if (after.text.includes(INSIGHT_CONTENT_MARKER)) { - const messages = transcriptBlocksToLocalizedMessages(blocks, t); const tailPrefix = `${before.id}-`; const firstTailMessageIndex = previous.messages.findIndex( (message) => message.id === before.id || message.id.startsWith(tailPrefix), ); - const stablePrefixLength = - firstTailMessageIndex >= 0 ? firstTailMessageIndex : 0; - for (let i = 0; i < stablePrefixLength; i += 1) { + if (firstTailMessageIndex < 0) return undefined; + const messages = transcriptBlocksToLocalizedMessages(blocks, t); + for (let i = 0; i < firstTailMessageIndex; i += 1) { if ( messages[i]?.id !== previous.messages[i]?.id || messages[i]?.role !== previous.messages[i]?.role From 511ee1e2ae7269baa035225529b9aa7eeffd2fc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=92=89=E8=90=81?= Date: Mon, 24 Aug 2026 17:56:48 +0000 Subject: [PATCH 4/5] test(web-shell): strengthen streaming review follow-up tests --- packages/web-shell/client/App.test.tsx | 16 ++++++++++++---- .../components/messages/ToolGroup.test.tsx | 1 + .../useAnimationFrameTranscriptBlocks.test.tsx | 13 +++++++++++++ .../web-shell/client/hooks/useMessages.test.ts | 6 ++++-- 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/packages/web-shell/client/App.test.tsx b/packages/web-shell/client/App.test.tsx index 63552c9441a..92c60b345d8 100644 --- a/packages/web-shell/client/App.test.tsx +++ b/packages/web-shell/client/App.test.tsx @@ -595,8 +595,13 @@ vi.mock('./hooks/useMessages', () => ({ })); vi.mock('./hooks/useAnimationFrameTranscriptBlocks', () => ({ - useAnimationFrameTranscriptSnapshot: () => ({ - blocks: testState.liveBlocks ?? testState.blocks, + useAnimationFrameTranscriptSnapshot: (options?: { + structuralOnly?: boolean; + }) => ({ + blocks: + options?.structuralOnly === true + ? testState.blocks + : (testState.liveBlocks ?? testState.blocks), }), })); @@ -5225,7 +5230,10 @@ describe('App live transcript boundary', () => { .mockResolvedValue(); testState.prompt = '/copy'; testState.blocks = [{ id: 'assistant', text: 'a' }]; - testState.liveBlocks = [{ id: 'assistant', text: 'ab' }]; + testState.liveBlocks = [ + { id: 'assistant', text: 'ab' }, + { id: 'tool', kind: 'tool' }, + ]; testState.messages = [{ id: 'assistant', role: 'assistant', content: 'a' }]; testState.streamingTailMessages = [ { id: 'assistant', role: 'assistant', content: 'ab' }, @@ -5237,7 +5245,7 @@ describe('App live transcript boundary', () => { expect(testState.latestMessageListProps?.messages).toMatchObject([ { id: 'assistant', role: 'assistant', content: 'ab' }, ]); - expect(testState.latestMessageListProps?.transcriptBlockCount).toBe(1); + expect(testState.latestMessageListProps?.transcriptBlockCount).toBe(2); await clickSubmit(document.body); await vi.waitFor(() => expect(writeText).toHaveBeenCalledWith('ab')); diff --git a/packages/web-shell/client/components/messages/ToolGroup.test.tsx b/packages/web-shell/client/components/messages/ToolGroup.test.tsx index f3ea38b2021..7acde478310 100644 --- a/packages/web-shell/client/components/messages/ToolGroup.test.tsx +++ b/packages/web-shell/client/components/messages/ToolGroup.test.tsx @@ -535,6 +535,7 @@ describe('tool group summary logic', () => { act(() => container.querySelector('button')?.click()); expect(container.querySelector('iframe')).toBe(iframe); expect(iframe?.dataset['testState']).toBe('preserved'); + expect((content as HTMLElement | null)?.style.display).toBe(''); }); it('keeps an MCP App open when multiple tools share a summary', () => { diff --git a/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx b/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx index 8928dea1ccd..778834187ca 100644 --- a/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx +++ b/packages/web-shell/client/hooks/useAnimationFrameTranscriptBlocks.test.tsx @@ -130,6 +130,11 @@ afterEach(() => { describe('useAnimationFrameTranscriptSnapshot', () => { it('caches structural snapshots when the store has no change summary', () => { + let pendingFrame: FrameRequestCallback | null = null; + vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { + pendingFrame = callback; + return 1; + }); testStore.disableBlockChangeSummary(); container = document.createElement('div'); document.body.append(container); @@ -139,6 +144,14 @@ describe('useAnimationFrameTranscriptSnapshot', () => { expect(renderCount).toBe(1); expect(latestBlocks).toEqual([]); + + // Without a change summary every notification may be structural, so the + // consumer must keep the pre-change update behavior and wake. + act(() => testStore.update([{ id: 'a' } as DaemonTranscriptBlock])); + act(() => pendingFrame?.(1_000)); + + expect(renderCount).toBeGreaterThan(1); + expect(latestBlocks).toHaveLength(1); }); it('keeps structural consumers asleep for pure tail appends', () => { diff --git a/packages/web-shell/client/hooks/useMessages.test.ts b/packages/web-shell/client/hooks/useMessages.test.ts index a520b49ab8c..39cd71759d0 100644 --- a/packages/web-shell/client/hooks/useMessages.test.ts +++ b/packages/web-shell/client/hooks/useMessages.test.ts @@ -742,9 +742,11 @@ describe('background agent task reconciliation', () => { const t = (key: string) => key; const source = {}; const agent = backgroundAgentBlock('agent-call'); + // An empty assistant block projects no message (unlike thought), so the + // insight append below hits the "no matching projected message" fallback. const tail = baseBlock({ - id: 'empty-thought', - kind: 'thought', + id: 'empty-assistant', + kind: 'assistant', text: '', streaming: true, }); From 51548f2cb23a79415778f2d2fcb733b0d93e4c4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=92=89=E8=90=81?= Date: Mon, 24 Aug 2026 20:45:07 +0000 Subject: [PATCH 5/5] test(web-shell): pin structural snapshot opt-in and matched insight path (#9914) --- packages/web-shell/client/App.test.tsx | 23 ++++-- .../client/hooks/useMessages.test.ts | 78 +++++++++++++++++++ 2 files changed, 95 insertions(+), 6 deletions(-) diff --git a/packages/web-shell/client/App.test.tsx b/packages/web-shell/client/App.test.tsx index 92c60b345d8..fd2c674129b 100644 --- a/packages/web-shell/client/App.test.tsx +++ b/packages/web-shell/client/App.test.tsx @@ -373,6 +373,9 @@ const { sessionHasActivePrompt: false, blocks: [] as unknown[], liveBlocks: undefined as unknown[] | undefined, + snapshotCallOptions: [] as Array< + { structuralOnly?: boolean } | undefined + >, messages: [] as unknown[], streamingTailMessages: undefined as unknown[] | undefined, queuedPromptHoldHistory: [] as boolean[], @@ -597,12 +600,15 @@ vi.mock('./hooks/useMessages', () => ({ vi.mock('./hooks/useAnimationFrameTranscriptBlocks', () => ({ useAnimationFrameTranscriptSnapshot: (options?: { structuralOnly?: boolean; - }) => ({ - blocks: - options?.structuralOnly === true - ? testState.blocks - : (testState.liveBlocks ?? testState.blocks), - }), + }) => { + testState.snapshotCallOptions.push(options); + return { + blocks: + options?.structuralOnly === true + ? testState.blocks + : (testState.liveBlocks ?? testState.blocks), + }; + }, })); vi.mock('./hooks/useBackgroundTasks', () => ({ @@ -5030,6 +5036,7 @@ beforeEach(() => { testState.sessionHasActivePrompt = false; testState.blocks = []; testState.liveBlocks = undefined; + testState.snapshotCallOptions = []; testState.messages = []; testState.streamingTailMessages = undefined; testState.queuedPromptHoldHistory = []; @@ -5246,6 +5253,10 @@ describe('App live transcript boundary', () => { { id: 'assistant', role: 'assistant', content: 'ab' }, ]); expect(testState.latestMessageListProps?.transcriptBlockCount).toBe(2); + expect(testState.snapshotCallOptions).toContainEqual({ + structuralOnly: true, + }); + expect(testState.snapshotCallOptions).toContainEqual(undefined); await clickSubmit(document.body); await vi.waitFor(() => expect(writeText).toHaveBeenCalledWith('ab')); diff --git a/packages/web-shell/client/hooks/useMessages.test.ts b/packages/web-shell/client/hooks/useMessages.test.ts index 39cd71759d0..015c697f405 100644 --- a/packages/web-shell/client/hooks/useMessages.test.ts +++ b/packages/web-shell/client/hooks/useMessages.test.ts @@ -810,6 +810,84 @@ describe('background agent task reconciliation', () => { await act(async () => root.unmount()); }); + it('keeps agent reconciliation when an insight tail matches a projected message', async () => { + const container = document.createElement('div'); + const root = createRoot(container); + const t = (key: string) => key; + const source = {}; + const agent = backgroundAgentBlock('agent-call'); + // An empty thought block projects a thinking message (unlike assistant), + // so the insight append below matches the tail's projected message. + const tail = baseBlock({ + id: 'empty-thought', + kind: 'thought', + text: '', + streaming: true, + }); + let latest: Message[] = []; + hookState.connection.status = 'connected'; + hookState.resolveSubagentSession.mockReset(); + hookState.resolveSubagentSession.mockResolvedValue( + backgroundAgentResolution('completed'), + ); + function Consumer({ + blocks, + summary, + }: { + blocks: DaemonTranscriptBlock[]; + summary: DaemonTranscriptBlockChangeSummary; + }) { + latest = useMessagesFromBlocks(t, blocks, summary); + return null; + } + + await act(async () => + root.render( + createElement(Consumer, { + blocks: [agent, tail], + summary: { + source, + revision: 1, + tailAppendBarrierRevision: 1, + }, + }), + ), + ); + await vi.waitFor(() => + expect(latest[0]).toMatchObject({ + role: 'tool_group', + tools: [{ status: 'completed' }], + }), + ); + const reconciledToolGroup = latest[0]; + + adapterSpies.project.mockClear(); + await act(async () => + root.render( + createElement(Consumer, { + blocks: [ + agent, + { ...tail, text: 'prefix "insight_progress":{}', updatedAt: 2 }, + ], + summary: { + source, + revision: 2, + tailAppendBarrierRevision: 1, + tailBlockId: tail.id, + }, + }), + ), + ); + + expect(adapterSpies.project).toHaveBeenCalled(); + expect(latest[0]).toBe(reconciledToolGroup); + expect(latest).toMatchObject([ + { role: 'tool_group', tools: [{ status: 'completed' }] }, + { role: 'thinking', content: 'prefix "insight_progress":{}' }, + ]); + await act(async () => root.unmount()); + }); + it('uses terminal agent notifications as a reconciliation trigger without requiring toolUseId', () => { expect( getBackgroundAgentNotificationKey([