From b164882164dbcf6efd0aa1f2dc54d0dec049335c Mon Sep 17 00:00:00 2001 From: wsp Date: Sat, 14 Nov 2026 15:14:28 +0800 Subject: [PATCH] fix(flow-chat): Preserve segment snapshots Keep changed segments immutable so suspended renders cannot alter callbacks retained by the committed view. Publish the reusable segment cache only after commit while preserving unchanged segment identities. Add append, replacement, and concurrent rendering regression coverage. All 23 focused tests and the Web UI type check pass. The broader Web UI check is blocked by an existing Dialog typography token violation. Refs: #3798 --- .../modern/FLOWCHAT_VERIFICATION.md | 1 + .../components/modern/FlowGroupRenderer.tsx | 11 ++-- ...lowGroupRenderSegments.concurrent.test.tsx | 52 +++++++++++++++++++ .../modern/flowGroupRenderSegments.test.ts | 21 ++++++++ .../modern/flowGroupRenderSegments.ts | 24 ++------- 5 files changed, 83 insertions(+), 26 deletions(-) create mode 100644 src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.concurrent.test.tsx diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md index fde3fd4072..22540c5e6e 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md @@ -16,6 +16,7 @@ each missing what the other had. | Test | Contract it holds | |---|---| +| `flowGroupRenderSegments.test.ts`, `flowGroupRenderSegments.concurrent.test.tsx`, `FlowGroupLifecycle.test.tsx` | unchanged segment reuse, immutable tail snapshots on append/replacement, retained callbacks during suspended renders, and collection lifecycle; local DOM fixtures, not live remote evidence | | `../../store/FlowChatStore.test.ts`, `ModernFlowChatContainer.history-restore.test.tsx` | live arrival before hydration never caches a guessed global ordinal; first catalog adoption drops unversioned ranges while retaining canonical live bodies; catalog IDs and sparse legacy storage slots keep the first history Turn reachable on local/simulated Peer surfaces, including legacy `backendTurnIndex` payloads; not live remote evidence | | `flowChatTurnSummaries.test.ts`, `../../utils/flowChatTurnIdentity.test.ts`, `../../utils/flowChatTurnOrdinal.test.ts` | stable summary identity across streamed body updates; append/rollback, catalog and storage-index corrections, partial-tail offsets, catalog-only/empty history windows, provisional usage reports and legacy identity compatibility; batched catalog lookup without per-Turn rescans | | `../../timeline/useTimelineInteraction.test.tsx` | selection/focus retention and cleanup; mutation/resize bursts coalesce before dimension reads, inactive viewports keep leases without measurement and refresh on reveal, while explicit active selection/focus changes retain immediately; supplied DOM geometry, not native performance evidence | diff --git a/src/web-ui/src/flow_chat/components/modern/FlowGroupRenderer.tsx b/src/web-ui/src/flow_chat/components/modern/FlowGroupRenderer.tsx index 0d8e2ee1b9..1bb5f3ec8a 100644 --- a/src/web-ui/src/flow_chat/components/modern/FlowGroupRenderer.tsx +++ b/src/web-ui/src/flow_chat/components/modern/FlowGroupRenderer.tsx @@ -114,11 +114,12 @@ export const FlowGroupRenderer: React.FC = React.memo(({ const allItems = useMemo(() => recordedItems.filter(isFlowItemVisible), [recordedItems]); const parallelRows = useMemo(() => getConcurrentCapsuleRows(allItems), [allItems]); const prevSegmentsRef = useRef([]); - const renderSegments = useMemo(() => { - const next = buildFlowGroupRenderSegments(allItems, prevSegmentsRef.current); - prevSegmentsRef.current = next; - return next; - }, [allItems]); + const renderSegments = useMemo( + () => buildFlowGroupRenderSegments(allItems, prevSegmentsRef.current), [allItems], + ); + useLayoutEffect(() => { + prevSegmentsRef.current = renderSegments; + }, [renderSegments]); const toolItemCount = useMemo(() => allItems.filter(item => item.type === 'tool').length, [allItems]); const filePath = category === 'file-edit' ? fileEditTarget(allItems.find(item => item.type === 'tool')) : undefined; const fileStatus = useMemo(() => fileEditGroupStatus(category === 'file-edit' ? allItems : []), [category, allItems]); diff --git a/src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.concurrent.test.tsx b/src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.concurrent.test.tsx new file mode 100644 index 0000000000..f708cd5e14 --- /dev/null +++ b/src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.concurrent.test.tsx @@ -0,0 +1,52 @@ +// @vitest-environment jsdom +import React, { act, Suspense, startTransition, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { createRoot } from 'react-dom/client'; +import { expect, it, vi } from 'vitest'; +import type { FlowItem, FlowToolItem } from '../../types/flow-chat'; +import { buildFlowGroupRenderSegments, type FlowGroupRenderSegment } from './flowGroupRenderSegments'; + +it('keeps retained render callbacks on committed members while an append suspends', async () => { + const read = (index: number): FlowToolItem => ({ + id: `call-${index}`, type: 'tool', toolName: 'Read', timestamp: 1, status: 'completed', + toolCall: { id: `call-${index}`, input: {} }, + } as FlowToolItem); + const initial: FlowItem[] = [read(0)]; + let update!: (items: FlowItem[]) => void; + let committedRender!: () => string[]; + let attempted = false; + const pending = new Promise(() => {}); + + function Group({ items }: { items: FlowItem[] }) { + const previous = useRef([]); + const segments = useMemo(() => buildFlowGroupRenderSegments(items, previous.current), [items]); + useLayoutEffect(() => { + previous.current = segments; + // DeferredContent retains a render closure over the source segment. + committedRender = () => segments[0].items.map(item => item.id); + }, [segments]); + if (items.length === 2) { + attempted = true; + throw pending; + } + return
{items.length} committed
; + } + function Host() { + const [items, setItems] = useState(initial); + update = setItems; + return ; + } + + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); + const container = document.createElement('div'); + const root = createRoot(container); + try { + await act(async () => { root.render(); }); + await act(async () => { startTransition(() => update([...initial, read(1)])); }); + expect(attempted).toBe(true); + expect(container.textContent).toBe('1 committed'); + expect(committedRender()).toEqual(['call-0']); + } finally { + await act(async () => root.unmount()); + vi.unstubAllGlobals(); + } +}); diff --git a/src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.test.ts b/src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.test.ts index 0c93ec8560..dcd25d3ef2 100644 --- a/src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.test.ts +++ b/src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.test.ts @@ -31,3 +31,24 @@ it('reuses closed segment object references when appending new items', () => { expect(secondPass[1]).toBe(firstPass[1]); expect(secondPass.length).toBe(3); }); + +it.each(['append', 'replace'] as const)('preserves the previous tail snapshot on %s', update => { + const initial = Array.from({ length: 17 }, (_, index) => read(index)); + const before = buildFlowGroupRenderSegments(initial); + const tail = before[1]; + const originalMembers = tail.items; + const originalHeight = tail.estimatedHeightPx; + const updated = update === 'append' + ? [...initial, read(17)] + : [...initial.slice(0, -1), { ...initial[16], status: 'running' as const }]; + const after = buildFlowGroupRenderSegments(updated, before); + + expect(after[0]).toBe(before[0]); + expect(after[1]).not.toBe(tail); + expect(after[1].key).toBe(tail.key); + expect(after[1].items).toEqual(updated.slice(16)); + expect(after[1].estimatedHeightPx).toBe(buildFlowGroupRenderSegments(updated)[1].estimatedHeightPx); + expect(tail.items).toBe(originalMembers); + expect(tail.items).toEqual(initial.slice(16)); + expect(tail.estimatedHeightPx).toBe(originalHeight); +}); diff --git a/src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.ts b/src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.ts index 768f57fc4a..bf0917251c 100644 --- a/src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.ts +++ b/src/web-ui/src/flow_chat/components/modern/flowGroupRenderSegments.ts @@ -30,7 +30,7 @@ export function estimateFlowGroupItemsHeight(items: readonly FlowItem[]): number /** * Stable append boundaries keep reasoning beside its successor and capsule runs together. * When `previous` segments are provided, settled prefix segments are reused verbatim by reference, - * and the growing trailing segment is incrementally updated, enabling high-frequency streaming reuse. + * while changed segments get new snapshots so retained render callbacks remain consistent. */ export function buildFlowGroupRenderSegments( items: readonly FlowItem[], @@ -44,7 +44,7 @@ export function buildFlowGroupRenderSegments( const segIdx = segments.length; const reusable = previous?.[segIdx]; - // Case 1: Closed settled segment where member items are completely unchanged by reference + // Reuse only segments whose members are completely unchanged by reference. if ( reusable && reusable.startIndex === start && @@ -54,25 +54,7 @@ export function buildFlowGroupRenderSegments( ) { segments.push(reusable); } - // Case 2: Live/growing trailing segment where items share the same key & prefix - else if ( - reusable && - reusable.startIndex === start && - reusable.key === members[0]?.id && - ( - // Either identical length with replaced streaming tail object - (reusable.items.length === members.length && - reusable.items.slice(0, -1).every((it, idx) => it === members[idx])) || - // Or growing by appended items - (reusable.items.length <= members.length && - reusable.items.every((it, idx) => it === members[idx])) - ) - ) { - reusable.items = members; - reusable.estimatedHeightPx = estimateFlowGroupItemsHeight(members); - segments.push(reusable); - } - // Case 3: Fresh segment + // Changed members must not mutate a snapshot held by a committed render. else { segments.push({ key: members[0]?.id ?? `seg-${start}`,