:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(llma): Rebuild session details page to show messages (#58357)
Marcel Poelkerede1da0167ef
diff --git a/products/llm_analytics/frontend/ConversationDisplay/ConversationDisplay.tsx b/products/llm_analytics/frontend/ConversationDisplay/ConversationDisplay.tsxindex 222312181694..3d2a6871dcb4 100644--- a/products/llm_analytics/frontend/ConversationDisplay/ConversationDisplay.tsx+++ b/products/llm_analytics/frontend/ConversationDisplay/ConversationDisplay.tsx@@ -6,9 +6,10 @@ import { LemonButton } from '@posthog/lemon-ui'import { EventType } from '~/types'import { AIDataLoading } from '../components/AIDataLoading'+import { buildInputSourceIndices } from '../extractSessionTurns'import { useAIData } from '../hooks/useAIData'import { openInPlayground } from '../playground/llmPlaygroundPromptsLogic'-import { costContextFromProperties, normalizeMessage, normalizeMessages } from '../utils'+import { costContextFromProperties, normalizeMessages } from '../utils'import { ConversationMessagesDisplay } from './ConversationMessagesDisplay'import { MetadataHeader } from './MetadataHeader'@@ -47,21 +48,7 @@ export function ConversationDisplay({const showPlaygroundButton = eventProperties.$ai_model && input- const inputSourceIndices = React.useMemo(() => {- const indices: number[] = []- if (tools) {- indices.push(-1)- }- if (Array.isArray(input)) {- for (let i = 0; i < input.length; i++) {- const expanded = normalizeMessage(input[i], 'user')- for (let j = 0; j < expanded.length; j++) {- indices.push(i)- }- }- }- return indices- }, [input, tools])+ const inputSourceIndices = React.useMemo(() => buildInputSourceIndices(input, tools), [input, tools])return (<>diff --git a/products/llm_analytics/frontend/LLMAnalyticsSessionScene.tsx b/products/llm_analytics/frontend/LLMAnalyticsSessionScene.tsxindex adaa6fb121e0..7b8b9575aa1a 100644--- a/products/llm_analytics/frontend/LLMAnalyticsSessionScene.tsx+++ b/products/llm_analytics/frontend/LLMAnalyticsSessionScene.tsx@@ -2,7 +2,6 @@ import { BindLogic, useActions, useValues } from 'kea'import { combineUrl, router } from 'kea-router'import { Suspense, lazy } from 'react'-import { IconChevronDown, IconChevronRight } from '@posthog/icons'import { LemonButton, LemonTag, Spinner, SpinnerOverlay, Tooltip } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'@@ -19,11 +18,14 @@ import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPimport { urls } from 'scenes/urls'import { SceneBreadcrumbBackButton } from '~/layout/scenes/components/SceneBreadcrumbs'+import { LLMTrace } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType } from '~/types'import { AIObservabilityRenameBanner } from './AIObservabilityRenameBanner'import { LLMAnalyticsTraceEvents } from './components/LLMAnalyticsTraceEvents'import { SentimentBar } from './components/SentimentTag'+import { ConversationMessagesDisplay } from './ConversationDisplay/ConversationMessagesDisplay'+import { SessionTurn } from './extractSessionTurns'import { TraceSummary, llmAnalyticsSessionDataLogic } from './llmAnalyticsSessionDataLogic'import { llmAnalyticsSessionLogic } from './llmAnalyticsSessionLogic'import { llmSentimentLazyLoaderLogic } from './llmSentimentLazyLoaderLogic'@@ -87,28 +89,18 @@ function SessionTraceSentimentBar({ traceId, createdAt }: { traceId: string; crefunction SessionSceneWrapper(): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)- const { searchParams } = useValues(router)- const traceSearchParams = sanitizeTraceUrlSearchParams(searchParams, { removeSearch: true })const showFeedback = !!featureFlags[FEATURE_FLAGS.POSTHOG_AI_CONVERSATION_FEEDBACK_LLMA_SESSIONS]const showSentiment = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_SENTIMENT]- const {- traces,- responseLoading,- responseError,- expandedTraceIds,- expandedGenerationIds,- fullTraces,- loadingFullTraces,- traceSummaries,- summariesLoading,- hasMoreData,- nextDataLoading,- } = useValues(llmAnalyticsSessionDataLogic)+ const { traces, responseLoading, responseError, sessionTurns, hasMoreData, nextDataLoading, summariesLoading } =+ useValues(llmAnalyticsSessionDataLogic)const { sessionId } = useValues(llmAnalyticsSessionLogic)- const { toggleTraceExpanded, toggleGenerationExpanded, summarizeAllTraces, loadNextData } =- useActions(llmAnalyticsSessionDataLogic)+ const { summarizeAllTraces, loadNextData } = useActions(llmAnalyticsSessionDataLogic)const { dataProcessingAccepted } = useValues(maxGlobalLogic)+ // Compute the URL search-param passthrough once for the page, not per turn —+ // every `SessionTurnView` consumes the same `traceSearchParams`.+ const { searchParams } = useValues(router)+ const traceSearchParams = sanitizeTraceUrlSearchParams(searchParams, { removeSearch: true })const showSessionSummarization =featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_SESSION_SUMMARIZATION] ||@@ -120,227 +112,315 @@ function SessionSceneWrapper(): JSX.Element {totalCost: acc.totalCost + (trace.totalCost || 0),totalLatency: acc.totalLatency + (trace.totalLatency || 0),traceCount: acc.traceCount + 1,- firstSeen: !acc.firstSeen || trace.createdAt < acc.firstSeen ? trace.createdAt : acc.firstSeen,- lastSeen: !acc.lastSeen || trace.createdAt > acc.lastSeen ? trace.createdAt : acc.lastSeen,}),- { totalCost: 0, totalLatency: 0, traceCount: 0, firstSeen: '', lastSeen: '' }+ { totalCost: 0, totalLatency: 0, traceCount: 0 })+ if (responseLoading) {+ return <SpinnerOverlay />+ }+ if (responseError) {+ return <InsightErrorState />+ }+ if (!traces || traces.length === 0) {+ return <InsightEmptyState heading="No traces found" detail="This session has no traces." />+ }+return (- <>- {responseLoading ? (- <SpinnerOverlay />- ) : responseError ? (- <InsightErrorState />- ) : !traces || traces.length === 0 ? (- <InsightEmptyState heading="No traces found" detail="This session has no traces." />- ) : (- <div className="relative flex flex-col gap-3">- <SceneBreadcrumbBackButton />- <AIObservabilityRenameBanner />- <div className="flex items-start justify-between">- <header className="flex gap-1.5 flex-wrap">- <LemonTag size="medium" className="bg-surface-primary">- <span className="font-mono">{sessionId}</span>- </LemonTag>- <LemonTag size="medium" className="bg-surface-primary">- {sessionStats.traceCount}- {hasMoreData ? '+' : ''} {sessionStats.traceCount === 1 ? 'trace' : 'traces'}- </LemonTag>- {sessionStats.totalCost > 0 && (- <LemonTag size="medium" className="bg-surface-primary">- Total: {formatLLMCost(sessionStats.totalCost)}- </LemonTag>- )}- {sessionStats.totalLatency > 0 && (- <LemonTag size="medium" className="bg-surface-primary">- {sessionStats.totalLatency.toFixed(2)}s- </LemonTag>- )}- {/* This is an internal component, it's lazy loaded and behind feature flag. */}- {showFeedback && (- <Suspense fallback={<Spinner />}>- <LLMASessionFeedbackDisplay sessionId={sessionId} />- </Suspense>- )}- </header>- {showSessionSummarization && (- <div className="flex gap-2">- {!dataProcessingAccepted ? (- <AIConsentPopoverWrapper- showArrow- onApprove={summarizeAllTraces}- hidden={summariesLoading}- >- <AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- type="primary"- size="small"- loading={summariesLoading}- disabledReason="AI data processing must be approved to summarize traces"- data-attr="llm-session-summarize-all"- >- Summarize all traces- </LemonButton>- </AccessControlAction>- </AIConsentPopoverWrapper>- ) : (- <AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- type="primary"- size="small"- onClick={summarizeAllTraces}- loading={summariesLoading}- data-attr="llm-session-summarize-all"- >- Summarize all traces- </LemonButton>- </AccessControlAction>- )}- </div>- )}- </div>- <div className="bg-surface-primary border rounded p-4">- <h3 className="font-semibold text-sm mb-3">Traces in this session</h3>- <div className="space-y-2">- {traces.map((trace, index) => {- const isTraceExpanded = expandedTraceIds.has(trace.id)- const summary: TraceSummary | undefined = traceSummaries[trace.id]- const turnNumber = index + 1+ <div className="relative flex flex-col gap-4">+ <SceneBreadcrumbBackButton />+ <AIObservabilityRenameBanner />+ <header className="flex items-start justify-between gap-3 flex-wrap">+ <div className="flex gap-1.5 flex-wrap">+ <LemonTag size="medium" className="bg-surface-primary">+ <span className="font-mono">{sessionId}</span>+ </LemonTag>+ <LemonTag size="medium" className="bg-surface-primary">+ {sessionStats.traceCount}+ {hasMoreData ? '+' : ''} {sessionStats.traceCount === 1 ? 'turn' : 'turns'}+ </LemonTag>+ {sessionStats.totalCost > 0 && (+ <LemonTag size="medium" className="bg-surface-primary">+ Total: {formatLLMCost(sessionStats.totalCost)}+ </LemonTag>+ )}+ {sessionStats.totalLatency > 0 && (+ <LemonTag size="medium" className="bg-surface-primary">+ {sessionStats.totalLatency.toFixed(2)}s+ </LemonTag>+ )}+ {showFeedback && (+ <Suspense fallback={<Spinner />}>+ <LLMASessionFeedbackDisplay sessionId={sessionId} />+ </Suspense>+ )}+ </div>+ {showSessionSummarization && (+ <SummarizeAllButton+ loading={summariesLoading}+ dataProcessingAccepted={dataProcessingAccepted}+ onSummarize={summarizeAllTraces}+ />+ )}+ </header>- return (- <div key={trace.id} className="border rounded">- <div- className="p-3 hover:bg-side-light cursor-pointer flex items-start gap-2"- onClick={() => toggleTraceExpanded(trace.id)}- >- <div className="flex-shrink-0 mt-0.5">- {isTraceExpanded ? (- <IconChevronDown className="text-lg" />- ) : (- <IconChevronRight className="text-lg" />- )}- </div>- <div className="flex-1">- <div className="flex items-center gap-2 mb-2 flex-wrap">- <span className="text-xs font-semibold text-muted">- #{turnNumber}- </span>- <strong className="font-mono text-xs">- {trace.id.slice(0, 8)}...- </strong>- {trace.traceName && (- <span className="text-sm">{trace.traceName}</span>- )}- {(trace.errorCount ?? 0) > 0 && (- <LemonTag type="danger" size="small">- {trace.errorCount === 1- ? '1 error'- : `${trace.errorCount} errors`}- </LemonTag>- )}- {typeof trace.totalLatency === 'number' && (- <LemonTag type="muted">- {trace.totalLatency.toFixed(2)}s- </LemonTag>- )}- {typeof trace.totalCost === 'number' && (- <LemonTag type="muted">- {formatLLMCost(trace.totalCost)}- </LemonTag>- )}- {showSentiment && (- <SessionTraceSentimentBar- traceId={trace.id}- createdAt={trace.createdAt}- />- )}- <Link- to={- combineUrl(urls.llmAnalyticsTrace(trace.id), {- ...traceSearchParams,- timestamp: getTraceTimestamp(trace.createdAt),- }).url- }- onClick={(e) => e.stopPropagation()}- className="text-xs"- >- View full trace →- </Link>- </div>- {showSessionSummarization && summary && (- <div className="flex items-center gap-2 mb-2">- {summary.loading ? (- <div className="flex items-center gap-2 text-muted text-sm">- <Spinner className="text-lg" />- <span>Generating summary...</span>- </div>- ) : summary.error ? (- <Tooltip title={summary.error}>- <span className="text-danger text-sm">- Failed to generate summary- </span>- </Tooltip>- ) : (- <Link- to={- combineUrl(urls.llmAnalyticsTrace(trace.id), {- ...traceSearchParams,- timestamp: getTraceTimestamp(trace.createdAt),- tab: 'summary',- }).url- }- onClick={(e) => e.stopPropagation()}- className="text-sm font-medium"- >- {summary.title}- </Link>- )}- </div>- )}- <div className="text-xs text-muted">- <TZLabel time={trace.createdAt} />- </div>- </div>- </div>- {isTraceExpanded && (- <div className="border-t bg-bg-light">- <div className="p-3 space-y-2">- <LLMAnalyticsTraceEvents- trace={fullTraces[trace.id]}- isLoading={loadingFullTraces.has(trace.id)}- expandedEventIds={expandedGenerationIds}- onToggleEventExpand={toggleGenerationExpanded}- traceId={trace.id}- />- </div>- </div>- )}- </div>- )- })}- {hasMoreData && (- <div className="flex justify-center pt-2">- <LemonButton- type="secondary"- loading={nextDataLoading}- onClick={loadNextData}- data-attr="llm-session-load-more-traces"- >- Load more traces- </LemonButton>- </div>- )}- </div>+ <div className="flex flex-col">+ {sessionTurns.map((turn, index) => (+ <SessionTurnView+ key={turn.trace.id}+ turn={turn}+ turnNumber={index + 1}+ showSentiment={showSentiment}+ showSessionSummarization={!!showSessionSummarization}+ traceSearchParams={traceSearchParams}+ />+ ))}+ {hasMoreData && (+ <div className="flex justify-center pt-4">+ <LemonButton+ type="secondary"+ loading={nextDataLoading}+ onClick={loadNextData}+ data-attr="llm-session-load-more-traces"+ >+ Load more turns+ </LemonButton></div>+ )}+ </div>+ </div>+ )+}++function SummarizeAllButton({+ loading,+ dataProcessingAccepted,+ onSummarize,+}: {+ loading: boolean+ dataProcessingAccepted: boolean+ onSummarize: () => void+}): JSX.Element {+ if (!dataProcessingAccepted) {+ return (+ <AIConsentPopoverWrapper showArrow onApprove={onSummarize} hidden={loading}>+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="primary"+ size="small"+ loading={loading}+ disabledReason="AI data processing must be approved to summarize traces"+ data-attr="llm-session-summarize-all"+ >+ Summarize all turns+ </LemonButton>+ </AccessControlAction>+ </AIConsentPopoverWrapper>+ )+ }+ return (+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="primary"+ size="small"+ onClick={onSummarize}+ loading={loading}+ data-attr="llm-session-summarize-all"+ >+ Summarize all turns+ </LemonButton>+ </AccessControlAction>+ )+}++function SessionTurnView({+ turn,+ turnNumber,+ showSentiment,+ showSessionSummarization,+ traceSearchParams,+}: {+ turn: SessionTurn+ turnNumber: number+ showSentiment: boolean+ showSessionSummarization: boolean+ traceSearchParams: Record<string, unknown>+}): JSX.Element {+ const { traceSummaries, loadingFullTraces, fullTraces, reasoningExpandedTraceIds, expandedGenerationIds } =+ useValues(llmAnalyticsSessionDataLogic)+ const { toggleReasoning, toggleGenerationExpanded, loadFullTrace } = useActions(llmAnalyticsSessionDataLogic)++ const trace = turn.trace+ const summary: TraceSummary | undefined = traceSummaries[trace.id]+ const isLoading = loadingFullTraces.has(trace.id)+ const reasoningShown = reasoningExpandedTraceIds.has(trace.id)+ const fullTrace = fullTraces[trace.id]+ const baseTraceParams = {+ ...traceSearchParams,+ timestamp: getTraceTimestamp(trace.createdAt),+ }+ const traceUrl = combineUrl(urls.llmAnalyticsTrace(trace.id), baseTraceParams).url+ const summaryUrl = combineUrl(urls.llmAnalyticsTrace(trace.id), { ...baseTraceParams, tab: 'summary' }).url++ return (+ <div className="flex flex-col gap-2 py-4 border-t first:border-t-0 first:pt-0">+ <div className="flex items-center gap-2 flex-wrap text-xs text-muted">+ <span className="font-semibold text-default">Turn {turnNumber}</span>+ {(trace.errorCount ?? 0) > 0 && (+ <LemonTag type="danger" size="small">+ {trace.errorCount === 1 ? '1 error' : `${trace.errorCount} errors`}+ </LemonTag>+ )}+ {typeof trace.totalLatency === 'number' && <span>{trace.totalLatency.toFixed(2)}s</span>}+ {typeof trace.totalCost === 'number' && <span>· {formatLLMCost(trace.totalCost)}</span>}+ <span>+ · <TZLabel time={trace.createdAt} />+ </span>+ {showSentiment && (+ <span className="ml-1">+ <SessionTraceSentimentBar traceId={trace.id} createdAt={trace.createdAt} />+ </span>+ )}+ <div className="flex-1" />+ <Link to={traceUrl} className="text-xs">+ Open trace →+ </Link>+ </div>++ {showSessionSummarization && summary && <TurnSummaryLine summary={summary} summaryUrl={summaryUrl} />}++ <TurnBody turn={turn} isLoading={isLoading} onLoad={() => loadFullTrace(trace.id)} />++ {turn.isLoaded && turn.userVisibleTurn && (+ <ReasoningToggle+ traceId={trace.id}+ fullTrace={fullTrace}+ reasoningShown={reasoningShown}+ onToggle={() => toggleReasoning(trace.id)}+ expandedEventIds={expandedGenerationIds}+ onToggleEventExpand={toggleGenerationExpanded}+ />+ )}+ </div>+ )+}++function TurnSummaryLine({ summary, summaryUrl }: { summary: TraceSummary; summaryUrl: string }): JSX.Element {+ if (summary.loading) {+ return (+ <div className="flex items-center gap-2 text-muted text-sm">+ <Spinner className="text-lg" />+ <span>Generating summary...</span>+ </div>+ )+ }+ if (summary.error) {+ return (+ <Tooltip title={summary.error}>+ <span className="text-danger text-sm">Failed to generate summary</span>+ </Tooltip>+ )+ }+ return (+ <Link to={summaryUrl} className="text-sm font-medium">+ {summary.title}+ </Link>+ )+}++function TurnBody({+ turn,+ isLoading,+ onLoad,+}: {+ turn: SessionTurn+ isLoading: boolean+ onLoad: () => void+}): JSX.Element {+ if (isLoading) {+ return (+ <div className="flex items-center gap-2 text-muted text-sm py-2">+ <Spinner className="text-lg" />+ <span>Loading conversation…</span>+ </div>+ )+ }+ if (!turn.isLoaded) {+ return (+ <div className="py-2">+ <LemonButton size="small" type="secondary" onClick={onLoad}>+ Show conversation+ </LemonButton>+ </div>+ )+ }+ if (!turn.userVisibleTurn) {+ return <div className="text-muted text-sm py-2">No conversational turn to render in this trace.</div>+ }+ // `turn.newInputs` / `outputs` come pre-deduped from `extractSessionTurns`.+ // Rendering goes through the same `ConversationMessagesDisplay` the Trace page+ // uses, so parser coverage is identical: shapes recognized by `normalizeMessage`+ // render natively, anything else falls back to JSON. See `extractSessionTurns.ts`+ // and `messageSignature.ts` for the dedup + user-visible-turn conventions.+ return (+ <ConversationMessagesDisplay+ inputNormalized={turn.newInputs}+ outputNormalized={turn.outputs}+ inputSourceIndices={turn.newInputSourceIndices}+ errorData={turn.userVisibleTurn.properties.$ai_error}+ httpStatus={turn.userVisibleTurn.properties.$ai_http_status}+ raisedError={turn.userVisibleTurn.properties.$ai_is_error}+ bordered+ // Explicit so the Session view doesn't silently inherit a future+ // change to the Trace page's default — the two surfaces can diverge.+ displayOption="collapse_except_output_and_last_input"+ traceId={turn.userVisibleTurn.properties.$ai_trace_id}+ generationEventId={turn.userVisibleTurn.id}+ />+ )+}++function ReasoningToggle({+ traceId,+ fullTrace,+ reasoningShown,+ onToggle,+ expandedEventIds,+ onToggleEventExpand,+}: {+ traceId: string+ fullTrace: LLMTrace | undefined+ reasoningShown: boolean+ onToggle: () => void+ expandedEventIds: Set<string>+ onToggleEventExpand: (eventId: string) => void+}): JSX.Element {+ return (+ <div className="flex flex-col gap-2">+ <button+ type="button"+ onClick={onToggle}+ className="self-start text-xs text-muted hover:text-default underline"+ >+ {reasoningShown ? 'Hide reasoning' : 'Show reasoning'}+ </button>+ {reasoningShown && (+ <div className="border rounded bg-bg-light p-3">+ <LLMAnalyticsTraceEvents+ trace={fullTrace}+ isLoading={false}+ expandedEventIds={expandedEventIds}+ onToggleEventExpand={onToggleEventExpand}+ traceId={traceId}+ /></div>)}- </>+ </div>)}diff --git a/products/llm_analytics/frontend/extractSessionTurns.test.ts b/products/llm_analytics/frontend/extractSessionTurns.test.tsnew file mode 100644index 000000000000..201bc59acfb3--- /dev/null+++ b/products/llm_analytics/frontend/extractSessionTurns.test.ts@@ -0,0 +1,642 @@+import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'++import { buildInputSourceIndices, extractSessionTurns, pickUserVisibleTurn } from './extractSessionTurns'++function makeGeneration(+ id: string,+ createdAt: string,+ overrides: Partial<LLMTraceEvent['properties']> = {}+): LLMTraceEvent {+ return {+ id,+ event: '$ai_generation',+ createdAt,+ properties: {+ $ai_input: [{ role: 'user', content: 'hi' }],+ $ai_output_choices: [{ role: 'assistant', content: 'hello' }],+ ...overrides,+ },+ }+}++function makeTrace(id: string, events: LLMTraceEvent[], overrides: Partial<LLMTrace> = {}): LLMTrace {+ return {+ id,+ createdAt: events[0]?.createdAt ?? '2026-05-11T00:00:00.000Z',+ distinctId: 'user-1',+ events,+ ...overrides,+ }+}++describe('pickUserVisibleTurn', () => {+ it('returns undefined when the trace has no generation events', () => {+ const trace = makeTrace('t1', [+ { id: 's1', event: '$ai_span', createdAt: '2026-05-11T00:00:00.000Z', properties: {} },+ ])+ expect(pickUserVisibleTurn(trace)).toBeUndefined()+ })++ it('returns the latest $ai_generation by createdAt', () => {+ const g1 = makeGeneration('g1', '2026-05-11T00:00:00.000Z')+ const g2 = makeGeneration('g2', '2026-05-11T00:00:01.000Z')+ const g3 = makeGeneration('g3', '2026-05-11T00:00:02.000Z')+ // Events out of order in the array shouldn't change the answer.+ const trace = makeTrace('t1', [g2, g3, g1])+ expect(pickUserVisibleTurn(trace)?.id).toBe('g3')+ })++ it('ignores non-generation events even if they are newer', () => {+ const g1 = makeGeneration('g1', '2026-05-11T00:00:00.000Z')+ const traceEvent: LLMTraceEvent = {+ id: 'trace',+ event: '$ai_trace',+ createdAt: '2026-05-11T00:00:09.000Z',+ properties: {},+ }+ const trace = makeTrace('t1', [g1, traceEvent])+ expect(pickUserVisibleTurn(trace)?.id).toBe('g1')+ })+})++describe('buildInputSourceIndices', () => {+ it('returns an empty array for non-array inputs', () => {+ expect(buildInputSourceIndices('not an array', undefined)).toEqual([])+ })++ it('prepends -1 when tools are present', () => {+ const indices = buildInputSourceIndices([{ role: 'user', content: 'hi' }], [{ name: 'lookup' }])+ expect(indices[0]).toBe(-1)+ })++ it('emits one index per normalized message, repeating when one raw entry expands', () => {+ // A single raw entry with typed parts may normalize to multiple CompatMessages.+ const raw = [+ { role: 'user', content: 'Hi' },+ {+ role: 'assistant',+ content: [+ { type: 'thinking', thinking: 'pondering' },+ { type: 'text', text: 'Hello' },+ ],+ },+ ]+ const indices = buildInputSourceIndices(raw, undefined)+ // First entry maps to 0; second entry expands to 2 messages, both mapping to 1.+ expect(indices[0]).toBe(0)+ // We don't assert on the rest of the shape — `normalizeMessage`'s expansion is+ // covered by utils.test.ts — but every emitted index should be in {0, 1}.+ for (const i of indices) {+ expect([0, 1]).toContain(i)+ }+ })+})++describe('extractSessionTurns — cross-trace dedup', () => {+ it('returns isLoaded=false placeholders for traces whose full data is missing', () => {+ const t1 = makeTrace('t1', [makeGeneration('g1', '2026-05-11T00:00:00.000Z')])+ const turns = extractSessionTurns([t1], {})+ expect(turns).toHaveLength(1)+ expect(turns[0].isLoaded).toBe(false)+ expect(turns[0].newInputs).toEqual([])+ expect(turns[0].outputs).toEqual([])+ })++ it('returns an isLoaded turn with no userVisibleTurn for span-only traces', () => {+ // No $ai_generation in the trace — `pickUserVisibleTurn` finds nothing,+ // so the placeholder turn signals "loaded, but no conversational content+ // to render". `TurnBody` renders the "No conversational turn to render"+ // message in this state.+ const t1 = makeTrace('t1', [+ { id: 's1', event: '$ai_span', createdAt: '2026-05-11T00:00:00.000Z', properties: {} },+ ])+ const turns = extractSessionTurns([t1], { t1 })+ expect(turns).toHaveLength(1)+ expect(turns[0].isLoaded).toBe(true)+ expect(turns[0].userVisibleTurn).toBeUndefined()+ expect(turns[0].newInputs).toEqual([])+ expect(turns[0].outputs).toEqual([])+ })++ it('shows the full input on the first turn (nothing seen yet)', () => {+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: [{ role: 'user', content: 'Hi! Can you help me plan a trip to Japan?' }],+ $ai_output_choices: [{ role: 'assistant', content: 'Of course! What time of year?' }],+ }),+ ])+ const turns = extractSessionTurns([t1], { t1 })+ expect(turns[0].isLoaded).toBe(true)+ expect(turns[0].newInputs).toHaveLength(1)+ expect(turns[0].newInputs[0].content).toBe('Hi! Can you help me plan a trip to Japan?')+ expect(turns[0].outputs).toHaveLength(1)+ })++ it('hides messages already shown in earlier turns', () => {+ // Turn 1 sends: [user: "Hi"] → assistant: "Hello"+ // Turn 2 sends: [user: "Hi", assistant: "Hello", user: "Tell me a joke"]+ // Without dedup we would re-render the first two; with dedup, only the new user message.+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: [{ role: 'user', content: 'Hi' }],+ $ai_output_choices: [{ role: 'assistant', content: 'Hello' }],+ }),+ ])+ const t2 = makeTrace('t2', [+ makeGeneration('g2', '2026-05-11T00:00:01.000Z', {+ $ai_input: [+ { role: 'user', content: 'Hi' },+ { role: 'assistant', content: 'Hello' },+ { role: 'user', content: 'Tell me a joke' },+ ],+ $ai_output_choices: [{ role: 'assistant', content: 'Why did the chicken...' }],+ }),+ ])+ const turns = extractSessionTurns([t1, t2], { t1, t2 })+ expect(turns[1].newInputs).toHaveLength(1)+ expect(turns[1].newInputs[0].content).toBe('Tell me a joke')+ // The output is rendered in full — it's new this turn.+ expect(turns[1].outputs).toHaveLength(1)+ expect(turns[1].outputs[0].content).toBe('Why did the chicken...')+ })++ it('renders identical messages within the same turn (count-based dedup)', () => {+ // Dedup tracks how many copies of each signature have been shown so far,+ // not just whether the signature has been seen. Within-turn duplicates+ // are real content (the trace shows the agent saw both) and render as+ // separate bubbles — hiding one would silently drop information from the+ // transcript. Prior behavior collapsed within-turn duplicates as a side+ // effect of set-based dedup; the count-based model unifies cross-turn+ // and within-turn handling so legitimate repeats always survive.+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: [+ { role: 'tool', content: 'Memory appended.' },+ { role: 'tool', content: 'Memory appended.' },+ { role: 'user', content: 'Continue' },+ ],+ $ai_output_choices: [{ role: 'assistant', content: 'ok' }],+ }),+ ])+ const turns = extractSessionTurns([t1], { t1 })+ expect(turns[0].newInputs.map((m) => m.role)).toEqual(['tool', 'tool', 'user'])+ })++ it('renders a repeated user message that arrives after the assistant replied to its first occurrence', () => {+ // Radu's review case: the user typed "continue" twice, with an+ // assistant reply in between. Turn 2's $ai_input carries the full+ // running history — [continue, sure, continue] — and the second+ // "continue" must render despite signature-matching the first.+ // Set-based dedup would silently drop it, leaving the transcript+ // appearing to skip a real user turn.+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: [{ role: 'user', content: 'continue' }],+ $ai_output_choices: [{ role: 'assistant', content: 'sure' }],+ }),+ ])+ const t2 = makeTrace('t2', [+ makeGeneration('g2', '2026-05-11T00:00:01.000Z', {+ $ai_input: [+ { role: 'user', content: 'continue' },+ { role: 'assistant', content: 'sure' },+ { role: 'user', content: 'continue' },+ ],+ $ai_output_choices: [{ role: 'assistant', content: 'ok' }],+ }),+ ])+ const turns = extractSessionTurns([t1, t2], { t1, t2 })+ expect(turns[1].newInputs).toHaveLength(1)+ expect(turns[1].newInputs[0].role).toBe('user')+ expect(turns[1].newInputs[0].content).toBe('continue')+ // The new "continue" lives at index 2 of turn 2's raw input.+ expect(turns[1].newInputSourceIndices).toEqual([2])+ })++ it('renders the same user message N times when it appears N times across N turns', () => {+ // Generalisation of the "continue" case: the user keeps asking the+ // exact same thing across three turns. Each turn's $ai_input adds one+ // more copy on top of the prior history; the count-based dedup+ // surfaces exactly the one new copy per turn.+ const make = (index: number, inputs: { role: string; content: string }[]): LLMTrace =>+ makeTrace(`t${index}`, [+ makeGeneration(`g${index}`, `2026-05-11T00:00:0${index - 1}.000Z`, {+ $ai_input: inputs,+ $ai_output_choices: [{ role: 'assistant', content: `reply ${index}` }],+ }),+ ])+ const t1 = make(1, [{ role: 'user', content: 'same?' }])+ const t2 = make(2, [+ { role: 'user', content: 'same?' },+ { role: 'assistant', content: 'reply 1' },+ { role: 'user', content: 'same?' },+ ])+ const t3 = make(3, [+ { role: 'user', content: 'same?' },+ { role: 'assistant', content: 'reply 1' },+ { role: 'user', content: 'same?' },+ { role: 'assistant', content: 'reply 2' },+ { role: 'user', content: 'same?' },+ ])+ const turns = extractSessionTurns([t1, t2, t3], { t1, t2, t3 })+ // Each turn surfaces exactly the one new user message.+ expect(turns[0].newInputs.map((m) => m.content)).toEqual(['same?'])+ expect(turns[1].newInputs.map((m) => m.content)).toEqual(['same?'])+ expect(turns[2].newInputs.map((m) => m.content)).toEqual(['same?'])+ })++ it('renders only the delta when a later turn carries more copies than were shown', () => {+ // Asymmetric counts: turn 1 had two copies of the same tool response+ // (both rendered under count-based dedup). Turn 2 carries three copies+ // in its running history — the third one is new and must render.+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: [+ { role: 'tool', content: 'ack' },+ { role: 'tool', content: 'ack' },+ ],+ $ai_output_choices: [{ role: 'assistant', content: 'thanks' }],+ }),+ ])+ const t2 = makeTrace('t2', [+ makeGeneration('g2', '2026-05-11T00:00:01.000Z', {+ $ai_input: [+ { role: 'tool', content: 'ack' },+ { role: 'tool', content: 'ack' },+ { role: 'assistant', content: 'thanks' },+ { role: 'tool', content: 'ack' },+ ],+ $ai_output_choices: [{ role: 'assistant', content: 'done' }],+ }),+ ])+ const turns = extractSessionTurns([t1, t2], { t1, t2 })+ expect(turns[1].newInputs.map((m) => m.role)).toEqual(['tool'])+ // The new tool message is at index 3 of turn 2's raw input.+ expect(turns[1].newInputSourceIndices).toEqual([3])+ })++ it('renders an assistant reply that exactly repeats a prior turn output', () => {+ // The assistant emits the same reply across two turns (e.g. a curt+ // "done" after similar requests). Each turn's output is a brand-new+ // emission and must render in full, regardless of whether earlier+ // outputs had the same signature.+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: [{ role: 'user', content: 'first' }],+ $ai_output_choices: [{ role: 'assistant', content: 'done' }],+ }),+ ])+ const t2 = makeTrace('t2', [+ makeGeneration('g2', '2026-05-11T00:00:01.000Z', {+ $ai_input: [+ { role: 'user', content: 'first' },+ { role: 'assistant', content: 'done' },+ { role: 'user', content: 'second' },+ ],+ $ai_output_choices: [{ role: 'assistant', content: 'done' }],+ }),+ ])+ const turns = extractSessionTurns([t1, t2], { t1, t2 })+ // Turn 2 input delta is the new user message; the repeated assistant+ // "done" in the history was already shown as turn 1's output.+ expect(turns[1].newInputs.map((m) => m.content)).toEqual(['second'])+ // Turn 2 output renders in full — outputs are never dedup'd.+ expect(turns[1].outputs.map((m) => m.content)).toEqual(['done'])++ // Now a third turn carries both prior outputs in its history. Each+ // was already accounted for (turn 1's output bumped seen to 1; turn+ // 2's output bumped it to 2), so neither re-renders, and the new+ // user message surfaces alone.+ const t3 = makeTrace('t3', [+ makeGeneration('g3', '2026-05-11T00:00:02.000Z', {+ $ai_input: [+ { role: 'user', content: 'first' },+ { role: 'assistant', content: 'done' },+ { role: 'user', content: 'second' },+ { role: 'assistant', content: 'done' },+ { role: 'user', content: 'third' },+ ],+ $ai_output_choices: [{ role: 'assistant', content: 'ok' }],+ }),+ ])+ const turnsAfterT3 = extractSessionTurns([t1, t2, t3], { t1, t2, t3 })+ expect(turnsAfterT3[2].newInputs.map((m) => m.content)).toEqual(['third'])+ })++ it('treats messages with same content but different roles as distinct', () => {+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: [{ role: 'user', content: 'ok' }],+ $ai_output_choices: [{ role: 'assistant', content: 'noted' }],+ }),+ ])+ const t2 = makeTrace('t2', [+ makeGeneration('g2', '2026-05-11T00:00:01.000Z', {+ $ai_input: [+ { role: 'user', content: 'ok' },+ // Same content as the earlier user message, but different role — must NOT dedup.+ { role: 'assistant', content: 'ok' },+ ],+ $ai_output_choices: [{ role: 'assistant', content: 'done' }],+ }),+ ])+ const turns = extractSessionTurns([t1, t2], { t1, t2 })+ expect(turns[1].newInputs.map((m) => m.role)).toEqual(['assistant'])+ })++ it('source indices line up with the rendered messages after dedup', () => {+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: [{ role: 'user', content: 'Hi' }],+ $ai_output_choices: [{ role: 'assistant', content: 'Hello' }],+ }),+ ])+ const t2 = makeTrace('t2', [+ makeGeneration('g2', '2026-05-11T00:00:01.000Z', {+ $ai_input: [+ { role: 'user', content: 'Hi' }, // index 0 — dedup'd+ { role: 'assistant', content: 'Hello' }, // index 1 — dedup'd+ { role: 'user', content: 'New question' }, // index 2 — rendered+ ],+ $ai_output_choices: [{ role: 'assistant', content: 'Answer' }],+ }),+ ])+ const turns = extractSessionTurns([t1, t2], { t1, t2 })+ expect(turns[1].newInputSourceIndices).toEqual([2])+ })++ it('dedups an assistant message even when its output shape differs from the next-turn-input shape', () => {+ // SDK pattern observed in the wild: $ai_output_choices comes back as a+ // flat-string OpenAI-style message, but the next call's $ai_input+ // wraps that same assistant reply as Anthropic-style typed parts+ // (e.g. an app stores history as typed parts even though it called+ // OpenAI; OpenAI Responses → Chat Completions migration; LangChain+ // round-tripping). The output's signature in `seenSignatures` is the+ // flat-string form; the next turn's input produces a typed-parts+ // signature. Without convergence in `normalizeMessage`, the assistant+ // message re-renders as new — a silent regression of the kind dedup+ // is supposed to prevent. This test pins that convergence.+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: [{ role: 'user', content: 'Hi' }],+ // Flat-string OpenAI Chat Completions output.+ $ai_output_choices: [{ role: 'assistant', content: 'Hello' }],+ }),+ ])+ const t2 = makeTrace('t2', [+ makeGeneration('g2', '2026-05-11T00:00:01.000Z', {+ $ai_input: [+ { role: 'user', content: 'Hi' },+ // Same assistant content, but rewrapped as Anthropic-style typed parts.+ { role: 'assistant', content: [{ type: 'text', text: 'Hello' }] },+ { role: 'user', content: 'Continue' },+ ],+ $ai_output_choices: [{ role: 'assistant', content: 'Sure!' }],+ }),+ ])+ const turns = extractSessionTurns([t1, t2], { t1, t2 })+ // Only "Continue" should survive — turn 1's flat-string assistant+ // output should match turn 2's typed-parts assistant input.+ expect(turns[1].newInputs.map((m) => m.role)).toEqual(['user'])+ expect(turns[1].newInputs[0].content).toBe('Continue')+ })+})++// Fixtures below mirror the shape of real production payloads — typed parts,+// `cache_control` on text parts, OpenAI `tool_calls` with JSON-string arguments,+// Anthropic `thinking` / `tool_use` / `tool_result` parts — but use neutral+// travel-domain content. The tests below assert only on `role` sequences, so+// content is irrelevant to correctness; what matters is preserving every+// structural feature the dedup signature has to handle.++/** OpenAI Chat Completions multi-turn with `tool_calls` (string args). */+const OPENAI_CHAT_TURN1_INPUT: unknown[] = [+ { role: 'system', content: 'You are a helpful travel assistant.' },+ { role: 'system', content: 'User preferences: metric units.' },+ { role: 'user', content: 'What is the weather like in Berlin this weekend?' },+]+const OPENAI_CHAT_TURN1_OUTPUT: unknown[] = [{ role: 'assistant', content: 'Let me check the forecast for you.' }]+const OPENAI_CHAT_TURN2_INPUT: unknown[] = [+ ...OPENAI_CHAT_TURN1_INPUT,+ ...OPENAI_CHAT_TURN1_OUTPUT,+ {+ role: 'assistant',+ content: 'I should call the weather API.',+ refusal: null,+ tool_calls: [+ {+ function: {+ // OpenAI emits arguments as a JSON-encoded string, not a parsed object.+ arguments: '{"city":"Berlin","date":"saturday"}',+ name: 'get_weather',+ },+ id: 'call_anon_abc123',+ type: 'function',+ },+ ],+ },+ // Tool response in this trace had no `tool_call_id` — observed in real production data.+ { role: 'tool', content: 'Sunny, 22°C.' },+]+const OPENAI_CHAT_TURN2_OUTPUT: unknown[] = [+ { role: 'assistant', content: 'Berlin will be sunny and around 22°C on Saturday.' },+]++/** Anthropic multi-part system prompt with `cache_control` metadata on text parts. */+const ANTHROPIC_CACHE_CONTROL_TURN1_INPUT: unknown[] = [+ {+ role: 'system',+ content: [+ {+ cache_control: { ttl: '1h', type: 'ephemeral' },+ text: 'You are a helpful travel assistant.',+ type: 'text',+ },+ ],+ },+ { role: 'system', content: 'Preferences: metric units.' },+ { role: 'system', content: 'Locale: en-DE.' },+ { role: 'user', content: [{ text: 'Hello.', type: 'text' }] },+ {+ role: 'user',+ content: [+ {+ cache_control: { type: 'ephemeral' },+ text: 'What is the weather in Berlin this weekend?',+ type: 'text',+ },+ ],+ },+]+const ANTHROPIC_CACHE_CONTROL_TURN1_OUTPUT: unknown[] = [+ { role: 'assistant', content: [{ type: 'text', text: 'Let me check the forecast.' }] },+]+const ANTHROPIC_CACHE_CONTROL_TURN2_INPUT: unknown[] = [+ ...ANTHROPIC_CACHE_CONTROL_TURN1_INPUT,+ ...ANTHROPIC_CACHE_CONTROL_TURN1_OUTPUT,+ {+ role: 'user',+ content: [{ cache_control: { type: 'ephemeral' }, text: 'What about Sunday?', type: 'text' }],+ },+]+const ANTHROPIC_CACHE_CONTROL_TURN2_OUTPUT: unknown[] = [+ { role: 'assistant', content: [{ type: 'text', text: 'Sunday will be cloudy.' }] },+]++/** Anthropic with extended-thinking + tool_use + tool_result content parts. */+const ANTHROPIC_TOOL_USE_TURN1_INPUT: unknown[] = [+ { role: 'user', content: 'What is the weather in Berlin?' },+ {+ role: 'assistant',+ content: [+ { signature: 'anon_signature_xyz', thinking: 'I should call the weather tool.', type: 'thinking' },+ {+ caller: { type: 'direct' },+ id: 'toolu_anon01',+ input: { city: 'Berlin' },+ name: 'get_weather',+ type: 'tool_use',+ },+ ],+ },+]+const ANTHROPIC_TOOL_USE_TURN1_OUTPUT: unknown[] = [+ {+ role: 'assistant',+ content: [{ type: 'text', text: 'Berlin is sunny, 22°C. Anything else?' }],+ },+]+const ANTHROPIC_TOOL_USE_TURN2_INPUT: unknown[] = [+ ...ANTHROPIC_TOOL_USE_TURN1_INPUT,+ {+ role: 'user',+ content: [+ {+ content: [{ text: 'Sunny, 22°C.', type: 'text' }],+ tool_use_id: 'toolu_anon01',+ type: 'tool_result',+ },+ { cache_control: { type: 'ephemeral' }, text: 'Thanks.', type: 'text' },+ ],+ },+ ...ANTHROPIC_TOOL_USE_TURN1_OUTPUT,+ { role: 'user', content: 'And in Paris?' },+]+const ANTHROPIC_TOOL_USE_TURN2_OUTPUT: unknown[] = [+ { role: 'assistant', content: [{ type: 'text', text: 'Paris is cloudy, 18°C.' }] },+]++interface RealShapeCase {+ name: string+ turn1Input: unknown[]+ turn1Output: unknown[]+ turn2Input: unknown[]+ turn2Output: unknown[]+ /**+ * Role sequence we expect `normalizeMessages` to emit for the delta in+ * turn 2's input — i.e. the messages we actually want to *render* after+ * hiding everything turn 1 already showed. Pinning roles (not just count)+ * catches content drift: if `normalizeMessage`'s expansion ever changes+ * which parts merge or split, the count could coincidentally stay the+ * same while the rendered conversation silently differs.+ */+ expectedNewInputRolesTurn2: string[]+}++const REAL_SHAPE_CASES: RealShapeCase[] = [+ {+ name: 'OpenAI Chat with tool_calls',+ turn1Input: OPENAI_CHAT_TURN1_INPUT,+ turn1Output: OPENAI_CHAT_TURN1_OUTPUT,+ turn2Input: OPENAI_CHAT_TURN2_INPUT,+ turn2Output: OPENAI_CHAT_TURN2_OUTPUT,+ // Turn 2's delta beyond turn 1: assistant (reasoning + tool_calls) and tool response.+ expectedNewInputRolesTurn2: ['assistant', 'tool'],+ },+ {+ name: 'Anthropic with cache_control typed parts',+ turn1Input: ANTHROPIC_CACHE_CONTROL_TURN1_INPUT,+ turn1Output: ANTHROPIC_CACHE_CONTROL_TURN1_OUTPUT,+ turn2Input: ANTHROPIC_CACHE_CONTROL_TURN2_INPUT,+ turn2Output: ANTHROPIC_CACHE_CONTROL_TURN2_OUTPUT,+ // Turn 2's delta: one new user follow-up message.+ expectedNewInputRolesTurn2: ['user'],+ },+ {+ name: 'Anthropic with thinking + tool_use + tool_result',+ turn1Input: ANTHROPIC_TOOL_USE_TURN1_INPUT,+ turn1Output: ANTHROPIC_TOOL_USE_TURN1_OUTPUT,+ turn2Input: ANTHROPIC_TOOL_USE_TURN2_INPUT,+ turn2Output: ANTHROPIC_TOOL_USE_TURN2_OUTPUT,+ // Turn 2's delta is one Anthropic user-role message with `[tool_result, text]`+ // parts plus a follow-up user message. `normalizeMessage` expands the typed-+ // parts entry into two normalized messages (the tool_result part takes role+ // "assistant (tool result)"; the text part takes role "user"), then the+ // follow-up user message adds a third. Pinning the role sequence catches+ // drift if `normalizeMessage` ever rebalances this split.+ expectedNewInputRolesTurn2: ['assistant (tool result)', 'user', 'user'],+ },+]++describe('extractSessionTurns — real production shapes (anonymized)', () => {+ it.each(REAL_SHAPE_CASES)('first turn renders the full input ($name)', ({ turn1Input, turn1Output }) => {+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: turn1Input,+ $ai_output_choices: turn1Output,+ }),+ ])+ const turns = extractSessionTurns([t1], { t1 })+ expect(turns[0].isLoaded).toBe(true)+ // We don't assert an exact count for turn 1 — `normalizeMessages` is the+ // authority on expansion of typed parts. We just confirm it produced+ // *something* renderable.+ expect(turns[0].newInputs.length).toBeGreaterThan(0)+ })++ it.each(REAL_SHAPE_CASES)(+ 'second turn hides everything from turn 1 and renders only the delta ($name)',+ ({ turn1Input, turn1Output, turn2Input, turn2Output, expectedNewInputRolesTurn2 }) => {+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: turn1Input,+ $ai_output_choices: turn1Output,+ }),+ ])+ const t2 = makeTrace('t2', [+ makeGeneration('g2', '2026-05-11T00:00:01.000Z', {+ $ai_input: turn2Input,+ $ai_output_choices: turn2Output,+ }),+ ])+ const turns = extractSessionTurns([t1, t2], { t1, t2 })+ expect(turns[1].isLoaded).toBe(true)+ // Pin the role sequence after dedup. The count alone wouldn't+ // catch silent content drift if `normalizeMessage` ever swapped+ // which parts merge or split.+ expect(turns[1].newInputs.map((m) => m.role)).toEqual(expectedNewInputRolesTurn2)+ // Output is always new content; never dedup'd.+ expect(turns[1].outputs.length).toBeGreaterThan(0)+ }+ )++ it.each(REAL_SHAPE_CASES)('signature is JSON-stringifiable for every turn 2 input ($name)', ({ turn2Input }) => {+ // Regression guard: if `normalizeMessage` ever returned a non-JSON-+ // stringifiable field (Date, function, undefined etc.) the signature+ // would silently throw at runtime. Walk every entry through the+ // signature path to ensure it stays stable for this shape.+ const t1 = makeTrace('t1', [+ makeGeneration('g1', '2026-05-11T00:00:00.000Z', {+ $ai_input: [],+ $ai_output_choices: [],+ }),+ ])+ const t2 = makeTrace('t2', [+ makeGeneration('g2', '2026-05-11T00:00:01.000Z', {+ $ai_input: turn2Input,+ $ai_output_choices: [],+ }),+ ])+ expect(() => extractSessionTurns([t1, t2], { t1, t2 })).not.toThrow()+ })+})diff --git a/products/llm_analytics/frontend/extractSessionTurns.ts b/products/llm_analytics/frontend/extractSessionTurns.tsnew file mode 100644index 000000000000..d323a318f8aa--- /dev/null+++ b/products/llm_analytics/frontend/extractSessionTurns.ts@@ -0,0 +1,146 @@+import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'++import { messageSignature } from './messageSignature'+import { CompatMessage } from './types'+import { normalizeMessage, normalizeMessages } from './utils'++// Heuristic mirrors the LLMA skill script `print_summary.py` at+// `products/llm_analytics/skills/exploring-llm-traces/scripts/` — keep in sync.++/**+ * Pick the event that represents the user-visible turn for a trace.+ *+ * Current heuristic: the latest `$ai_generation` by `createdAt` — an+ * implementation detail callers should treat as opaque. A future opt-in+ * `$ai_user_visible: true` convention would change how this picks. Wrong+ * for traces where the last generation is a logging/cleanup call; the+ * "Show reasoning" affordance is the user's fallback.+ */+export function pickUserVisibleTurn(trace: LLMTrace | undefined): LLMTraceEvent | undefined {+ if (!trace?.events?.length) {+ return undefined+ }+ let latest: LLMTraceEvent | undefined+ let latestTs = -Infinity+ for (const event of trace.events) {+ if (event.event !== '$ai_generation') {+ continue+ }+ const ts = new Date(event.createdAt).getTime()+ if (ts > latestTs) {+ latest = event+ latestTs = ts+ }+ }+ return latest+}++/**+ * Maps each normalized message back to its index in the raw `$ai_input`.+ * Many-to-one: `normalizeMessage` may expand one raw entry into multiple+ * messages. A leading `-1` marks the synthetic "available tools" message.+ *+ * Used by `ConversationMessagesDisplay` to map per-message sentiment to the+ * right rendered bubble after dedup. Also used by the Trace page renderer.+ */+export function buildInputSourceIndices(rawInput: unknown, tools: unknown): number[] {+ const indices: number[] = []+ if (tools) {+ indices.push(-1)+ }+ if (Array.isArray(rawInput)) {+ for (let i = 0; i < rawInput.length; i++) {+ const expanded = normalizeMessage(rawInput[i], 'user')+ for (let j = 0; j < expanded.length; j++) {+ indices.push(i)+ }+ }+ }+ return indices+}++export interface SessionTurn {+ /** The trace this turn corresponds to. */+ trace: LLMTrace+ /** True if `fullTraces[trace.id]` was available and we computed messages. */+ isLoaded: boolean+ /** Input messages new to this turn (already-seen messages from prior turns hidden). */+ newInputs: CompatMessage[]+ /** Output messages from this turn's last generation. */+ outputs: CompatMessage[]+ /** Maps each `newInputs[i]` back to its source index in the raw `$ai_input` array. */+ newInputSourceIndices: number[]+ /** The event sourced by `pickUserVisibleTurn` — used for model, error, latency, and the id passed to `ConversationMessagesDisplay`. */+ userVisibleTurn?: LLMTraceEvent+}++/**+ * Walk traces in order and hide inputs already shown in an earlier turn.+ * Without this, turn N would re-render turns 1..N-1 because each `$ai_input`+ * carries the full running history.+ *+ * Count-based, not set-based: a message at its Nth occurrence in a turn's+ * input renders iff fewer than N copies have been shown so far. Preserves+ * legitimate repeats within a turn.+ */+export function extractSessionTurns(traces: LLMTrace[], fullTraces: Record<string, LLMTrace>): SessionTurn[] {+ const msgCountShown = new Map<string, number>()+ return traces.map((trace) => {+ const fullTrace = fullTraces[trace.id]+ if (!fullTrace) {+ return {+ trace,+ isLoaded: false,+ newInputs: [],+ outputs: [],+ newInputSourceIndices: [],+ }+ }+ const userVisibleTurn = pickUserVisibleTurn(fullTrace)+ if (!userVisibleTurn) {+ return {+ trace,+ isLoaded: true,+ newInputs: [],+ outputs: [],+ newInputSourceIndices: [],+ }+ }+ const { properties } = userVisibleTurn+ const rawInput = properties.$ai_input ?? properties.$ai_input_state+ const rawOutput = properties.$ai_output_choices ?? properties.$ai_output_state ?? properties.$ai_output+ const tools = properties.$ai_tools++ const inputMessages = normalizeMessages(rawInput, 'user', tools)+ const outputMessages = normalizeMessages(rawOutput, 'assistant')+ const sourceIndices = buildInputSourceIndices(rawInput, tools)++ const newInputs: CompatMessage[] = []+ const newInputSourceIndices: number[] = []+ const msgCountThisTurn = new Map<string, number>()+ inputMessages.forEach((message, i) => {+ const sig = messageSignature(message)+ const turnCount = (msgCountThisTurn.get(sig) ?? 0) + 1+ msgCountThisTurn.set(sig, turnCount)+ const shownCount = msgCountShown.get(sig) ?? 0+ if (turnCount > shownCount) {+ newInputs.push(message)+ newInputSourceIndices.push(sourceIndices[i] ?? i)+ msgCountShown.set(sig, turnCount)+ }+ })+ for (const message of outputMessages) {+ const sig = messageSignature(message)+ msgCountShown.set(sig, (msgCountShown.get(sig) ?? 0) + 1)+ }++ return {+ trace,+ isLoaded: true,+ newInputs,+ outputs: outputMessages,+ newInputSourceIndices,+ userVisibleTurn,+ }+ })+}diff --git a/products/llm_analytics/frontend/llmAnalyticsSessionDataLogic.ts b/products/llm_analytics/frontend/llmAnalyticsSessionDataLogic.tsindex 70a8477087c6..9d8fce672a2c 100644--- a/products/llm_analytics/frontend/llmAnalyticsSessionDataLogic.ts+++ b/products/llm_analytics/frontend/llmAnalyticsSessionDataLogic.ts@@ -17,6 +17,8 @@ import {} from '~/queries/schema/schema-general'import { InsightLogicProps } from '~/types'+import { SessionTurn, extractSessionTurns } from './extractSessionTurns'+import { llmAnalyticsSummarizationBatchCheckCreate } from './generated/api'import type { llmAnalyticsSessionDataLogicType } from './llmAnalyticsSessionDataLogicType'import { llmAnalyticsSessionLogic } from './llmAnalyticsSessionLogic'import { restoreTree } from './llmAnalyticsTraceDataLogic'@@ -28,6 +30,13 @@ export interface TraceSummary {error: string | null}+// Eager-load the first N traces on mount; later turns render a "Show conversation"+// button. Picking first N and not first and last N, because cross-trace dedup walks+// chronologically and accumulates `seenSignatures`; any gap in loaded turns would+// let the later turns' running history show as "new" content.+// Most sessions have less than 10 turns, a proper fix later is a bulk query.+const AUTO_LOAD_LIMIT = 10+export interface SessionDataLogicProps {sessionId: stringquery: DataTableNode@@ -71,7 +80,10 @@ export const llmAnalyticsSessionDataLogic = kea<llmAnalyticsSessionDataLogicType})),actions({- toggleTraceExpanded: (traceId: string) => ({ traceId }),+ // Reasoning panel = the per-turn `LLMAnalyticsTraceEvents` tree shown via the+ // "Show reasoning" link. Distinct from "trace loaded" because the conversation+ // bubbles render as soon as the full trace is fetched, regardless of reasoning state.+ toggleReasoning: (traceId: string) => ({ traceId }),toggleGenerationExpanded: (generationId: string) => ({ generationId }),loadFullTrace: (traceId: string) => ({ traceId }),loadFullTraceSuccess: (traceId: string, trace: LLMTrace) => ({ traceId, trace }),@@ -86,10 +98,10 @@ export const llmAnalyticsSessionDataLogic = kea<llmAnalyticsSessionDataLogicType}),reducers({- expandedTraceIds: [+ reasoningExpandedTraceIds: [new Set<string>() as Set<string>,{- toggleTraceExpanded: (state, { traceId }) => {+ toggleReasoning: (state, { traceId }) => {const newSet = new Set(state)if (newSet.has(traceId)) {newSet.delete(traceId)@@ -180,6 +192,11 @@ export const llmAnalyticsSessionDataLogic = kea<llmAnalyticsSessionDataLogicTypereturn [...(tracesResponse?.results || [])].reverse()},],+ sessionTurns: [+ (s) => [s.traces, s.fullTraces],+ (traces: LLMTrace[], fullTraces: Record<string, LLMTrace>): SessionTurn[] =>+ extractSessionTurns(traces, fullTraces),+ ],summariesLoading: [(s) => [s.traceSummaries],(traceSummaries: Record<string, TraceSummary>): boolean =>@@ -187,48 +204,54 @@ export const llmAnalyticsSessionDataLogic = kea<llmAnalyticsSessionDataLogicType],}),- listeners(({ actions, values }) => ({- loadCachedSummaries: async ({ traceIds }) => {- if (traceIds.length === 0) {- return- }-- if (!values.dataProcessingAccepted) {- return- }+ listeners(({ actions, values }) => {+ // Closure-scoped in-flight lock for `loadFullTrace`. Mirrors the pattern used+ // by sibling lazy loaders in this product (llmPersonsLazyLoaderLogic,+ // llmSentimentLazyLoaderLogic, traceReviewsLazyLoaderLogic, etc.). We can't+ // rely on `values.loadingFullTraces` for this guard because kea reducers run+ // synchronously *before* listeners — so the reducer has already added this+ // traceId by the time the listener checks. The closure-scoped Set lets the+ // listener distinguish "this dispatch's reducer just added the id" from+ // "a prior dispatch is still mid-flight".+ const inFlightTraceFetches = new Set<string>()- const teamId = values.currentTeamId- if (!teamId) {- return- }+ return {+ loadCachedSummaries: async ({ traceIds }) => {+ if (traceIds.length === 0) {+ return+ }- try {- // nosemgrep: prefer-codegen-api- const data = await api.create(`api/environments/${teamId}/llm_analytics/summarization/batch_check/`, {- trace_ids: traceIds,- mode: 'minimal',- })+ if (!values.dataProcessingAccepted) {+ return+ }- if (data.summaries && data.summaries.length > 0) {- actions.loadCachedSummariesSuccess(data.summaries)+ const teamId = values.currentTeamId+ if (!teamId) {+ return}- } catch {- // Silently fail - this is just a cache optimization- }- },- toggleTraceExpanded: async ({ traceId }) => {- if (- values.expandedTraceIds.has(traceId) &&- !values.fullTraces[traceId] &&- !values.loadingFullTraces.has(traceId)- ) {- actions.loadFullTrace(traceId)+ try {+ const data = await llmAnalyticsSummarizationBatchCheckCreate(String(teamId), {+ trace_ids: traceIds,+ mode: 'minimal',+ })++ if (data.summaries && data.summaries.length > 0) {+ actions.loadCachedSummariesSuccess(data.summaries)+ }+ } catch {+ // Silently fail - this is just a cache optimization+ }+ },+ loadFullTrace: async ({ traceId }) => {+ if (values.fullTraces[traceId] || inFlightTraceFetches.has(traceId)) {+ return+ }+ inFlightTraceFetches.add(traceId)const traceQuery: TraceQuery = {kind: NodeKind.TraceQuery,traceId,}-try {const response = await api.query(traceQuery)if (response.results && response.results[0]) {@@ -239,70 +262,79 @@ export const llmAnalyticsSessionDataLogic = kea<llmAnalyticsSessionDataLogicType} catch (error) {console.error('Error loading full trace:', error)actions.loadFullTraceFailure(traceId)+ } finally {+ inFlightTraceFetches.delete(traceId)+ }+ },+ summarizeAllTraces: async () => {+ if (!values.dataProcessingAccepted) {+ return}- }- },- summarizeAllTraces: async () => {- if (!values.dataProcessingAccepted) {- return- }- const hasSummaries = Object.keys(values.traceSummaries).length > 0- const traces = values.traces- for (const trace of traces) {- actions.summarizeTrace(trace.id, hasSummaries)- }- },- summarizeTrace: async ({ traceId, forceRefresh }) => {- const teamId = values.currentTeamId- if (!teamId) {- actions.summarizeTraceFailure(traceId, 'Team ID not available')- return- }+ const hasSummaries = Object.keys(values.traceSummaries).length > 0+ const traces = values.traces+ for (const trace of traces) {+ actions.summarizeTrace(trace.id, hasSummaries)+ }+ },+ summarizeTrace: async ({ traceId, forceRefresh }) => {+ const teamId = values.currentTeamId+ if (!teamId) {+ actions.summarizeTraceFailure(traceId, 'Team ID not available')+ return+ }- try {- // First fetch the full trace with all events (session query only has direct children)- let fullTrace: LLMTrace | undefined = values.fullTraces[traceId]- if (!fullTrace) {- const traceQuery: TraceQuery = {- kind: NodeKind.TraceQuery,- traceId,- }- const traceResponse = await api.query(traceQuery)- if (traceResponse.results && traceResponse.results[0]) {- fullTrace = traceResponse.results[0]- } else {- throw new Error('Failed to load full trace')+ try {+ // First fetch the full trace with all events (session query only has direct children)+ let fullTrace: LLMTrace | undefined = values.fullTraces[traceId]+ if (!fullTrace) {+ const traceQuery: TraceQuery = {+ kind: NodeKind.TraceQuery,+ traceId,+ }+ const traceResponse = await api.query(traceQuery)+ if (traceResponse.results && traceResponse.results[0]) {+ fullTrace = traceResponse.results[0]+ } else {+ throw new Error('Failed to load full trace')+ }}- }- // Build the hierarchy tree from full trace events- const hierarchy = restoreTree(fullTrace.events || [], traceId)+ // Build the hierarchy tree from full trace events+ const hierarchy = restoreTree(fullTrace.events || [], traceId)- // nosemgrep: prefer-codegen-api- const data = await api.create(`api/environments/${teamId}/llm_analytics/summarization/`, {- summarize_type: 'trace',- mode: 'minimal',- force_refresh: forceRefresh,- data: {- trace: fullTrace,- hierarchy,- },- })+ // nosemgrep: prefer-codegen-api+ const data = await api.create(`api/environments/${teamId}/llm_analytics/summarization/`, {+ summarize_type: 'trace',+ mode: 'minimal',+ force_refresh: forceRefresh,+ data: {+ trace: fullTrace,+ hierarchy,+ },+ })- actions.summarizeTraceSuccess(traceId, data.summary?.title || 'Untitled trace')- } catch (error) {- actions.summarizeTraceFailure(traceId, error instanceof Error ? error.message : 'Unknown error')- }- },- })),+ actions.summarizeTraceSuccess(traceId, data.summary?.title || 'Untitled trace')+ } catch (error) {+ actions.summarizeTraceFailure(traceId, error instanceof Error ? error.message : 'Unknown error')+ }+ },+ }+ }),subscriptions(({ actions, values }) => ({traces: (traces: LLMTrace[]) => {- // Load cached summaries when traces are loaded- if (traces.length > 0 && Object.keys(values.traceSummaries).length === 0) {- const traceIds = traces.map((t) => t.id)- actions.loadCachedSummaries(traceIds)+ if (traces.length === 0) {+ return+ }+ // Cache lookup for existing trace summaries+ if (Object.keys(values.traceSummaries).length === 0) {+ actions.loadCachedSummaries(traces.map((t) => t.id))+ }+ for (const trace of traces.slice(0, AUTO_LOAD_LIMIT)) {+ if (!values.fullTraces[trace.id] && !values.loadingFullTraces.has(trace.id)) {+ actions.loadFullTrace(trace.id)+ }}},})),diff --git a/products/llm_analytics/frontend/messageSignature.test.ts b/products/llm_analytics/frontend/messageSignature.test.tsnew file mode 100644index 000000000000..07e52e918204--- /dev/null+++ b/products/llm_analytics/frontend/messageSignature.test.ts@@ -0,0 +1,159 @@+import { messageSignature } from './messageSignature'+import { CompatMessage } from './types'++describe('messageSignature', () => {+ it('produces the same signature for messages with identical role + content', () => {+ const a: CompatMessage = { role: 'user', content: 'Hi there' }+ const b: CompatMessage = { role: 'user', content: 'Hi there' }+ expect(messageSignature(a)).toEqual(messageSignature(b))+ })++ const distinctCases: { name: string; a: CompatMessage; b: CompatMessage }[] = [+ {+ name: 'role',+ a: { role: 'user', content: 'same' },+ b: { role: 'assistant', content: 'same' },+ },+ {+ name: 'content for typed-parts arrays',+ a: { role: 'user', content: [{ type: 'text', text: 'Hello' }] },+ b: { role: 'user', content: [{ type: 'text', text: 'Goodbye' }] },+ },+ {+ name: 'tool_calls so assistants with different tool calls are distinct',+ a: {+ role: 'assistant',+ content: '',+ tool_calls: [{ id: '1', type: 'function', function: { name: 'lookup', arguments: '{"q":"a"}' } }],+ },+ b: {+ role: 'assistant',+ content: '',+ tool_calls: [{ id: '1', type: 'function', function: { name: 'lookup', arguments: '{"q":"b"}' } }],+ },+ },+ {+ name: 'tool_call_id for tool responses with the same content',+ a: { role: 'tool', content: 'ok', tool_call_id: 'call_a' },+ b: { role: 'tool', content: 'ok', tool_call_id: 'call_b' },+ },+ ]++ it.each(distinctCases)('distinguishes by $name', ({ a, b }) => {+ expect(messageSignature(a)).not.toEqual(messageSignature(b))+ })+})++describe('messageSignature — transport-metadata stripping', () => {+ // The transport-metadata test cases below use content-part fields that+ // intentionally exceed the strict `CompatMessage` content shapes (Anthropic's+ // `cache_control` / `signature` / `caller` aren't modelled by `TextContentItem`+ // or friends). The `as unknown as CompatMessage` casts say "this is shaped+ // like production payloads we want to pin behavior against, not like the+ // SDK-spec types we ship in `types.ts`".+ const dedupCases: { name: string; a: CompatMessage; b: CompatMessage }[] = [+ {+ // Common Anthropic pattern: a caller stabilises the prefix once it's+ // safe to cache, so turn N+1 has cache_control where turn N didn't.+ // The user-visible text is identical; we must dedup, otherwise the+ // transcript leaks unrendered duplicates back in.+ name: 'Anthropic typed-parts when one turn adds cache_control and another does not',+ a: {+ role: 'system',+ content: [{ type: 'text', text: 'Hello' }],+ } as unknown as CompatMessage,+ b: {+ role: 'system',+ content: [{ type: 'text', text: 'Hello', cache_control: { type: 'ephemeral' } }],+ } as unknown as CompatMessage,+ },+ {+ // Same text, different cache hint. Transport-only change; still the+ // same user-visible content.+ name: 'Anthropic typed-parts when the cache_control hint changes between turns',+ a: {+ role: 'system',+ content: [{ type: 'text', text: 'Hello', cache_control: { type: 'ephemeral' } }],+ } as unknown as CompatMessage,+ b: {+ role: 'system',+ content: [{ type: 'text', text: 'Hello', cache_control: { type: 'ephemeral', ttl: '1h' } }],+ } as unknown as CompatMessage,+ },+ {+ // `signature` is Anthropic's verification crypto on thinking parts —+ // not user-visible and observed to vary between echoes of the same+ // reasoning step in production traces.+ name: 'Anthropic thinking parts even when the cryptographic signature differs',+ a: {+ role: 'assistant',+ content: [{ type: 'thinking', thinking: 'I should look this up.' }],+ } as unknown as CompatMessage,+ b: {+ role: 'assistant',+ content: [{ type: 'thinking', thinking: 'I should look this up.', signature: 'crypto_sig_xyz' }],+ } as unknown as CompatMessage,+ },+ {+ // `caller` is routing metadata observed on tool_use parts in+ // production — not user-visible.+ name: 'tool_use parts even when the caller routing metadata differs',+ a: {+ role: 'assistant',+ content: [{ type: 'tool_use', id: 'toolu_1', name: 'lookup', input: { q: 'cats' } }],+ } as unknown as CompatMessage,+ b: {+ role: 'assistant',+ content: [+ {+ type: 'tool_use',+ id: 'toolu_1',+ name: 'lookup',+ input: { q: 'cats' },+ caller: { type: 'direct' },+ },+ ],+ } as unknown as CompatMessage,+ },+ {+ // Observed in production: OpenAI tool responses sometimes ship without+ // tool_call_id. Two such responses with the same content are+ // indistinguishable from each other in `$ai_input`, and treating them+ // as one is the only safe thing to do — there's no other key to+ // disambiguate by.+ name: 'two tool responses with identical content even when tool_call_id is missing',+ a: { role: 'tool', content: 'Memory appended.' },+ b: { role: 'tool', content: 'Memory appended.' },+ },+ ]++ it.each(dedupCases)('dedups $name', ({ a, b }) => {+ expect(messageSignature(a)).toEqual(messageSignature(b))+ })++ it('OpenAI tool_calls with the same name but different JSON-string arguments produce distinct signatures', () => {+ const a: CompatMessage = {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ function: { name: 'lookup', arguments: '{"q":"first"}' },+ id: 'call_a',+ type: 'function',+ },+ ],+ }+ const b: CompatMessage = {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ function: { name: 'lookup', arguments: '{"q":"second"}' },+ id: 'call_a',+ type: 'function',+ },+ ],+ }+ expect(messageSignature(a)).not.toEqual(messageSignature(b))+ })+})diff --git a/products/llm_analytics/frontend/messageSignature.ts b/products/llm_analytics/frontend/messageSignature.tsnew file mode 100644index 000000000000..691b36f838a5--- /dev/null+++ b/products/llm_analytics/frontend/messageSignature.ts@@ -0,0 +1,66 @@+import { CompatMessage } from './types'++// Heuristic mirrors the LLMA skill script `extract_conversation.py` at+// `products/llm_analytics/skills/exploring-llm-traces/scripts/` — keep in sync.++/**+ * Provider-specific transport metadata that lives on typed content parts but+ * does NOT change what the user sees. Stripped before signing so that the+ * same user-visible message dedups across turns even if the caller changes+ * its cache hint, the SDK adds a verification signature, or routing metadata+ * differs between echoes.+ *+ * - `cache_control` — Anthropic cache hints on text parts; vary across turns.+ * - `signature` — Anthropic crypto signature on `thinking` parts; varies between echoes.+ * - `caller` — routing metadata on `tool_use` parts; not user-visible.+ *+ * The replacer fires recursively for every key during serialisation, so these+ * fields are dropped at any nesting level.+ */+const TRANSPORT_METADATA_KEYS = new Set(['cache_control', 'signature', 'caller'])++function isPlainTextPart(part: unknown): boolean {+ return (+ typeof part === 'object' &&+ part !== null &&+ (part as Record<string, unknown>).type === 'text' &&+ typeof (part as Record<string, unknown>).text === 'string'+ )+}++function normalizeSignatureField(key: string, value: unknown): unknown {+ if (TRANSPORT_METADATA_KEYS.has(key)) {+ return undefined+ }+ // Converge text-only typed-parts with their flat-string equivalent. SDKs+ // round-trip the same assistant reply between `content: 'Hello'` (OpenAI+ // flat-string) and `content: [{type: 'text', text: 'Hello'}]` (typed parts);+ // without this convergence the signatures diverge and the message re-renders.+ // Only flatten all-text arrays — mixed content (text + tool_use) has no+ // flat-string equivalent.+ if (key === 'content' && Array.isArray(value) && value.length > 0 && value.every(isPlainTextPart)) {+ return value.map((part) => (part as { text: string }).text).join('')+ }+ return value+}++/**+ * Stable string hash for a normalized message. Keys on role, content,+ * tool_calls, tool_call_id, and the synthetic tools list — ignoring transport+ * metadata (see `TRANSPORT_METADATA_KEYS`) and converging text-only typed-parts+ * arrays with their flat-string equivalent (see `normalizeSignatureField`).+ */+export function messageSignature(message: CompatMessage): string {+ // JSON.stringify preserves order+ return JSON.stringify(+ {+ role: message.role ?? '',+ content: message.content ?? '',+ tool_calls: message.tool_calls ?? null,+ tool_call_id: message.tool_call_id ?? '',+ tools: (message as { tools?: unknown }).tools ?? null,+ },+ // Call normalizeSignatureField for each field above:+ normalizeSignatureField+ )+}