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(llma): add trace timeline to trace and drawer views (#66466)

Marco Gancitanof5338719f318
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a8e2367c7147..a209e71ea736 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4817,17 +4817,17 @@ snapshots:
scenes-app-ai-observability-skills--skill-detail-stacked-below-2-xl-breakpoint--wide--light:
hash: v1.k794b7964.c11f045bc7ed6084b7f7f19bd99149c5111512aeb77416ef125fb1a41aeb77e8.98xhehD94Y0U5Psv6_cm1LcBdamkWuJOZUCT_LcPTls
scenes-app-ai-observability-trace--full--dark:
- hash: v1.k794b7964.f3e72c88a2a806c0ada39895dbcb456e7fe0f2189713f5846c79d4dc2b4026a8.Z_3G8LMuQ_pQQaDePYPaFL5wAiunP8cEZ8kL52Vbb3Y
+ hash: v1.k794b7964.325f925fcd4c305ed13592f3fdce3cc5d2a4671f259a6733eebc370ecffabf88.Ja1u6az53dW27qeRxcaqlMfMUTM-0CDpc6mRbLmd1-o
scenes-app-ai-observability-trace--full--light:
- hash: v1.k794b7964.b6ea320a50592371cb2a4f6aa3f81192aaf3a675ac7fb08df78e27596871bdda.3k3rkENV3F2ClFoDU-_wVpGe3ay0NxKYB4wF6ssRrIw
+ hash: v1.k794b7964.45e6ff0d8cbe572d69536cd7f44cee15983d3d90a2b5ed9cee21cb9ec43b5c0e.dB-uNSPlFosn9cUw9jjL2wlVsNfi4CESFNj70mDuUKU
scenes-app-ai-observability-trace--full-specific-event--dark:
- hash: v1.k794b7964.147fcebe3ce95ee9db0a6360c9423ee120ef7636ec77a4cd0fa9c13dce090f9d.wQRrIzJvdhUpisPPYZqv1R7f1bGl250VfPbGe62ricw
+ hash: v1.k794b7964.d97bb3a4e3897d2af5b314c91e68d610ee269fd1315947e4713bbb7ff87c6225.AU0MzOpLLIA5WT_Of0rUy4SrO-LGDJGxNpRKf2_cmHM
scenes-app-ai-observability-trace--full-specific-event--light:
- hash: v1.k794b7964.f15a66b4ed9897f64d1597917843b550b1f06c36f5aec4f67ce7f3d4677fef77.J74xHKaJNErZoO1bYLUu8WG9AWbpLyDAxVXgn8v6slQ
+ hash: v1.k794b7964.54ea513f3a8c58cf5df9287dc95a879d0b771b12b3913fca40227741703fa72f.GyAqqNLhD27t5U1Snyzp8nf9C_VTaFobf0dPkO0iRzI
scenes-app-ai-observability-trace--without-content--dark:
- hash: v1.k794b7964.c376c545e9caa6a8d454e22a74de021ead383aa3aca9ff57fa72aa0130d11c82.aBt9cxRtKR-opOoD3OqZAp7-sbnA8S10HFWuHPavrYk
+ hash: v1.k794b7964.43c0a5235771b6bdb554e89d09b43f6aa3603ed7ebe2e0d84858e0d2c15eb278.yNl0wPG__RV5KWRQSSk1AAiPFcFBXftZFMuYZ9uXZeY
scenes-app-ai-observability-trace--without-content--light:
- hash: v1.k794b7964.84327a51677f1395a6dbc17d0901c4c8db451fbf8fdb05a965947f8940efeae6.ENQZswYy8KpOHX_PfyPwO_9t_C88UkyFfde12FPNyoA
+ hash: v1.k794b7964.2323b84137ee00e4c878b51c9c1c67feaa0b32e3ed1e02d3eff1614a8a71eb13.BVOCgmldcwW_4jjNPlSgjd9FUYrVrAp7x2qkjKKM3RA
scenes-app-aigateway--empty--dark:
hash: v1.k794b7964.a79751753cae893fcc58a4c977084260de54c1cedfbaf95e007c24e17b349bc0.P3gRNI2aaymd2jiM8kkbBUuRCvPxY4EGX66u3hdLODw
scenes-app-aigateway--empty--light:
@@ -6711,7 +6711,7 @@ snapshots:
scenes-app-settings-organization--settings-organization-details--dark:
hash: v1.k794b7964.42bb07ba29e5727f687fd3792eff1df7c8cb4b536343c95d9e51658a89677e3e.cGfJpWmm01Oxd5JLWEfkzexgdZI7AGiVVPdWvziNzPI
scenes-app-settings-organization--settings-organization-details--light:
- hash: v1.k794b7964.8e9901f5a372bee2463d7886081867b4ac7d138fbd89210b9f266cbe3c3a665e.czZ02t4o4RI4Nwrl6F2ZxBHS9yNPgY9CpEBwu3mu0fs
+ hash: v1.k794b7964.5832cdd23724d21e797adaeb677a0ee983e7e61bd3ec7095aff87966b99a3f3b.hqLxN9o3Ki2bs4ZUCNCgCF07IvOl6mm-DzG0H3ku2S8
scenes-app-settings-organization--settings-organization-members--dark:
hash: v1.k794b7964.9b7c856187e6b01c2abe4dfcfcba4593258de828b3a289d2924cfcf1fb5497dc.n-Z_pbWeZvSzYjKOkvb-ajQi97HcZHzhXCPKhN6M1g0
scenes-app-settings-organization--settings-organization-members--light:
diff --git a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx b/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
index 6dc033179f05..ecf196860c91 100644
--- a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilitySessionScene.tsx
@@ -31,6 +31,7 @@ import { SentimentBar } from './components/SentimentTag'
import { SessionPlayerControls } from './components/SessionPlayer/SessionPlayerControls'
import { SessionSeekbar } from './components/SessionPlayer/SessionSeekbar'
import { TypingIndicator } from './components/SessionPlayer/TypingIndicator'
+import { TraceTimeline } from './components/TraceTimeline/TraceTimeline'
import { TranscriptBubbleStream } from './ConversationDisplay/TranscriptBubbleStream'
import { SessionTurn } from './extractSessionTurns'
import { llmSessionTitleLazyLoaderLogic } from './llmSessionTitleLazyLoaderLogic'
@@ -105,9 +106,8 @@ function SessionSceneWrapper({ showBreadcrumb = false }: { showBreadcrumb?: bool
expandedGenerationIds,
} = useValues(aiObservabilitySessionDataLogic)
const { sessionId, dateRange } = useValues(aiObservabilitySessionLogic)
- const { summarizeAllTraces, loadNextData, closeStepsDrawer, toggleGenerationExpanded } = useActions(
- aiObservabilitySessionDataLogic
- )
+ const { summarizeAllTraces, loadNextData, closeStepsDrawer, toggleGenerationExpanded, focusGenerationExpanded } =
+ useActions(aiObservabilitySessionDataLogic)
const { dataProcessingAccepted } = useValues(maxGlobalLogic)
const { getSessionTitle } = useValues(llmSessionTitleLazyLoaderLogic)
const { ensureSessionTitleLoaded } = useActions(llmSessionTitleLazyLoaderLogic)
@@ -314,6 +314,13 @@ function SessionSceneWrapper({ showBreadcrumb = false }: { showBreadcrumb?: bool
>
{drawerTraceId ? (
<div className="flex flex-col gap-3">
+ <TraceTimeline
+ events={fullTraces[drawerTraceId]?.events ?? []}
+ selectedEventId={
+ expandedGenerationIds.size === 1 ? Array.from(expandedGenerationIds)[0] : null
+ }
+ onSelectEvent={focusGenerationExpanded}
+ />
<AIObservabilityTraceEvents
trace={fullTraces[drawerTraceId]}
isLoading={loadingFullTraces.has(drawerTraceId)}
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.scss b/products/ai_observability/frontend/AIObservabilityTraceScene.scss
index 37015dce325d..d1bee0817f2b 100644
--- a/products/ai_observability/frontend/AIObservabilityTraceScene.scss
+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.scss
@@ -1,8 +1,9 @@
-// Constrain the trace scene to fill the visible area below the breadcrumbs on
-// desktop, so the trace tree and event content panels can scroll independently
-// instead of sharing a single page-level scroll.
+// Constrain the trace scene to fill the visible area below the scene layout
+// header on desktop, so the trace tree and event content panels can scroll
+// independently instead of sharing a single page-level scroll. Subtracts the
+// scene layout header plus the scene padding applied above and below the wrapper.
.AIObservabilityTraceScene__wrapper {
@media screen and (min-width: 768px) {
- height: calc(100vh - var(--breadcrumbs-height-full) - var(--scene-padding) - var(--scene-padding-bottom));
+ height: calc(100dvh - var(--scene-layout-header-height) - var(--scene-padding) * 2);
}
}
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
index 07b38c712684..af0d44415a45 100644
--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
@@ -74,6 +74,7 @@ import { JSONValueDisplay } from './components/JSONValueDisplay'
import { MetricTag } from './components/MetricTag'
import { SentimentBar } from './components/SentimentTag'
import { TagsTabContent } from './components/TagsTabContent'
+import { TraceTimeline } from './components/TraceTimeline/TraceTimeline'
import {
ConversationDisplayOption,
ConversationMessagesDisplay,
@@ -442,6 +443,7 @@ function TraceSceneWrapper(): JSX.Element {
const traceDataLogic = useMountedLogic(aiObservabilityTraceDataLogic)
useMountedLogic(traceReviewsLazyLoaderLogic)
const { traceId, searchQuery, commentCount, viewMode } = useValues(traceLogic)
+ const { setEventId } = useActions(traceLogic)
const { searchParams } = useValues(router)
const {
enrichedTree,
@@ -537,6 +539,11 @@ function TraceSceneWrapper(): JSX.Element {
</div>
</div>
</div>
+ <TraceTimeline
+ events={trace.events}
+ selectedEventId={effectiveEventId ?? null}
+ onSelectEvent={setEventId}
+ />
<div className="flex flex-1 min-h-0 gap-3 flex-col md:flex-row">
<TraceSidebar
trace={trace}
@@ -1095,10 +1102,7 @@ function TraceSidebar({
}
return (
- <aside
- className="flex flex-col gap-3 w-full md:w-80 md:min-h-0 md:self-start md:max-h-full"
- id="trace-events-sidebar"
- >
+ <aside className="flex flex-col gap-3 w-full md:w-80 md:min-h-0" id="trace-events-sidebar">
<TraceWorkflowPanel traceId={trace.id} />
<div className="border border-primary bg-surface-primary rounded overflow-hidden flex flex-col flex-1 min-h-0">
<h3 className="font-medium text-sm px-2 my-2">Tree</h3>
@@ -1495,7 +1499,7 @@ const EventContent = React.memo(
}
return (
- <div className="flex-1 min-h-0 md:min-w-0 md:self-start md:max-h-full bg-surface-primary border rounded flex flex-col border-primary p-4 overflow-y-auto">
+ <div className="flex-1 min-h-0 md:min-w-0 bg-surface-primary border rounded flex flex-col border-primary p-4 overflow-y-auto">
{!event ? (
<InsightEmptyState heading="Event not found" detail="Check if the event ID is correct." />
) : (
diff --git a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx b/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
index 45026dcf2b29..688a6b211e42 100644
--- a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
@@ -30,7 +30,6 @@ import {
formatLLMCost,
formatLLMLatency,
formatLLMUsage,
- getTraceStepCount,
getTraceTimestamp,
LLM_TRACES_PAGE_SIZE,
sanitizeTraceUrlSearchParams,
@@ -176,12 +175,6 @@ export const useTracesQueryContext = (): QueryContext<DataTableNode> => {
renderTitle: () => <Tooltip title="Number of errors in this trace">Errors</Tooltip>,
render: ErrorsColumn,
},
- stepCount: {
- renderTitle: () => (
- <Tooltip title="Number of steps (generations, spans, embeddings) in this trace">Steps</Tooltip>
- ),
- render: StepsColumn,
- },
totalLatency: {
renderTitle: () => <Tooltip title="Total latency of all operations in this trace">Latency</Tooltip>,
render: LatencyColumn,
@@ -341,16 +334,6 @@ const ErrorsColumn: QueryContextColumnComponent = ({ record }) => {
}
ErrorsColumn.displayName = 'ErrorsColumn'
-const StepsColumn: QueryContextColumnComponent = ({ record }) => {
- const row = record as LLMTrace
- return (
- <Tooltip title="Number of steps (generations, spans, embeddings) in this trace">
- <span>{getTraceStepCount(row)}</span>
- </Tooltip>
- )
-}
-StepsColumn.displayName = 'StepsColumn'
-
// `undefined` = cache miss (still loading). Checking the cached record
// directly avoids a one-frame dash flash before a separate loading reducer
// catches up on the first render.
diff --git a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts
index f7b634c5cbeb..69ec5ec76f50 100644
--- a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts
@@ -29,7 +29,7 @@ import {
findSidebarOccurrences,
findTraceOccurrences,
} from './searchUtils'
-import { formatLLMUsage, getEventType, getSessionID, isLLMEvent } from './utils'
+import { formatLLMUsage, getEventType, getSessionID, isLLMEvent, operationStartMs } from './utils'
export interface TraceDataLogicProps {
traceId: string
@@ -717,6 +717,21 @@ export function restoreTree(events: LLMTraceEvent[], traceId: string): TraceTree
}
}
+ // Order siblings by when their operation began (longer first on ties),
+ // matching the timeline — events are captured at completion, so raw
+ // timestamp order can differ.
+ const byOperationStart = (a: string, b: string): number => {
+ const eventA = idMap.get(a)
+ const eventB = idMap.get(b)
+ if (!eventA || !eventB) {
+ return 0
+ }
+ return (
+ operationStartMs(eventA) - operationStartMs(eventB) ||
+ (Number(eventB.properties.$ai_latency) || 0) - (Number(eventA.properties.$ai_latency) || 0)
+ )
+ }
+
function traverse(spanId: any): TraceTreeNode | null {
if (visitedNodes.has(spanId)) {
console.warn('Circular reference detected in trace tree:', spanId)
@@ -732,7 +747,11 @@ export function restoreTree(events: LLMTraceEvent[], traceId: string): TraceTree
const children = childrenMap.get(spanId)
const result: TraceTreeNode = {
event,
- children: children?.map((child) => traverse(child)).filter((node): node is TraceTreeNode => node !== null),
+ children: children
+ ?.slice()
+ .sort(byOperationStart)
+ .map((child) => traverse(child))
+ .filter((node): node is TraceTreeNode => node !== null),
}
if (result.children && result.children.length > 0 && event.event !== '$ai_generation') {
@@ -744,6 +763,6 @@ export function restoreTree(events: LLMTraceEvent[], traceId: string): TraceTree
}
const directChildren = childrenMap.get(traceId) || []
- const rootIds = [...directChildren, ...findOrphanedRoots(idMap, traceId)]
+ const rootIds = [...directChildren, ...findOrphanedRoots(idMap, traceId)].sort(byOperationStart)
return rootIds.map((childId) => traverse(childId)).filter((node): node is TraceTreeNode => node !== null)
}
diff --git a/products/ai_observability/frontend/components/AIObservabilityTraceEvents.tsx b/products/ai_observability/frontend/components/AIObservabilityTraceEvents.tsx
index b0f0ad6c61b3..9973b7a7f400 100644
--- a/products/ai_observability/frontend/components/AIObservabilityTraceEvents.tsx
+++ b/products/ai_observability/frontend/components/AIObservabilityTraceEvents.tsx
@@ -2,6 +2,7 @@ import { Spinner } from 'lib/lemon-ui/Spinner'
import { LLMTrace } from '~/queries/schema/schema-general'
+import { operationStartMs } from '../utils'
import { AIObservabilityEventCard } from './AIObservabilityEventCard'
interface AIObservabilityTraceEventsProps {
@@ -28,7 +29,8 @@ export function AIObservabilityTraceEvents({
const allEvents =
trace.events
?.filter((e) => e.event === '$ai_generation' || e.event === '$ai_span' || e.event === '$ai_embedding')
- .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()) || []
+ // Order by operation start (events are captured at completion), matching the timeline
+ .sort((a, b) => operationStartMs(a) - operationStartMs(b)) || []
if (allEvents.length === 0) {
return (
diff --git a/products/ai_observability/frontend/components/TraceTimeline/TraceTimeline.tsx b/products/ai_observability/frontend/components/TraceTimeline/TraceTimeline.tsx
new file mode 100644
index 000000000000..619e67b0c3a9
--- /dev/null
+++ b/products/ai_observability/frontend/components/TraceTimeline/TraceTimeline.tsx
@@ -0,0 +1,234 @@
+import { useActions, useValues } from 'kea'
+import { useMemo, useState } from 'react'
+
+import { IconChevronDown, IconExpand45 } from '@posthog/icons'
+import { LemonButton, LemonModal, Tooltip } from '@posthog/lemon-ui'
+
+import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'
+import { cn } from 'lib/utils/css-classes'
+
+import { LLMTraceEvent } from '~/queries/schema/schema-general'
+
+import { TraceBarKind, TraceTimelineBar, buildTicks, buildTraceTimeline, formatDuration } from './buildTraceTimeline'
+import { traceTimelineLogic } from './traceTimelineLogic'
+
+// Same hues as the tree's EventTypeTag: generation green, embedding amber,
+// span neutral, trace purple. Opaque fills so the gridlines don't show through
+// the bars; selecting a bar amplifies its own hue with a ring, and an error
+// swaps the border to red (amplified the same way when selected).
+const KIND_BAR: Record<TraceBarKind, { fill: string; border: string; ring: string }> = {
+ generation: { fill: 'bg-fill-success-secondary text-success', border: 'border-success', ring: 'ring-success' },
+ span: { fill: 'bg-fill-secondary text-secondary', border: 'border-primary', ring: 'ring-[var(--border-bold)]' },
+ embedding: { fill: 'bg-fill-warning-secondary text-warning', border: 'border-warning', ring: 'ring-warning' },
+ trace: { fill: 'bg-fill-secondary text-purple', border: 'border-purple', ring: 'ring-[var(--purple)]' },
+}
+
+const BAR_H = 16
+// Wide enough for the nesting connectors drawn in the gap to stay legible.
+const LANE_GAP = 6
+const LANE_H = BAR_H + LANE_GAP
+// Beyond this many lanes the chart scrolls vertically instead of growing, so a
+// deeply nested trace can't crowd out the rest of the page.
+const MAX_VISIBLE_LANES = 6
+
+export function TraceTimeline({
+ events,
+ selectedEventId,
+ onSelectEvent,
+}: {
+ events: LLMTraceEvent[]
+ selectedEventId: string | null
+ onSelectEvent: (id: string) => void
+}): JSX.Element | null {
+ const { collapsed } = useValues(traceTimelineLogic)
+ const { setCollapsed } = useActions(traceTimelineLogic)
+ const [isFullScreen, setIsFullScreen] = useState(false)
+ const { bars, totalMs, laneCount } = useMemo(() => buildTraceTimeline(events), [events])
+ // One └ hook per parent per row, anchored at that row's first child — a row
+ // of siblings shares a single connector instead of one hook per bar.
+ const elbows = useMemo(() => {
+ const barById = new Map(bars.map((b) => [b.id, b]))
+ const seen = new Set<string>()
+ const result: { child: TraceTimelineBar; parent: TraceTimelineBar }[] = []
+ // bars are sorted by lane then startMs, so the first hit per key is the
+ // row's earliest child.
+ for (const bar of bars) {
+ const parent = bar.parentEventId ? barById.get(bar.parentEventId) : undefined
+ if (!parent || parent.lane >= bar.lane) {
+ continue
+ }
+ const key = `${bar.parentEventId}:${bar.lane}`
+ if (!seen.has(key)) {
+ seen.add(key)
+ result.push({ child: bar, parent })
+ }
+ }
+ return result
+ }, [bars])
+
+ // Nothing to draw without at least one bar of nonzero width.
+ if (!bars.length || totalMs <= 0) {
+ return null
+ }
+
+ const ticks = buildTicks(totalMs)
+ const presentKinds = Array.from(new Set(bars.map((b) => b.kind)))
+ const hasErrors = bars.some((b) => b.isError)
+ const pct = (ms: number): number => (ms / totalMs) * 100
+ const chartHeight = laneCount * LANE_H - LANE_GAP
+
+ // Rendered inline (capped height) and inside the full-screen modal (viewport height).
+ const renderCanvas = (maxHeight: number | string): JSX.Element => (
+ <div className="px-3 pb-2">
+ <div className="relative h-4 mb-1.5 text-[10px] leading-4 text-muted">
+ {ticks.map((tick) => (
+ <span
+ key={tick}
+ className={cn('absolute whitespace-nowrap', tick > 0 && '-translate-x-1/2')}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ left: `${pct(tick)}%` }}
+ >
+ {formatDuration(tick)}
+ </span>
+ ))}
+ </div>
+ {/* The negative margin + matching padding move the clip edge out by
+ 2px without shifting the canvas, so the outer state rings on bars
+ at the chart's edges don't get clipped. The scroll shadows signal
+ when more lanes hide beyond the height cap. */}
+ <ScrollableShadows
+ direction="vertical"
+ className="-m-0.5"
+ innerClassName="p-0.5"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ maxHeight }}
+ >
+ {/* eslint-disable-next-line react/forbid-dom-props */}
+ <div className="relative" style={{ height: chartHeight }}>
+ {ticks.slice(1).map((tick) => (
+ <div
+ key={tick}
+ aria-hidden
+ className="absolute top-0 bottom-0 border-l border-primary opacity-60"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ left: `${pct(tick)}%` }}
+ />
+ ))}
+ {elbows.map(({ child, parent }) => {
+ const elbowTop = parent.lane * LANE_H + BAR_H + 1
+ return (
+ // └-shaped elbow from the parent's underside into the
+ // row's first child, directory-tree style.
+ <div
+ key={`elbow-${child.id}`}
+ aria-hidden
+ className="absolute w-1 rounded-bl-sm border-l border-b border-border-bold"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ left: `calc(${pct(child.startMs)}% - 4px)`,
+ top: elbowTop,
+ height: child.lane * LANE_H + BAR_H / 2 - elbowTop,
+ }}
+ />
+ )
+ })}
+ {bars.map((bar) => {
+ const isInstant = bar.durationMs <= 0
+ const selected = selectedEventId === bar.id
+ const dur = isInstant ? undefined : formatDuration(bar.durationMs)
+ const tooltip = [bar.label, dur, bar.isError ? 'error' : undefined].filter(Boolean).join(' · ')
+ return (
+ <Tooltip key={bar.id} title={tooltip}>
+ <button
+ type="button"
+ onClick={() => onSelectEvent(bar.id)}
+ aria-label={tooltip}
+ className={cn(
+ 'absolute flex items-center overflow-hidden rounded-[3px] border cursor-pointer',
+ KIND_BAR[bar.kind].fill,
+ bar.isError ? 'border-danger' : KIND_BAR[bar.kind].border,
+ selected && [
+ 'ring-2 z-10',
+ bar.isError ? 'ring-danger' : KIND_BAR[bar.kind].ring,
+ ]
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ left: `${pct(bar.startMs)}%`,
+ width: isInstant ? 3 : `max(${pct(bar.durationMs)}%, 3px)`,
+ top: bar.lane * LANE_H,
+ height: BAR_H,
+ }}
+ data-attr="trace-timeline-bar"
+ >
+ {/* Truncates to the bar; the padding swallows it entirely on
+ slivers. The tooltip always carries the full text. */}
+ {!isInstant && (
+ <span className="px-1 text-[10px] leading-none font-medium truncate">
+ {bar.label} <span className="opacity-70">{dur}</span>
+ </span>
+ )}
+ </button>
+ </Tooltip>
+ )
+ })}
+ </div>
+ </ScrollableShadows>
+ </div>
+ )
+
+ return (
+ <div className="border rounded bg-surface-primary shrink-0" data-attr="trace-timeline">
+ <div className="flex items-center gap-2 px-2 py-1">
+ <LemonButton
+ size="xsmall"
+ icon={<IconChevronDown className={cn('transition-transform', collapsed && '-rotate-90')} />}
+ onClick={() => setCollapsed(!collapsed)}
+ aria-label={collapsed ? 'Expand timeline' : 'Collapse timeline'}
+ />
+ <span className="text-sm font-semibold">
+ Timeline <span className="text-muted font-normal">({formatDuration(totalMs)})</span>
+ </span>
+ <div className="flex-1" />
+ {!collapsed && (
+ <div className="hidden sm:flex items-center gap-3 pr-1 text-xs text-muted">
+ {presentKinds.map((kind) => (
+ <span key={kind} className="flex items-center gap-1">
+ <span
+ className={cn(
+ 'w-2.5 h-2.5 rounded-[3px] border',
+ KIND_BAR[kind].fill,
+ KIND_BAR[kind].border
+ )}
+ />
+ {kind}
+ </span>
+ ))}
+ {hasErrors && (
+ <span className="flex items-center gap-1">
+ <span className="w-2.5 h-2.5 rounded-[3px] border border-danger bg-fill-secondary" />
+ error
+ </span>
+ )}
+ </div>
+ )}
+ <LemonButton
+ size="xsmall"
+ icon={<IconExpand45 />}
+ onClick={() => setIsFullScreen(true)}
+ tooltip="Expand timeline"
+ aria-label="Expand timeline full screen"
+ />
+ </div>
+ {!collapsed && renderCanvas(MAX_VISIBLE_LANES * LANE_H - LANE_GAP + 4)}
+ <LemonModal
+ isOpen={isFullScreen}
+ onClose={() => setIsFullScreen(false)}
+ fullScreen
+ title={`Timeline (${formatDuration(totalMs)})`}
+ >
+ {renderCanvas('calc(100vh - 11rem)')}
+ </LemonModal>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/components/TraceTimeline/buildTraceTimeline.test.ts b/products/ai_observability/frontend/components/TraceTimeline/buildTraceTimeline.test.ts
new file mode 100644
index 000000000000..01b973bc7b57
--- /dev/null
+++ b/products/ai_observability/frontend/components/TraceTimeline/buildTraceTimeline.test.ts
@@ -0,0 +1,184 @@
+import { LLMTraceEvent } from '~/queries/schema/schema-general'
+
+import { buildTicks, buildTraceTimeline, formatDuration } from './buildTraceTimeline'
+
+const T0 = 1_000_000_000_000
+
+function ev(
+ id: string,
+ event: string,
+ atMs: number,
+ latencySec?: number,
+ props: Record<string, any> = {}
+): LLMTraceEvent {
+ return {
+ id,
+ event,
+ createdAt: new Date(T0 + atMs).toISOString(),
+ properties: {
+ $ai_trace_id: 't1',
+ ...(latencySec !== undefined ? { $ai_latency: latencySec } : {}),
+ ...props,
+ },
+ }
+}
+
+describe('buildTraceTimeline', () => {
+ it('nests SDK events (createdAt = operation end) under their parents, one lane per depth', () => {
+ // Root trace ends at 3000ms, the agent span inside it at 2800ms, the
+ // generation inside that at 1500ms — each bar must start latency before it.
+ const { bars, totalMs, laneCount } = buildTraceTimeline([
+ ev('root', '$ai_trace', 3000, 3, { $ai_span_id: 't1' }),
+ ev('agent', '$ai_span', 2800, 2.5, { $ai_span_id: 's1', $ai_parent_id: 't1' }),
+ ev('gen', '$ai_generation', 1500, 1, {
+ $ai_generation_id: 'g1',
+ $ai_parent_id: 's1',
+ $ai_is_error: true,
+ }),
+ ])
+ expect(bars).toEqual([
+ expect.objectContaining({
+ id: 'root',
+ startMs: 0,
+ durationMs: 3000,
+ lane: 0,
+ kind: 'trace',
+ parentEventId: null,
+ }),
+ expect.objectContaining({
+ id: 'agent',
+ startMs: 300,
+ durationMs: 2500,
+ lane: 1,
+ kind: 'span',
+ parentEventId: 'root',
+ }),
+ expect.objectContaining({
+ id: 'gen',
+ startMs: 500,
+ durationMs: 1000,
+ lane: 2,
+ kind: 'generation',
+ isError: true,
+ parentEventId: 'agent',
+ }),
+ ])
+ expect(totalMs).toBe(3000)
+ expect(laneCount).toBe(3)
+ })
+
+ it('keeps OTel-ingested events (createdAt = span start) at their timestamp', () => {
+ // Same trace as above but stamped at span starts, as the OTel pipeline does —
+ // $ai_ingestion_source marks them, so bars must not be shifted by their latency.
+ const otel = { $ai_ingestion_source: 'otel' }
+ const { bars, totalMs } = buildTraceTimeline([
+ ev('root', '$ai_trace', 0, 3, { $ai_span_id: 't1', ...otel }),
+ ev('agent', '$ai_span', 300, 2.5, { $ai_span_id: 's1', $ai_parent_id: 't1', ...otel }),
+ ev('gen', '$ai_generation', 500, 1, { $ai_generation_id: 'g1', $ai_parent_id: 's1', ...otel }),
+ ])
+ expect(bars).toEqual([
+ expect.objectContaining({ id: 'root', startMs: 0, durationMs: 3000, lane: 0 }),
+ expect.objectContaining({ id: 'agent', startMs: 300, durationMs: 2500, lane: 1 }),
+ expect.objectContaining({ id: 'gen', startMs: 500, durationMs: 1000, lane: 2 }),
+ ])
+ expect(totalMs).toBe(3000)
+ })
+
+ it('spills overlapping siblings into extra sub-lanes and reuses freed ones', () => {
+ const { bars, laneCount } = buildTraceTimeline([
+ ev('root', '$ai_trace', 3000, 3, { $ai_span_id: 't1' }),
+ // g2 [100, 1600] and g1 [200, 1500] overlap in time; g3 [2000, 2900] doesn't.
+ ev('g2', '$ai_generation', 1600, 1.5, { $ai_generation_id: 'g2', $ai_parent_id: 't1' }),
+ ev('g1', '$ai_generation', 1500, 1.3, { $ai_generation_id: 'g1', $ai_parent_id: 't1' }),
+ ev('g3', '$ai_generation', 2900, 0.9, { $ai_generation_id: 'g3', $ai_parent_id: 't1' }),
+ ])
+ const byId = Object.fromEntries(bars.map((b) => [b.id, b]))
+ expect(byId['root'].lane).toBe(0)
+ expect(byId['g2'].lane).not.toBe(byId['g1'].lane)
+ expect(byId['g3'].lane).toBe(byId['g2'].lane) // g2's lane is free again by 2000ms
+ expect(laneCount).toBe(3)
+ })
+
+ it('keeps children directly beneath their parent when an overlapping sibling spills over', () => {
+ // Two concurrent top-level spans (title [1000,5000] and memory [1000,1800]) plus a
+ // later span (root [6000,9000]) with a generation inside. Depth-banded layouts wedge
+ // memory's overflow lane between root and its child; flame packing must not.
+ const { bars, laneCount } = buildTraceTimeline([
+ ev('title', '$ai_span', 5000, 4, { $ai_span_id: 'title' }),
+ ev('title-gen', '$ai_generation', 4900, 3.8, { $ai_generation_id: 'tg', $ai_parent_id: 'title' }),
+ ev('memory', '$ai_span', 1800, 0.8, { $ai_span_id: 'memory' }),
+ ev('root', '$ai_span', 9000, 3, { $ai_span_id: 'root' }),
+ ev('root-gen', '$ai_generation', 8900, 2.8, { $ai_generation_id: 'rg', $ai_parent_id: 'root' }),
+ ])
+ const byId = Object.fromEntries(bars.map((b) => [b.id, b]))
+ expect(byId['root-gen'].lane).toBe(byId['root'].lane + 1) // child hugs its parent
+ expect(byId['title-gen'].lane).toBe(byId['title'].lane + 1)
+ expect(byId['memory'].lane).toBe(2) // pushed below title's whole subtree
+ expect(byId['root'].lane).toBe(0)
+ expect(laneCount).toBe(3)
+ })
+
+ it.each([
+ ['$ai_generation', 'generation'],
+ ['$ai_embedding', 'embedding'],
+ ['$ai_trace', 'trace'],
+ ['$ai_span', 'span'],
+ ['$ai_tool_call', 'span'], // any unrecognized $ai_* event renders as a span, like the tree
+ ])('maps %s to kind %s', (event, kind) => {
+ const { bars } = buildTraceTimeline([ev('a', event, 1000, 1)])
+ expect(bars[0].kind).toBe(kind)
+ })
+
+ it('drops annotation events and renders latency-less events as instant markers', () => {
+ const { bars, totalMs } = buildTraceTimeline([
+ ev('gen', '$ai_generation', 1000, 1),
+ ev('mark', '$ai_span', 500), // no $ai_latency → instant
+ ev('feedback', '$ai_feedback', 1200),
+ ev('metric', '$ai_metric', 1300),
+ ])
+ expect(bars.map((b) => b.id).sort()).toEqual(['gen', 'mark'])
+ expect(bars.find((b) => b.id === 'mark')).toMatchObject({ startMs: 500, durationMs: 0 })
+ expect(totalMs).toBe(1000)
+ })
+
+ it('treats latencies that overflow to Infinity as instant instead of hanging the axis', () => {
+ // 1e306 seconds is finite, but * 1000 overflows to Infinity — an
+ // unclamped value makes totalMs Infinity and the tick loop never ends.
+ const { bars, totalMs } = buildTraceTimeline([
+ ev('big', '$ai_generation', 1000, 1e306, { $ai_ingestion_source: 'otel' }),
+ ev('ok', '$ai_generation', 2000, 1),
+ ])
+ expect(bars.find((b) => b.id === 'big')?.durationMs).toBe(0)
+ expect(isFinite(totalMs)).toBe(true)
+ })
+
+ it('ignores non-string span names and models when labeling', () => {
+ // Sender-controlled properties can be malformed objects; rendering one
+ // as a React child crashes the scene.
+ const { bars } = buildTraceTimeline([
+ ev('a', '$ai_generation', 1000, 1, { $ai_span_name: { nested: true }, $ai_model: 'gpt-4.1' }),
+ ])
+ expect(bars[0].label).toBe('gpt-4.1')
+ })
+
+ it('returns empty for no events', () => {
+ expect(buildTraceTimeline([])).toEqual({ bars: [], totalMs: 0, laneCount: 0 })
+ })
+
+ it.each([
+ [250_000, [0, 60_000, 120_000, 180_000, 240_000]], // a ~4m trace ticks whole minutes, not 50s steps
+ [47_800, [0, 10_000, 20_000, 30_000, 40_000]],
+ [90_000, [0, 15_000, 30_000, 45_000, 60_000, 75_000, 90_000]],
+ ])('axis ticks for %ims land on clock-friendly steps', (totalMs, expected) => {
+ expect(buildTicks(totalMs)).toEqual(expected)
+ })
+
+ it.each([
+ [1500, '1.5s'],
+ [119_600, '2m'], // rounds up whole — never "1m 60s"
+ [250_000, '4m 10s'],
+ [5_400_000, '1h 30m'],
+ ])('formats %ims as %s', (ms, expected) => {
+ expect(formatDuration(ms)).toBe(expected)
+ })
+})
diff --git a/products/ai_observability/frontend/components/TraceTimeline/buildTraceTimeline.ts b/products/ai_observability/frontend/components/TraceTimeline/buildTraceTimeline.ts
new file mode 100644
index 000000000000..183177c16879
--- /dev/null
+++ b/products/ai_observability/frontend/components/TraceTimeline/buildTraceTimeline.ts
@@ -0,0 +1,241 @@
+import { LLMTraceEvent } from '~/queries/schema/schema-general'
+
+import { LLMEventKind, getLLMEventKind, latencyMs, operationStartMs } from '../../utils'
+
+export type TraceBarKind = LLMEventKind
+
+export interface TraceTimelineBar {
+ id: string
+ label: string
+ startMs: number
+ // 0 means the event has no latency — rendered as an instant marker.
+ durationMs: number
+ kind: TraceBarKind
+ isError: boolean
+ // Flame-chart row: an event's children always render directly below it;
+ // concurrent siblings are pushed below each other's whole subtree.
+ lane: number
+ // event.id of the direct parent's bar, when the parent is drawn — lets the
+ // chart draw nesting connectors and tell children from concurrent siblings.
+ parentEventId: string | null
+}
+
+export interface TraceTimelineData {
+ bars: TraceTimelineBar[]
+ totalMs: number
+ laneCount: number
+}
+
+// Annotation events the trace tree hides too — they aren't steps in time.
+const HIDDEN_EVENTS = new Set(['$ai_feedback', '$ai_metric'])
+
+// Axis steps land on clock-friendly values (…15s, 30s, 1m, 2m…), not decimal
+// multiples — a 4m trace should tick 1m/2m/3m, never 50s/1m 40s.
+const TICK_STEPS_MS = [
+ 1, 2, 5, 10, 20, 50, 100, 200, 500, 1_000, 2_000, 5_000, 10_000, 15_000, 30_000, 60_000, 120_000, 300_000, 600_000,
+ 900_000, 1_800_000, 3_600_000, 7_200_000, 10_800_000, 21_600_000, 43_200_000, 86_400_000,
+]
+const MAX_TICKS = 6
+
+export function buildTicks(totalMs: number): number[] {
+ // Non-finite totals would make the tick loop below never terminate.
+ if (!isFinite(totalMs) || totalMs < 10) {
+ return [0]
+ }
+ const step =
+ TICK_STEPS_MS.find((s) => totalMs / s <= MAX_TICKS) ??
+ 86_400_000 * Math.ceil(totalMs / (MAX_TICKS * 86_400_000))
+ const ticks: number[] = []
+ for (let tick = 0; tick <= totalMs; tick += step) {
+ ticks.push(tick)
+ }
+ return ticks
+}
+
+// Compact durations: 240ms, 1.5s, 4m 30s, 2h 15m — terse enough to fit inside
+// bars and axis labels.
+export function formatDuration(ms: number): string {
+ if (ms <= 0) {
+ return '0'
+ }
+ if (ms < 1000) {
+ return `${Math.round(ms)}ms`
+ }
+ if (ms < 60_000) {
+ return `${parseFloat((ms / 1000).toFixed(2))}s`
+ }
+ if (ms < 3_600_000) {
+ const totalSeconds = Math.round(ms / 1000)
+ const minutes = Math.floor(totalSeconds / 60)
+ const seconds = totalSeconds % 60
+ return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`
+ }
+ const totalMinutes = Math.round(ms / 60_000)
+ const hours = Math.floor(totalMinutes / 60)
+ const minutes = totalMinutes % 60
+ return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`
+}
+
+// Instant events still occupy a sliver of time when resolving lane collisions.
+const OVERLAP_MIN_MS = 1
+
+function labelOf(event: LLMTraceEvent): string {
+ const p = event.properties || {}
+ // Properties are sender-controlled and can be non-strings; rendering an
+ // object as a React child would crash the scene.
+ const name = typeof p.$ai_span_name === 'string' ? p.$ai_span_name : undefined
+ const model = typeof p.$ai_model === 'string' ? p.$ai_model : undefined
+ return name || model || event.event || event.id
+}
+
+interface TimedEvent {
+ idx: number
+ event: LLMTraceEvent
+ /** The operation's start as epoch ms, see the timestamp-convention note below. */
+ startAt: number
+ latencyMs: number
+ /** Same node identity conventions as restoreTree, so nesting matches the tree. */
+ nodeId: string
+ parentId: string | null
+}
+
+export function buildTraceTimeline(events: LLMTraceEvent[]): TraceTimelineData {
+ const timed: TimedEvent[] = []
+ for (const event of events) {
+ if (HIDDEN_EVENTS.has(event.event)) {
+ continue
+ }
+ const t = new Date(event.createdAt).getTime()
+ if (!isFinite(t)) {
+ continue
+ }
+ const p = event.properties || {}
+ timed.push({
+ idx: timed.length,
+ event,
+ startAt: operationStartMs(event),
+ latencyMs: latencyMs(event),
+ nodeId: p.$ai_generation_id ?? p.$ai_span_id ?? event.id,
+ parentId: p.$ai_parent_id ?? p.$ai_trace_id ?? null,
+ })
+ }
+ if (!timed.length) {
+ return { bars: [], totalMs: 0, laneCount: 0 }
+ }
+
+ const byNodeId = new Map<string, TimedEvent>()
+ for (const timedEvent of timed) {
+ byNodeId.set(timedEvent.nodeId, timedEvent)
+ }
+
+ const traceStart = Math.min(...timed.map((e) => e.startAt))
+
+ const bars: TraceTimelineBar[] = timed.map((timedEvent) => ({
+ id: timedEvent.event.id,
+ label: labelOf(timedEvent.event),
+ startMs: timedEvent.startAt - traceStart,
+ durationMs: timedEvent.latencyMs,
+ kind: getLLMEventKind(timedEvent.event),
+ isError: !!timedEvent.event.properties?.$ai_is_error,
+ lane: 0,
+ parentEventId: null,
+ }))
+
+ const totalMs = Math.max(...bars.map((b) => b.startMs + b.durationMs))
+
+ // Restore the forest with the tree's parent-resolution rules: an event whose
+ // parent isn't among the events (e.g. the $ai_trace root the query runner
+ // strips out) starts its own top-level subtree.
+ const childrenOf = new Map<string, TimedEvent[]>()
+ const roots: TimedEvent[] = []
+ for (const timedEvent of timed) {
+ const parent = timedEvent.parentId != null ? byNodeId.get(timedEvent.parentId) : undefined
+ if (!parent || parent === timedEvent) {
+ roots.push(timedEvent)
+ continue
+ }
+ bars[timedEvent.idx].parentEventId = parent.event.id
+ const siblings = childrenOf.get(parent.nodeId)
+ if (siblings) {
+ siblings.push(timedEvent)
+ } else {
+ childrenOf.set(parent.nodeId, [timedEvent])
+ }
+ }
+
+ const startOf = (e: TimedEvent): number => e.startAt
+ const endOf = (e: TimedEvent): number => e.startAt + Math.max(e.latencyMs, OVERLAP_MIN_MS)
+
+ // Each sibling subtree is a rectangle: its time interval × its height in lanes.
+ // Siblings pack greedily; one that overlaps another in time drops below that
+ // sibling's whole rectangle, so a bar's children are always directly beneath it.
+ const offs: number[] = []
+ const visited = new Set<number>()
+
+ function packBand(siblings: TimedEvent[]): number {
+ const ordered = [...siblings].sort(
+ (a, b) => startOf(a) - startOf(b) || endOf(b) - startOf(b) - (endOf(a) - startOf(a))
+ )
+ const placed: { start: number; end: number; off: number; h: number }[] = []
+ let bandHeight = 0
+ for (const sibling of ordered) {
+ if (visited.has(sibling.idx)) {
+ continue
+ }
+ visited.add(sibling.idx)
+ const kids = childrenOf.get(sibling.nodeId)
+ const h = 1 + (kids ? packBand(kids) : 0)
+ const start = startOf(sibling)
+ const end = endOf(sibling)
+ const overlapping = placed.filter((p) => p.end > start && p.start < end)
+ let off = 0
+ for (const candidate of [0, ...overlapping.map((p) => p.off + p.h)].sort((a, b) => a - b)) {
+ if (!overlapping.some((p) => candidate < p.off + p.h && p.off < candidate + h)) {
+ off = candidate
+ break
+ }
+ }
+ offs[sibling.idx] = off
+ placed.push({ start, end, off, h })
+ bandHeight = Math.max(bandHeight, off + h)
+ }
+ return bandHeight
+ }
+
+ let laneCount = packBand(roots)
+
+ const assignLanes = (timedEvent: TimedEvent, baseLane: number): void => {
+ const lane = baseLane + (offs[timedEvent.idx] ?? 0)
+ bars[timedEvent.idx].lane = lane
+ // Only the canonical event for a node id owns its children, so duplicated
+ // span ids don't assign the same subtree twice.
+ if (byNodeId.get(timedEvent.nodeId) !== timedEvent) {
+ return
+ }
+ for (const kid of childrenOf.get(timedEvent.nodeId) ?? []) {
+ assignLanes(kid, lane + 1)
+ }
+ }
+ for (const root of roots) {
+ assignLanes(root, 0)
+ }
+
+ // Events stranded by a parent-reference cycle never get reached from a root —
+ // lay them out flat at the bottom instead of dropping them.
+ const stranded = timed.filter((e) => !visited.has(e.idx))
+ if (stranded.length) {
+ const laneEnds: number[] = []
+ for (const timedEvent of [...stranded].sort((a, b) => startOf(a) - startOf(b))) {
+ let subLane = laneEnds.findIndex((end) => end <= startOf(timedEvent))
+ if (subLane === -1) {
+ subLane = laneEnds.length
+ }
+ laneEnds[subLane] = endOf(timedEvent)
+ bars[timedEvent.idx].lane = laneCount + subLane
+ }
+ laneCount += laneEnds.length
+ }
+
+ bars.sort((a, b) => a.lane - b.lane || a.startMs - b.startMs)
+ return { bars, totalMs, laneCount }
+}
diff --git a/products/ai_observability/frontend/components/TraceTimeline/traceTimelineLogic.ts b/products/ai_observability/frontend/components/TraceTimeline/traceTimelineLogic.ts
new file mode 100644
index 000000000000..8fff51e8358a
--- /dev/null
+++ b/products/ai_observability/frontend/components/TraceTimeline/traceTimelineLogic.ts
@@ -0,0 +1,21 @@
+import { actions, kea, path, reducers } from 'kea'
+
+import { buildAiObservabilityStorageConfig } from '../../preferenceStorage'
+import type { traceTimelineLogicType } from './traceTimelineLogicType'
+
+export const traceTimelineLogic = kea<traceTimelineLogicType>([
+ path(['products', 'ai_observability', 'frontend', 'components', 'TraceTimeline', 'traceTimelineLogic']),
+ actions({
+ setCollapsed: (collapsed: boolean) => ({ collapsed }),
+ }),
+ reducers({
+ // Persisted per team so a user's choice to hide the timeline sticks across every trace.
+ collapsed: [
+ false,
+ buildAiObservabilityStorageConfig('trace.timeline.collapsed'),
+ {
+ setCollapsed: (_, { collapsed }) => collapsed,
+ },
+ ],
+ }),
+])
diff --git a/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts
index 3234d1bd3a6b..bd1076a7d046 100644
--- a/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts
+++ b/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts
@@ -131,7 +131,6 @@ export const aiObservabilityTracesTabLogic = kea<aiObservabilityTracesTabLogicTy
...(showSentimentColumn ? ['__llm_sentiment'] : []),
'__llm_tools',
'errorCount',
- 'stepCount',
'totalLatency',
'usage',
'totalCost',
diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.ts
index fa056098cbbb..6c83e25f65d9 100644
--- a/products/ai_observability/frontend/utils.test.ts
+++ b/products/ai_observability/frontend/utils.test.ts
@@ -12,7 +12,6 @@ import {
getInternalTagName,
getSessionID,
getSessionStartTimestamp,
- getTraceStepCount,
hasCostBreakdown,
hasStringContentField,
isEmptyJSONStructure,
@@ -2611,29 +2610,6 @@ describe.each(IMPLS)('AI observability utils [$name]', ({ normalizeMessage, norm
})
})
- describe('getTraceStepCount', () => {
- const event = (eventName: string): LLMTraceEvent => ({
- id: eventName,
- event: eventName,
- properties: {},
- createdAt: '2026-01-01T00:00:00Z',
- })
-
- it('counts generations, spans, and embeddings while excluding metric and feedback events', () => {
- expect(
- getTraceStepCount({
- events: [
- event('$ai_generation'),
- event('$ai_span'),
- event('$ai_embedding'),
- event('$ai_metric'),
- event('$ai_feedback'),
- ],
- })
- ).toBe(3)
- })
- })
-
describe('formatAiErrorForDisplay', () => {
it.each<[string, unknown, string]>([
['string passes through', 'rate limit exceeded', 'rate limit exceeded'],
diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.ts
index f1fff067ce6a..86589633cbe5 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -248,12 +248,6 @@ export function eventLabel(event: LLMTraceEvent): string {
return asString(event.properties.$ai_span_name) || asString(event.properties.$ai_model) || event.event
}
-const TRACE_STEP_EVENT_TYPES = new Set(['$ai_generation', '$ai_span', '$ai_embedding'])
-
-export function getTraceStepCount(trace: Partial<Pick<LLMTrace, 'events'>>): number {
- return trace.events?.filter((event) => TRACE_STEP_EVENT_TYPES.has(event.event)).length ?? 0
-}
-
export function formatAiErrorForDisplay(value: unknown): string {
if (typeof value === 'string') {
return value || 'Unknown error'
@@ -332,20 +326,41 @@ export function getSessionID(event: LLMTrace | LLMTraceEvent, childEvents?: LLMT
return sessionIdFromEvents(childEvents ?? event.events)
}
-export function getEventType(event: LLMTrace | LLMTraceEvent): string {
- if (isLLMEvent(event)) {
- switch (event.event) {
- case '$ai_generation':
- return 'generation'
- case '$ai_embedding':
- return 'embedding'
- case '$ai_trace':
- return 'trace'
- default:
- return 'span'
- }
+export type LLMEventKind = 'generation' | 'embedding' | 'trace' | 'span'
+
+export function getLLMEventKind(event: LLMTraceEvent): LLMEventKind {
+ switch (event.event) {
+ case '$ai_generation':
+ return 'generation'
+ case '$ai_embedding':
+ return 'embedding'
+ case '$ai_trace':
+ return 'trace'
+ default:
+ return 'span'
}
- return 'trace'
+}
+
+export function getEventType(event: LLMTrace | LLMTraceEvent): string {
+ return isLLMEvent(event) ? getLLMEventKind(event) : 'trace'
+}
+
+// Clamp AFTER the seconds-to-ms conversion: a finite-but-huge latency (1e306s)
+// overflows to Infinity when multiplied, which would hang the axis tick loop.
+export function latencyMs(event: LLMTraceEvent): number {
+ const ms = Number(event.properties?.$ai_latency) * 1000
+ return isFinite(ms) && ms > 0 ? ms : 0
+}
+
+/**
+ * Epoch ms when the operation behind an event began. PostHog AI SDKs capture an
+ * event when the operation finishes (timestamp = end, $ai_latency = duration),
+ * while OTel-ingested spans keep the span's start time. Shared by the timeline,
+ * the trace tree, and the drawer's event list so they all order events the same way.
+ */
+export function operationStartMs(event: LLMTraceEvent): number {
+ const t = new Date(event.createdAt).getTime()
+ return event.properties?.$ai_ingestion_source === 'otel' ? t : t - latencyMs(event)
}
export function getRecordingStatus(event: LLMTrace | LLMTraceEvent): string | null {