: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): Redesign sessions details page with chat layout (#58366)
Marcel Poelkerea3f5e2ea608
diff --git a/products/llm_analytics/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx b/products/llm_analytics/frontend/ConversationDisplay/ConversationMessagesDisplay.tsxindex e8f4f3b48f67..177cedd75028 100644--- a/products/llm_analytics/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx+++ b/products/llm_analytics/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx@@ -19,6 +19,7 @@ import { containsSearchQuery } from '../searchUtils'import { CompatMessage, MultiModalContentItem, VercelSDKImageMessage } from '../types'import {getGeminiInlineData,+ hasStringContentField,isAnthropicDocumentMessage,isAnthropicImageMessage,isEmptyJSONStructure,@@ -557,8 +558,8 @@ function extractMinimalPreview(content: string | { type: string; content: string}).filter(Boolean).join(' ')- } else if (typeof content === 'object' && content !== null && 'content' in content) {- text = typeof content.content === 'string' ? content.content : JSON.stringify(content)+ } else if (hasStringContentField(content)) {+ text = content.content} else {text = JSON.stringify(content)}diff --git a/products/llm_analytics/frontend/ConversationDisplay/TranscriptBubbleStream.test.ts b/products/llm_analytics/frontend/ConversationDisplay/TranscriptBubbleStream.test.tsnew file mode 100644index 000000000000..6127f7ec017f--- /dev/null+++ b/products/llm_analytics/frontend/ConversationDisplay/TranscriptBubbleStream.test.ts@@ -0,0 +1,149 @@+import posthog from 'posthog-js'++import { CompatMessage } from '../types'+import { captureUnrenderableMessageOnce, hasNonTextContent, unrenderableContentKinds } from './TranscriptBubbleStream'++jest.mock('posthog-js', () => ({+ __esModule: true,+ default: { capture: jest.fn() },+}))++const mockedCapture = posthog.capture as jest.Mock++beforeEach(() => mockedCapture.mockClear())++describe('hasNonTextContent', () => {+ it.each<[name: string, content: CompatMessage['content'], expected: boolean]>([+ ['returns false for a plain string content', 'Hello there', false],+ ['returns false for an empty array', [], false],+ ['returns false for content with only text items', [{ type: 'text', text: 'Hi' }], false],+ [+ 'returns false for Vercel SDK text parts (`{ type: "text", content }`)',+ [{ type: 'text', content: 'Hi from Vercel SDK' }] as unknown as CompatMessage['content'],+ false,+ ],+ [+ 'returns false for Vercel SDK input_text parts',+ [{ type: 'input_text', text: 'Hi' }] as unknown as CompatMessage['content'],+ false,+ ],+ [+ 'returns true for a thinking part — reasoning is routed to "Show steps", not the bubble',+ [+ { type: 'thinking', thinking: 'let me work through this', signature: 'sig' },+ ] as unknown as CompatMessage['content'],+ true,+ ],+ [+ 'returns false for content with only tool-step items (steps panel covers them)',+ [+ { type: 'function', function: { name: 'get_weather' } },+ { type: 'tool_use', id: 'toolu_1', name: 'search_docs', input: {} },+ { type: 'tool_result', tool_use_id: 'toolu_1', content: 'ok' },+ { type: 'tool-call', toolCallId: 'a', toolName: 'search_docs', input: {} },+ { type: 'function_call', call_id: 'c1', name: 'search_docs', arguments: '{}' },+ ] as unknown as CompatMessage['content'],+ false,+ ],+ [+ 'returns true for content with an image item',+ [+ { type: 'image_url', image_url: { url: 'https://example.com/a.png' } },+ ] as unknown as CompatMessage['content'],+ true,+ ],+ [+ 'returns true for content with a file item',+ [+ {+ type: 'file',+ file: { filename: 'report.pdf', file_data: 'data:application/pdf;base64,AAA' },+ },+ ] as unknown as CompatMessage['content'],+ true,+ ],+ [+ 'returns true for content with an audio item',+ [{ type: 'audio', data: 'AAA', mime_type: 'audio/wav' }] as unknown as CompatMessage['content'],+ true,+ ],+ [+ 'returns true for an unrecognized item shape',+ [{ type: 'video', src: 'foo' }] as unknown as CompatMessage['content'],+ true,+ ],+ [+ 'returns true when text co-exists with non-text — text co-existence does not suppress the signal',+ [+ { type: 'text', text: 'Look at this:' },+ { type: 'image_url', image_url: { url: 'https://example.com/a.png' } },+ ] as unknown as CompatMessage['content'],+ true,+ ],+ [+ 'returns true when a tool call sits alongside an image (tool call filtered, image surfaces)',+ [+ { type: 'tool_use', id: 'toolu_1', name: 'search_docs', input: {} },+ { type: 'image_url', image_url: { url: 'https://example.com/a.png' } },+ ] as unknown as CompatMessage['content'],+ true,+ ],+ ])('%s', (_, content, expected) => {+ const message: CompatMessage = { role: 'user', content }+ expect(hasNonTextContent(message)).toBe(expected)+ })+})++describe('unrenderableContentKinds', () => {+ it('returns the distinct sorted set of unrenderable item type discriminators', () => {+ const message: CompatMessage = {+ role: 'user',+ content: [+ { type: 'text', text: 'Look at these:' },+ { type: 'image_url', image_url: { url: 'a' } },+ { type: 'image_url', image_url: { url: 'b' } },+ { type: 'file', file: { filename: 'f', file_data: 'd' } },+ { type: 'tool_use', id: 'toolu_1', name: 'x', input: {} },+ ] as unknown as CompatMessage['content'],+ }+ expect(unrenderableContentKinds(message)).toEqual(['file', 'image_url'])+ })++ it('returns [] for content with no unrenderable items', () => {+ expect(unrenderableContentKinds({ role: 'user', content: 'Hi' })).toEqual([])+ expect(unrenderableContentKinds({ role: 'user', content: [{ type: 'text', text: 'Hi' }] })).toEqual([])+ })+})++describe('captureUnrenderableMessageOnce', () => {+ const imageMessage = (url: string): CompatMessage => ({+ role: 'user',+ content: [{ type: 'image_url', image_url: { url } }] as unknown as CompatMessage['content'],+ })++ it('fires the capture with role and content_kinds', () => {+ const seen = new Set<string>()+ captureUnrenderableMessageOnce(imageMessage('a'), seen)+ expect(mockedCapture).toHaveBeenCalledTimes(1)+ expect(mockedCapture).toHaveBeenCalledWith(+ 'llma transcript message unrenderable',+ expect.objectContaining({ role: 'user', content_kinds: ['image_url'] })+ )+ })++ it('dedups repeat calls with an identical message', () => {+ const seen = new Set<string>()+ const msg = imageMessage('a')+ captureUnrenderableMessageOnce(msg, seen)+ captureUnrenderableMessageOnce(msg, seen)+ captureUnrenderableMessageOnce(msg, seen)+ expect(mockedCapture).toHaveBeenCalledTimes(1)+ })++ it('fires again for a different image URL even though the role and text are identical', () => {+ const seen = new Set<string>()+ captureUnrenderableMessageOnce(imageMessage('a'), seen)+ captureUnrenderableMessageOnce(imageMessage('b'), seen)+ expect(mockedCapture).toHaveBeenCalledTimes(2)+ })+})diff --git a/products/llm_analytics/frontend/ConversationDisplay/TranscriptBubbleStream.tsx b/products/llm_analytics/frontend/ConversationDisplay/TranscriptBubbleStream.tsxnew file mode 100644index 000000000000..6e7ee6ab6e8f--- /dev/null+++ b/products/llm_analytics/frontend/ConversationDisplay/TranscriptBubbleStream.tsx@@ -0,0 +1,132 @@+import posthog from 'posthog-js'+import { useEffect, useMemo, useRef } from 'react'++import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { MessageTemplate } from 'scenes/max/messages/MessageTemplate'++import { CompatMessage } from '../types'+import { AVAILABLE_TOOLS_ROLE, extractTextContent, hasStringContentField, isToolStepItem } from '../utils'++// Roles that carry no user-visible content in a chat-app view. System prompts+// and the synthetic "available tools" message are noise here; their effects are+// visible through the assistant's behavior, and the full message tree is still+// one click away via "Show steps".+const HIDDEN_ROLES = new Set<string>(['system', AVAILABLE_TOOLS_ROLE])++function extractText(message: CompatMessage): string {+ const content = message.content+ if (typeof content === 'string') {+ return content+ }+ if (Array.isArray(content)) {+ const parts: string[] = []+ for (const part of content) {+ const text = extractTextContent(part)+ if (text !== undefined) {+ parts.push(text)+ }+ }+ return parts.join('\n')+ }+ if (hasStringContentField(content)) {+ return content.content+ }+ return ''+}++function isUnrenderableContentItem(item: unknown): boolean {+ return extractTextContent(item) === undefined && !isToolStepItem(item)+}++export function hasNonTextContent(message: CompatMessage): boolean {+ const content = message.content+ if (!Array.isArray(content)) {+ return false+ }+ return content.some(isUnrenderableContentItem)+}++// Item kinds for the analytics capture, so we can pivot by what we failed to render.+export function unrenderableContentKinds(message: CompatMessage): string[] {+ const content = message.content+ if (!Array.isArray(content)) {+ return []+ }+ const kinds = content+ .filter(isUnrenderableContentItem)+ .map((item) => (typeof item === 'object' && item !== null && 'type' in item ? String(item.type) : typeof item))+ return Array.from(new Set(kinds)).sort()+}++// Content-hash so the analytics capture dedups across kea selector recomputes+// (a sibling turn's `loadFullTrace` invalidates every turn's `newInputs` reference).+function unrenderableKey(message: CompatMessage): string {+ let serialized: string+ try {+ serialized = JSON.stringify(message.content)+ } catch {+ serialized = String(message.content)+ }+ return `${message.role}::${serialized}`+}++export function captureUnrenderableMessageOnce(message: CompatMessage, seen: Set<string>): void {+ const key = unrenderableKey(message)+ if (seen.has(key)) {+ return+ }+ seen.add(key)+ posthog.capture('llma transcript message unrenderable', {+ role: message.role,+ content_kinds: unrenderableContentKinds(message),+ })+}++/**+ * Renders a deduplicated turn as a chat-app-style bubble stream — user on the+ * right, everything else (assistant, tool responses, etc.) on the left. Skips+ * `system` and `available tools` pseudo-messages; their context is implicit in+ * the assistant's reply and reachable via the per-turn "Show steps" panel.+ *+ * Deliberately minimal: no headers, no per-message expand toggles, no metadata+ * row, no playground button. The Trace page's `ConversationMessagesDisplay`+ * covers those cases; this surface optimizes for top-to-bottom readability.+ */+export function TranscriptBubbleStream({+ inputs,+ outputs,+}: {+ inputs: CompatMessage[]+ outputs: CompatMessage[]+}): JSX.Element | null {+ const visible = useMemo(() => {+ return [...inputs, ...outputs]+ .filter((m) => !HIDDEN_ROLES.has(m.role))+ .map((m) => ({ message: m, text: extractText(m), nonText: hasNonTextContent(m) }))+ .filter(({ text, nonText }) => text.length > 0 || nonText)+ }, [inputs, outputs])++ const capturedRef = useRef<Set<string>>(new Set())+ useEffect(() => {+ for (const { message, nonText } of visible) {+ if (nonText) {+ captureUnrenderableMessageOnce(message, capturedRef.current)+ }+ }+ }, [visible])++ if (visible.length === 0) {+ return null+ }++ return (+ <div className="flex flex-col gap-1.5">+ {visible.map(({ message, text, nonText }, i) => (+ <MessageTemplate key={i} type={message.role === 'user' ? 'human' : 'ai'} wrapperClassName="max-w-[75%]">+ {text && <LemonMarkdown className="whitespace-pre-wrap break-words">{text}</LemonMarkdown>}+ {nonText && <div className="italic text-muted text-xs mt-1">(has attachments)</div>}+ </MessageTemplate>+ ))}+ </div>+ )+}diff --git a/products/llm_analytics/frontend/LLMAnalyticsSessionScene.tsx b/products/llm_analytics/frontend/LLMAnalyticsSessionScene.tsxindex 7b8b9575aa1a..6ff183d61667 100644--- a/products/llm_analytics/frontend/LLMAnalyticsSessionScene.tsx+++ b/products/llm_analytics/frontend/LLMAnalyticsSessionScene.tsx@@ -2,6 +2,7 @@ import { BindLogic, useActions, useValues } from 'kea'import { combineUrl, router } from 'kea-router'import { Suspense, lazy } from 'react'+import { IconWrench } from '@posthog/icons'import { LemonButton, LemonTag, Spinner, SpinnerOverlay, Tooltip } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'@@ -24,7 +25,7 @@ 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 { TranscriptBubbleStream } from './ConversationDisplay/TranscriptBubbleStream'import { SessionTurn } from './extractSessionTurns'import { TraceSummary, llmAnalyticsSessionDataLogic } from './llmAnalyticsSessionDataLogic'import { llmAnalyticsSessionLogic } from './llmAnalyticsSessionLogic'@@ -165,11 +166,10 @@ function SessionSceneWrapper(): JSX.Element {</header><div className="flex flex-col">- {sessionTurns.map((turn, index) => (+ {sessionTurns.map((turn) => (<SessionTurnViewkey={turn.trace.id}turn={turn}- turnNumber={index + 1}showSentiment={showSentiment}showSessionSummarization={!!showSessionSummarization}traceSearchParams={traceSearchParams}@@ -241,25 +241,23 @@ function SummarizeAllButton({function SessionTurnView({turn,- turnNumber,showSentiment,showSessionSummarization,traceSearchParams,}: {turn: SessionTurn- turnNumber: numbershowSentiment: booleanshowSessionSummarization: booleantraceSearchParams: Record<string, unknown>}): JSX.Element {- const { traceSummaries, loadingFullTraces, fullTraces, reasoningExpandedTraceIds, expandedGenerationIds } =+ const { traceSummaries, loadingFullTraces, fullTraces, stepsExpandedTraceIds, expandedGenerationIds } =useValues(llmAnalyticsSessionDataLogic)- const { toggleReasoning, toggleGenerationExpanded, loadFullTrace } = useActions(llmAnalyticsSessionDataLogic)+ const { toggleSteps, toggleGenerationExpanded, loadFullTrace } = useActions(llmAnalyticsSessionDataLogic)const trace = turn.traceconst summary: TraceSummary | undefined = traceSummaries[trace.id]const isLoading = loadingFullTraces.has(trace.id)- const reasoningShown = reasoningExpandedTraceIds.has(trace.id)+ const stepsShown = stepsExpandedTraceIds.has(trace.id)const fullTrace = fullTraces[trace.id]const baseTraceParams = {...traceSearchParams,@@ -268,45 +266,84 @@ function SessionTurnView({const traceUrl = combineUrl(urls.llmAnalyticsTrace(trace.id), baseTraceParams).urlconst summaryUrl = combineUrl(urls.llmAnalyticsTrace(trace.id), { ...baseTraceParams, tab: 'summary' }).url+ const canShowSteps = turn.isLoaded && turn.userVisibleTurn+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 className="flex flex-col">+ <div className="flex items-center gap-3 py-3 text-xs text-muted">+ <div className="flex-1 border-t" />+ <TZLabel time={trace.createdAt} formatDate="MMM D, YYYY" formatTime="h:mm A" />+ <div className="flex-1 border-t" /></div>+ <div className="flex gap-10 pb-4">+ <div className="flex-1 min-w-0 flex flex-col gap-2">+ {showSessionSummarization && summary && (+ <TurnSummaryLine summary={summary} summaryUrl={summaryUrl} />+ )}- {showSessionSummarization && summary && <TurnSummaryLine summary={summary} summaryUrl={summaryUrl} />}+ <TurnBody turn={turn} isLoading={isLoading} onLoad={() => loadFullTrace(trace.id)} />- <TurnBody turn={turn} isLoading={isLoading} onLoad={() => loadFullTrace(trace.id)} />+ {turn.tools.length > 0 && (+ <div className="flex items-center gap-1.5 flex-wrap text-xs text-muted">+ <IconWrench className="text-sm shrink-0" />+ {turn.tools.map((name) => (+ <LemonTag key={name} size="small" className="font-mono">+ {name}+ </LemonTag>+ ))}+ </div>+ )}++ {(trace.errorCount ?? 0) > 0 && (+ <div className="flex items-center gap-2 min-w-0">+ <LemonTag type="danger" size="small" className="shrink-0">+ {trace.errorCount === 1 ? '1 error' : `${trace.errorCount} errors`}+ </LemonTag>+ {turn.errors.length > 0 && (+ <Tooltip+ title={+ <div className="flex flex-col gap-1">+ {turn.errors.map((e, i) => (+ <div key={i}>+ <strong>{e.label}:</strong> {e.message}+ </div>+ ))}+ </div>+ }+ >+ <span className="text-xs text-muted truncate">+ {turn.errors[0].label} · {turn.errors[0].message}+ {turn.errors.length > 1 && ` · +${turn.errors.length - 1} more`}+ </span>+ </Tooltip>+ )}+ </div>+ )}++ {canShowSteps && stepsShown && (+ <StepsPanel+ traceId={trace.id}+ fullTrace={fullTrace}+ expandedEventIds={expandedGenerationIds}+ onToggleEventExpand={toggleGenerationExpanded}+ />+ )}+ </div>- {turn.isLoaded && turn.userVisibleTurn && (- <ReasoningToggle- traceId={trace.id}- fullTrace={fullTrace}- reasoningShown={reasoningShown}- onToggle={() => toggleReasoning(trace.id)}- expandedEventIds={expandedGenerationIds}- onToggleEventExpand={toggleGenerationExpanded}- />- )}+ <div className="w-40 shrink-0 flex flex-col gap-1 text-xs text-muted">+ {showSentiment && <SessionTraceSentimentBar traceId={trace.id} createdAt={trace.createdAt} />}+ <div className="flex flex-col gap-1 items-start">+ {canShowSteps && (+ <LemonButton size="xsmall" type="tertiary" onClick={() => toggleSteps(trace.id)}>+ {stepsShown ? 'Hide steps' : 'Show steps'}+ </LemonButton>+ )}+ <Link to={traceUrl} target="_blank" className="text-xs">+ Open trace+ </Link>+ </div>+ </div>+ </div></div>)}@@ -364,63 +401,29 @@ function TurnBody({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}- />- )+ return <TranscriptBubbleStream inputs={turn.newInputs} outputs={turn.outputs} />}-function ReasoningToggle({+function StepsPanel({traceId,fullTrace,- reasoningShown,- onToggle,expandedEventIds,onToggleEventExpand,}: {traceId: stringfullTrace: LLMTrace | undefined- reasoningShown: boolean- onToggle: () => voidexpandedEventIds: 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 className="border rounded bg-bg-light p-3">+ <LLMAnalyticsTraceEvents+ trace={fullTrace}+ isLoading={false}+ expandedEventIds={expandedEventIds}+ onToggleEventExpand={onToggleEventExpand}+ traceId={traceId}+ /></div>)}diff --git a/products/llm_analytics/frontend/extractSessionTurns.test.ts b/products/llm_analytics/frontend/extractSessionTurns.test.tsindex 201bc59acfb3..7dd1e980566a 100644--- a/products/llm_analytics/frontend/extractSessionTurns.test.ts+++ b/products/llm_analytics/frontend/extractSessionTurns.test.ts@@ -1,6 +1,11 @@import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'-import { buildInputSourceIndices, extractSessionTurns, pickUserVisibleTurn } from './extractSessionTurns'+import {+ buildInputSourceIndices,+ extractSessionTurns,+ pickUserVisibleTurn,+ SessionTurnError,+} from './extractSessionTurns'function makeGeneration(id: string,@@ -100,6 +105,8 @@ describe('extractSessionTurns — cross-trace dedup', () => {expect(turns[0].isLoaded).toBe(false)expect(turns[0].newInputs).toEqual([])expect(turns[0].outputs).toEqual([])+ expect(turns[0].tools).toEqual([])+ expect(turns[0].errors).toEqual([])})it('returns an isLoaded turn with no userVisibleTurn for span-only traces', () => {@@ -209,8 +216,6 @@ describe('extractSessionTurns — cross-trace dedup', () => {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', () => {@@ -271,8 +276,6 @@ describe('extractSessionTurns — cross-trace dedup', () => {])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', () => {@@ -344,25 +347,49 @@ describe('extractSessionTurns — cross-trace dedup', () => {expect(turns[1].newInputs.map((m) => m.role)).toEqual(['assistant'])})- it('source indices line up with the rendered messages after dedup', () => {+ it('keeps two image+text messages distinct when the images differ', () => {+ // Regression guard: someone stripping attachment data from+ // `messageSignature` thinking it's not needed for identity would+ // collapse these two messages and silently drop the second image.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' }],+ $ai_input: [+ {+ role: 'user',+ content: [+ { type: 'text', text: 'What about this one?' },+ { type: 'image_url', image_url: { url: 'https://example.com/a.png' } },+ ],+ },+ ],+ $ai_output_choices: [{ role: 'assistant', content: 'A cat.' }],}),])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+ {+ role: 'user',+ content: [+ { type: 'text', text: 'What about this one?' },+ { type: 'image_url', image_url: { url: 'https://example.com/a.png' } },+ ],+ },+ { role: 'assistant', content: 'A cat.' },+ {+ role: 'user',+ content: [+ { type: 'text', text: 'What about this one?' },+ { type: 'image_url', image_url: { url: 'https://example.com/b.png' } },+ ],+ },],- $ai_output_choices: [{ role: 'assistant', content: 'Answer' }],+ $ai_output_choices: [{ role: 'assistant', content: 'A dog.' }],}),])const turns = extractSessionTurns([t1, t2], { t1, t2 })- expect(turns[1].newInputSourceIndices).toEqual([2])+ expect(turns[1].newInputs).toHaveLength(1)+ expect(turns[1].newInputs[0].role).toBe('user')})it('dedups an assistant message even when its output shape differs from the next-turn-input shape', () => {@@ -402,6 +429,132 @@ describe('extractSessionTurns — cross-trace dedup', () => {})})+describe('extractSessionTurns — tools and errors', () => {+ it('dedupes repeated tool names into first-appearance order on the SessionTurn', () => {+ const span = (id: string, name: string): LLMTraceEvent => ({+ id,+ event: '$ai_span',+ createdAt: '2026-05-11T00:00:00.000Z',+ properties: { $ai_span_name: name },+ })+ const t1 = makeTrace('t1', [+ span('s1', 'fetch_user'),+ span('s2', 'subscription_lookup'),+ span('s3', 'fetch_user'), // duplicate — first-appearance order wins+ makeGeneration('g1', '2026-05-11T00:00:01.000Z', {+ // Generation also calls `fetch_user` — must collapse with the spans.+ $ai_output_choices: [+ {+ role: 'assistant',+ content: '',+ tool_calls: [{ id: 'a', type: 'function', function: { name: 'fetch_user', arguments: '{}' } }],+ },+ ],+ }),+ ])+ const [turn] = extractSessionTurns([t1], { t1 })+ expect(turn.tools).toEqual(['fetch_user', 'subscription_lookup'])+ })++ it('surfaces the first chronological error with label + message', () => {+ const errorSpan: LLMTraceEvent = {+ id: 's1',+ event: '$ai_span',+ createdAt: '2026-05-11T00:00:01.000Z',+ properties: {+ $ai_span_name: 'subscription_lookup',+ $ai_is_error: 'true',+ $ai_error: { message: '404 not found: subscription does not exist' },+ },+ }+ const t1 = makeTrace('t1', [makeGeneration('g1', '2026-05-11T00:00:00.000Z'), errorSpan])+ const [turn] = extractSessionTurns([t1], { t1 })+ expect(turn.errors).toEqual([+ {+ label: 'subscription_lookup',+ message: '404 not found: subscription does not exist',+ },+ ])+ })++ it('returns errors=[] when no event has an error flag', () => {+ const t1 = makeTrace('t1', [makeGeneration('g1', '2026-05-11T00:00:00.000Z')])+ const [turn] = extractSessionTurns([t1], { t1 })+ expect(turn.errors).toEqual([])+ })++ // Payload-wins rule: a populated `$ai_error` outranks `$ai_is_error: "false"`,+ // and the flag-only path uses strict `=== 'true'` so the string `"false"` doesn't+ // get treated as truthy.+ it.each<[name: string, errorPayload: unknown, expectedErrors: SessionTurnError[]]>([+ ['no $ai_error payload — flag rules, stays non-error', undefined, []],+ [+ '$ai_error populated — payload rules, becomes an error',+ { message: 'connection timeout' },+ [{ label: 'fetch_user', message: 'connection timeout' }],+ ],+ ])('with `$ai_is_error: "false"` and %s', (_, errorPayload, expectedErrors) => {+ const event: LLMTraceEvent = {+ id: 's1',+ event: '$ai_span',+ createdAt: '2026-05-11T00:00:01.000Z',+ properties: {+ $ai_span_name: 'fetch_user',+ $ai_is_error: 'false',+ ...(errorPayload !== undefined ? { $ai_error: errorPayload } : {}),+ },+ }+ const t1 = makeTrace('t1', [makeGeneration('g1', '2026-05-11T00:00:00.000Z'), event])+ const [turn] = extractSessionTurns([t1], { t1 })+ expect(turn.errors).toEqual(expectedErrors)+ })++ it('dedups errors by label + message — retries collapse to one entry', () => {+ // Three retries of the same failure should appear as one entry, not three.+ // `trace.errorCount` (from the summary) keeps the raw event count; `errors.length`+ // reflects the count of DISTINCT failures.+ const errorSpan = (id: string, createdAt: string): LLMTraceEvent => ({+ id,+ event: '$ai_span',+ createdAt,+ properties: {+ $ai_span_name: 'fetch_user',+ $ai_is_error: 'true',+ $ai_error: { message: 'connection timeout' },+ },+ })+ const t1 = makeTrace('t1', [+ errorSpan('s1', '2026-05-11T00:00:00.000Z'),+ errorSpan('s2', '2026-05-11T00:00:01.000Z'),+ errorSpan('s3', '2026-05-11T00:00:02.000Z'),+ makeGeneration('g1', '2026-05-11T00:00:03.000Z'),+ ])+ const [turn] = extractSessionTurns([t1], { t1 })+ expect(turn.errors).toEqual([{ label: 'fetch_user', message: 'connection timeout' }])+ })++ it('preserves distinct errors in chronological first-appearance order', () => {+ // Three different failures appearing in order should all surface — and the+ // order should be chronological (by createdAt), not whatever order the+ // events array happened to come back in.+ const errorEvent = (id: string, createdAt: string, spanName: string, message: string): LLMTraceEvent => ({+ id,+ event: '$ai_span',+ createdAt,+ properties: { $ai_span_name: spanName, $ai_is_error: 'true', $ai_error: { message } },+ })+ const t1 = makeTrace('t1', [+ // Deliberately out of chronological order in the array.+ errorEvent('s3', '2026-05-11T00:00:02.000Z', 'send_email', 'rate limited'),+ errorEvent('s1', '2026-05-11T00:00:00.000Z', 'fetch_user', 'connection timeout'),+ errorEvent('s2', '2026-05-11T00:00:01.000Z', 'subscription_lookup', '404 not found'),+ makeGeneration('g1', '2026-05-11T00:00:03.000Z'),+ ])+ const [turn] = extractSessionTurns([t1], { t1 })+ expect(turn.errors.map((e) => e.label)).toEqual(['fetch_user', 'subscription_lookup', 'send_email'])+ })+})+// 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 neutraldiff --git a/products/llm_analytics/frontend/extractSessionTurns.ts b/products/llm_analytics/frontend/extractSessionTurns.tsindex d323a318f8aa..8c208b5556c5 100644--- a/products/llm_analytics/frontend/extractSessionTurns.ts+++ b/products/llm_analytics/frontend/extractSessionTurns.ts@@ -2,7 +2,15 @@ import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'import { messageSignature } from './messageSignature'import { CompatMessage } from './types'-import { normalizeMessage, normalizeMessages } from './utils'+import {+ eventLabel,+ formatAiErrorForDisplay,+ getToolNamesCalled,+ normalizeMessage,+ normalizeMessages,+ readAiInput,+ readAiOutput,+} from './utils'// Heuristic mirrors the LLMA skill script `print_summary.py` at// `products/llm_analytics/skills/exploring-llm-traces/scripts/` — keep in sync.@@ -14,7 +22,7 @@ import { normalizeMessage, normalizeMessages } from './utils'* 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.+ * "Show steps" affordance is the user's fallback.*/export function pickUserVisibleTurn(trace: LLMTrace | undefined): LLMTraceEvent | undefined {if (!trace?.events?.length) {@@ -59,6 +67,13 @@ export function buildInputSourceIndices(rawInput: unknown, tools: unknown): numbreturn indices}+export interface SessionTurnError {+ /** Human-readable label for *what* failed — `$ai_span_name`, `$ai_model`, or the raw event type as a last resort. */+ label: string+ /** Extracted error message. For `$ai_error` objects we surface `.message` directly; everything else is JSON-stringified. */+ message: string+}+export interface SessionTurn {/** The trace this turn corresponds to. */trace: LLMTrace@@ -68,10 +83,65 @@ export interface SessionTurn {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`. */+ /** The event sourced by `pickUserVisibleTurn` — used for model, error, latency, and the id passed to renderers. */userVisibleTurn?: LLMTraceEvent+ /**+ * Distinct tool names called in this turn, in first-appearance order. Pulled+ * from both `$ai_span_name` on instrumented `$ai_span` events and from+ * `tool_calls` / `tool_use` parts in generation outputs.+ */+ tools: string[]+ /**+ * Distinct errors in the trace, deduped by `label + message` and ordered by+ * first chronological occurrence. Retries of the same failure collapse to a+ * single entry; truly distinct failures all appear. `trace.errorCount` still+ * reflects total error events (including retries); `errors.length` is the+ * count of UNIQUE kinds.+ */+ errors: SessionTurnError[]+}++function getToolNamesCalledUnique(events: LLMTraceEvent[]): string[] {+ // `Set` insertion order preserves first-appearance+ return Array.from(new Set(getToolNamesCalled(events)))+}++/**+ * Distinct errors keyed by `label + message`, in chronological first-appearance+ * order. Retries of the same failure collapse to one entry. The chip already+ * shows the raw event count (including retries); listing *distinct kinds* of+ * failures inline reads more usefully than listing every retry.+ */+function collectDistinctErrors(events: LLMTraceEvent[]): SessionTurnError[] {+ const sorted = [...events].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())+ const seen = new Set<string>()+ const ordered: SessionTurnError[] = []+ for (const event of sorted) {+ // A populated `$ai_error` payload is the authoritative signal — if it's+ // there, treat the event as an error regardless of `$ai_is_error`.+ // (Note that PostHog SDKs serialize booleans as strings)+ const hasErrorPayload = !!event.properties.$ai_error+ const isErrorFlag = event.properties.$ai_is_error+ const isError = hasErrorPayload || isErrorFlag === true || isErrorFlag === 'true'+ if (!isError) {+ continue+ }+ const label = eventLabel(event)+ const rawError = event.properties.$ai_error+ const message =+ typeof rawError === 'object' &&+ rawError !== null &&+ 'message' in rawError &&+ typeof rawError.message === 'string'+ ? rawError.message+ : formatAiErrorForDisplay(rawError)+ const key = `${label}::${message}`+ if (!seen.has(key)) {+ seen.add(key)+ ordered.push({ label, message })+ }+ }+ return ordered}/**@@ -93,9 +163,12 @@ export function extractSessionTurns(traces: LLMTrace[], fullTraces: Record<strinisLoaded: false,newInputs: [],outputs: [],- newInputSourceIndices: [],+ tools: [],+ errors: [],}}+ const tools = getToolNamesCalledUnique(fullTrace.events ?? [])+ const errors = collectDistinctErrors(fullTrace.events ?? [])const userVisibleTurn = pickUserVisibleTurn(fullTrace)if (!userVisibleTurn) {return {@@ -103,32 +176,30 @@ export function extractSessionTurns(traces: LLMTrace[], fullTraces: Record<strinisLoaded: true,newInputs: [],outputs: [],- newInputSourceIndices: [],+ tools,+ errors,}}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 rawInput = readAiInput(properties)+ const rawOutput = readAiOutput(properties)+ const aiTools = properties.$ai_tools- const inputMessages = normalizeMessages(rawInput, 'user', tools)+ const inputMessages = normalizeMessages(rawInput, 'user', aiTools)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) => {+ for (const message of inputMessages) {const sig = messageSignature(message)const turnCount = (msgCountThisTurn.get(sig) ?? 0) + 1msgCountThisTurn.set(sig, turnCount)const shownCount = msgCountShown.get(sig) ?? 0if (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)@@ -139,8 +210,9 @@ export function extractSessionTurns(traces: LLMTrace[], fullTraces: Record<strinisLoaded: true,newInputs,outputs: outputMessages,- newInputSourceIndices,userVisibleTurn,+ tools,+ errors,}})}diff --git a/products/llm_analytics/frontend/llmAnalyticsAIDataLogic.ts b/products/llm_analytics/frontend/llmAnalyticsAIDataLogic.tsindex c6fe71c28375..e01e15e1e83e 100644--- a/products/llm_analytics/frontend/llmAnalyticsAIDataLogic.ts+++ b/products/llm_analytics/frontend/llmAnalyticsAIDataLogic.ts@@ -6,6 +6,7 @@ import api from 'lib/api'import { NodeKind, TraceQuery } from '~/queries/schema/schema-general'import type { llmAnalyticsAIDataLogicType } from './llmAnalyticsAIDataLogicType'+import { readAiInput, readAiOutput } from './utils'export interface AIData {input: unknown@@ -64,8 +65,8 @@ async function loadAIDataAsync(params: LoadAIDataParams): Promise<AIData> {}const props = event.properties ?? {}return {- input: props.$ai_input ?? props.$ai_input_state ?? input,- output: props.$ai_output_choices ?? props.$ai_output_state ?? output,+ input: readAiInput(props) ?? input,+ output: readAiOutput(props) ?? output,tools: props.$ai_tools ?? tools,}} catch (error) {diff --git a/products/llm_analytics/frontend/llmAnalyticsSessionDataLogic.ts b/products/llm_analytics/frontend/llmAnalyticsSessionDataLogic.tsindex 9d8fce672a2c..84a997160eb9 100644--- a/products/llm_analytics/frontend/llmAnalyticsSessionDataLogic.ts+++ b/products/llm_analytics/frontend/llmAnalyticsSessionDataLogic.ts@@ -80,10 +80,10 @@ export const llmAnalyticsSessionDataLogic = kea<llmAnalyticsSessionDataLogicType})),actions({- // 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 }),+ // Steps panel = the per-turn `LLMAnalyticsTraceEvents` tree shown via the+ // "Show steps" link. Distinct from "trace loaded" because the conversation+ // bubbles render as soon as the full trace is fetched, regardless of steps state.+ toggleSteps: (traceId: string) => ({ traceId }),toggleGenerationExpanded: (generationId: string) => ({ generationId }),loadFullTrace: (traceId: string) => ({ traceId }),loadFullTraceSuccess: (traceId: string, trace: LLMTrace) => ({ traceId, trace }),@@ -98,10 +98,10 @@ export const llmAnalyticsSessionDataLogic = kea<llmAnalyticsSessionDataLogicType}),reducers({- reasoningExpandedTraceIds: [+ stepsExpandedTraceIds: [new Set<string>() as Set<string>,{- toggleReasoning: (state, { traceId }) => {+ toggleSteps: (state, { traceId }) => {const newSet = new Set(state)if (newSet.has(traceId)) {newSet.delete(traceId)diff --git a/products/llm_analytics/frontend/messageSignature.test.ts b/products/llm_analytics/frontend/messageSignature.test.tsindex 07e52e918204..209be1f3b171 100644--- a/products/llm_analytics/frontend/messageSignature.test.ts+++ b/products/llm_analytics/frontend/messageSignature.test.ts@@ -37,6 +37,26 @@ describe('messageSignature', () => {a: { role: 'tool', content: 'ok', tool_call_id: 'call_a' },b: { role: 'tool', content: 'ok', tool_call_id: 'call_b' },},+ {+ // Pins attachment-aware dedup: same text, different image URL must+ // produce different signatures so the second image isn't silently+ // collapsed into the first.+ name: 'image URLs in mixed text+image content',+ a: {+ role: 'user',+ content: [+ { type: 'text', text: 'Look at this' },+ { type: 'image_url', image_url: { url: 'https://example.com/a.png' } },+ ],+ },+ b: {+ role: 'user',+ content: [+ { type: 'text', text: 'Look at this' },+ { type: 'image_url', image_url: { url: 'https://example.com/b.png' } },+ ],+ },+ },]it.each(distinctCases)('distinguishes by $name', ({ a, b }) => {diff --git a/products/llm_analytics/frontend/traceExportUtils.ts b/products/llm_analytics/frontend/traceExportUtils.tsindex 2964fe6f554d..6bf0db616273 100644--- a/products/llm_analytics/frontend/traceExportUtils.ts+++ b/products/llm_analytics/frontend/traceExportUtils.ts@@ -5,7 +5,7 @@ import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'import { EnrichedTraceTreeNode } from './llmAnalyticsTraceDataLogic'import { CompatMessage } from './types'-import { formatLLMEventTitle, normalizeMessages } from './utils'+import { formatLLMEventTitle, normalizeMessages, readAiOutput } from './utils'interface EventMetrics {latency?: number@@ -68,10 +68,7 @@ function buildEventExport(event: LLMTraceEvent, children?: EnrichedTraceTreeNodeif (isGeneration) {// For generations, normalize messages without toolsconst inputMessages: CompatMessage[] = normalizeMessages(event.properties.$ai_input, 'user')- const outputMessages: CompatMessage[] = normalizeMessages(- event.properties.$ai_output_choices ?? event.properties.$ai_output,- 'assistant'- )+ const outputMessages: CompatMessage[] = normalizeMessages(readAiOutput(event.properties), 'assistant')const messages: CompatMessage[] = []if (inputMessages.length > 0) {diff --git a/products/llm_analytics/frontend/types.ts b/products/llm_analytics/frontend/types.tsindex 3624e5afed17..56255373bf21 100644--- a/products/llm_analytics/frontend/types.ts+++ b/products/llm_analytics/frontend/types.ts@@ -3,6 +3,10 @@ export interface RoleBasedMessage {content: string | { type: string; content: string } | MultiModalContentItem[]}+export interface StringContentObject {+ content: string+}+export interface OpenAIToolCall {type: stringid?: stringdiff --git a/products/llm_analytics/frontend/utils.test.ts b/products/llm_analytics/frontend/utils.test.tsindex cd7ca3f0e1c6..2dfe62483fe7 100644--- a/products/llm_analytics/frontend/utils.test.ts+++ b/products/llm_analytics/frontend/utils.test.ts@@ -2,15 +2,20 @@ import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'import { AnthropicInputMessage, OpenAICompletionMessage } from './types'import {+ asString,costContextFromProperties,costContextFromTrace,formatAiErrorForDisplay,formatLLMEventTitle,getSessionID,getSessionStartTimestamp,+ getToolNamesCalled,hasCostBreakdown,+ hasStringContentField,isEmptyJSONStructure,isLangChainMessage,+ isTextContentItem,+ isToolStepItem,looksLikeXml,normalizeMessage,normalizeMessages,@@ -2162,6 +2167,90 @@ describe('AI observability utils', () => {})})+ describe('hasStringContentField', () => {+ it.each<[name: string, input: unknown, expected: boolean]>([+ ['accepts {content: "hi"}', { content: 'hi' }, true],+ ['accepts {type: "text", content: "hi"} — extra fields are fine', { type: 'text', content: 'hi' }, true],+ ['accepts {content: ""} — empty string still passes', { content: '' }, true],+ ['rejects {content: 42} — non-string content', { content: 42 }, false],+ ['rejects {content: null}', { content: null }, false],+ ['rejects missing `content` property', { type: 'text' }, false],+ ['rejects null', null, false],+ ['rejects undefined', undefined, false],+ ['rejects a plain string', 'hi', false],+ ['rejects an array', [{ content: 'hi' }], false],+ ])('%s', (_, input, expected) => {+ expect(hasStringContentField(input)).toBe(expected)+ })+ })++ describe('isToolStepItem', () => {+ it.each<[name: string, input: unknown, expected: boolean]>([+ ['accepts Anthropic `tool_use`', { type: 'tool_use', id: 'toolu_1', name: 'x', input: {} }, true],+ ['accepts Vercel SDK `tool-call`', { type: 'tool-call', toolCallId: 'a', toolName: 'x', input: {} }, true],+ ['accepts unified `{type: "function"}`', { type: 'function', function: { name: 'x' } }, true],+ [+ 'accepts OpenAI Responses `function_call`',+ { type: 'function_call', call_id: 'c1', name: 'x', arguments: '{}' },+ true,+ ],+ [+ 'accepts OpenAI Responses built-in tool call (e.g. web_search_call)',+ { id: 'ws1', type: 'web_search_call', status: 'completed' },+ true,+ ],+ ['accepts Anthropic `tool_result`', { type: 'tool_result', tool_use_id: 'toolu_1', content: 'ok' }, true],+ [+ 'accepts Vercel SDK `tool-result`',+ { type: 'tool-result', toolCallId: 'a', toolName: 'search_docs', result: 'ok' },+ true,+ ],+ ['rejects text content items', { type: 'text', text: 'hi' }, false],+ ['rejects image items', { type: 'image_url', image_url: { url: 'x' } }, false],+ ['rejects file items', { type: 'file', file: { filename: 'f', file_data: 'd' } }, false],+ ['rejects null', null, false],+ ['rejects a plain string', 'function', false],+ ['rejects `{type: "function"}` without a `function` payload', { type: 'function' }, false],+ [+ 'rejects `{type: "function", function: "not-an-object"}`',+ { type: 'function', function: 'not-an-object' },+ false,+ ],+ ])('%s', (_, input, expected) => {+ expect(isToolStepItem(input)).toBe(expected)+ })+ })++ describe('isTextContentItem', () => {+ it.each<[name: string, input: unknown, expected: boolean]>([+ ['accepts {type: "text", text: "hi"}', { type: 'text', text: 'hi' }, true],+ ['accepts {type: "text", text: ""}', { type: 'text', text: '' }, true],+ ['rejects missing `text` property', { type: 'text' }, false],+ ['rejects wrong `type` literal', { type: 'image', text: 'hi' }, false],+ ['rejects null', null, false],+ ['rejects undefined', undefined, false],+ ['rejects a plain string', 'hi', false],+ ['rejects an array', [{ type: 'text', text: 'hi' }], false],+ ])('%s', (_, input, expected) => {+ expect(isTextContentItem(input)).toBe(expected)+ })+ })++ describe('asString', () => {+ it.each<[name: string, input: unknown, expected: string | undefined]>([+ ['returns a non-empty string unchanged', 'hello', 'hello'],+ ['returns an empty string as itself (caller decides via `||`)', '', ''],+ ['returns undefined for undefined', undefined, undefined],+ ['returns undefined for null', null, undefined],+ ['returns undefined for a number', 42, undefined],+ ['returns undefined for a boolean', true, undefined],+ ['returns undefined for an object', { value: 'oops' }, undefined],+ ['returns undefined for an array', ['oops'], undefined],+ ])('%s', (_, input, expected) => {+ expect(asString(input)).toBe(expected)+ })+ })+describe('formatAiErrorForDisplay', () => {it.each<[string, unknown, string]>([['string passes through', 'rate limit exceeded', 'rate limit exceeded'],@@ -2188,4 +2277,189 @@ describe('AI observability utils', () => {expect(formatAiErrorForDisplay(circular)).toBe('[object Object]')})})++ describe('getToolNamesCalled', () => {+ const span = (id: string, createdAt: string, spanName?: string): LLMTraceEvent => ({+ id,+ event: '$ai_span',+ createdAt,+ properties: spanName ? { $ai_span_name: spanName } : {},+ })+ const generation = (id: string, createdAt: string, outputChoices: unknown): LLMTraceEvent => ({+ id,+ event: '$ai_generation',+ createdAt,+ properties: { $ai_output_choices: outputChoices },+ })++ it('returns [] for an empty event list', () => {+ expect(getToolNamesCalled([])).toEqual([])+ })++ it('returns `$ai_span_name` from instrumented span events', () => {+ const events = [span('s1', '2026-05-11T00:00:00.000Z', 'fetch_user')]+ expect(getToolNamesCalled(events)).toEqual(['fetch_user'])+ })++ it('skips span events without a `$ai_span_name`', () => {+ const events = [span('s1', '2026-05-11T00:00:00.000Z')]+ expect(getToolNamesCalled(events)).toEqual([])+ })++ it('skips event types other than `$ai_span` and `$ai_generation`', () => {+ const events: LLMTraceEvent[] = [+ {+ id: 'trace',+ event: '$ai_trace',+ createdAt: '2026-05-11T00:00:00.000Z',+ properties: { $ai_span_name: 'irrelevant' },+ },+ ]+ expect(getToolNamesCalled(events)).toEqual([])+ })++ // Covers every output shape `normalizeMessages` understands — adding a new+ // SDK shape there should bring it under this case table without further+ // changes here.+ it.each<[name: string, outputChoices: unknown, expected: string[]]>([+ [+ 'OpenAI Chat Completions `tool_calls`',+ [+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ { id: 'a', type: 'function', function: { name: 'get_weather', arguments: '{}' } },+ { id: 'b', type: 'function', function: { name: 'search_docs', arguments: '{}' } },+ ],+ },+ ],+ ['get_weather', 'search_docs'],+ ],+ [+ 'Anthropic `tool_use` typed parts',+ [+ {+ role: 'assistant',+ content: [+ { type: 'text', text: 'Looking it up.' },+ { type: 'tool_use', id: 'toolu_1', name: 'get_weather', input: { city: 'Berlin' } },+ { type: 'tool_use', id: 'toolu_2', name: 'search_docs', input: {} },+ ],+ },+ ],+ ['get_weather', 'search_docs'],+ ],+ [+ 'OpenAI Responses `function_call` items',+ [+ { type: 'function_call', call_id: 'c1', name: 'get_weather', arguments: '{}' },+ { type: 'function_call', call_id: 'c2', name: 'search_docs', arguments: '{}' },+ ],+ ['get_weather', 'search_docs'],+ ],+ [+ 'Vercel SDK `tool-call` items',+ [+ { type: 'tool-call', toolCallId: 'a', toolName: 'get_weather', input: { city: 'Berlin' } },+ { type: 'tool-call', toolCallId: 'b', toolName: 'search_docs', input: {} },+ ],+ ['get_weather', 'search_docs'],+ ],+ [+ 'OpenAI Responses built-in tool calls',+ [+ { id: 'ws1', type: 'web_search_call', status: 'completed' },+ { id: 'mcp1', type: 'mcp_call', name: 'list_dashboards', status: 'completed' },+ ],+ ['web_search_call', 'list_dashboards'],+ ],+ [+ 'LiteLLM-style {choices:[{message:{tool_calls}}]} wrapper',+ {+ choices: [+ {+ finish_reason: 'tool_calls',+ index: 0,+ message: {+ role: 'assistant',+ content: null,+ tool_calls: [+ {+ id: 'a',+ type: 'function',+ function: { name: 'get_weather', arguments: '{"city":"Berlin"}' },+ },+ {+ id: 'b',+ type: 'function',+ function: { name: 'search_docs', arguments: '{}' },+ },+ ],+ },+ },+ ],+ },+ ['get_weather', 'search_docs'],+ ],+ ])('returns tool names from %s in $ai_generation outputs', (_, outputChoices, expected) => {+ const events = [generation('g1', '2026-05-11T00:00:00.000Z', outputChoices)]+ expect(getToolNamesCalled(events)).toEqual(expected)+ })++ it('preserves duplicates in the raw call sequence — caller decides whether to dedupe', () => {+ // Three identical tool calls across span + generation events should all appear.+ // Dedup is a session-page concern, not part of "what tools were called".+ const events = [+ span('s1', '2026-05-11T00:00:00.000Z', 'fetch_user'),+ generation('g1', '2026-05-11T00:00:01.000Z', [+ {+ role: 'assistant',+ content: '',+ tool_calls: [{ id: 'a', type: 'function', function: { name: 'fetch_user', arguments: '{}' } }],+ },+ ]),+ span('s2', '2026-05-11T00:00:02.000Z', 'fetch_user'),+ ]+ expect(getToolNamesCalled(events)).toEqual(['fetch_user', 'fetch_user', 'fetch_user'])+ })++ it('orders names chronologically regardless of input order', () => {+ // Events come back from ClickHouse in whatever order the query produced.+ const events = [+ span('s3', '2026-05-11T00:00:02.000Z', 'send_email'),+ span('s1', '2026-05-11T00:00:00.000Z', 'fetch_user'),+ span('s2', '2026-05-11T00:00:01.000Z', 'subscription_lookup'),+ ]+ expect(getToolNamesCalled(events)).toEqual(['fetch_user', 'subscription_lookup', 'send_email'])+ })++ it('skips tool calls with missing or empty names', () => {+ const events = [+ generation('g1', '2026-05-11T00:00:00.000Z', [+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ { id: 'a', type: 'function', function: { name: '', arguments: '{}' } },+ { id: 'b', type: 'function', function: { name: 'real_tool', arguments: '{}' } },+ ],+ },+ ]),+ ]+ expect(getToolNamesCalled(events)).toEqual(['real_tool'])+ })++ it('returns [] when a generation has no $ai_output_choices', () => {+ const events: LLMTraceEvent[] = [+ {+ id: 'g1',+ event: '$ai_generation',+ createdAt: '2026-05-11T00:00:00.000Z',+ properties: {},+ },+ ]+ expect(getToolNamesCalled(events)).toEqual([])+ })+ })})diff --git a/products/llm_analytics/frontend/utils.ts b/products/llm_analytics/frontend/utils.tsindex 4bd1692fea4f..afbf9557cc99 100644--- a/products/llm_analytics/frontend/utils.ts+++ b/products/llm_analytics/frontend/utils.ts@@ -3,7 +3,7 @@ import posthog from 'posthog-js'import api from 'lib/api'import { dayjs } from 'lib/dayjs'-import { isObject } from 'lib/utils'+import { isObject, isString } from 'lib/utils'import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'import { hogql } from '~/queries/utils'@@ -35,6 +35,8 @@ import {OpenAIResponsesFunctionCallOutput,OpenAIResponsesReasoning,OpenAIToolCall,+ StringContentObject,+ TextContentItem,VercelSDKImageMessage,VercelSDKInputImageMessage,VercelSDKInputTextMessage,@@ -221,6 +223,44 @@ export function formatTokens(tokens: number): string {return tokens.toFixed(0)}+/**+ * Defensive narrowing for values pulled out of `LLMTraceEvent.properties` (typed+ * as `Record<string, any>`). Returns the value when it's a string, otherwise+ * `undefined` — safer than `as string | undefined` which silently lets numbers+ * or objects through. Use this any time a `$ai_*` property is documented as a+ * string by convention but the runtime data could vary.+ */+export function asString(value: unknown): string | undefined {+ return isString(value) ? value : undefined+}++/**+ * Reads the input payload from an event's properties.+ * - `$ai_input`: emitted by every SDK integration on `$ai_generation`+ * (OpenAI, Anthropic, Gemini, and the framework wrappers).+ * - `$ai_input_state`: emitted by framework wrappers (LangChain, OpenAI Agents,+ * Claude Agent SDK) on `$ai_span` events that wrap a non-generation step.+ */+export function readAiInput(properties: Record<string, any>): unknown {+ return properties.$ai_input ?? properties.$ai_input_state+}++/**+ * Reads the output payload from an event's properties.+ * - `$ai_output_choices`: emitted by every SDK integration on `$ai_generation`.+ * - `$ai_output_state`: emitted by framework wrappers (LangChain, OpenAI Agents,+ * Claude Agent SDK) on `$ai_span` events.+ * - `$ai_output`: kept as a defensive fallback for events that the ingestion+ * pipeline treats as containing a heavy output payload+ */+export function readAiOutput(properties: Record<string, any>): unknown {+ return properties.$ai_output_choices ?? properties.$ai_output_state ?? properties.$ai_output+}++export function eventLabel(event: LLMTraceEvent): string {+ return asString(event.properties.$ai_span_name) || asString(event.properties.$ai_model) || event.event+}+export function formatAiErrorForDisplay(value: unknown): string {if (typeof value === 'string') {return value || 'Unknown error'@@ -386,14 +426,61 @@ export function parseOpenAIToolCalls(toolCalls: OpenAIToolCall[]): CompatToolCalreturn toolsWithParsedArguments}+export function isTextContentItem(item: unknown): item is TextContentItem {+ return !!item && typeof item === 'object' && 'type' in item && item.type === 'text' && 'text' in item+}+export function isAnthropicTextMessage(output: unknown): output is AnthropicTextMessage {- return !!output && typeof output === 'object' && 'type' in output && output.type === 'text' && 'text' in output+ return isTextContentItem(output)+}++export function hasStringContentField(value: unknown): value is StringContentObject {+ return typeof value === 'object' && value !== null && 'content' in value && isString(value.content)+}++// Returns the user-visible string from a content part+export function extractTextContent(item: unknown): string | undefined {+ if (typeof item === 'string') {+ return item+ }+ if (isTextContentItem(item)) {+ return item.text+ }+ if (isVercelSDKTextMessage(item)) {+ return item.content+ }+ if (isVercelSDKInputTextMessage(item)) {+ return item.text+ }+ return undefined}export function isAnthropicToolCallMessage(output: unknown): output is AnthropicToolCallMessage {return !!output && typeof output === 'object' && 'type' in output && output.type === 'tool_use'}+export function isToolStepItem(item: unknown): boolean {+ if (+ isAnthropicToolCallMessage(item) ||+ isAnthropicToolResultMessage(item) ||+ isVercelSDKToolCallMessage(item) ||+ isVercelSDKToolResultMessage(item) ||+ isOpenAIResponsesFunctionCall(item) ||+ isOpenAIResponsesBuiltinToolCall(item)+ ) {+ return true+ }+ return (+ typeof item === 'object' &&+ item !== null &&+ 'type' in item &&+ item.type === 'function' &&+ 'function' in item &&+ typeof item.function === 'object' &&+ item.function !== null+ )+}+export function isAnthropicThinkingMessage(output: unknown): output is AnthropicThinkingMessage {return !!output && typeof output === 'object' && 'type' in output && output.type === 'thinking'}@@ -1317,12 +1404,7 @@ export function normalizeMessage(rawMessage: unknown, defaultRole: string): Complet cajoledContent: string // Let's do what we canif (typeof rawMessage === 'string') {cajoledContent = rawMessage- } else if (- typeof rawMessage === 'object' &&- rawMessage !== null &&- 'content' in rawMessage &&- typeof rawMessage.content === 'string'- ) {+ } else if (hasStringContentField(rawMessage)) {cajoledContent = rawMessage.content} else {cajoledContent = JSON.stringify(rawMessage)@@ -1330,12 +1412,42 @@ export function normalizeMessage(rawMessage: unknown, defaultRole: string): Compreturn [{ role: roleToUse, content: cajoledContent }]}+// Synthetic role used by `normalizeMessages` to surface the `$ai_tools` payload+// as a pseudo-message+export const AVAILABLE_TOOLS_ROLE = 'available tools'++// Returns the tool names invoked across events in chronological order (duplicates preserved)+export function getToolNamesCalled(events: LLMTraceEvent[]): string[] {+ const sorted = [...events].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())+ const names: string[] = []+ // Pulls from `$ai_span_name` on instrumented `$ai_span` events+ // and from `tool_calls[].function.name` on normalized `$ai_generation` outputs+ for (const event of sorted) {+ if (event.event === '$ai_span') {+ const spanName = event.properties.$ai_span_name+ if (typeof spanName === 'string' && spanName) {+ names.push(spanName)+ }+ } else if (event.event === '$ai_generation') {+ for (const msg of normalizeMessages(event.properties.$ai_output_choices, 'assistant')) {+ for (const tc of msg.tool_calls ?? []) {+ const name = tc.function?.name+ if (typeof name === 'string' && name) {+ names.push(name)+ }+ }+ }+ }+ }+ return names+}+export function normalizeMessages(messages: unknown, defaultRole: string, tools?: unknown): CompatMessage[] {const normalizedMessages: CompatMessage[] = []if (tools) {normalizedMessages.push({- role: 'available tools',+ role: AVAILABLE_TOOLS_ROLE,content: '',tools,})