Skip to content

: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.

feat(aio): new trace scene behind flag (#108228)

Carlos Marchal4323416da7b7
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 8c3d87cddd69..78d6d3da337c 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -257,6 +257,7 @@ export const FEATURE_FLAGS = {
ACTION_REFERENCE_COUNT: 'action-reference-count', // owner: @andyzzhao #team-product-analytics, gates bulk action reference counting on actions list
ADVANCE_MARKETING_ANALYTICS_SETTINGS: 'advance-marketing-analytics-settings', // owner: @jabahamondes #team-web-analytics
AI_GATEWAY: 'ai-gateway', // owner: #team-agent-infra, gates the AI gateway UI and llm_gateway:read on project secret API keys
+ AI_OBSERVABILITY_TRACE_REDESIGN: 'ai-observability-trace-redesign', // owner: #team-ai-observability, gates the redesigned trace view
/** Alert edit modal: check history chart + chart/table toggle (table remains when off). */
ALERTS_15_MINUTE_INTERVAL: 'alerts-15-minute-interval', // owner: #team-analytics-platform, gates 15-minute insight alert interval
ALERTS_INLINE_NOTIFICATIONS: 'alerts-inline-notifications', // owner: @vdekrijger
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
index 475497242cdf..d9143891b5dc 100644
--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
@@ -95,6 +95,7 @@ import { LLMInputOutput } from './LLMInputOutput'
import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'
import { normalizeMessages } from './messageNormalization'
import { openInPlayground } from './playground/llmPlaygroundPromptsLogic'
+import { TraceScene } from './redesign/trace/TraceScene'
import { ReviewQueuePickerModal } from './reviewQueues/ReviewQueuePickerModal'
import { reviewQueuesApi } from './reviewQueues/reviewQueuesApi'
import { SearchHighlight } from './SearchHighlight'
@@ -421,8 +422,13 @@ function TraceNavigation(): JSX.Element {
)
}
+function TraceSceneForFlag(): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
+ return featureFlags[FEATURE_FLAGS.AI_OBSERVABILITY_TRACE_REDESIGN] ? <TraceScene /> : <AIObservabilityTraceScene />
+}
+
export const scene: SceneExport = {
- component: AIObservabilityTraceScene,
+ component: TraceSceneForFlag,
logic: aiObservabilityTraceLogic,
}
diff --git a/products/ai_observability/frontend/redesign/trace/TraceScene.tsx b/products/ai_observability/frontend/redesign/trace/TraceScene.tsx
new file mode 100644
index 000000000000..3f090e02afc0
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/TraceScene.tsx
@@ -0,0 +1,103 @@
+import { useActions, useValues } from 'kea'
+
+import { aiObservabilityTraceLogic } from '../../aiObservabilityTraceLogic'
+import { traceViewAdapterLogic, traceViewAdapterLogicValues } from './adapter/traceViewAdapterLogic'
+import { TraceView, TraceViewProps, TraceViewReadyProps } from './components/TraceView'
+import { NodeDetailTab, TraceMode } from './types'
+
+type ReadyValues = Pick<
+ traceViewAdapterLogicValues,
+ | 'header'
+ | 'summary'
+ | 'mode'
+ | 'tree'
+ | 'selectedNodeId'
+ | 'detailData'
+ | 'detailTab'
+ | 'canViewInThread'
+ | 'thread'
+ | 'timeline'
+>
+
+interface ReadyActions {
+ setMode: (mode: TraceMode) => void
+ selectNode: (id: string) => void
+ selectAndShowSpans: (id: string) => void
+ setDetailTab: (tab: NodeDetailTab) => void
+ viewInThread: () => void
+}
+
+function toReadyProps(values: ReadyValues, actions: ReadyActions): TraceViewReadyProps | null {
+ if (!values.header || !values.summary) {
+ return null
+ }
+ return {
+ header: values.header,
+ summary: values.summary,
+ mode: values.mode,
+ onModeChange: actions.setMode,
+ tree: values.tree,
+ selectedNodeId: values.selectedNodeId,
+ onSelectNode: actions.selectNode,
+ onSelectFromView: actions.selectAndShowSpans,
+ detail: values.detailData
+ ? {
+ ...values.detailData,
+ tab: values.detailTab,
+ onTabChange: actions.setDetailTab,
+ onViewInThread: values.canViewInThread ? actions.viewInThread : null,
+ }
+ : null,
+ thread: values.thread,
+ timeline: values.timeline,
+ }
+}
+
+export function TraceScene(): JSX.Element {
+ const { traceId, query } = useValues(aiObservabilityTraceLogic)
+ const logic = traceViewAdapterLogic({ traceId, query })
+ // Every kea value getter is a hook, so read them all on every render, whatever the status.
+ const {
+ status,
+ errorMessage,
+ backLink,
+ header,
+ summary,
+ mode,
+ tree,
+ selectedNodeId,
+ detailData,
+ detailTab,
+ canViewInThread,
+ thread,
+ timeline,
+ } = useValues(logic)
+ const actions = useActions(logic)
+
+ const readyProps =
+ status === 'ready'
+ ? toReadyProps(
+ {
+ header,
+ summary,
+ mode,
+ tree,
+ selectedNodeId,
+ detailData,
+ detailTab,
+ canViewInThread,
+ thread,
+ timeline,
+ },
+ actions
+ )
+ : null
+
+ const props: TraceViewProps = readyProps
+ ? { status: 'ready', ...readyProps }
+ : status === 'error'
+ ? { status: 'error', errorMessage, backLink }
+ : { status: 'loading' }
+
+ return <TraceView {...props} />
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/eventIO.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/eventIO.test.ts
new file mode 100644
index 000000000000..b5af1ef69dd0
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/eventIO.test.ts
@@ -0,0 +1,140 @@
+import { LLMTraceEvent } from '~/queries/schema/schema-general'
+
+import { AIData } from '../../../aiObservabilityAIDataLogic'
+import { heavyDataLookup, resolveEventIO } from './eventIO'
+import { makeEvent } from './testFixtures'
+
+interface ResolveEventIOCase {
+ name: string
+ event: LLMTraceEvent
+ cache: Record<string, AIData | null>
+ expected: { input: unknown; output: unknown; loading: boolean }
+}
+
+const resolveEventIOCases: ResolveEventIOCase[] = [
+ {
+ name: 'a generation with inline input and output',
+ event: makeEvent({
+ id: 'gen-1',
+ event: '$ai_generation',
+ properties: {
+ $ai_input: [{ role: 'user', content: 'Why did my invoice go up?' }],
+ $ai_output_choices: [{ role: 'assistant', content: 'Two seats were added.' }],
+ },
+ }),
+ cache: {},
+ expected: {
+ input: [{ role: 'user', content: 'Why did my invoice go up?' }],
+ output: [{ role: 'assistant', content: 'Two seats were added.' }],
+ loading: false,
+ },
+ },
+ {
+ name: 'a generation missing input, with no cache entry yet',
+ event: makeEvent({ id: 'gen-2', event: '$ai_generation', properties: {} }),
+ cache: {},
+ expected: { input: undefined, output: undefined, loading: true },
+ },
+ {
+ name: 'a generation missing input, with a cache entry that found nothing',
+ event: makeEvent({ id: 'gen-3', event: '$ai_generation', properties: {} }),
+ cache: { 'gen-3': null },
+ expected: { input: undefined, output: undefined, loading: false },
+ },
+ {
+ name: 'a generation missing input, with a loaded cache entry',
+ event: makeEvent({ id: 'gen-4', event: '$ai_generation', properties: {} }),
+ cache: {
+ 'gen-4': {
+ input: [{ role: 'user', content: 'Cached question' }],
+ output: [{ role: 'assistant', content: 'Cached answer' }],
+ tools: null,
+ },
+ },
+ expected: {
+ input: [{ role: 'user', content: 'Cached question' }],
+ output: [{ role: 'assistant', content: 'Cached answer' }],
+ loading: false,
+ },
+ },
+ {
+ name: 'an embedding',
+ event: makeEvent({ id: 'emb-1', event: '$ai_embedding', properties: { $ai_input: 'embed this text' } }),
+ cache: {},
+ expected: { input: 'embed this text', output: null, loading: false },
+ },
+ {
+ name: 'a span',
+ event: makeEvent({
+ id: 'span-1',
+ event: '$ai_span',
+ properties: { $ai_input_state: { step: 1 }, $ai_output_state: { step: 2 } },
+ }),
+ cache: {},
+ expected: { input: { step: 1 }, output: { step: 2 }, loading: false },
+ },
+ {
+ name: 'an OTel span that carries generation-style input and output',
+ event: makeEvent({
+ id: 'span-2',
+ event: '$ai_span',
+ properties: {
+ $ai_input: [{ role: 'user', content: 'Suggest hashtags' }],
+ $ai_output_choices: 'Added #levelup',
+ },
+ }),
+ cache: {},
+ expected: { input: [{ role: 'user', content: 'Suggest hashtags' }], output: 'Added #levelup', loading: false },
+ },
+]
+
+describe('eventIO', () => {
+ describe('resolveEventIO', () => {
+ it.each(resolveEventIOCases)('$name', ({ event, cache, expected }) => {
+ expect(resolveEventIO(event, cache)).toEqual(expected)
+ })
+ })
+
+ describe('heavyDataLookup', () => {
+ it('returns null for a generation with both input and output present', () => {
+ const event = makeEvent({
+ id: 'gen-1',
+ event: '$ai_generation',
+ properties: {
+ $ai_input: [{ role: 'user', content: 'Why did my invoice go up?' }],
+ $ai_output_choices: [{ role: 'assistant', content: 'Two seats were added.' }],
+ },
+ })
+ expect(heavyDataLookup(event, 'trace-1')).toBeNull()
+ })
+
+ it('returns null for a span', () => {
+ const event = makeEvent({
+ id: 'span-1',
+ event: '$ai_span',
+ properties: { $ai_input_state: { step: 1 }, $ai_output_state: { step: 2 } },
+ })
+ expect(heavyDataLookup(event, 'trace-1')).toBeNull()
+ })
+
+ it('returns a lookup for a generation missing output', () => {
+ const event = makeEvent({
+ id: 'gen-2',
+ event: '$ai_generation',
+ createdAt: '2026-09-01T10:15:02Z',
+ properties: {
+ $ai_input: [{ role: 'user', content: 'Why did my invoice go up?' }],
+ $ai_tools: [{ name: 'lookup_invoice' }],
+ },
+ })
+ expect(heavyDataLookup(event, 'trace-1')).toEqual({
+ eventId: 'gen-2',
+ input: [{ role: 'user', content: 'Why did my invoice go up?' }],
+ output: undefined,
+ tools: [{ name: 'lookup_invoice' }],
+ traceId: 'trace-1',
+ timestamp: '2026-09-01T10:15:02Z',
+ })
+ })
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/eventIO.ts b/products/ai_observability/frontend/redesign/trace/adapter/eventIO.ts
new file mode 100644
index 000000000000..0bccdd33fbba
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/eventIO.ts
@@ -0,0 +1,43 @@
+import { LLMTraceEvent } from '~/queries/schema/schema-general'
+
+import { AIData, AIDataLookup } from '../../../aiObservabilityAIDataLogic'
+import { getLLMEventKind, readAiInput, readAiOutput } from '../../../utils'
+
+function generationOutput(event: LLMTraceEvent): unknown {
+ return event.properties.$ai_output_choices ?? event.properties.$ai_output
+}
+
+function isMissingGenerationData(event: LLMTraceEvent): boolean {
+ return event.properties.$ai_input == null || generationOutput(event) == null
+}
+
+export function heavyDataLookup(event: LLMTraceEvent, traceId: string): AIDataLookup | null {
+ if (getLLMEventKind(event) !== 'generation' || !isMissingGenerationData(event)) {
+ return null
+ }
+ return {
+ eventId: event.id,
+ input: event.properties.$ai_input,
+ output: generationOutput(event),
+ tools: event.properties.$ai_tools,
+ traceId,
+ timestamp: event.createdAt,
+ }
+}
+
+export function resolveEventIO(
+ event: LLMTraceEvent,
+ cache: Record<string, AIData | null>
+): { input: unknown; output: unknown; loading: boolean } {
+ const kind = getLLMEventKind(event)
+ if (kind === 'generation') {
+ const cached = cache[event.id]
+ const input = cached?.input ?? event.properties.$ai_input
+ const output = cached?.output ?? generationOutput(event)
+ return { input, output, loading: isMissingGenerationData(event) && cached === undefined }
+ }
+ if (kind === 'embedding') {
+ return { input: event.properties.$ai_input, output: null, loading: false }
+ }
+ return { input: readAiInput(event.properties), output: readAiOutput(event.properties), loading: false }
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/propertyReaders.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/propertyReaders.test.ts
new file mode 100644
index 000000000000..5c3d21dc4549
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/propertyReaders.test.ts
@@ -0,0 +1,14 @@
+import { readNumber } from './propertyReaders'
+
+describe('readNumber', () => {
+ it.each([
+ ['', null],
+ [' ', null],
+ ['0.2', 0.2],
+ [0, 0],
+ ['abc', null],
+ [undefined, null],
+ ])('reads %p as %p', (input, expected) => {
+ expect(readNumber(input)).toBe(expected)
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/propertyReaders.ts b/products/ai_observability/frontend/redesign/trace/adapter/propertyReaders.ts
new file mode 100644
index 000000000000..636c014d380d
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/propertyReaders.ts
@@ -0,0 +1,11 @@
+export function readString(value: unknown): string | null {
+ return typeof value === 'string' && value !== '' ? value : null
+}
+
+export function readNumber(value: unknown): number | null {
+ if (typeof value === 'string' && value.trim() === '') {
+ return null
+ }
+ const parsed = typeof value === 'string' ? Number(value) : value
+ return typeof parsed === 'number' && Number.isFinite(parsed) ? parsed : null
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/testFixtures.ts b/products/ai_observability/frontend/redesign/trace/adapter/testFixtures.ts
new file mode 100644
index 000000000000..7ace1379e0fd
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/testFixtures.ts
@@ -0,0 +1,38 @@
+import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
+
+import { EnrichedTraceTreeNode } from '../../../aiObservabilityTraceDataLogic'
+
+export function makeEvent(overrides: Partial<LLMTraceEvent> & { id: string }): LLMTraceEvent {
+ return { event: '$ai_span', properties: {}, createdAt: '2026-09-01T10:15:00Z', ...overrides }
+}
+
+export function makeTrace(overrides: Partial<LLMTrace> = {}): LLMTrace {
+ return {
+ id: 'trace-1',
+ createdAt: '2026-09-01T10:15:00Z',
+ distinctId: 'user-ana',
+ traceName: 'answer-billing-question',
+ totalCost: 0.0021,
+ inputTokens: 1840,
+ outputTokens: 212,
+ totalLatency: 2.31,
+ events: [],
+ ...overrides,
+ }
+}
+
+export function enrich(
+ event: LLMTraceEvent,
+ children: EnrichedTraceTreeNode[] = [],
+ display: Partial<Pick<EnrichedTraceTreeNode, 'displayTotalCost' | 'displayLatency' | 'aggregation'>> = {}
+): EnrichedTraceTreeNode {
+ return {
+ event,
+ children,
+ displayTotalCost: display.displayTotalCost ?? null,
+ displayLatency: display.displayLatency ?? 0,
+ displayUsage: null,
+ attachedFeedback: [],
+ aggregation: display.aggregation,
+ }
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toAttachment.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toAttachment.test.ts
new file mode 100644
index 000000000000..1d7eaca9338c
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toAttachment.test.ts
@@ -0,0 +1,85 @@
+import { AttachmentPart, toAttachment } from './toAttachment'
+
+const BLOB_HASH = 'a'.repeat(64)
+
+describe('toAttachment', () => {
+ it.each<[string, Record<string, unknown> & { type: string }, Omit<AttachmentPart, 'kind'>]>([
+ [
+ 'an OpenAI image_url',
+ { type: 'image_url', image_url: { url: 'https://cdn.example.com/receipt.png' } },
+ { mediaType: 'image', name: null, mimeType: null, url: 'https://cdn.example.com/receipt.png' },
+ ],
+ [
+ 'an OpenAI input_audio with raw base64',
+ { type: 'input_audio', input_audio: { data: 'UklGRg==', format: 'wav' } },
+ { mediaType: 'audio', name: null, mimeType: 'audio/wav', url: 'data:audio/wav;base64,UklGRg==' },
+ ],
+ [
+ 'an OpenAI file with a filename',
+ { type: 'file', file: { file_data: 'data:application/pdf;base64,JVBERi0=', filename: 'quote.pdf' } },
+ {
+ mediaType: 'file',
+ name: 'quote.pdf',
+ mimeType: 'application/pdf',
+ url: 'data:application/pdf;base64,JVBERi0=',
+ },
+ ],
+ [
+ 'an Anthropic base64 image',
+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'iVBORw0=' } },
+ { mediaType: 'image', name: null, mimeType: 'image/png', url: 'data:image/png;base64,iVBORw0=' },
+ ],
+ [
+ 'an Anthropic document',
+ { type: 'document', source: { type: 'base64', media_type: 'application/pdf', data: 'JVBERi0=' } },
+ {
+ mediaType: 'file',
+ name: null,
+ mimeType: 'application/pdf',
+ url: 'data:application/pdf;base64,JVBERi0=',
+ },
+ ],
+ [
+ 'a Vercel file part whose mime type says it is an image',
+ { type: 'file', mediaType: 'image/jpeg', file: 'https://cdn.example.com/latte.jpg' },
+ { mediaType: 'image', name: null, mimeType: 'image/jpeg', url: 'https://cdn.example.com/latte.jpg' },
+ ],
+ [
+ 'a file part with an unresolvable upload reference',
+ { type: 'file', mediaType: 'image/png', file: 'upload://screen-01' },
+ { mediaType: 'image', name: null, mimeType: 'image/png', url: null },
+ ],
+ [
+ 'Gemini audio stored as a blob pointer',
+ { type: 'audio', mime_type: 'audio/wav', data: `phaiblob://v1/sha256/${BLOB_HASH}?mime=audio/wav` },
+ {
+ mediaType: 'audio',
+ name: null,
+ mimeType: 'audio/wav',
+ url: `/api/projects/7/ai_blob/v1/sha256/${BLOB_HASH}`,
+ },
+ ],
+ [
+ 'a Gemini inline_data image',
+ { type: 'image', inline_data: { mime_type: 'image/webp', data: 'UklGRg==' } },
+ { mediaType: 'image', name: null, mimeType: 'image/webp', url: 'data:image/webp;base64,UklGRg==' },
+ ],
+ [
+ 'a Gemini inlineData document sent as an image part',
+ { type: 'image', inlineData: { mimeType: 'application/pdf', data: 'JVBERi0=' } },
+ {
+ mediaType: 'file',
+ name: null,
+ mimeType: 'application/pdf',
+ url: 'data:application/pdf;base64,JVBERi0=',
+ },
+ ],
+ [
+ 'an image whose payload the SDK redacted',
+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: '[base64 image redacted]' } },
+ { mediaType: 'image', name: null, mimeType: 'image/png', url: null },
+ ],
+ ])('maps %s', (_name, item, expected) => {
+ expect(toAttachment(item, 7)).toEqual({ kind: 'attachment', ...expected })
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toAttachment.ts b/products/ai_observability/frontend/redesign/trace/adapter/toAttachment.ts
new file mode 100644
index 000000000000..820e87cc6438
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toAttachment.ts
@@ -0,0 +1,104 @@
+import { isObject } from 'lib/utils/guards'
+
+import { parseAiBlobPointer, resolveAiBlobUrl, resolveDataUri } from '../../../aiBlob'
+import { isRenderableMediaSource } from '../../../mediaSource'
+import { AttachmentMediaType, MessagePart } from '../types'
+
+export type AttachmentPart = Extract<MessagePart, { kind: 'attachment' }>
+
+export type TeamId = number | string | null
+
+const MEDIA_TYPE_BY_ITEM_TYPE: Record<string, AttachmentMediaType> = {
+ image: 'image',
+ image_url: 'image',
+ input_image: 'image',
+ audio: 'audio',
+ input_audio: 'audio',
+ video: 'video',
+ file: 'file',
+ document: 'file',
+ input_file: 'file',
+}
+
+// Providers nest the payload under one of these keys, each with its own field names.
+const NESTED_PAYLOAD_KEYS = ['source', 'file', 'input_audio', 'image_url', 'inline_data', 'inlineData']
+const SOURCE_KEYS = ['url', 'file_url', 'image_url', 'file_data', 'image', 'data', 'file']
+const MIME_KEYS = ['mediaType', 'mimeType', 'mime_type', 'media_type']
+const NAME_KEYS = ['filename', 'name']
+
+const URL_SCHEME = /^[a-z][\w+.-]*:/i
+const BASE64 = /^[A-Za-z0-9+/=\s]+$/
+const DATA_URI_MIME = /^data:([^;,]+)/i
+
+export function isAttachmentItemType(type: string): boolean {
+ return type in MEDIA_TYPE_BY_ITEM_TYPE
+}
+
+function readString(containers: Record<string, unknown>[], keys: string[]): string | null {
+ for (const key of keys) {
+ for (const container of containers) {
+ const value = container[key]
+ if (typeof value === 'string' && value !== '') {
+ return value
+ }
+ }
+ }
+ return null
+}
+
+function audioFormatMime(containers: Record<string, unknown>[]): string | null {
+ const format = readString(containers, ['format'])
+ return format ? `audio/${format}` : null
+}
+
+function mediaTypeOf(itemType: string, mimeType: string | null): AttachmentMediaType {
+ const byItemType = MEDIA_TYPE_BY_ITEM_TYPE[itemType] ?? 'file'
+ if (!mimeType) {
+ return byItemType
+ }
+ const topLevel = mimeType.split('/')[0]
+ return topLevel === 'image' || topLevel === 'audio' || topLevel === 'video' ? topLevel : 'file'
+}
+
+// Raw base64 payloads become data: URIs. The app's CSP allows media only from its own origin, data: and blob:,
+// so stored blob pointers must resolve to the same-origin blob endpoint.
+function resolveUrl(source: string | null, mimeType: string | null, teamId: TeamId): string | null {
+ if (source === null) {
+ return null
+ }
+ if (isRenderableMediaSource(source)) {
+ return resolveAiBlobUrl(source, teamId)
+ }
+ if (URL_SCHEME.test(source) || !mimeType || !BASE64.test(source)) {
+ return null
+ }
+ return resolveDataUri(source, mimeType, teamId)
+}
+
+function sourceMime(source: string | null): string | null {
+ if (source === null) {
+ return null
+ }
+ return DATA_URI_MIME.exec(source)?.[1] ?? parseAiBlobPointer(source)?.mime ?? null
+}
+
+export function toAttachment(item: Record<string, unknown> & { type: string }, teamId: TeamId): AttachmentPart {
+ const nested = NESTED_PAYLOAD_KEYS.map((key) => item[key]).filter(isObject)
+ const containers = [...nested, item]
+ const source = readString(containers, SOURCE_KEYS)
+ const mimeType =
+ readString(containers, MIME_KEYS) ??
+ (item.type === 'input_audio' ? audioFormatMime(containers) : null) ??
+ sourceMime(source)
+ const mediaType = mediaTypeOf(item.type, mimeType)
+ const isKnownMedia = isAttachmentItemType(item.type)
+ // Matches the legacy player, which assumes WAV for raw audio sent without a mime type.
+ const payloadMime = mimeType ?? (mediaType === 'audio' ? 'audio/wav' : null)
+ return {
+ kind: 'attachment',
+ mediaType,
+ name: readString(containers, NAME_KEYS) ?? (isKnownMedia ? null : item.type),
+ mimeType,
+ url: isKnownMedia ? resolveUrl(source, payloadMime, teamId) : null,
+ }
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toEvalResults.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toEvalResults.test.ts
new file mode 100644
index 000000000000..2e4e84624153
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toEvalResults.test.ts
@@ -0,0 +1,143 @@
+import { urls } from 'scenes/urls'
+
+import { EvaluationOutputConfig, EvaluationRun, LLMJudgeEvaluation } from '../../../evaluations/types'
+import { TraceTreeNode } from '../types'
+import { EvalResultsContext, toEvalResults } from './toEvalResults'
+
+const node = (
+ id: string,
+ kind: TraceTreeNode['kind'],
+ name: string,
+ children: TraceTreeNode[] = []
+): TraceTreeNode => ({
+ id,
+ kind,
+ name,
+ model: null,
+ hasError: false,
+ children,
+ stats: {
+ costUsd: null,
+ inputTokens: null,
+ outputTokens: null,
+ cacheReadTokens: null,
+ cacheWriteTokens: null,
+ latencyMs: null,
+ },
+})
+
+const tree = [
+ node('trace-1', 'trace', 'answer-billing-question', [
+ node('gen-1', 'generation', 'gpt-4.1-mini (openai)'),
+ node('span-1', 'span', 'lookup-invoice'),
+ node('gen-2', 'generation', 'gpt-4.1-mini (openai)'),
+ ]),
+]
+
+const run = (overrides: Partial<EvaluationRun> = {}): EvaluationRun => ({
+ id: 'r1',
+ evaluation_id: 'ev-helpful',
+ evaluation_name: 'Answers the question',
+ generation_id: null,
+ trace_id: 'trace-1',
+ timestamp: '2026-09-01T10:16:00Z',
+ result: true,
+ reasoning: 'Direct answer.',
+ status: 'completed',
+ ...overrides,
+})
+
+const evaluation = (id: string, outputConfig: EvaluationOutputConfig): LLMJudgeEvaluation => ({
+ id,
+ name: id,
+ enabled: true,
+ status: 'active',
+ status_reason: null,
+ status_reason_detail: null,
+ evaluation_type: 'llm_judge',
+ evaluation_config: { prompt: 'Grade the answer.' },
+ output_type: 'numeric',
+ output_config: outputConfig,
+ conditions: [],
+ target: 'generation',
+ target_config: {},
+ model_configuration: null,
+ created_at: '2026-08-01T00:00:00Z',
+ updated_at: '2026-08-01T00:00:00Z',
+})
+
+const context = (overrides: Partial<EvalResultsContext> = {}): EvalResultsContext => ({
+ tree,
+ viewedNodeId: 'trace-1',
+ evaluations: [evaluation('ev-quality', { passing_rule: { operator: 'gte', threshold: 0.7 } })],
+ detectorEvaluationIds: ['ev-detector'],
+ ...overrides,
+})
+
+describe('toEvalResults', () => {
+ it.each<[string, Partial<EvaluationRun>, string, string]>([
+ ['a failed run', { status: 'failed' }, 'error', 'Error'],
+ ['a running run', { status: 'running' }, 'pending', 'Running'],
+ ['a true result', { result: true }, 'pass', 'True'],
+ ['a false result', { result: false }, 'fail', 'False'],
+ ['a true result from a detector', { evaluation_id: 'ev-detector', result: true }, 'fail', 'True'],
+ ['a false result from a detector', { evaluation_id: 'ev-detector', result: false }, 'pass', 'False'],
+ ['a skipped run, whose result is still false', { skipped: true, result: false }, 'inconclusive', 'Skipped'],
+ ['a missing result', { result: null }, 'inconclusive', 'N/A'],
+ ['a score with no passing rule', { result_type: 'numeric', score: 0.82 }, 'unrated', '0.82'],
+ [
+ 'a score under the passing threshold',
+ { evaluation_id: 'ev-quality', result_type: 'numeric', score: 0.4 },
+ 'fail',
+ '0.4',
+ ],
+ ['a numeric run with no score', { result_type: 'numeric', score: null }, 'inconclusive', 'No score'],
+ ['a positive sentiment', { result_type: 'sentiment', sentiment_label: 'positive' }, 'pass', 'Positive'],
+ ['a neutral sentiment', { result_type: 'sentiment', sentiment_label: 'neutral' }, 'unrated', 'Neutral'],
+ ['an unknown sentiment', { result_type: 'sentiment', sentiment_label: null }, 'inconclusive', 'Unknown'],
+ ])('maps %s to %s', (_name, overrides, outcome, label) => {
+ expect(toEvalResults([run(overrides)], context())).toMatchObject([{ outcome, label }])
+ })
+
+ it('lists the newest verdict first, dating a backfill by when it ran, and marks backfills', () => {
+ const results = toEvalResults(
+ [
+ run({ id: 'live', timestamp: '2026-09-01T10:16:00Z' }),
+ run({
+ id: 'backfill',
+ timestamp: '2026-09-01T10:15:30Z',
+ start_time: '2026-09-20T08:00:00Z',
+ backfill_id: 'backfill-1',
+ }),
+ run({ id: 'older', timestamp: '2026-09-01T10:15:45Z' }),
+ ],
+ context()
+ )
+ expect(results.map((result) => [result.id, result.isBackfill, result.timestamp])).toEqual([
+ ['backfill', true, '2026-09-01T10:15:30Z'],
+ ['live', false, '2026-09-01T10:16:00Z'],
+ ['older', false, '2026-09-01T10:15:45Z'],
+ ])
+ expect(results[0].href).toBe(urls.aiObservabilityEvaluation('ev-helpful'))
+ })
+
+ it.each([
+ ['a trace-level run seen on the root targets nothing', 'trace-1', null, null],
+ [
+ 'a run on a generation seen on the root names that generation apart from its namesake',
+ 'trace-1',
+ 'gen-2',
+ { nodeId: 'gen-2', label: 'gpt-4.1-mini (openai) #2' },
+ ],
+ ['a run on the viewed generation targets nothing', 'gen-1', 'gen-1', null],
+ [
+ 'a run on a generation missing from the tree falls back to a short id',
+ 'trace-1',
+ 'gen-0123456789abcdef',
+ { nodeId: 'gen-0123456789abcdef', label: 'gen-01234567...' },
+ ],
+ ])('%s', (_name, viewedNodeId, generationId, expected) => {
+ const [result] = toEvalResults([run({ generation_id: generationId })], context({ viewedNodeId }))
+ expect(result.target).toEqual(expected)
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toEvalResults.ts b/products/ai_observability/frontend/redesign/trace/adapter/toEvalResults.ts
new file mode 100644
index 000000000000..c0fc61bb6dd6
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toEvalResults.ts
@@ -0,0 +1,89 @@
+import { urls } from 'scenes/urls'
+
+import { EvaluationResultDisplayOptions, getEvaluationResultDisplay } from '../../../components/EvaluationResultTag'
+import { EvaluationConfig, EvaluationRun } from '../../../evaluations/types'
+import { EvalOutcome, EvalResult, EvalTarget, TraceTreeNode } from '../types'
+
+export interface EvalResultsContext {
+ /** Every node of the trace, root first, to resolve and name what each run targets. */
+ tree: TraceTreeNode[]
+ viewedNodeId: string
+ evaluations: EvaluationConfig[]
+ detectorEvaluationIds: string[]
+}
+
+function displayOptions(run: EvaluationRun, context: EvalResultsContext): EvaluationResultDisplayOptions {
+ const outputConfig = context.evaluations.find((evaluation) => evaluation.id === run.evaluation_id)?.output_config
+ return {
+ trueIsFailure: context.detectorEvaluationIds.includes(run.evaluation_id),
+ passingRule: outputConfig?.passing_rule,
+ categoryOptions: outputConfig?.options,
+ }
+}
+
+function outcomeOf(run: EvaluationRun, tagType: string | undefined): EvalOutcome {
+ if (run.status === 'failed') {
+ return 'error'
+ }
+ if (run.status === 'running') {
+ return 'pending'
+ }
+ if (tagType === 'success') {
+ return 'pass'
+ }
+ if (tagType === 'danger') {
+ return 'fail'
+ }
+ return tagType === 'none' ? 'unrated' : 'inconclusive'
+}
+
+function flatten(nodes: TraceTreeNode[]): TraceTreeNode[] {
+ return nodes.flatMap((node) => [node, ...flatten(node.children)])
+}
+
+// Two steps can share a name, such as two calls to the same model, so repeated names get their position.
+function nodeLabels(tree: TraceTreeNode[]): Map<string, string> {
+ const nodes = flatten(tree)
+ const totals = new Map<string, number>()
+ nodes.forEach((node) => totals.set(node.name, (totals.get(node.name) ?? 0) + 1))
+ const seen = new Map<string, number>()
+ return new Map(
+ nodes.map((node) => {
+ const position = (seen.get(node.name) ?? 0) + 1
+ seen.set(node.name, position)
+ return [node.id, (totals.get(node.name) ?? 0) > 1 ? `${node.name} #${position}` : node.name]
+ })
+ )
+}
+
+function targetOf(run: EvaluationRun, labels: Map<string, string>, context: EvalResultsContext): EvalTarget | null {
+ const nodeId = run.generation_id ?? context.tree[0]?.id
+ if (!nodeId || nodeId === context.viewedNodeId) {
+ return null
+ }
+ return { nodeId, label: labels.get(nodeId) ?? `${nodeId.slice(0, 12)}...` }
+}
+
+function producedAt(run: EvaluationRun): number {
+ return new Date(run.start_time ?? run.timestamp).getTime()
+}
+
+export function toEvalResults(runs: EvaluationRun[], context: EvalResultsContext): EvalResult[] {
+ const labels = nodeLabels(context.tree)
+ return [...runs]
+ .sort((a, b) => producedAt(b) - producedAt(a))
+ .map((run) => {
+ const display = getEvaluationResultDisplay(run, displayOptions(run, context))
+ return {
+ id: run.id,
+ name: run.evaluation_name,
+ href: urls.aiObservabilityEvaluation(run.evaluation_id),
+ outcome: outcomeOf(run, display.type),
+ label: display.label,
+ reasoning: run.reasoning || null,
+ timestamp: run.timestamp,
+ isBackfill: !!run.backfill_id,
+ target: targetOf(run, labels, context),
+ }
+ })
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toHeader.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toHeader.test.ts
new file mode 100644
index 000000000000..fddae06424ed
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toHeader.test.ts
@@ -0,0 +1,55 @@
+import { makeTrace } from './testFixtures'
+import { TraceNeighbours, toHeader } from './toHeader'
+
+const noNeighbours: TraceNeighbours = {
+ olderTraceId: null,
+ olderTimestamp: null,
+ newerTraceId: null,
+ newerTimestamp: null,
+}
+
+describe('toHeader', () => {
+ it('links neighbours with their timestamps and the list context, and leaves missing neighbours null', () => {
+ const header = toHeader(
+ makeTrace(),
+ { ...noNeighbours, olderTraceId: 'trace-0', olderTimestamp: '2026-09-01T10:00:00Z' },
+ { date_from: '-7d', event: 'gen-1', line: '4', back_to: 'generations' }
+ )
+ expect(header.olderHref).toBe(
+ '/ai-observability/traces/trace-0?date_from=-7d&timestamp=2026-09-01T10%3A00%3A00Z'
+ )
+ expect(header.newerHref).toBeNull()
+ })
+
+ it.each([
+ [
+ 'the traces list by default, keeping its filters',
+ { date_from: '-7d', event: 'gen-1' },
+ '/ai-observability/traces?date_from=-7d',
+ ],
+ [
+ 'the generations list when opened from it',
+ { back_to: 'generations', date_from: '-7d', tab: 'evals' },
+ '/ai-observability/generations?date_from=-7d',
+ ],
+ [
+ 'the reviews tab when opened from reviews',
+ { back_to: 'reviews' },
+ '/ai-observability/reviews?human_reviews_tab=reviews',
+ ],
+ [
+ 'the review queue when opened from one',
+ { back_to: 'reviews', queue_id: 'queue-1' },
+ '/ai-observability/reviews?queue_id=queue-1',
+ ],
+ ])('goes back to %s', (_name, searchParams, expected) => {
+ expect(toHeader(makeTrace(), noNeighbours, searchParams).backLink.href).toBe(expected)
+ })
+
+ it.each([
+ ['a named trace keeps its name', 'answer-billing-question', 'answer-billing-question'],
+ ['an unnamed trace gets a fallback distinct from the Trace badge', undefined, 'Untitled trace'],
+ ])('%s', (_name, traceName, expected) => {
+ expect(toHeader(makeTrace({ traceName }), noNeighbours, {}).name).toBe(expected)
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toHeader.ts b/products/ai_observability/frontend/redesign/trace/adapter/toHeader.ts
new file mode 100644
index 000000000000..cd7ca7e23adc
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toHeader.ts
@@ -0,0 +1,61 @@
+import { combineUrl } from 'kea-router'
+
+import { urls } from 'scenes/urls'
+
+import { LLMTrace } from '~/queries/schema/schema-general'
+
+import { sanitizeTraceUrlSearchParams } from '../../../utils'
+import { TraceHeaderProps } from '../components/TraceHeader'
+import { LabeledLink } from '../types'
+import { hasTraceError } from './toTraceTree'
+
+export interface TraceNeighbours {
+ olderTraceId: string | null
+ olderTimestamp: string | null
+ newerTraceId: string | null
+ newerTimestamp: string | null
+}
+
+type SearchParams = Record<string, unknown>
+
+function neighbourHref(traceId: string | null, timestamp: string | null, searchParams: SearchParams): string | null {
+ return traceId
+ ? combineUrl(urls.aiObservabilityTrace(traceId), {
+ ...sanitizeTraceUrlSearchParams(searchParams),
+ timestamp: timestamp ?? undefined,
+ }).url
+ : null
+}
+
+// Matches the legacy scene: a link opened from a review queue returns to that queue, other links to the reviews tab.
+function reviewsBackHref(searchParams: SearchParams): string {
+ const inQueue = typeof searchParams.queue_id === 'string' && searchParams.queue_id !== ''
+ return combineUrl(urls.aiObservabilityReviews(), {
+ ...sanitizeTraceUrlSearchParams(searchParams),
+ human_reviews_tab: inQueue ? undefined : 'reviews',
+ }).url
+}
+
+export function toBackLink(searchParams: SearchParams): LabeledLink {
+ if (searchParams.back_to === 'reviews') {
+ return { label: 'Back to reviews', href: reviewsBackHref(searchParams) }
+ }
+ const listParams = sanitizeTraceUrlSearchParams(searchParams)
+ if (searchParams.back_to === 'generations') {
+ return {
+ label: 'Back to generations',
+ href: combineUrl(urls.aiObservabilityGenerations(), listParams).url,
+ }
+ }
+ return { label: 'Back to traces', href: combineUrl(urls.aiObservabilityTraces(), listParams).url }
+}
+
+export function toHeader(trace: LLMTrace, neighbours: TraceNeighbours, searchParams: SearchParams): TraceHeaderProps {
+ return {
+ name: trace.traceName || 'Untitled trace',
+ hasError: hasTraceError(trace),
+ olderHref: neighbourHref(neighbours.olderTraceId, neighbours.olderTimestamp, searchParams),
+ newerHref: neighbourHref(neighbours.newerTraceId, neighbours.newerTimestamp, searchParams),
+ backLink: toBackLink(searchParams),
+ }
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toNodeDetail.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toNodeDetail.test.ts
new file mode 100644
index 000000000000..1d2ec0701989
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toNodeDetail.test.ts
@@ -0,0 +1,193 @@
+import { LLMTracePerson } from '~/queries/schema/schema-general'
+
+import { EvaluationRun } from '../../../evaluations/types'
+import { isLLMEvent } from '../../../utils'
+import { EvalResult, EvalsState, TraceTreeNode } from '../types'
+import { makeEvent, makeTrace } from './testFixtures'
+import { toNodeDetail } from './toNodeDetail'
+
+const node = (id: string, kind: 'trace' | 'span' | 'generation'): TraceTreeNode => ({
+ id,
+ kind,
+ name: id,
+ model: null,
+ hasError: false,
+ children: [],
+ stats: {
+ costUsd: null,
+ inputTokens: null,
+ outputTokens: null,
+ cacheReadTokens: null,
+ cacheWriteTokens: null,
+ latencyMs: null,
+ },
+})
+
+const run = (overrides: Partial<EvaluationRun> = {}): EvaluationRun => ({
+ id: 'r1',
+ evaluation_id: 'ev1',
+ evaluation_name: 'Answers the question',
+ generation_id: 'gen-1',
+ trace_id: 'trace-1',
+ timestamp: '2026-09-01T10:16:00Z',
+ result: true,
+ reasoning: 'Direct answer.',
+ status: 'completed',
+ ...overrides,
+})
+
+function readyResults(evals: EvalsState): EvalResult[] {
+ if (evals.status !== 'ready') {
+ throw new Error(`expected ready evals, got status "${evals.status}"`)
+ }
+ return evals.results
+}
+
+const cachedPerson: LLMTracePerson = {
+ uuid: 'person-1',
+ created_at: '2026-09-01T10:00:00Z',
+ distinct_id: 'user-ana',
+ properties: { email: '[email protected]' },
+}
+
+describe('toNodeDetail', () => {
+ const base = {
+ trace: makeTrace(),
+ tree: [],
+ cache: {},
+ evalRuns: [],
+ evalRunsLoading: false,
+ evaluations: [],
+ detectorEvaluationIds: [],
+ evaluationsSettled: true,
+ teamId: 7,
+ person: null,
+ }
+
+ it('generation without inline IO and no cache entry yields loading', () => {
+ const event = makeEvent({ id: 'gen-1', event: '$ai_generation', properties: {} })
+ const detail = toNodeDetail({ ...base, event, node: node('gen-1', 'generation') })
+ expect(detail.content).toEqual({ kind: 'loading' })
+ })
+
+ it('generation with content yields messages, properties and its own evals', () => {
+ const event = makeEvent({
+ id: 'gen-1',
+ event: '$ai_generation',
+ properties: {
+ $ai_input: [{ role: 'user', content: 'Hi' }],
+ $ai_output_choices: [{ role: 'assistant', content: 'Hello' }],
+ $ai_model: 'gpt-4.1-mini',
+ $ai_provider: 'openai',
+ $ai_temperature: 0.2,
+ $ai_session_id: 'sess-1',
+ $ai_prompt_name: 'billing-answer',
+ $ai_prompt_version: 6,
+ },
+ })
+ const detail = toNodeDetail({
+ ...base,
+ event,
+ node: node('gen-1', 'generation'),
+ evalRuns: [run(), run({ id: 'r2', generation_id: 'gen-other' })],
+ })
+ expect(detail.content).toMatchObject({
+ kind: 'messages',
+ input: [{ role: 'user', parts: [{ kind: 'text', text: 'Hi' }] }],
+ output: [{ role: 'assistant', parts: [{ kind: 'text', text: 'Hello' }] }],
+ })
+ expect(detail.properties).toMatchObject({
+ provider: 'openai',
+ temperature: 0.2,
+ sessionId: 'sess-1',
+ promptVersion: 6,
+ })
+ expect(readyResults(detail.evals).map((result) => result.id)).toEqual(['r1'])
+ })
+
+ it.each([
+ ['eval runs are loading', { evalRunsLoading: true }],
+ ['the evaluation configs that decide detector polarity have not loaded', { evaluationsSettled: false }],
+ ])('reports evals as loading while %s', (_name, overrides) => {
+ const event = makeEvent({ id: 'gen-1', event: '$ai_generation', properties: {} })
+ const detail = toNodeDetail({
+ ...base,
+ ...overrides,
+ event,
+ node: node('gen-1', 'generation'),
+ evalRuns: [run()],
+ })
+ expect(detail.evals).toEqual({ status: 'loading' })
+ })
+
+ it.each([
+ { name: 'a cached person', person: cachedPerson, expectedPersonLabel: '[email protected]' },
+ { name: 'no cached person', person: null, expectedPersonLabel: 'user-ana' },
+ ])(
+ 'span shows its state as input and output, surfaces its error, and labels the person with $name',
+ ({ person, expectedPersonLabel }) => {
+ const event = makeEvent({
+ id: 'span-1',
+ properties: {
+ $ai_input_state: { q: 'x' },
+ $ai_output_state: null,
+ $ai_is_error: true,
+ $ai_error: 'Timeout',
+ },
+ })
+ const detail = toNodeDetail({ ...base, event, node: node('span-1', 'span'), person })
+ expect(detail.content).toEqual({ kind: 'io', input: { q: 'x' }, output: undefined })
+ expect(detail.error).toBe('Timeout')
+ expect(detail.properties.person).toBe(expectedPersonLabel)
+ }
+ )
+
+ it('trace root shows the trace state and every eval run', () => {
+ const trace = makeTrace({ inputState: { question: 'Hi' }, outputState: { answer: 'Hello' } })
+ const detail = toNodeDetail({
+ ...base,
+ trace,
+ event: trace,
+ node: node('trace-1', 'trace'),
+ evalRuns: [run(), run({ id: 'r2' })],
+ })
+ expect(detail.content).toEqual({ kind: 'io', input: { question: 'Hi' }, output: { answer: 'Hello' } })
+ expect(readyResults(detail.evals)).toHaveLength(2)
+ expect(detail.raw).not.toHaveProperty('events')
+ })
+
+ it.each([
+ {
+ name: 'trace state holding message arrays',
+ event: makeTrace({
+ inputState: [{ role: 'user', content: 'Move my flight to Friday' }],
+ outputState: [{ role: 'assistant', content: 'Moved to Friday 09:15' }],
+ }),
+ kind: 'trace' as const,
+ },
+ {
+ name: 'an OTel span with a message array input and a text output',
+ event: makeEvent({
+ id: 'span-2',
+ properties: {
+ $ai_input: [{ role: 'user', content: 'Move my flight to Friday' }],
+ $ai_output_choices: 'Moved to Friday 09:15',
+ },
+ }),
+ kind: 'span' as const,
+ },
+ ])('renders $name as input and output messages', ({ event, kind }) => {
+ const trace = isLLMEvent(event) ? base.trace : event
+ const detail = toNodeDetail({
+ ...base,
+ trace,
+ event,
+ node: node(isLLMEvent(event) ? event.id : trace.id, kind),
+ })
+ expect(detail.content).toMatchObject({
+ kind: 'messages',
+ input: [{ role: 'user', parts: [{ kind: 'text', text: 'Move my flight to Friday' }] }],
+ output: [{ role: 'assistant', parts: [{ kind: 'text', text: 'Moved to Friday 09:15' }] }],
+ })
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toNodeDetail.ts b/products/ai_observability/frontend/redesign/trace/adapter/toNodeDetail.ts
new file mode 100644
index 000000000000..c400a4d3cce7
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toNodeDetail.ts
@@ -0,0 +1,116 @@
+import { LLMTrace, LLMTraceEvent, LLMTracePerson } from '~/queries/schema/schema-general'
+
+import { AIData } from '../../../aiObservabilityAIDataLogic'
+import { EvaluationConfig, EvaluationRun } from '../../../evaluations/types'
+import { isLLMEvent } from '../../../utils'
+import { NodeDetailProps } from '../components/NodeDetail'
+import { EvalsState, NodeContent, NodeProperties, TraceTreeNode } from '../types'
+import { resolveEventIO } from './eventIO'
+import { readNumber, readString } from './propertyReaders'
+import { TeamId } from './toAttachment'
+import { toEvalResults } from './toEvalResults'
+import { personLabel } from './toSummary'
+import { toMessageIO } from './toThread'
+import { isMessageIO } from './toThreadMessages'
+import { eventError } from './toTraceTree'
+
+export type NodeDetailData = Omit<NodeDetailProps, 'tab' | 'onTabChange' | 'onViewInThread' | 'onSelectNode'>
+
+interface NodeDetailArgs {
+ trace: LLMTrace
+ event: LLMTrace | LLMTraceEvent
+ node: TraceTreeNode
+ cache: Record<string, AIData | null>
+ tree: TraceTreeNode[]
+ evalRuns: EvaluationRun[]
+ evalRunsLoading: boolean
+ evaluations: EvaluationConfig[]
+ detectorEvaluationIds: string[]
+ evaluationsSettled: boolean
+ teamId: TeamId
+ person: LLMTracePerson | null
+}
+
+function ioContent(io: { input: unknown; output: unknown }, node: TraceTreeNode, teamId: TeamId): NodeContent {
+ if (node.kind === 'generation' || isMessageIO(io.input, io.output)) {
+ return { kind: 'messages', ...toMessageIO(io, node.id, teamId) }
+ }
+ return { kind: 'io', input: io.input, output: io.output }
+}
+
+function eventContent(
+ event: LLMTraceEvent,
+ node: TraceTreeNode,
+ cache: Record<string, AIData | null>,
+ teamId: TeamId
+): NodeContent {
+ const io = resolveEventIO(event, cache)
+ return io.loading ? { kind: 'loading' } : ioContent(io, node, teamId)
+}
+
+function eventProperties(event: LLMTraceEvent, trace: LLMTrace, person: LLMTracePerson | null): NodeProperties {
+ const properties = event.properties
+ return {
+ timestamp: event.createdAt,
+ provider: readString(properties.$ai_provider),
+ temperature: readNumber(properties.$ai_temperature),
+ sessionId: readString(properties.$ai_session_id),
+ promptName: readString(properties.$ai_prompt_name),
+ promptVersion: readNumber(properties.$ai_prompt_version),
+ person: personLabel(trace, person),
+ }
+}
+
+function traceProperties(trace: LLMTrace, person: LLMTracePerson | null): NodeProperties {
+ return {
+ timestamp: trace.createdAt,
+ provider: null,
+ temperature: null,
+ sessionId: trace.aiSessionId ?? null,
+ promptName: null,
+ promptVersion: null,
+ person: personLabel(trace, person),
+ }
+}
+
+// Detector polarity comes from the evaluation configs, so results wait for them to avoid showing a flipped verdict.
+function evalsState(runs: EvaluationRun[], node: TraceTreeNode, args: NodeDetailArgs): EvalsState {
+ if (args.evalRunsLoading || !args.evaluationsSettled) {
+ return { status: 'loading' }
+ }
+ return {
+ status: 'ready',
+ results: toEvalResults(runs, {
+ tree: args.tree,
+ viewedNodeId: node.id,
+ evaluations: args.evaluations,
+ detectorEvaluationIds: args.detectorEvaluationIds,
+ }),
+ }
+}
+
+export function toNodeDetail(args: NodeDetailArgs): NodeDetailData {
+ const { trace, event, node, cache, evalRuns, teamId, person } = args
+ const runs = node.kind === 'trace' ? evalRuns : evalRuns.filter((run) => run.generation_id === node.id)
+ const evals = evalsState(runs, node, args)
+
+ if (!isLLMEvent(event)) {
+ const { events: _events, ...raw } = trace
+ return {
+ node,
+ content: ioContent({ input: trace.inputState, output: trace.outputState }, node, teamId),
+ error: null,
+ properties: traceProperties(trace, person),
+ evals,
+ raw,
+ }
+ }
+ return {
+ node,
+ content: eventContent(event, node, cache, teamId),
+ error: eventError(event),
+ properties: eventProperties(event, trace, person),
+ evals,
+ raw: { event: event.event, id: event.id, createdAt: event.createdAt, properties: event.properties },
+ }
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toSummary.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toSummary.test.ts
new file mode 100644
index 000000000000..4697b0faf0cc
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toSummary.test.ts
@@ -0,0 +1,47 @@
+import { LLMTracePerson } from '~/queries/schema/schema-general'
+
+import { makeTrace } from './testFixtures'
+import { toSummary } from './toSummary'
+
+describe('toSummary', () => {
+ it.each<{
+ description: string
+ person: LLMTracePerson | null
+ expectedLabel: string
+ }>([
+ {
+ description: 'email present',
+ person: {
+ uuid: 'p1',
+ created_at: '',
+ distinct_id: 'user-ana',
+ properties: { email: '[email protected]' },
+ },
+ expectedLabel: '[email protected]',
+ },
+ {
+ description: 'only name present',
+ person: {
+ uuid: 'p2',
+ created_at: '',
+ distinct_id: 'user-bob',
+ properties: { name: 'Bob' },
+ },
+ expectedLabel: 'Bob',
+ },
+ {
+ description: 'no person',
+ person: null,
+ expectedLabel: 'user-ana',
+ },
+ ])('labels the person by email, then name, then distinct id ($description)', ({ person, expectedLabel }) => {
+ const summary = toSummary(makeTrace(), person)
+ expect(summary.person?.label).toBe(expectedLabel)
+ })
+
+ it('keeps totals null rather than 0 when the trace has no cost or latency', () => {
+ const totals = toSummary(makeTrace({ totalCost: undefined, totalLatency: undefined }), null).totals
+ expect(totals.costUsd).toBeNull()
+ expect(totals.latencyMs).toBeNull()
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toSummary.ts b/products/ai_observability/frontend/redesign/trace/adapter/toSummary.ts
new file mode 100644
index 000000000000..36d3c3e92d21
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toSummary.ts
@@ -0,0 +1,23 @@
+import { urls } from 'scenes/urls'
+
+import { LLMTrace, LLMTracePerson } from '~/queries/schema/schema-general'
+
+import { TraceSummaryBarProps } from '../components/TraceSummaryBar'
+import { readString } from './propertyReaders'
+import { traceStats } from './toTraceTree'
+
+export function personLabel(trace: LLMTrace, person: LLMTracePerson | null): string {
+ const properties = person?.properties ?? {}
+ return readString(properties.email) ?? readString(properties.name) ?? trace.distinctId
+}
+
+export function toSummary(trace: LLMTrace, person: LLMTracePerson | null): TraceSummaryBarProps {
+ return {
+ traceId: trace.id,
+ timestamp: trace.createdAt,
+ person: trace.distinctId
+ ? { label: personLabel(trace, person), href: urls.personByDistinctId(trace.distinctId) }
+ : null,
+ totals: traceStats(trace),
+ }
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toThread.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toThread.test.ts
new file mode 100644
index 000000000000..9579d6343e3b
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toThread.test.ts
@@ -0,0 +1,72 @@
+import { ConversationState, ConversationTurn } from '../types'
+import { makeEvent, makeTrace } from './testFixtures'
+import { toThread } from './toThread'
+
+function readyTurns(thread: ConversationState): ConversationTurn[] {
+ if (thread.status !== 'ready') {
+ throw new Error(`expected a ready thread, got status "${thread.status}"`)
+ }
+ return thread.turns
+}
+
+describe('toThread', () => {
+ const generation = makeEvent({
+ id: 'gen-1',
+ event: '$ai_generation',
+ createdAt: '2026-09-01T10:15:02Z',
+ properties: {
+ $ai_input: [{ role: 'user', content: 'Why did my invoice go up?' }],
+ $ai_output_choices: [{ role: 'assistant', content: 'Two seats were added.' }],
+ },
+ })
+
+ it('builds one turn for the trace from its user-visible generation', () => {
+ const thread = toThread(makeTrace({ events: [generation] }), {}, 7)
+ expect(thread).toMatchObject({ status: 'ready', activeTurnId: 'trace-1' })
+ const turns = readyTurns(thread)
+ expect(turns).toHaveLength(1)
+ expect(turns[0].messages.map((m) => [m.role, m.sourceNodeId])).toEqual([
+ ['user', 'gen-1'],
+ ['assistant', 'gen-1'],
+ ])
+ expect(turns[0].error).toBeNull()
+ })
+
+ it('carries the error of a failed generation on its turn', () => {
+ const failed = makeEvent({
+ id: 'gen-3',
+ event: '$ai_generation',
+ properties: {
+ $ai_input: [{ role: 'user', content: 'Describe this photo.' }],
+ $ai_output_choices: [],
+ $ai_is_error: true,
+ $ai_error: 'Model does not support image input',
+ },
+ })
+ expect(readyTurns(toThread(makeTrace({ events: [failed] }), {}, 7))[0].error).toBe(
+ 'Model does not support image input'
+ )
+ })
+
+ it.each([
+ ['is loading while its offloaded content is not cached', {}, { status: 'loading' }],
+ [
+ 'uses its offloaded content once cached',
+ {
+ 'gen-2': {
+ input: [{ role: 'user', content: 'Hi' }],
+ output: [{ role: 'assistant', content: 'Hello' }],
+ tools: null,
+ },
+ },
+ { status: 'ready', turns: [{ messages: [{ role: 'user' }, { role: 'assistant' }] }] },
+ ],
+ ])('an offloaded generation %s', (_name, cache, expected) => {
+ const offloaded = makeEvent({ id: 'gen-2', event: '$ai_generation', properties: {} })
+ expect(toThread(makeTrace({ events: [offloaded] }), cache, 7)).toMatchObject(expected)
+ })
+
+ it('gives an empty turn when the trace has no generation', () => {
+ expect(readyTurns(toThread(makeTrace({ events: [makeEvent({ id: 's1' })] }), {}, 7))[0].messages).toEqual([])
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toThread.ts b/products/ai_observability/frontend/redesign/trace/adapter/toThread.ts
new file mode 100644
index 000000000000..b0d66f82361c
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toThread.ts
@@ -0,0 +1,52 @@
+import { LLMTrace } from '~/queries/schema/schema-general'
+
+import { AIData } from '../../../aiObservabilityAIDataLogic'
+import { pickUserVisibleTurn } from '../../../extractSessionTurns'
+import { ConversationState, ThreadMessage } from '../types'
+import { resolveEventIO } from './eventIO'
+import { TeamId } from './toAttachment'
+import { toThreadMessages } from './toThreadMessages'
+import { eventError } from './toTraceTree'
+
+export interface MessageIO {
+ input: ThreadMessage[]
+ output: ThreadMessage[]
+}
+
+export function toMessageIO(io: { input: unknown; output: unknown }, sourceNodeId: string, teamId: TeamId): MessageIO {
+ return {
+ input: toThreadMessages(io.input, {
+ defaultRole: 'user',
+ idPrefix: `${sourceNodeId}-in`,
+ sourceNodeId,
+ teamId,
+ }),
+ output: toThreadMessages(io.output, {
+ defaultRole: 'assistant',
+ idPrefix: `${sourceNodeId}-out`,
+ sourceNodeId,
+ teamId,
+ }),
+ }
+}
+
+function readyThread(trace: LLMTrace, messages: ThreadMessage[], error: string | null): ConversationState {
+ return {
+ status: 'ready',
+ turns: [{ id: trace.id, timestamp: trace.createdAt, messages, error }],
+ activeTurnId: trace.id,
+ }
+}
+
+export function toThread(trace: LLMTrace, cache: Record<string, AIData | null>, teamId: TeamId): ConversationState {
+ const turnEvent = pickUserVisibleTurn(trace)
+ if (!turnEvent) {
+ return readyThread(trace, [], null)
+ }
+ const io = resolveEventIO(turnEvent, cache)
+ if (io.loading) {
+ return { status: 'loading' }
+ }
+ const { input, output } = toMessageIO(io, turnEvent.id, teamId)
+ return readyThread(trace, [...input, ...output], eventError(turnEvent))
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.test.ts
new file mode 100644
index 000000000000..e326f1316714
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.test.ts
@@ -0,0 +1,242 @@
+import { ThreadMessagesOptions, isMessageIO, toThreadMessages } from './toThreadMessages'
+
+const options = (
+ defaultRole: 'user' | 'assistant',
+ idPrefix: string,
+ sourceNodeId: string | null
+): ThreadMessagesOptions => ({ defaultRole, idPrefix, sourceNodeId, teamId: 7 })
+
+describe('toThreadMessages', () => {
+ it('keeps roles and text in order, mapping the OpenAI developer role to system', () => {
+ const messages = toThreadMessages(
+ [
+ { role: 'system', content: 'Answer billing questions.' },
+ { role: 'developer', content: 'Follow the house style.' },
+ { role: 'user', content: 'Why did my invoice go up?' },
+ ],
+ options('user', 'in', 'gen-1')
+ )
+ expect(messages.map((m) => [m.role, m.parts])).toEqual([
+ ['system', [{ kind: 'text', text: 'Answer billing questions.' }]],
+ ['system', [{ kind: 'text', text: 'Follow the house style.' }]],
+ ['user', [{ kind: 'text', text: 'Why did my invoice go up?' }]],
+ ])
+ expect(messages[0]).toMatchObject({ id: 'in-0', sourceNodeId: 'gen-1', isInternal: false })
+ })
+
+ it('pairs tool results with their calls instead of repeating them as messages', () => {
+ const messages = toThreadMessages(
+ [
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ {
+ type: 'function',
+ id: 'call-1',
+ function: { name: 'lookup_invoice', arguments: '{"month":"2026-08"}' },
+ },
+ ],
+ },
+ { role: 'tool', tool_call_id: 'call-1', content: '{"total_usd":180}' },
+ { role: 'assistant', content: 'Two seats were added.' },
+ ],
+ options('assistant', 'out', 'gen-1')
+ )
+ expect(messages).toHaveLength(2)
+ expect(messages[0].parts).toEqual([
+ { kind: 'toolCall', name: 'lookup_invoice', args: { month: '2026-08' }, result: '{"total_usd":180}' },
+ ])
+ expect(messages[0].isInternal).toBe(true)
+ expect(messages[1]).toMatchObject({ role: 'assistant', isInternal: false })
+ })
+
+ it('marks unmatched tool results as internal tool messages', () => {
+ const [message] = toThreadMessages(
+ [{ role: 'tool', tool_call_id: 'gone', content: 'late result' }],
+ options('user', 'in', null)
+ )
+ expect(message).toMatchObject({
+ role: 'tool',
+ isInternal: true,
+ parts: [{ kind: 'text', text: 'late result' }],
+ })
+ })
+
+ it('turns non-text content items into attachments', () => {
+ const [message] = toThreadMessages(
+ [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'What is in this receipt?' },
+ { type: 'image_url', image_url: { url: 'https://example.com/r.png' } },
+ ],
+ },
+ ],
+ options('user', 'in', null)
+ )
+ expect(message.parts).toEqual([
+ { kind: 'text', text: 'What is in this receipt?' },
+ {
+ kind: 'attachment',
+ mediaType: 'image',
+ name: null,
+ mimeType: null,
+ url: 'https://example.com/r.png',
+ },
+ ])
+ })
+
+ it('reads a media item the normalizer passed through as JSON text as an attachment', () => {
+ const messages = toThreadMessages(
+ [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Transcribe this.' },
+ { type: 'input_audio', input_audio: { data: 'UklGRg==', format: 'mp3' } },
+ ],
+ },
+ ],
+ options('user', 'in', null)
+ )
+ expect(messages.flatMap((message) => message.parts)).toEqual([
+ { kind: 'text', text: 'Transcribe this.' },
+ {
+ kind: 'attachment',
+ mediaType: 'audio',
+ name: null,
+ mimeType: 'audio/mp3',
+ url: 'data:audio/mp3;base64,UklGRg==',
+ },
+ ])
+ })
+
+ it('keeps the text and reasoning summary of OpenAI Responses output items', () => {
+ const messages = toThreadMessages(
+ [
+ {
+ type: 'reasoning',
+ id: 'rs_1',
+ summary: [{ type: 'summary_text', text: 'Compare the two plans by seat price.' }],
+ },
+ {
+ type: 'message',
+ id: 'msg_1',
+ role: 'assistant',
+ status: 'completed',
+ content: [{ type: 'output_text', text: 'The team plan is cheaper for 5 seats.', annotations: [] }],
+ },
+ ],
+ options('assistant', 'out', 'gen-1')
+ )
+ expect(messages.map((message) => [message.role, message.parts, message.isInternal])).toEqual([
+ ['assistant', [{ kind: 'thinking', text: 'Compare the two plans by seat price.' }], true],
+ ['assistant', [{ kind: 'text', text: 'The team plan is cheaper for 5 seats.' }], false],
+ ])
+ })
+
+ it('returns nothing for empty input', () => {
+ expect(toThreadMessages(null, options('user', 'in', null))).toEqual([])
+ })
+
+ it('pairs an Anthropic tool_use with a tool_result carried on a later message, and keeps thinking separate', () => {
+ const messages = toThreadMessages(
+ [
+ {
+ role: 'assistant',
+ content: [
+ { type: 'thinking', thinking: 'Let me check the invoice.' },
+ { type: 'tool_use', id: 'call-1', name: 'lookup_invoice', input: { month: '2026-08' } },
+ ],
+ },
+ {
+ role: 'user',
+ content: [{ type: 'tool_result', tool_use_id: 'call-1', content: '{"total_usd":180}' }],
+ },
+ ],
+ options('assistant', 'gen', 'gen-1')
+ )
+ expect(messages).toHaveLength(2)
+ expect(messages[0]).toMatchObject({
+ isInternal: true,
+ parts: [{ kind: 'thinking', text: 'Let me check the invoice.' }],
+ })
+ expect(messages[1]).toMatchObject({
+ isInternal: true,
+ parts: [
+ { kind: 'toolCall', name: 'lookup_invoice', args: { month: '2026-08' }, result: '{"total_usd":180}' },
+ ],
+ })
+ })
+
+ it('keeps an Anthropic tool_result carrying an image as its own message with the attachment', () => {
+ const messages = toThreadMessages(
+ [
+ {
+ role: 'assistant',
+ content: [{ type: 'tool_use', id: 'call-1', name: 'take_screenshot', input: {} }],
+ },
+ {
+ role: 'user',
+ content: [
+ {
+ type: 'tool_result',
+ tool_use_id: 'call-1',
+ content: [
+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'AAAA' } },
+ ],
+ },
+ ],
+ },
+ ],
+ options('assistant', 'gen', 'gen-1')
+ )
+ expect(messages.map((message) => [message.role, message.parts])).toEqual([
+ ['assistant', [{ kind: 'toolCall', name: 'take_screenshot', args: {} }]],
+ [
+ 'tool',
+ [
+ {
+ kind: 'attachment',
+ mediaType: 'image',
+ name: null,
+ mimeType: 'image/png',
+ url: 'data:image/png;base64,AAAA',
+ },
+ ],
+ ],
+ ])
+ })
+
+ it.each([
+ [
+ 'a refusal',
+ { role: 'assistant', content: null, refusal: 'I cannot share account passwords.' },
+ 'I cannot share account passwords.',
+ ],
+ [
+ 'a spoken reply',
+ { role: 'assistant', content: null, audio: { id: 'audio-1', transcript: 'Your plan renews on Friday.' } },
+ 'Your plan renews on Friday.',
+ ],
+ ])('keeps the text of %s that has no content', (_name, message, expectedText) => {
+ expect(toThreadMessages([message], options('assistant', 'out', 'gen-1'))).toMatchObject([
+ { role: 'assistant', parts: [{ kind: 'text', text: expectedText }] },
+ ])
+ })
+
+ it.each<[string, unknown, unknown, boolean]>([
+ ['role-bearing arrays', [{ role: 'user', content: 'Hi' }], [{ role: 'assistant', content: 'Hello' }], true],
+ ['LangChain message dicts', [{ type: 'human', content: 'Hi' }], null, true],
+ ['workflow step arrays', [{ step: 1 }, { step: 2 }], [{ step: 3 }], false],
+ ['an array mixing messages and state', [{ role: 'user', content: 'Hi' }, { step: 1 }], null, false],
+ ['state objects', { question: 'Hi' }, { answer: 'Hello' }, false],
+ ['a string next to a step array', [{ step: 1 }, { step: 2 }], 'done', false],
+ ['a string next to a role array', [{ role: 'user', content: 'Hi' }], 'Hello', true],
+ ['strings on both sides', 'Hi', 'Hello', false],
+ ])('isMessageIO treats %s correctly', (_name, input, output, expected) => {
+ expect(isMessageIO(input, output)).toBe(expected)
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.ts b/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.ts
new file mode 100644
index 000000000000..723998046e96
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toThreadMessages.ts
@@ -0,0 +1,186 @@
+import { isObject } from 'lib/utils/guards'
+
+import { normalizeMessages } from '../../../messageNormalization'
+import { CompatMessage } from '../../../types'
+import { INTERNAL_THINKING_ROLE, INTERNAL_TOOL_RESULT_ROLE, extractText, extractTextContent } from '../../../utils'
+import { MessagePart, MessageRole, ThreadMessage } from '../types'
+import { TeamId, isAttachmentItemType, toAttachment } from './toAttachment'
+
+const TEXT_ITEM_TYPES = new Set(['text', 'input_text', 'output_text'])
+const SKIPPED_ROLES = new Set(['available tools'])
+const LANGCHAIN_MESSAGE_TYPES = new Set(['system', 'human', 'ai', 'tool', 'function', 'chat'])
+
+type ToolCallPart = Extract<MessagePart, { kind: 'toolCall' }>
+type ContentItem = Record<string, unknown> & { type: string }
+
+export interface ThreadMessagesOptions {
+ defaultRole: 'user' | 'assistant'
+ idPrefix: string
+ sourceNodeId: string | null
+ teamId: TeamId
+}
+
+function isContentItem(item: unknown): item is ContentItem {
+ return isObject(item) && typeof item.type === 'string'
+}
+
+function parseArguments(args: unknown): unknown {
+ if (typeof args !== 'string') {
+ return args
+ }
+ try {
+ return JSON.parse(args)
+ } catch {
+ return args
+ }
+}
+
+// The normalizer passes some media items it has no recipe for through as their JSON text.
+function parseMediaItem(content: string): ContentItem | null {
+ if (!content.startsWith('{')) {
+ return null
+ }
+ const parsed = parseArguments(content)
+ return isContentItem(parsed) && isAttachmentItemType(parsed.type) ? parsed : null
+}
+
+function itemText(item: unknown): string | undefined {
+ if (isContentItem(item) && TEXT_ITEM_TYPES.has(item.type) && typeof item.text === 'string') {
+ return item.text
+ }
+ return extractTextContent(item)
+}
+
+function contentText(message: CompatMessage): string {
+ if (!Array.isArray(message.content)) {
+ return extractText(message)
+ }
+ return message.content
+ .map(itemText)
+ .filter((text): text is string => text !== undefined)
+ .join('\n')
+}
+
+// OpenAI puts a refusal or a spoken reply next to `content`, which is then null.
+function sideChannelTexts(message: CompatMessage): string[] {
+ const refusal: unknown = message.refusal
+ const audio: unknown = message.audio
+ const transcript = isObject(audio) ? audio.transcript : undefined
+ return [refusal, transcript].filter((text): text is string => typeof text === 'string' && text !== '')
+}
+
+function messageText(message: CompatMessage): string {
+ return [contentText(message), ...sideChannelTexts(message)].filter((text) => text !== '').join('\n')
+}
+
+function contentParts(message: CompatMessage, teamId: TeamId): { text: string; attachments: MessagePart[] } {
+ const mediaItem = typeof message.content === 'string' ? parseMediaItem(message.content) : null
+ if (mediaItem) {
+ return { text: '', attachments: [toAttachment(mediaItem, teamId)] }
+ }
+ const items: unknown[] = Array.isArray(message.content) ? message.content : []
+ return {
+ text: messageText(message),
+ attachments: items
+ .filter(isContentItem)
+ .filter((item) => !TEXT_ITEM_TYPES.has(item.type))
+ .map((item) => toAttachment(item, teamId)),
+ }
+}
+
+function toRole(role: string): MessageRole {
+ if (role === 'developer') {
+ return 'system'
+ }
+ if (role === 'system' || role === 'user' || role === 'tool') {
+ return role
+ }
+ return role === INTERNAL_TOOL_RESULT_ROLE ? 'tool' : 'assistant'
+}
+
+function isEmptyIO(value: unknown): boolean {
+ return value === null || value === undefined || value === ''
+}
+
+// The normalizer's catch-all recipe accepts any array, so its `recognized` flag cannot tell messages from
+// workflow state. Only role-bearing messages and LangChain message dicts count.
+function isMessageLike(item: unknown): boolean {
+ if (!isObject(item)) {
+ return false
+ }
+ if (typeof item.role === 'string') {
+ return true
+ }
+ return typeof item.type === 'string' && LANGCHAIN_MESSAGE_TYPES.has(item.type) && 'content' in item
+}
+
+function isMessageArray(raw: unknown): boolean {
+ return Array.isArray(raw) && raw.length > 0 && raw.every(isMessageLike)
+}
+
+export function toThreadMessages(
+ raw: unknown,
+ { defaultRole, idPrefix, sourceNodeId, teamId }: ThreadMessagesOptions
+): ThreadMessage[] {
+ if (isEmptyIO(raw)) {
+ return []
+ }
+ const compat: CompatMessage[] = normalizeMessages(raw, defaultRole).messages
+ const pendingCalls = new Map<string, ToolCallPart>()
+ const messages: ThreadMessage[] = []
+
+ compat.forEach((message, index) => {
+ if (SKIPPED_ROLES.has(message.role)) {
+ return
+ }
+ const role = toRole(message.role)
+ const { text, attachments } = contentParts(message, teamId)
+
+ // A tool call part holds its result as text only, so a result carrying media stays its own
+ // message and keeps its attachments.
+ const pendingCall =
+ role === 'tool' && message.tool_call_id && attachments.length === 0
+ ? pendingCalls.get(message.tool_call_id)
+ : undefined
+ if (pendingCall && message.tool_call_id) {
+ pendingCall.result = text || message.content
+ pendingCalls.delete(message.tool_call_id)
+ return
+ }
+
+ const parts: MessagePart[] = []
+ if (text) {
+ parts.push(message.role === INTERNAL_THINKING_ROLE ? { kind: 'thinking', text } : { kind: 'text', text })
+ }
+ parts.push(...attachments)
+ for (const toolCall of message.tool_calls ?? []) {
+ const part: ToolCallPart = {
+ kind: 'toolCall',
+ name: toolCall.function.name,
+ args: parseArguments(toolCall.function.arguments),
+ }
+ if (toolCall.id) {
+ pendingCalls.set(toolCall.id, part)
+ }
+ parts.push(part)
+ }
+ if (parts.length === 0) {
+ return
+ }
+ messages.push({
+ id: `${idPrefix}-${index}`,
+ role,
+ parts,
+ isInternal: role === 'tool' || parts.every((part) => part.kind === 'thinking' || part.kind === 'toolCall'),
+ sourceNodeId,
+ })
+ })
+ return messages
+}
+
+export function isMessageIO(input: unknown, output: unknown): boolean {
+ const captured = [input, output].filter((value) => !isEmptyIO(value))
+ return (
+ captured.some(isMessageArray) && captured.every((value) => typeof value === 'string' || isMessageArray(value))
+ )
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toTimeline.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toTimeline.test.ts
new file mode 100644
index 000000000000..3c12b74b9e37
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toTimeline.test.ts
@@ -0,0 +1,45 @@
+import { enrich, makeEvent, makeTrace } from './testFixtures'
+import { toTimeline } from './toTimeline'
+import { toTraceTree } from './toTraceTree'
+
+describe('toTimeline', () => {
+ it('lists each parent directly above its children, with their depth and errors, and leaves unknown latency empty', () => {
+ const event = (
+ id: string,
+ parentId: string,
+ second: number,
+ latency?: number,
+ error?: string
+ ): ReturnType<typeof makeEvent> =>
+ makeEvent({
+ id,
+ event: id.startsWith('gen') ? '$ai_generation' : '$ai_span',
+ createdAt: `2026-09-01T10:15:0${second}.000Z`,
+ properties: {
+ $ai_trace_id: 'trace-1',
+ $ai_parent_id: parentId,
+ ...(latency !== undefined ? { $ai_latency: latency } : {}),
+ ...(error !== undefined ? { $ai_error: error } : {}),
+ },
+ })
+ const firstGeneration = event('gen-1', 'trace-1', 1, 1)
+ const firstTool = event('span-1', 'gen-1', 2, undefined, 'Tool timed out')
+ const secondGeneration = event('gen-2', 'trace-1', 3, 1)
+ const secondTool = event('span-2', 'gen-2', 4, 0.5)
+ const trace = makeTrace({ events: [firstGeneration, secondGeneration, firstTool, secondTool] })
+ const tree = toTraceTree(trace, [
+ enrich(firstGeneration, [enrich(firstTool)]),
+ enrich(secondGeneration, [enrich(secondTool)]),
+ ])
+
+ const timeline = toTimeline(trace, tree)
+
+ expect(timeline.rows.map((row) => [row.id, row.depth, row.durationMs, row.hasError])).toEqual([
+ ['gen-1', 0, 1000, false],
+ ['span-1', 1, null, true],
+ ['gen-2', 0, 1000, false],
+ ['span-2', 1, 500, false],
+ ])
+ expect(timeline.totalMs).toBeGreaterThan(0)
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toTimeline.ts b/products/ai_observability/frontend/redesign/trace/adapter/toTimeline.ts
new file mode 100644
index 000000000000..5cb6591a0cdf
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toTimeline.ts
@@ -0,0 +1,35 @@
+import { LLMTrace } from '~/queries/schema/schema-general'
+
+import { buildTraceTimeline } from '../../../components/TraceTimeline/buildTraceTimeline'
+import { TimelineRowData, TraceTreeNode } from '../types'
+import { hasTraceError, isErrorEvent, preOrderIds } from './toTraceTree'
+
+export function toTimeline(trace: LLMTrace, tree: TraceTreeNode[]): { rows: TimelineRowData[]; totalMs: number } {
+ const { bars, totalMs } = buildTraceTimeline(trace.events)
+ const eventsById = new Map(trace.events.map((event) => [event.id, event]))
+ const hasError = (id: string): boolean => {
+ if (id === trace.id) {
+ return hasTraceError(trace)
+ }
+ const event = eventsById.get(id)
+ return event ? isErrorEvent(event) : false
+ }
+ const treeIndex = new Map(preOrderIds(tree).map((id, index) => [id, index]))
+ const position = (id: string): number => treeIndex.get(id) ?? Number.MAX_SAFE_INTEGER
+ const ordered = [...bars].sort((a, b) => position(a.id) - position(b.id))
+ const depthById = new Map<string, number>()
+ const rows = ordered.map((bar) => {
+ const depth = bar.parentEventId !== null ? (depthById.get(bar.parentEventId) ?? 0) + 1 : 0
+ depthById.set(bar.id, depth)
+ return {
+ id: bar.id,
+ kind: bar.kind,
+ name: bar.label,
+ depth,
+ startMs: bar.startMs,
+ durationMs: bar.durationMs > 0 ? bar.durationMs : null,
+ hasError: hasError(bar.id),
+ }
+ })
+ return { rows, totalMs }
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toTraceTree.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toTraceTree.test.ts
new file mode 100644
index 000000000000..aa0f5c526f9f
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toTraceTree.test.ts
@@ -0,0 +1,102 @@
+import { enrich, makeEvent, makeTrace } from './testFixtures'
+import { hasTraceError, isErrorEvent, toTraceTree } from './toTraceTree'
+
+describe('toTraceTree', () => {
+ describe('isErrorEvent', () => {
+ it.each([
+ ['a populated $ai_error with no flag', { $ai_error: 'boom' }, true],
+ ['$ai_is_error: true with no error payload', { $ai_is_error: true }, true],
+ ['$ai_is_error: "true" (SDK-serialized boolean)', { $ai_is_error: 'true' }, true],
+ ['neither an error payload nor a truthy flag', { $ai_is_error: false }, false],
+ ])('%s -> %s', (_description, properties, expected) => {
+ expect(isErrorEvent(makeEvent({ id: 'e1', properties }))).toBe(expected)
+ })
+
+ it.each([
+ ['an error count from the traces list', makeTrace({ errorCount: 1 }), true],
+ [
+ 'a failed event in a single-trace read, which carries no error count',
+ makeTrace({ events: [makeEvent({ id: 'e1', properties: { $ai_error: 'Rate limited' } })] }),
+ true,
+ ],
+ ['no error count and no failed event', makeTrace({ events: [makeEvent({ id: 'e1' })] }), false],
+ ])('hasTraceError with %s -> %s', (_description, trace, expected) => {
+ expect(hasTraceError(trace)).toBe(expected)
+ })
+ })
+
+ const generation = makeEvent({
+ id: 'gen-1',
+ event: '$ai_generation',
+ properties: {
+ $ai_span_name: 'draft-answer',
+ $ai_model: 'gpt-4.1-mini',
+ $ai_input_tokens: 1822,
+ $ai_output_tokens: '212',
+ $ai_cache_read_input_tokens: 1024,
+ $ai_cache_creation_input_tokens: '256',
+ },
+ })
+ const span = makeEvent({ id: 'span-1', event: '$ai_span', properties: { $ai_span_name: 'retrieve-context' } })
+ const embedding = makeEvent({ id: 'emb-1', event: '$ai_embedding', properties: { $ai_is_error: true } })
+
+ const tree = toTraceTree(makeTrace({ errorCount: 1 }), [
+ enrich(span, [enrich(embedding)], {
+ displayLatency: 0.41,
+ aggregation: {
+ totalCost: null,
+ totalLatency: 0.41,
+ inputTokens: 18,
+ outputTokens: 0,
+ hasGenerationChildren: false,
+ },
+ }),
+ enrich(generation, [], { displayTotalCost: 0.0021, displayLatency: 1.88 }),
+ ])
+
+ it('wraps events under a root node for the trace itself', () => {
+ expect(tree).toHaveLength(1)
+ expect(tree[0]).toMatchObject({ id: 'trace-1', kind: 'trace', name: 'answer-billing-question', hasError: true })
+ expect(tree[0].children.map((child) => child.id)).toEqual(['span-1', 'gen-1'])
+ expect(tree[0].stats).toEqual({
+ costUsd: 0.0021,
+ inputTokens: 1840,
+ outputTokens: 212,
+ cacheReadTokens: null,
+ cacheWriteTokens: null,
+ latencyMs: 2310,
+ })
+ })
+
+ it('maps event types to node kinds', () => {
+ const [spanNode, generationNode] = tree[0].children
+ expect(spanNode.kind).toBe('span')
+ expect(spanNode.children[0].kind).toBe('embedding')
+ expect(generationNode.kind).toBe('generation')
+ })
+
+ it("uses the node's own stats and converts latency to milliseconds", () => {
+ const generationNode = tree[0].children[1]
+ expect(generationNode.stats).toEqual({
+ costUsd: 0.0021,
+ inputTokens: 1822,
+ outputTokens: 212,
+ cacheReadTokens: 1024,
+ cacheWriteTokens: 256,
+ latencyMs: 1880,
+ })
+ expect(generationNode.model).toBe('gpt-4.1-mini')
+ })
+
+ it('keeps unknown cost null and uses span roll-ups for tokens', () => {
+ const spanNode = tree[0].children[0]
+ expect(spanNode.stats.costUsd).toBeNull()
+ expect(spanNode.stats.inputTokens).toBe(18)
+ expect(spanNode.stats.outputTokens).toBeNull()
+ })
+
+ it('flags errored events', () => {
+ expect(tree[0].children[0].children[0].hasError).toBe(true)
+ expect(tree[0].children[1].hasError).toBe(false)
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toTraceTree.ts b/products/ai_observability/frontend/redesign/trace/adapter/toTraceTree.ts
new file mode 100644
index 000000000000..b62286eeb7b3
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toTraceTree.ts
@@ -0,0 +1,91 @@
+import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
+
+import { EnrichedTraceTreeNode } from '../../../aiObservabilityTraceDataLogic'
+import { aiTokenCount, formatLLMEventTitle, getLLMEventKind } from '../../../utils'
+import { toDisplayText } from '../components/jsonText'
+import { NodeStats, TraceTreeNode } from '../types'
+import { readString } from './propertyReaders'
+
+export function isErrorEvent(event: LLMTraceEvent): boolean {
+ const isErrorFlag = event.properties.$ai_is_error
+ return !!event.properties.$ai_error || isErrorFlag === true || isErrorFlag === 'true'
+}
+
+export function eventError(event: LLMTraceEvent): string | null {
+ return isErrorEvent(event) ? toDisplayText(event.properties.$ai_error ?? 'This step failed.') : null
+}
+
+// The single-trace query never sets `errorCount`, so the events are the source of truth there.
+export function hasTraceError(trace: LLMTrace): boolean {
+ return (trace.errorCount ?? 0) > 0 || trace.events.some(isErrorEvent)
+}
+
+export function traceStats(trace: LLMTrace): NodeStats {
+ return {
+ costUsd: trace.totalCost ?? null,
+ inputTokens: trace.inputTokens ?? null,
+ outputTokens: trace.outputTokens ?? null,
+ cacheReadTokens: null,
+ cacheWriteTokens: null,
+ latencyMs: trace.totalLatency != null ? trace.totalLatency * 1000 : null,
+ }
+}
+
+function nodeStats(node: EnrichedTraceTreeNode): NodeStats {
+ const properties = node.event.properties
+ return {
+ costUsd: node.displayTotalCost,
+ inputTokens: node.aggregation
+ ? node.aggregation.inputTokens || null
+ : aiTokenCount(properties.$ai_input_tokens),
+ outputTokens: node.aggregation
+ ? node.aggregation.outputTokens || null
+ : aiTokenCount(properties.$ai_output_tokens),
+ cacheReadTokens: aiTokenCount(properties.$ai_cache_read_input_tokens),
+ cacheWriteTokens: aiTokenCount(properties.$ai_cache_creation_input_tokens),
+ latencyMs: node.displayLatency > 0 ? node.displayLatency * 1000 : null,
+ }
+}
+
+function toNode(node: EnrichedTraceTreeNode): TraceTreeNode {
+ return {
+ id: node.event.id,
+ kind: getLLMEventKind(node.event),
+ name: formatLLMEventTitle(node.event),
+ model: readString(node.event.properties.$ai_model),
+ stats: nodeStats(node),
+ hasError: isErrorEvent(node.event),
+ children: (node.children ?? []).map(toNode),
+ }
+}
+
+export function toTraceTree(trace: LLMTrace, enrichedTree: EnrichedTraceTreeNode[]): TraceTreeNode[] {
+ return [
+ {
+ id: trace.id,
+ kind: 'trace',
+ name: formatLLMEventTitle(trace),
+ model: null,
+ stats: traceStats(trace),
+ hasError: hasTraceError(trace),
+ children: enrichedTree.map(toNode),
+ },
+ ]
+}
+
+export function findTreeNode(nodes: TraceTreeNode[], id: string): TraceTreeNode | null {
+ for (const node of nodes) {
+ if (node.id === id) {
+ return node
+ }
+ const found = findTreeNode(node.children, id)
+ if (found) {
+ return found
+ }
+ }
+ return null
+}
+
+export function preOrderIds(nodes: TraceTreeNode[]): string[] {
+ return nodes.flatMap((node) => [node.id, ...preOrderIds(node.children)])
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/traceSceneWiring.test.tsx b/products/ai_observability/frontend/redesign/trace/adapter/traceSceneWiring.test.tsx
new file mode 100644
index 000000000000..1fb8e5108dd6
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/traceSceneWiring.test.tsx
@@ -0,0 +1,54 @@
+import { cleanup, render, waitFor } from '@testing-library/react'
+import { router } from 'kea-router'
+
+import { urls } from 'scenes/urls'
+
+import { performQuery } from '~/queries/query'
+import { initKeaTests } from '~/test/init'
+
+import { aiObservabilityTraceLogic } from '../../../aiObservabilityTraceLogic'
+import { TraceScene } from '../TraceScene'
+import { makeEvent, makeTrace } from './testFixtures'
+
+jest.mock('~/queries/query', () => ({ ...jest.requireActual('~/queries/query'), performQuery: jest.fn() }))
+jest.mock('../../../utils', () => ({
+ ...jest.requireActual('../../../utils'),
+ queryEvaluationRuns: jest.fn().mockResolvedValue([]),
+}))
+
+const generation = makeEvent({
+ id: 'gen-1',
+ event: '$ai_generation',
+ createdAt: '2026-09-01T10:15:02Z',
+ properties: {
+ $ai_trace_id: 'trace-1',
+ $ai_parent_id: 'trace-1',
+ $ai_input: [{ role: 'user', content: 'Why did my invoice go up?' }],
+ $ai_output_choices: [{ role: 'assistant', content: 'Two seats were added.' }],
+ },
+})
+
+describe('TraceScene', () => {
+ afterEach(cleanup)
+
+ it('renders the loaded trace after showing the loading state', async () => {
+ initKeaTests()
+ type QueryResult = Awaited<ReturnType<typeof performQuery>>
+ let resolveQuery: (value: QueryResult) => void = () => {}
+ jest.mocked(performQuery).mockReturnValue(
+ new Promise<QueryResult>((resolve) => {
+ resolveQuery = resolve
+ })
+ )
+ aiObservabilityTraceLogic.mount()
+ router.actions.push(urls.aiObservabilityTrace('trace-1'))
+
+ const { findAllByText, queryByText } = render(<TraceScene />)
+ expect(queryByText('answer-billing-question')).toBeNull()
+
+ resolveQuery({ results: [makeTrace({ events: [generation] })] })
+
+ expect((await findAllByText('answer-billing-question')).length).toBeGreaterThan(0)
+ await waitFor(() => expect(queryByText('Two seats were added.')).not.toBeNull())
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.test.ts
new file mode 100644
index 000000000000..5d53581869c9
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.test.ts
@@ -0,0 +1,165 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { urls } from 'scenes/urls'
+
+import { performQuery } from '~/queries/query'
+import { initKeaTests } from '~/test/init'
+
+import { aiObservabilityAIDataLogic } from '../../../aiObservabilityAIDataLogic'
+import { aiObservabilityTraceLogic } from '../../../aiObservabilityTraceLogic'
+import { makeEvent, makeTrace } from './testFixtures'
+import { traceViewAdapterLogic } from './traceViewAdapterLogic'
+
+jest.mock('~/queries/query', () => ({ ...jest.requireActual('~/queries/query'), performQuery: jest.fn() }))
+jest.mock('../../../utils', () => ({
+ ...jest.requireActual('../../../utils'),
+ queryEvaluationRuns: jest.fn().mockResolvedValue([]),
+}))
+
+const offloadedGeneration = makeEvent({
+ id: 'gen-1',
+ event: '$ai_generation',
+ createdAt: '2026-09-01T10:15:02Z',
+ properties: { $ai_trace_id: 'trace-1', $ai_parent_id: 'trace-1' },
+})
+
+// The latest generation, so `pickUserVisibleTurn` picks this one for the thread. Carries
+// inline input/output so `toThread` produces messages tagged with this event's id.
+const answeredGeneration = makeEvent({
+ id: 'gen-2',
+ event: '$ai_generation',
+ createdAt: '2026-09-01T10:15:03Z',
+ properties: {
+ $ai_trace_id: 'trace-1',
+ $ai_parent_id: 'trace-1',
+ $ai_input: [{ role: 'user', content: 'Why did my invoice go up?' }],
+ $ai_output_choices: [{ role: 'assistant', content: 'Two seats were added.' }],
+ },
+})
+
+const offloadedLatestGeneration = makeEvent({
+ id: 'gen-3',
+ event: '$ai_generation',
+ createdAt: '2026-09-01T10:15:04Z',
+ properties: { $ai_trace_id: 'trace-1', $ai_parent_id: 'trace-1' },
+})
+
+const unrelatedSpan = makeEvent({
+ id: 'span-1',
+ event: '$ai_span',
+ createdAt: '2026-09-01T10:15:01Z',
+ properties: { $ai_trace_id: 'trace-1', $ai_parent_id: 'trace-1' },
+})
+
+describe('traceViewAdapterLogic', () => {
+ let logic: ReturnType<typeof traceViewAdapterLogic.build>
+
+ function remount(): void {
+ logic.unmount()
+ const { query } = aiObservabilityTraceLogic.values
+ logic = traceViewAdapterLogic({ traceId: 'trace-1', query })
+ logic.mount()
+ }
+
+ beforeEach(async () => {
+ initKeaTests()
+ jest.mocked(performQuery).mockResolvedValue({
+ results: [makeTrace({ events: [offloadedGeneration, answeredGeneration, unrelatedSpan] })],
+ } as any)
+ aiObservabilityTraceLogic.mount()
+ router.actions.push(urls.aiObservabilityTrace('trace-1'))
+ const { query } = aiObservabilityTraceLogic.values
+ logic = traceViewAdapterLogic({ traceId: 'trace-1', query })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ status: 'ready' })
+ })
+
+ afterEach(() => logic.unmount())
+
+ it.each([
+ ['a generation when it is selected', null, () => logic.actions.selectNode('gen-1'), 'gen-1'],
+ [
+ 'the offloaded latest generation, which the thread shows, on mount',
+ [answeredGeneration, offloadedLatestGeneration],
+ null,
+ 'gen-3',
+ ],
+ ])('asks the heavy-data loader for %s', async (_name, events, act, expectedEventId) => {
+ if (events) {
+ jest.mocked(performQuery).mockResolvedValue({ results: [makeTrace({ events })] } as any)
+ }
+ await expectLogic(logic, () => (act ? act() : remount())).toDispatchActions([
+ (action) =>
+ action.type === aiObservabilityAIDataLogic.actionTypes.ensureAIDataLoaded &&
+ action.payload.lookups.some((lookup: { eventId: string }) => lookup.eventId === expectedEventId),
+ ])
+ })
+
+ it('falls back to the root node when the event id is unknown', async () => {
+ await expectLogic(logic, () => logic.actions.selectNode('does-not-exist')).toMatchValues({
+ selectedNodeId: 'trace-1',
+ canViewInThread: true,
+ })
+ })
+
+ it('selecting from the thread or timeline switches to spans', async () => {
+ logic.actions.setMode('timeline')
+ await expectLogic(logic, () => logic.actions.selectAndShowSpans('gen-1')).toMatchValues({
+ mode: 'spans',
+ selectedNodeId: 'gen-1',
+ })
+ })
+
+ it.each([
+ ['gen-2', 'a generation whose messages the thread carries', true],
+ ['span-1', 'a span the thread never mentions', false],
+ ])('canViewInThread for %s (%s) is %s', async (nodeId, _description, expected) => {
+ await expectLogic(logic, () => logic.actions.selectNode(nodeId)).toMatchValues({ canViewInThread: expected })
+ })
+
+ it('clears a search query left over from a shared legacy URL, so it does not silently filter the tree, and keeps the other params', async () => {
+ router.actions.push(
+ urls.aiObservabilityTrace('trace-1', {
+ search: 'does-not-match-anything',
+ event: 'gen-2',
+ line: '4',
+ back_to: 'generations',
+ date_from: '-7d',
+ })
+ )
+ remount()
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ status: 'ready' })
+ expect(logic.values.tree[0].children.map((child) => child.id)).toEqual(['span-1', 'gen-1', 'gen-2'])
+ expect(router.values.searchParams).toEqual({
+ event: 'gen-2',
+ line: 4,
+ back_to: 'generations',
+ date_from: '-7d',
+ })
+ })
+
+ it.each([
+ [
+ 'the trace is not found',
+ () => Promise.resolve({ results: [] } as any),
+ 'It may have been deleted, or it is outside the retention period.',
+ ],
+ [
+ 'the query fails',
+ () => Promise.reject(new Error('boom')),
+ 'Something went wrong while loading it. Try again in a moment.',
+ ],
+ ])('status is error when %s', async (_description, mockResult, expectedMessage) => {
+ logic.unmount()
+ jest.mocked(performQuery).mockReset().mockImplementationOnce(mockResult)
+ const { query } = aiObservabilityTraceLogic.values
+ logic = traceViewAdapterLogic({ traceId: 'trace-1', query })
+ logic.mount()
+
+ await expectLogic(logic)
+ .toFinishAllListeners()
+ .toMatchValues({ status: 'error', errorMessage: expectedMessage })
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.ts b/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.ts
new file mode 100644
index 000000000000..418d3f5912e7
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.ts
@@ -0,0 +1,426 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { router } from 'kea-router'
+import { subscriptions } from 'kea-subscriptions'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { DataTableNode, LLMTrace, LLMTraceEvent, LLMTracePerson } from '~/queries/schema/schema-general'
+
+import type {
+ ErrorTrackingQueryResponse,
+ HogQLAutocompleteResponse,
+ HogQLMetadataResponse,
+ HogQLQueryResponse,
+ HogQueryResponse,
+ LogAttributesQueryResponse,
+ LogValuesQueryResponse,
+ MetricsQueryResponse,
+ SessionsQueryResponse,
+ TraceSpansAggregationQueryResponse,
+ TraceSpansAttributeBreakdownQueryResponse,
+ TraceSpansQueryResponse,
+ TraceSpansTreeQueryResponse,
+} from '../../../../../../frontend/src/queries/schema/schema-general'
+import { AIData, AIDataLookup, aiObservabilityAIDataLogic } from '../../../aiObservabilityAIDataLogic'
+import { EnrichedTraceTreeNode, aiObservabilityTraceDataLogic } from '../../../aiObservabilityTraceDataLogic'
+import { aiObservabilityTraceLogic } from '../../../aiObservabilityTraceLogic'
+import { llmEvaluationsLogic } from '../../../evaluations/llmEvaluationsLogic'
+import { EvaluationConfig, EvaluationRun } from '../../../evaluations/types'
+import { pickUserVisibleTurn } from '../../../extractSessionTurns'
+import { generationEvaluationRunsLogic } from '../../../generationEvaluationRunsLogic'
+import { llmPersonsLazyLoaderLogic } from '../../../llmPersonsLazyLoaderLogic'
+import { isLLMEvent } from '../../../utils'
+import { TraceHeaderProps } from '../components/TraceHeader'
+import { TraceSummaryBarProps } from '../components/TraceSummaryBar'
+import { ConversationState, LabeledLink, NodeDetailTab, TimelineRowData, TraceMode, TraceTreeNode } from '../types'
+import { heavyDataLookup } from './eventIO'
+import { toBackLink, toHeader } from './toHeader'
+import { NodeDetailData, toNodeDetail } from './toNodeDetail'
+import { toSummary } from './toSummary'
+import { toThread } from './toThread'
+import { toTimeline } from './toTimeline'
+import { findTreeNode, toTraceTree } from './toTraceTree'
+
+export interface TraceViewAdapterLogicProps {
+ traceId: string
+ query: DataTableNode
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceViewAdapterLogicValues {
+ aiDataCache: Record<string, AIData | null> // aiObservabilityAIDataLogic
+ enrichedTree: EnrichedTraceTreeNode[] // aiObservabilityTraceDataLogic
+ event: LLMTrace | LLMTraceEvent | null // aiObservabilityTraceDataLogic
+ response:
+ | ErrorTrackingQueryResponse
+ | HogQLAutocompleteResponse
+ | HogQLMetadataResponse
+ | HogQLQueryResponse<any[]>
+ | HogQueryResponse
+ | LogAttributesQueryResponse
+ | LogValuesQueryResponse
+ | MetricsQueryResponse
+ | Record<string, any>
+ | SessionsQueryResponse
+ | TraceSpansAggregationQueryResponse
+ | TraceSpansAttributeBreakdownQueryResponse
+ | TraceSpansQueryResponse
+ | TraceSpansTreeQueryResponse
+ | null // aiObservabilityTraceDataLogic
+ responseError: string | null // aiObservabilityTraceDataLogic
+ responseLoading: boolean // aiObservabilityTraceDataLogic
+ trace: LLMTrace | undefined // aiObservabilityTraceDataLogic
+ newerTimestamp: string | null // aiObservabilityTraceLogic
+ newerTraceId: string | null // aiObservabilityTraceLogic
+ olderTimestamp: string | null // aiObservabilityTraceLogic
+ olderTraceId: string | null // aiObservabilityTraceLogic
+ generationEvaluationRuns: EvaluationRun[] // generationEvaluationRunsLogic
+ generationEvaluationRunsLoading: boolean // generationEvaluationRunsLogic
+ detectorEvaluationIds: string[] // llmEvaluationsLogic
+ evaluations: EvaluationConfig[] // llmEvaluationsLogic
+ evaluationsSettled: boolean // llmEvaluationsLogic
+ personsCache: Record<string, LLMTracePerson | null> // llmPersonsLazyLoaderLogic
+ searchParams: Record<string, any> // router
+ currentTeamId: number | null // teamLogic
+ backLink: LabeledLink
+ canViewInThread: boolean
+ detailData: NodeDetailData | null
+ detailTab: NodeDetailTab
+ errorMessage: string
+ header: TraceHeaderProps | null
+ heavyDataLookups: AIDataLookup[]
+ mode: TraceMode
+ selectedNodeId: string | null
+ selectedTreeNode: TraceTreeNode | null
+ status: 'error' | 'loading' | 'ready'
+ summary: TraceSummaryBarProps | null
+ thread: ConversationState
+ timeline: {
+ rows: TimelineRowData[]
+ totalMs: number
+ }
+ tree: TraceTreeNode[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceViewAdapterLogicActions {
+ ensureAIDataLoaded: (lookups: AIDataLookup[]) => {
+ lookups: AIDataLookup[]
+ } // aiObservabilityAIDataLogic
+ setEventId: (eventId: string | null) => {
+ eventId: string | null
+ } // aiObservabilityTraceLogic
+ selectAndShowSpans: (id: string) => {
+ id: string
+ }
+ selectNode: (id: string) => {
+ id: string
+ }
+ setDetailTab: (tab: NodeDetailTab) => {
+ tab: NodeDetailTab
+ }
+ setMode: (mode: TraceMode) => {
+ mode: TraceMode
+ }
+ viewInThread: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceViewAdapterLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ status: (
+ trace: LLMTrace | undefined,
+ response:
+ | ErrorTrackingQueryResponse
+ | HogQLAutocompleteResponse
+ | HogQLMetadataResponse
+ | HogQLQueryResponse<any[]>
+ | HogQueryResponse
+ | LogAttributesQueryResponse
+ | LogValuesQueryResponse
+ | MetricsQueryResponse
+ | Record<string, any>
+ | SessionsQueryResponse
+ | TraceSpansAggregationQueryResponse
+ | TraceSpansAttributeBreakdownQueryResponse
+ | TraceSpansQueryResponse
+ | TraceSpansTreeQueryResponse
+ | null,
+ responseLoading: boolean,
+ responseError: string | null
+ ) => 'error' | 'loading' | 'ready'
+ errorMessage: (responseError: string | null) => string
+ tree: (trace: LLMTrace | undefined, enrichedTree: EnrichedTraceTreeNode[]) => TraceTreeNode[]
+ selectedNodeId: (event: LLMTrace | LLMTraceEvent | null, traceId: string) => string | null
+ selectedTreeNode: (tree: TraceTreeNode[], selectedNodeId: string | null) => TraceTreeNode | null
+ backLink: (searchParams: Record<string, any>) => LabeledLink
+ header: (
+ trace: LLMTrace | undefined,
+ olderTraceId: string | null,
+ olderTimestamp: string | null,
+ newerTraceId: string | null,
+ newerTimestamp: string | null,
+ searchParams: Record<string, any>
+ ) => TraceHeaderProps | null
+ summary: (
+ trace: LLMTrace | undefined,
+ personsCache: Record<string, LLMTracePerson | null>
+ ) => TraceSummaryBarProps | null
+ detailData: (
+ trace: LLMTrace | undefined,
+ event: LLMTrace | LLMTraceEvent | null,
+ tree: TraceTreeNode[],
+ selectedTreeNode: TraceTreeNode | null,
+ aiDataCache: Record<string, AIData | null>,
+ generationEvaluationRuns: EvaluationRun[],
+ generationEvaluationRunsLoading: boolean,
+ evaluations: EvaluationConfig[],
+ detectorEvaluationIds: string[],
+ evaluationsSettled: boolean,
+ currentTeamId: number | null,
+ personsCache: Record<string, LLMTracePerson | null>
+ ) => NodeDetailData | null
+ thread: (
+ trace: LLMTrace | undefined,
+ aiDataCache: Record<string, AIData | null>,
+ currentTeamId: number | null
+ ) => ConversationState
+ timeline: (
+ trace: LLMTrace | undefined,
+ tree: TraceTreeNode[]
+ ) => {
+ rows: TimelineRowData[]
+ totalMs: number
+ }
+ canViewInThread: (selectedNodeId: string | null, thread: ConversationState, traceId: string) => boolean
+ heavyDataLookups: (trace: LLMTrace | undefined, event: LLMTrace | LLMTraceEvent | null) => AIDataLookup[]
+ }
+}
+
+export type traceViewAdapterLogicType = MakeLogicType<
+ traceViewAdapterLogicValues,
+ traceViewAdapterLogicActions,
+ TraceViewAdapterLogicProps,
+ traceViewAdapterLogicMeta
+>
+
+export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
+ path((key) => ['products', 'ai_observability', 'frontend', 'redesign', 'trace', 'traceViewAdapterLogic', key]),
+ props({} as TraceViewAdapterLogicProps),
+ key((props) => props.traceId),
+ connect((props: TraceViewAdapterLogicProps) => ({
+ values: [
+ aiObservabilityTraceLogic,
+ ['olderTraceId', 'olderTimestamp', 'newerTraceId', 'newerTimestamp'],
+ aiObservabilityTraceDataLogic({
+ traceId: props.traceId,
+ query: props.query,
+ cachedResults: null,
+ searchQuery: '',
+ }),
+ ['trace', 'event', 'enrichedTree', 'response', 'responseLoading', 'responseError'],
+ aiObservabilityAIDataLogic,
+ ['aiDataCache'],
+ generationEvaluationRunsLogic({ traceId: props.traceId }),
+ ['generationEvaluationRuns', 'generationEvaluationRunsLoading'],
+ teamLogic,
+ ['currentTeamId'],
+ llmPersonsLazyLoaderLogic,
+ ['personsCache'],
+ llmEvaluationsLogic,
+ ['evaluations', 'detectorEvaluationIds', 'evaluationsSettled'],
+ router,
+ ['searchParams'],
+ ],
+ actions: [aiObservabilityTraceLogic, ['setEventId'], aiObservabilityAIDataLogic, ['ensureAIDataLoaded']],
+ })),
+ actions({
+ setMode: (mode: TraceMode) => ({ mode }),
+ setDetailTab: (tab: NodeDetailTab) => ({ tab }),
+ selectNode: (id: string) => ({ id }),
+ selectAndShowSpans: (id: string) => ({ id }),
+ viewInThread: true,
+ }),
+ reducers({
+ mode: [
+ 'spans' as TraceMode,
+ {
+ setMode: (_, { mode }) => mode,
+ selectAndShowSpans: () => 'spans',
+ viewInThread: () => 'thread',
+ },
+ ],
+ detailTab: ['messages' as NodeDetailTab, { setDetailTab: (_, { tab }) => tab }],
+ }),
+ selectors({
+ status: [
+ (s) => [s.trace, s.response, s.responseLoading, s.responseError],
+ (
+ trace: LLMTrace | undefined,
+ response: unknown,
+ responseLoading: boolean,
+ responseError: string | null
+ ): 'loading' | 'error' | 'ready' => {
+ if (trace) {
+ return 'ready'
+ }
+ return responseError || (response && !responseLoading) ? 'error' : 'loading'
+ },
+ ],
+ errorMessage: [
+ (s) => [s.responseError],
+ (responseError: string | null): string =>
+ responseError
+ ? 'Something went wrong while loading it. Try again in a moment.'
+ : 'It may have been deleted, or it is outside the retention period.',
+ ],
+ tree: [
+ (s) => [s.trace, s.enrichedTree],
+ (trace: LLMTrace | undefined, enrichedTree: EnrichedTraceTreeNode[]): TraceTreeNode[] =>
+ trace ? toTraceTree(trace, enrichedTree) : [],
+ ],
+ selectedNodeId: [
+ (s, p) => [s.event, p.traceId],
+ (event: LLMTrace | LLMTraceEvent | null, traceId: string): string | null =>
+ event ? (isLLMEvent(event) ? event.id : traceId) : null,
+ ],
+ selectedTreeNode: [
+ (s) => [s.tree, s.selectedNodeId],
+ (tree: TraceTreeNode[], selectedNodeId: string | null): TraceTreeNode | null =>
+ selectedNodeId ? findTreeNode(tree, selectedNodeId) : null,
+ ],
+ backLink: [
+ (s) => [s.searchParams],
+ (searchParams: Record<string, unknown>): LabeledLink => toBackLink(searchParams),
+ ],
+ header: [
+ (s) => [s.trace, s.olderTraceId, s.olderTimestamp, s.newerTraceId, s.newerTimestamp, s.searchParams],
+ (
+ trace: LLMTrace | undefined,
+ olderTraceId: string | null,
+ olderTimestamp: string | null,
+ newerTraceId: string | null,
+ newerTimestamp: string | null,
+ searchParams: Record<string, unknown>
+ ): TraceHeaderProps | null =>
+ trace
+ ? toHeader(trace, { olderTraceId, olderTimestamp, newerTraceId, newerTimestamp }, searchParams)
+ : null,
+ ],
+ summary: [
+ (s) => [s.trace, s.personsCache],
+ (
+ trace: LLMTrace | undefined,
+ personsCache: Record<string, LLMTracePerson | null>
+ ): TraceSummaryBarProps | null => (trace ? toSummary(trace, personsCache[trace.distinctId] ?? null) : null),
+ ],
+ detailData: [
+ (s) => [
+ s.trace,
+ s.event,
+ s.tree,
+ s.selectedTreeNode,
+ s.aiDataCache,
+ s.generationEvaluationRuns,
+ s.generationEvaluationRunsLoading,
+ s.evaluations,
+ s.detectorEvaluationIds,
+ s.evaluationsSettled,
+ s.currentTeamId,
+ s.personsCache,
+ ],
+ (
+ trace: LLMTrace | undefined,
+ event: LLMTrace | LLMTraceEvent | null,
+ tree: TraceTreeNode[],
+ node: TraceTreeNode | null,
+ cache: Record<string, AIData | null>,
+ evalRuns: EvaluationRun[],
+ evalRunsLoading: boolean,
+ evaluations: EvaluationConfig[],
+ detectorEvaluationIds: string[],
+ evaluationsSettled: boolean,
+ teamId: number | null,
+ personsCache: Record<string, LLMTracePerson | null>
+ ): NodeDetailData | null =>
+ trace && event && node
+ ? toNodeDetail({
+ trace,
+ event,
+ tree,
+ node,
+ cache,
+ evalRuns,
+ evalRunsLoading,
+ evaluations,
+ detectorEvaluationIds,
+ evaluationsSettled,
+ teamId,
+ person: personsCache[trace.distinctId] ?? null,
+ })
+ : null,
+ ],
+ thread: [
+ (s) => [s.trace, s.aiDataCache, s.currentTeamId],
+ (
+ trace: LLMTrace | undefined,
+ cache: Record<string, AIData | null>,
+ teamId: number | null
+ ): ConversationState => (trace ? toThread(trace, cache, teamId) : { status: 'loading' }),
+ ],
+ timeline: [
+ (s) => [s.trace, s.tree],
+ (trace: LLMTrace | undefined, tree: TraceTreeNode[]): { rows: TimelineRowData[]; totalMs: number } =>
+ trace ? toTimeline(trace, tree) : { rows: [], totalMs: 0 },
+ ],
+ canViewInThread: [
+ (s, p) => [s.selectedNodeId, s.thread, p.traceId],
+ (selectedNodeId: string | null, thread: ConversationState, traceId: string): boolean => {
+ if (!selectedNodeId) {
+ return false
+ }
+ if (selectedNodeId === traceId) {
+ return true
+ }
+ const turnMessages = thread.status === 'ready' ? (thread.turns[0]?.messages ?? []) : []
+ return turnMessages.some((message) => message.sourceNodeId === selectedNodeId)
+ },
+ ],
+ heavyDataLookups: [
+ (s) => [s.trace, s.event],
+ (trace: LLMTrace | undefined, event: LLMTrace | LLMTraceEvent | null): AIDataLookup[] => {
+ if (!trace) {
+ return []
+ }
+ const candidates = [event && isLLMEvent(event) ? event : null, pickUserVisibleTurn(trace) ?? null]
+ return candidates
+ .map((candidate) => (candidate ? heavyDataLookup(candidate, trace.id) : null))
+ .filter((lookup): lookup is AIDataLookup => lookup !== null)
+ },
+ ],
+ }),
+ listeners(({ actions }) => ({
+ selectNode: ({ id }) => actions.setEventId(id),
+ selectAndShowSpans: ({ id }) => actions.setEventId(id),
+ })),
+ subscriptions(({ actions }) => ({
+ heavyDataLookups: (lookups: AIDataLookup[]) => {
+ if (lookups.length > 0) {
+ actions.ensureAIDataLoaded(lookups)
+ }
+ },
+ })),
+ afterMount(() => {
+ // The legacy scene writes a `search` param into shared trace links. This view has no
+ // search UI, so without clearing it the tree silently filters down to whatever the
+ // stale query matched. Removing only that param keeps every other permalink param, and
+ // the legacy trace logic reads the new URL and clears its search query.
+ const { search, ...searchParams } = router.values.searchParams
+ if (search !== undefined) {
+ router.actions.replace(router.values.location.pathname, searchParams, router.values.hashParams)
+ }
+ }),
+])