From 40f0cc7046e0f43d6500c7b3ae2b23b665489f0c Mon Sep 17 00:00:00 2001 From: kev1n77 Date: Mon, 9 Nov 2026 20:26:32 +0800 Subject: [PATCH 1/2] perf(flow-chat): index legacy catalog storage lookups once per batch --- .../utils/flowChatTurnIdentity.test.ts | 21 ++++++++++++++++++- .../flow_chat/utils/flowChatTurnIdentity.ts | 14 ++++++++++--- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/web-ui/src/flow_chat/utils/flowChatTurnIdentity.test.ts b/src/web-ui/src/flow_chat/utils/flowChatTurnIdentity.test.ts index 332154a48a..126e9b6e0f 100644 --- a/src/web-ui/src/flow_chat/utils/flowChatTurnIdentity.test.ts +++ b/src/web-ui/src/flow_chat/utils/flowChatTurnIdentity.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { nextStorageTurnIndex } from './flowChatTurnIdentity'; +import { createTurnOrdinalResolver, nextStorageTurnIndex } from './flowChatTurnIdentity'; import type { DialogTurn } from '../types/flow-chat'; const SESSION_ID = 'acp_dsh_session'; @@ -83,3 +83,22 @@ describe('nextStorageTurnIndex', () => { ).toBeUndefined(); }); }); + +describe('batched Turn ordinal lookup', () => { + it('resolves catalog-backed legacy Turns without rescanning entries for each lookup', () => { + let entryReads = 0; + const entries = new Proxy(Array.from({ length: 100 }, (_, ordinal) => ({ + turnId: `turn-${ordinal}`, ordinal, storageTurnIndex: ordinal * 3, + })), { get(target, key, receiver) { + if (typeof key === 'string' && /^\d+$/.test(key)) entryReads++; + return Reflect.get(target, key, receiver); + } }); + const resolver = createTurnOrdinalResolver(session({ + dialogTurns: entries.map(e => turn(e.turnId)), + turnCatalog: { sessionId: SESSION_ID, totalTurnCount: 100, entries }, + })); + const readsAfterIndexing = entryReads; + expect(Array.from({ length: 100 }, (_, i) => resolver(i))).toEqual(Array.from({ length: 100 }, (_, i) => i)); + expect(entryReads).toBe(readsAfterIndexing); + }); +}); diff --git a/src/web-ui/src/flow_chat/utils/flowChatTurnIdentity.ts b/src/web-ui/src/flow_chat/utils/flowChatTurnIdentity.ts index a8c69d5c73..081795fa7d 100644 --- a/src/web-ui/src/flow_chat/utils/flowChatTurnIdentity.ts +++ b/src/web-ui/src/flow_chat/utils/flowChatTurnIdentity.ts @@ -196,23 +196,30 @@ export function nextStorageTurnIndex( function buildCatalogOrdinalMaps(session: TurnIdentitySession): { ordinalByTurnId: Map; ordinalByStorageIndex: Map; + storageIndexByTurnId: Map; } { const ordinalByTurnId = new Map(); const ordinalByStorageIndex = new Map(); + const storageIndexByTurnId = new Map(); for (const entry of validSessionTurnCatalog(session)?.entries ?? []) { const ordinal = asTurnOrdinal(entry.ordinal); if (entry.turnId) { ordinalByTurnId.set(entry.turnId, ordinal); } ordinalByStorageIndex.set(entry.storageTurnIndex, ordinal); + // resolveStorageTurnIndex uses the first matching catalog entry. Preserve + // that legacy fallback without scanning the catalog for every loaded Turn. + if (!storageIndexByTurnId.has(entry.turnId)) { + storageIndexByTurnId.set(entry.turnId, entry.storageTurnIndex); + } } - return { ordinalByTurnId, ordinalByStorageIndex }; + return { ordinalByTurnId, ordinalByStorageIndex, storageIndexByTurnId }; } export function createTurnOrdinalResolver( session: TurnIdentitySession, ): (localIndex: LocalTurnIndex | number) => TurnOrdinal | undefined { - const { ordinalByTurnId, ordinalByStorageIndex } = buildCatalogOrdinalMaps(session); + const { ordinalByTurnId, ordinalByStorageIndex, storageIndexByTurnId } = buildCatalogOrdinalMaps(session); const canonicalTurns = canonicalSessionTurns(session); const fallbackStartOrdinal = session.isPartial === true ? Math.max(0, projectedSessionTurnCount(session) - canonicalTurns.length) @@ -228,7 +235,8 @@ export function createTurnOrdinalResolver( return undefined; } - const storageTurnIndex = resolveStorageTurnIndex(session, turn); + const storageTurnIndex = turn.storageTurnIndex ?? turn.backendTurnIndex + ?? storageIndexByTurnId.get(turn.id); return ordinalByTurnId.get(turn.id) ?? (storageTurnIndex !== undefined ? ordinalByStorageIndex.get(storageTurnIndex) From cac8748ba822105f731ec7c5054355fb675e4cf5 Mon Sep 17 00:00:00 2001 From: kev1n77 Date: Mon, 9 Nov 2026 20:26:41 +0800 Subject: [PATCH 2/2] perf(flow-chat): reuse turn summaries across streamed body updates --- .../modern/FLOWCHAT_VERIFICATION.md | 1 + .../modern/FLOWCHAT_VIRTUALIZATION.md | 8 + .../modern/ModernFlowChatContainer.tsx | 50 +----- .../modern/flowChatTurnSummaries.test.ts | 160 ++++++++++++++++++ .../modern/flowChatTurnSummaries.ts | 147 ++++++++++++++++ 5 files changed, 321 insertions(+), 45 deletions(-) create mode 100644 src/web-ui/src/flow_chat/components/modern/flowChatTurnSummaries.test.ts create mode 100644 src/web-ui/src/flow_chat/components/modern/flowChatTurnSummaries.ts 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 f69bbec1e0..14fc86ad03 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 | |---|---| +| `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 | | `flowItemRhythm.test.ts`, `../../../tools/generative-ui/genUISpacing.test.ts` | mixed agent-card full-row children and exact generated-content gap matching through nested stacks, hidden children and insert/remove snapshots; native invalidation and performance are verified separately | | `../../store/modernFlowChatStore.test.ts`, `../../grouping/selectors.test.ts`, `../../grouping/activityGrouping.test.ts`, `../../../shared/utils/resourceBudget.test.ts` | cached/full projection equivalence across repeated thinking/tool-parameter streams, interior updates, rollback, completion and legacy retry/recovery; alternating live/history/side projections, completed-row reuse on append, same-store clear/reopen invalidation, warm equal-ID source isolation, group alias restoration and group-position independence; interrupted-prefix and shared-reference byte accounting | diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md index 9442ed11ec..911161dd2c 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md @@ -95,6 +95,14 @@ Search caches only match metadata for an active query in its owning view. Cleari search drops that cache, and unmounting drops the matcher. Lowercase transcript text exists only during a cache miss and is not retained beside the source body. +Turn navigation summaries use a reader-owned `createFlowChatTurnSummaryProjector`. +It retains only scalar Turn/catalog identities, ordinals and storage indexes. +Body-only streaming updates compare those identities and reuse the summary arrays; +structural changes rebuild one ordinal lookup shared by live and rendered +summaries. Catalog corrections, partial-tail offsets, provisional usage reports +and explicit history-window offsets keep their existing precedence. No Session, +Turn body, viewport position or editor state is retained by this cache. + ### Settled record identity Live text/thinking items can have client-generated IDs, while the host's settled diff --git a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx index 5579c2a5ab..5f2f6e88bc 100644 --- a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx +++ b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx @@ -123,10 +123,9 @@ import { canRetainContinuousHistoryProjection, } from './continuousHistoryProjection'; import { - canonicalSessionTurns, projectedSessionTurnCount, - resolveTurnOrdinal, } from '../../utils/flowChatTurnIdentity'; +import { createFlowChatTurnSummaryProjector, type FlowChatTurnSummary } from './flowChatTurnSummaries'; import type { FlowChatViewportSnapshot } from './flowChatViewportSnapshot'; import { peekConversationViewTransfer, registerConversationReader, takeConversationViewTransfer } from './flowChatViewHandoff'; import { getSubmittedMessagePreviews, subscribeSubmittedMessagePreviews } from '../../services/submittedMessagePresentation'; @@ -153,12 +152,6 @@ interface ModernFlowChatContainerProps { onOpenVisualization?: (type: string, data: any) => void; } -interface FlowChatTurnSummary { - turnId: string; - turnIndex: number; - storageTurnIndex?: number; -} - interface FlowChatHistoryPresentationState extends SessionHistoryPresentation { sessionId: string; revision: number; @@ -1060,31 +1053,16 @@ export const ModernFlowChatContainer: React.FC = ( searchCurrentMatch, ]); - const turnSummaries = useMemo(() => { - if (!activeSession) { - return []; - } - return canonicalSessionTurns(activeSession).map((turn, index) => ({ - turnId: turn.id, - turnIndex: (resolveTurnOrdinal(activeSession, turn) ?? index) + 1, - storageTurnIndex: turn.storageTurnIndex ?? turn.backendTurnIndex, - })); - }, [activeSession]); const renderedTurns = useMemo( () => renderedHistoryPresentation ? renderedHistoryPresentation.turns : activeSession?.dialogTurns ?? [], [activeSession?.dialogTurns, renderedHistoryPresentation], ); - const renderedTurnSummaries = useMemo(() => { - return renderedTurns - .filter(turn => turn.userMessage?.metadata?.usageReportProvisional !== true) - .map((turn, index) => ({ - turnId: turn.id, - turnIndex: index + 1, - storageTurnIndex: turn.storageTurnIndex ?? turn.backendTurnIndex, - })); - }, [renderedTurns]); + const [projectTurnSummaries] = useState(createFlowChatTurnSummaryProjector); + const { turnSummaries, renderedTurnSummaries, absoluteRenderedTurnSummaries } = projectTurnSummaries( + activeSession, renderedTurns, renderedHistoryPresentation?.range.startOrdinal, + ); const activeTurnCatalog = activeSession?.turnCatalog; const turnCatalog = activeTurnCatalog?.sessionId === activeSession?.sessionId ? activeTurnCatalog @@ -1092,24 +1070,6 @@ export const ModernFlowChatContainer: React.FC = ( const sessionTotalTurnCount = activeSession ? projectedSessionTurnCount(activeSession) : 0; - const absoluteRenderedTurnSummaries = useMemo(() => { - if (renderedHistoryPresentation) { - return renderedTurnSummaries.map((turn, index) => ({ - ...turn, - turnIndex: renderedHistoryPresentation.range.startOrdinal + index + 1, - })); - } - return renderedTurnSummaries.map(turn => ({ - ...turn, - turnIndex: activeSession - ? (resolveTurnOrdinal(activeSession, turn.turnId) ?? turn.turnIndex - 1) + 1 - : turn.turnIndex, - })); - }, [ - activeSession, - renderedHistoryPresentation, - renderedTurnSummaries, - ]); const absoluteRenderedTurnSummaryById = useMemo(() => { return new Map(absoluteRenderedTurnSummaries.map(turn => [turn.turnId, turn])); }, [absoluteRenderedTurnSummaries]); diff --git a/src/web-ui/src/flow_chat/components/modern/flowChatTurnSummaries.test.ts b/src/web-ui/src/flow_chat/components/modern/flowChatTurnSummaries.test.ts new file mode 100644 index 0000000000..3a39fcc12f --- /dev/null +++ b/src/web-ui/src/flow_chat/components/modern/flowChatTurnSummaries.test.ts @@ -0,0 +1,160 @@ +import { describe, expect, it } from 'vitest'; +import type { DialogTurn, Session } from '../../types/flow-chat'; +import { canonicalSessionTurns, resolveTurnOrdinal } from '../../utils/flowChatTurnIdentity'; +import { createFlowChatTurnSummaryProjector } from './flowChatTurnSummaries'; + +function turn(id: string, storageTurnIndex?: number): DialogTurn { + return { + id, sessionId: 'session', storageTurnIndex, status: 'completed', startTime: 1, + userMessage: { id: `user-${id}`, content: id, timestamp: 1 }, modelRounds: [], + }; +} + +function session(dialogTurns = [turn('a'), turn('b')], overrides: Partial = {}): Session { + return { + sessionId: 'session', dialogTurns, config: {}, status: 'idle', createdAt: 1, + lastActiveAt: 1, error: null, sessionKind: 'flow_chat', ...overrides, + }; +} + +// The previous container path remains an independent semantic oracle for small +// fixtures: single-Turn lookup, including its catalog-only and legacy fallbacks. +function reference(s: Session, rendered = s.dialogTurns, startOrdinal?: number) { + const turnSummaries = canonicalSessionTurns(s).map((t, index) => ({ + turnId: t.id, turnIndex: (resolveTurnOrdinal(s, t) ?? index) + 1, + storageTurnIndex: t.storageTurnIndex ?? t.backendTurnIndex, + })); + const renderedTurnSummaries = rendered.filter(t => t.userMessage?.metadata?.usageReportProvisional !== true) + .map((t, index) => ({ turnId: t.id, turnIndex: index + 1, storageTurnIndex: t.storageTurnIndex ?? t.backendTurnIndex })); + return { + turnSummaries, renderedTurnSummaries, + absoluteRenderedTurnSummaries: renderedTurnSummaries.map((t, index) => ({ + ...t, turnIndex: startOrdinal !== undefined ? startOrdinal + index + 1 + : (resolveTurnOrdinal(s, t.turnId) ?? t.turnIndex - 1) + 1, + })), + }; +} + +describe('FlowChat Turn summary projection', () => { + it('reuses all summary arrays across streamed text, completion and unrelated Session updates', () => { + const project = createFlowChatTurnSummaryProjector(); + let s = session(Array.from({ length: 1200 }, (_, i) => turn(`turn-${i}`, i))); + const first = project(s, s.dialogTurns); + for (let i = 0; i < 40; i++) { + s = { ...s, lastActiveAt: i, dialogTurns: s.dialogTurns.map((t, index) => index < 1199 ? t : { + ...t, status: i === 39 ? 'completed' : 'processing', + modelRounds: [{ id: 'round', index: 0, status: 'streaming', startTime: 1, isStreaming: true, isComplete: false, items: [ + { id: 'text', type: 'text', content: 'streamed text '.repeat(i + 1), isStreaming: true, timestamp: 1 }, + ] }], + }) }; + expect(project(s, s.dialogTurns)).toBe(first); + } + expect(first.turnSummaries).toHaveLength(1200); + expect(first.absoluteRenderedTurnSummaries.at(-1)?.turnIndex).toBe(1200); + }); + + it('invalidates partial-tail offsets on count changes, append, rollback and history completion', () => { + const project = createFlowChatTurnSummaryProjector(); + let s = session(undefined, { isPartial: true, totalTurnCount: 100 }); + expect(project(s, s.dialogTurns)).toEqual(reference(s)); + expect(project(s, s.dialogTurns).turnSummaries.map(t => t.turnIndex)).toEqual([99, 100]); + for (const patch of [ + { totalTurnCount: 101 }, + { dialogTurns: [...s.dialogTurns, turn('c')], totalTurnCount: 102 }, + { dialogTurns: [turn('replacement'), turn('b')], totalTurnCount: 100 }, + { isPartial: false }, + ]) { + s = { ...s, ...patch }; + expect(project(s, s.dialogTurns)).toEqual(reference(s)); + } + }); + + it('preserves catalog ordinals, deprecated storage indexes and catalog-only history', () => { + const project = createFlowChatTurnSummaryProjector(); + const legacy = turn('b'); legacy.backendTurnIndex = 99; + const s = session([turn('a', 40), legacy, turn('c')], { + isPartial: true, totalTurnCount: 12, + turnCatalog: { + schemaVersion: 1, sessionId: 'session', revision: 'catalog', complete: false, totalTurnCount: 12, + entries: ['a', 'b', 'c', 'history-only'].map((turnId, i) => ({ + turnId, ordinal: i + 8, storageTurnIndex: [40, 99, 200, 300][i], previewTruncated: false, + })), + }, + }); + const rendered = [turn('history-only')]; + expect(project(s, rendered)).toEqual(reference(s, rendered)); + expect(project(s, rendered).absoluteRenderedTurnSummaries[0].turnIndex).toBe(12); + const first = project(s, rendered, 4); + const moved = project(s, rendered, 7); + expect(moved.turnSummaries).toBe(first.turnSummaries); + expect(moved.renderedTurnSummaries).toBe(first.renderedTurnSummaries); + expect(moved.absoluteRenderedTurnSummaries[0].turnIndex).toBe(8); + expect(project(s, [], 7).absoluteRenderedTurnSummaries).toEqual([]); + }); + + it('keeps provisional usage reports out until committed, with the existing render filter', () => { + const project = createFlowChatTurnSummaryProjector(); + const provisional: DialogTurn = { + ...turn('usage'), kind: 'local_command', userMessage: { + id: 'usage-user', content: 'report', timestamp: 1, + metadata: { localCommandKind: 'usage_report', usageReportProvisional: true }, + }, + }; + const s = session([turn('a'), provisional, turn('b')], { isPartial: true, totalTurnCount: 100 }); + expect(project(s, s.dialogTurns)).toEqual(reference(s)); + provisional.userMessage!.metadata = { localCommandKind: 'usage_report', usageReportProvisional: false }; + expect(project(s, s.dialogTurns)).toEqual(reference(s)); + provisional.userMessage!.metadata = { usageReportProvisional: true }; + expect(project(s, s.dialogTurns)).toEqual(reference(s)); + }); + + it('refreshes equal-length identity corrections and catalog changes without retaining body updates', () => { + const project = createFlowChatTurnSummaryProjector(); + const s = session([turn('a', 40)], { + turnCatalog: { + schemaVersion: 1, sessionId: 'session', revision: 'catalog', complete: true, totalTurnCount: 1, + entries: [{ ordinal: 0, storageTurnIndex: 40, previewTruncated: false }], + }, + }); + const first = project(s, s.dialogTurns); + s.turnCatalog!.entries[0].ordinal = 9; + expect(project(s, s.dialogTurns).turnSummaries[0].turnIndex).toBe(10); + s.dialogTurns[0].storageTurnIndex = 41; + expect(project(s, s.dialogTurns)).toEqual(reference(s)); + s.dialogTurns[0].id = 'host-corrected-id'; + expect(project(s, s.dialogTurns).turnSummaries[0].turnId).toBe('host-corrected-id'); + expect(project(s, s.dialogTurns)).not.toBe(first); + }); + + it('ignores catalog preview-only changes and isolates cleared or switched Sessions', () => { + const project = createFlowChatTurnSummaryProjector(); + const s = session(undefined, { turnCatalog: { + schemaVersion: 1, sessionId: 'session', revision: 'one', complete: true, totalTurnCount: 2, + entries: [{ turnId: 'a', ordinal: 0, storageTurnIndex: 0, preview: 'old', previewTruncated: false }], + } }); + const first = project(s, s.dialogTurns); + const preview = { ...s, turnCatalog: { ...s.turnCatalog!, revision: 'two', entries: s.turnCatalog!.entries.map(e => ({ ...e, preview: 'new' })) } }; + expect(project(preview, preview.dialogTurns)).toBe(first); + const other = { ...s, sessionId: 'other', isPartial: true, totalTurnCount: 50 }; + expect(project(other, other.dialogTurns)).toEqual(reference(other)); + const empty = project(null, []); + expect(empty).toEqual({ turnSummaries: [], renderedTurnSummaries: [], absoluteRenderedTurnSummaries: [] }); + expect(project(undefined, [])).toBe(empty); + expect(project(s, s.dialogTurns)).toEqual(reference(s)); + }); + + it('keeps the single-Turn semantics for duplicate legacy IDs and missing catalog IDs', () => { + const s = session([turn('duplicate', 10), turn('duplicate', 20), turn(''), turn('fallback')], { + turnCatalog: { + schemaVersion: 1, sessionId: 'session', revision: 'legacy', complete: true, totalTurnCount: 4, + entries: [ + { ordinal: 0, storageTurnIndex: 10, previewTruncated: false }, + { ordinal: 1, storageTurnIndex: 20, previewTruncated: false }, + { turnId: '', ordinal: 2, storageTurnIndex: 30, previewTruncated: false }, + { turnId: '', ordinal: 3, storageTurnIndex: 40, previewTruncated: false }, + ], + }, + }); + expect(createFlowChatTurnSummaryProjector()(s, s.dialogTurns)).toEqual(reference(s)); + }); +}); diff --git a/src/web-ui/src/flow_chat/components/modern/flowChatTurnSummaries.ts b/src/web-ui/src/flow_chat/components/modern/flowChatTurnSummaries.ts new file mode 100644 index 0000000000..4d6aafe988 --- /dev/null +++ b/src/web-ui/src/flow_chat/components/modern/flowChatTurnSummaries.ts @@ -0,0 +1,147 @@ +import type { SessionTurnCatalog } from '@/shared/types/session-history'; +import type { DialogTurn, Session } from '../../types/flow-chat'; +import { createTurnOrdinalResolver, isProvisionalUsageReportTurn, validSessionTurnCatalog } from '../../utils/flowChatTurnIdentity'; + +export interface FlowChatTurnSummary { + turnId: string; + turnIndex: number; + storageTurnIndex?: number; +} + +interface TurnIdentity { + id: string; + storageTurnIndex?: number; + provisional: boolean; + excludedFromRendered: boolean; +} + +function matchesTurn(identity: TurnIdentity, turn: DialogTurn): boolean { + return identity.id === turn.id + && identity.storageTurnIndex === (turn.storageTurnIndex ?? turn.backendTurnIndex) + && identity.provisional === isProvisionalUsageReportTurn(turn) + && identity.excludedFromRendered === (turn.userMessage?.metadata?.usageReportProvisional === true); +} + +function turnIdentity(turn: DialogTurn): TurnIdentity { + return { + id: turn.id, + storageTurnIndex: turn.storageTurnIndex ?? turn.backendTurnIndex, + provisional: isProvisionalUsageReportTurn(turn), + excludedFromRendered: turn.userMessage?.metadata?.usageReportProvisional === true, + }; +} + +function matchesTurns(identities: TurnIdentity[], turns: DialogTurn[]): boolean { + return identities.length === turns.length && identities.every((identity, index) => matchesTurn(identity, turns[index])); +} + +type CatalogIdentity = Pick; + +interface SessionIdentity { + sessionId: string; + isPartial: boolean; + totalTurnCount: number | undefined; + catalogTotalTurnCount: number | undefined; + turns: TurnIdentity[]; + catalog: CatalogIdentity[]; +} + +interface TurnSummaries { + turnSummaries: FlowChatTurnSummary[]; + renderedTurnSummaries: FlowChatTurnSummary[]; + absoluteRenderedTurnSummaries: FlowChatTurnSummary[]; +} + +/** One reader's scalar metadata only; never retain streamed bodies or Sessions. */ +export function createFlowChatTurnSummaryProjector() { + let identity: SessionIdentity | undefined; + let renderedIdentities: TurnIdentity[] = []; + let renderedStartOrdinal: number | undefined; + let ordinalById = new Map(); + let result: TurnSummaries = { + turnSummaries: [], renderedTurnSummaries: [], absoluteRenderedTurnSummaries: [], + }; + + return (session: Session | null | undefined, renderedTurns: DialogTurn[], startOrdinal?: number): TurnSummaries => { + const catalog = session ? validSessionTurnCatalog(session) : undefined; + const entries = catalog?.entries ?? []; + // Text flushes replace Sessions and Turn arrays. Compare their small + // identity fields without allocating summaries or rebuilding ordinal maps. + const sessionChanged = session ? !identity + || identity.sessionId !== session.sessionId + || identity.isPartial !== (session.isPartial === true) + || identity.totalTurnCount !== session.totalTurnCount + || identity.catalogTotalTurnCount !== catalog?.totalTurnCount + || !matchesTurns(identity.turns, session.dialogTurns) + || identity.catalog.length !== entries.length + || !identity.catalog.every((entry, index) => entry.turnId === entries[index].turnId + && entry.ordinal === entries[index].ordinal + && entry.storageTurnIndex === entries[index].storageTurnIndex) + : identity !== undefined; + let turnSummaries = result.turnSummaries; + if (sessionChanged) { + identity = session ? { + sessionId: session.sessionId, + isPartial: session.isPartial === true, + totalTurnCount: session.totalTurnCount, + catalogTotalTurnCount: catalog?.totalTurnCount, + turns: session.dialogTurns.map(turnIdentity), + catalog: entries.map(({ turnId, ordinal, storageTurnIndex }) => ({ turnId, ordinal, storageTurnIndex })), + } : undefined; + ordinalById = new Map(); + // Catalog-only history uses the first matching entry, just as the + // single-Turn resolver does. Loaded identities take precedence below. + for (const entry of entries) { + if (entry.turnId !== undefined && !ordinalById.has(entry.turnId)) { + ordinalById.set(entry.turnId, entry.ordinal); + } + } + if (session) { + const resolveOrdinal = createTurnOrdinalResolver(session); + const seen = new Set(); + session.dialogTurns.forEach((turn, index) => { + if (seen.has(turn.id)) return; + seen.add(turn.id); + ordinalById.set(turn.id, resolveOrdinal(index)); + }); + } + turnSummaries = []; + for (const turn of identity?.turns ?? []) { + if (turn.provisional) continue; + turnSummaries.push({ + turnId: turn.id, + turnIndex: (ordinalById.get(turn.id) ?? turnSummaries.length) + 1, + storageTurnIndex: turn.storageTurnIndex, + }); + } + } + + const renderedChanged = !matchesTurns(renderedIdentities, renderedTurns); + let renderedTurnSummaries = result.renderedTurnSummaries; + if (renderedChanged) { + renderedIdentities = renderedTurns.map(turnIdentity); + renderedTurnSummaries = []; + for (const turn of renderedIdentities) { + if (turn.excludedFromRendered) continue; + renderedTurnSummaries.push({ + turnId: turn.id, + turnIndex: renderedTurnSummaries.length + 1, + storageTurnIndex: turn.storageTurnIndex, + }); + } + } + if (sessionChanged || renderedChanged || renderedStartOrdinal !== startOrdinal) { + renderedStartOrdinal = startOrdinal; + result = { + turnSummaries, + renderedTurnSummaries, + absoluteRenderedTurnSummaries: renderedTurnSummaries.map((turn, index) => ({ + ...turn, + turnIndex: startOrdinal !== undefined ? startOrdinal + index + 1 + : (ordinalById.get(turn.turnId) ?? turn.turnIndex - 1) + 1, + })), + }; + } + return result; + }; +}